text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Enable external database (non dss) suport for KeyValueStorage |
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
Debug travis to pypi deploy | import amazon
from setuptools import setup, find_packages
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
setup(name='python-amazon-simple-product-api',
version=amazon.__version__,
description="A simple Python wrapper for the Amazon.com Product Advertising API",
long_description=long_description,
# http://pypi.python.org/pypi?:action=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: Apache Software License",
],
keywords='amazon, product advertising, api',
author='Yoav Aviram',
author_email='[email protected]',
url='https://github.com/yoavaviram/python-amazon-simple-product-api',
license='Apache 2.0',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=["bottlenose", "lxml", "python-dateutil"],
)
| import amazon
from setuptools import setup, find_packages
long_description = pypandoc.convert('README.md', 'rst')
setup(name='python-amazon-simple-product-api',
version=amazon.__version__,
description="A simple Python wrapper for the Amazon.com Product Advertising API",
long_description=long_description,
# http://pypi.python.org/pypi?:action=list_classifiers
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: Apache Software License",
],
keywords='amazon, product advertising, api',
author='Yoav Aviram',
author_email='[email protected]',
url='https://github.com/yoavaviram/python-amazon-simple-product-api',
license='Apache 2.0',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=["bottlenose", "lxml", "python-dateutil"],
)
|
Change empy engine to use Interpreter class. | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, basedir=None, **kwargs):
"""Initialize Subsystem plus a possible base directory."""
em.Subsystem.__init__(self, **kwargs)
self.basedir = basedir
def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs)
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, dirname=None, **kwargs):
"""Initialize empy template."""
super(EmpyEngine, self).__init__(**kwargs)
if dirname is not None:
# FIXME: This is a really bad idea, as it works like a global.
# Blame EmPy.
em.theSubsystem = SubsystemWrapper(basedir=dirname)
self.output = StringIO()
self.interpreter = em.Interpreter(output=self.output)
self.template = template
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
self.output.truncate(0)
self.interpreter.string(self.template, locals=mapping)
return self.output.getvalue()
| #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, basedir=None, **kwargs):
"""Initialize Subsystem plus a possible base directory."""
em.Subsystem.__init__(self, **kwargs)
self.basedir = basedir
def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs)
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, dirname=None, **kwargs):
"""Initialize empy template."""
super(EmpyEngine, self).__init__(**kwargs)
if dirname is not None:
# FIXME: This is a really bad idea, as it works like a global.
# Blame EmPy.
em.theSubsystem = SubsystemWrapper(basedir=dirname)
self.template = template
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
return em.expand(self.template, mapping)
|
Allow brunch server to listen on 0.0.0.0 | exports.config = {
npm: {
styles: {
'normalize.css': ['normalize.css']
}
},
conventions: {
ignored: [
/[\\/]_/,
/\.spec\.js$/
]
},
files: {
javascripts: {
joinTo: 'app.js'
},
stylesheets: {
joinTo: 'app.css'
}
},
server: {
hostname: '0.0.0.0'
},
overrides: {
production: {
plugins: {
postcss: {
processors: [
require('autoprefixer'),
require('cssnano')
]
}
}
}
},
plugins: {
digest: {
prependHost: {
production: 'https://rxlabs.github.io/tasty-todo'
},
referenceFiles: /\.(css|html|js)$/
},
postcss: {
processors: [
require('autoprefixer')
]
},
sass: {
options: {
includePaths: ['node_modules']
}
},
static: {
processors: [
require('html-brunch-static')({
handlebars: {
enableProcessor: true,
helpers: {
join (context, block) {
return context.join(block.hash.delimiter)
},
updated_time () {
return new Date().toISOString()
}
}
}
})
]
}
}
}
| exports.config = {
npm: {
styles: {
'normalize.css': ['normalize.css']
}
},
conventions: {
ignored: [
/[\\/]_/,
/\.spec\.js$/
]
},
files: {
javascripts: {
joinTo: 'app.js'
},
stylesheets: {
joinTo: 'app.css'
}
},
overrides: {
production: {
plugins: {
postcss: {
processors: [
require('autoprefixer'),
require('cssnano')
]
}
}
}
},
plugins: {
digest: {
prependHost: {
production: 'https://rxlabs.github.io/tasty-todo'
},
referenceFiles: /\.(css|html|js)$/
},
postcss: {
processors: [
require('autoprefixer')
]
},
sass: {
options: {
includePaths: ['node_modules']
}
},
static: {
processors: [
require('html-brunch-static')({
handlebars: {
enableProcessor: true,
helpers: {
join (context, block) {
return context.join(block.hash.delimiter)
},
updated_time () {
return new Date().toISOString()
}
}
}
})
]
}
}
}
|
Add support for Python 3 | #!/usr/bin/env python
# Original author : Jonathan Zempel, https://github.com/jzempel
# Copied from https://gist.github.com/jzempel/4624227
# Copied here for the purpose of adding it to PyPI
from pkg_resources import parse_version
try:
from xmlrpclib import ServerProxy
except ImportError:
import xmlrpc.client
try:
pypi = ServerProxy("http://pypi.python.org/pypi")
except NameError:
pypi = xmlrpc.client.ServerProxy("http://pypi.python.org/pypi")
def main():
try:
from pip import get_installed_distributions
except ImportError:
from sys import exit
exit("pip not available")
for distribution in sorted(get_installed_distributions(),
key=lambda distribution: distribution.project_name):
remote = ''
project_name = distribution.project_name
releases = pypi.package_releases(project_name)
if not releases:
pypi.package_releases(project_name.capitalize())
if releases:
version = parse_version(releases[0])
if str(version) > str(distribution.parsed_version):
remote = "PyPI:{0}=={1}".format(project_name, releases[0])
else:
remote = "PyPI:{0} not found".format(project_name)
local = "{0}=={1}".format(project_name, distribution.version)
print("{0:40} {1}".format(local, remote))
return True
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# Original author : Jonathan Zempel, https://github.com/jzempel
# Copied from https://gist.github.com/jzempel/4624227
# Copied here for the purpose of adding it to PyPI
from pkg_resources import parse_version
from xmlrpclib import ServerProxy
pypi = ServerProxy("http://pypi.python.org/pypi")
def main():
try:
from pip import get_installed_distributions
except ImportError:
from sys import exit
exit("pip not available")
for distribution in sorted(get_installed_distributions(),
key=lambda distribution: distribution.project_name):
remote = ''
project_name = distribution.project_name
releases = pypi.package_releases(project_name)
if not releases:
pypi.package_releases(project_name.capitalize())
if releases:
version = parse_version(releases[0])
if version > distribution.parsed_version:
remote = "PyPI:{0}=={1}".format(project_name, releases[0])
else:
remote = "PyPI:{0} not found".format(project_name)
local = "{0}=={1}".format(project_name, distribution.version)
print "{0:40} {1}".format(local, remote)
return True
if __name__ == '__main__':
main()
|
Mark error flag if an object is not present on S3 | from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
results = self.postgres.session.query(WorkerResult).join(Analysis).\
filter(Analysis.finished_at != None).\
filter(WorkerResult.external_request_id == None)
for entry in results:
if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'):
continue
if 'VersionId' in entry.task_result:
continue
result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name,
entry.package.name,
entry.version.identifier,
entry.worker)
if s3.object_exists(result_object_key):
entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)}
else:
entry.task_result = None
entry.error = True
self.postgres.session.commit()
| from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
results = self.postgres.session.query(WorkerResult).join(Analysis).\
filter(Analysis.finished_at != None).\
filter(WorkerResult.external_request_id == None)
for entry in results:
if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'):
continue
if 'VersionId' in entry.task_result:
continue
result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name,
entry.package.name,
entry.version.identifier,
entry.worker)
entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)}
self.postgres.session.commit()
|
Use GET /me if you want the current user JSON | import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from django.utils import simplejson
from model import get_current_youtify_user
from model import YoutifyUser
from model import get_youtify_user_by_nick
from model import get_current_user_json
from model import get_youtify_user_json_for
class UserHandler(webapp.RequestHandler):
def get(self):
"""Get user as JSON"""
user_id = self.request.path.split('/')[-1]
if user_id is None or len(user_id) == 0:
self.error(404)
return
user = None
json = None
if user_id.isdigit():
user = YoutifyUser.get_by_id(int(user_id))
else:
user = get_youtify_user_by_nick(user_id)
if user is None:
self.error(404)
return
json = get_youtify_user_json_for(user)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json)
def post(self):
"""Update user"""
self.error(500)
def main():
application = webapp.WSGIApplication([
('/api/users/.*', UserHandler),
], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from django.utils import simplejson
from model import get_current_youtify_user
from model import YoutifyUser
from model import get_youtify_user_by_nick
from model import get_current_user_json
from model import get_youtify_user_json_for
class UserHandler(webapp.RequestHandler):
def get(self):
"""Get user as JSON"""
user_id = self.request.path.split('/')[-1]
if user_id is None or len(user_id) == 0:
self.error(404)
return
user = None
json = None
if user_id.isdigit():
user = YoutifyUser.get_by_id(int(user_id))
else:
user = get_youtify_user_by_nick(user_id)
if user is None:
self.error(404)
return
if user.google_user == users.get_current_user():
json = get_current_user_json()
else:
json = get_youtify_user_json_for(user)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json)
def post(self):
"""Update user"""
self.error(500)
def main():
application = webapp.WSGIApplication([
('/api/users/.*', UserHandler),
], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
Fix substringing of long breadcrumb items |
var Mocha = require('mocha'),
_ = require('underscore');
module.exports = function (browser, dashboard, suite /*, config*/) {
var tests = {
'has a breadcrumb': function () {
return browser
.$('#global-breadcrumb ol').isDisplayed()
.should.eventually.be.ok
.$('#global-breadcrumb ol li:nth-child(1) a').text()
.should.eventually.equal('Performance')
.$('#global-breadcrumb ol li:nth-child(1) a').getAttribute('href')
.should.eventually.match(/\/performance$/)
.$('#global-breadcrumb ol li:nth-child(2)').text()
.should.eventually.equal('Activity on GOV.UK')
.then(function () {
if (dashboard.slug !== 'site-activity') {
return browser
.$('#global-breadcrumb ol li:nth-child(3)').text()
.should.eventually.contain(dashboard.title.substr(0, 32));
}
});
},
'has a link to the site in the header': function () {
if (dashboard.relatedPages && dashboard.relatedPages.transaction) {
return browser
.$('#content .related-pages .related-transaction a').text()
.should.eventually.equal(dashboard.relatedPages.transaction.title)
.$('#content .related-pages .related-transaction a').getAttribute('href')
.should.eventually.equal(dashboard.relatedPages.transaction.url);
}
}
};
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
return suite;
};
|
var Mocha = require('mocha'),
_ = require('underscore');
module.exports = function (browser, dashboard, suite /*, config*/) {
var tests = {
'has a breadcrumb': function () {
return browser
.$('#global-breadcrumb ol').isDisplayed()
.should.eventually.be.ok
.$('#global-breadcrumb ol li:nth-child(1) a').text()
.should.eventually.equal('Performance')
.$('#global-breadcrumb ol li:nth-child(1) a').getAttribute('href')
.should.eventually.match(/\/performance$/)
.$('#global-breadcrumb ol li:nth-child(2)').text()
.should.eventually.equal('Activity on GOV.UK')
.then(function () {
if (dashboard.slug !== 'site-activity') {
return browser
.$('#global-breadcrumb ol li:nth-child(3)').text()
.should.eventually.equal(dashboard.title);
}
});
},
'has a link to the site in the header': function () {
if (dashboard.relatedPages && dashboard.relatedPages.transaction) {
return browser
.$('#content .related-pages .related-transaction a').text()
.should.eventually.equal(dashboard.relatedPages.transaction.title)
.$('#content .related-pages .related-transaction a').getAttribute('href')
.should.eventually.equal(dashboard.relatedPages.transaction.url);
}
}
};
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
return suite;
};
|
Implement basic functionality for cache stat monitoring | <?php
class Better_PHP_Cache
{
private $cache_files_dir;
private $monitor_cache_stats;
public function __construct($cache_files_dir, $monitor_cache_stats = TRUE)
{
if($cache_files_dir)
{
if(file_exists($cache_files_dir) && is_writable($cache_files_dir))
{
$this->cache_files_dir = $cache_files_dir;
}
}
if($monitor_cache_stats == TRUE)
{
$this->monitor_cache_stats = TRUE;
$cache_stats = apc_fetch('cache_stats');
if(!$cache_stats)
{
$cache_stats['monitoring_start_timestamp'] = time();
}
else
{
$cache_stats['total_monitored_duration_in_seconds'] = time() - $cache_stats['monitoring_start_timestamp'];
}
apc_store('cache_stats', $cache_stats);
}
}
public function store($entry_name, $entry_value, $time_to_live)
{
if(!($entry_name && $entry_value && $time_to_live))
{
return FALSE;
}
if($this->monitor_cache_stats == TRUE)
{
$cache_stats = apc_fetch($cache_stats);
$cache_stats[$entry_name]['store_count'] = $cache_stats[$entry_name]['store_count'] + 1;
apc_store('cache_stats', $cache_stats);
}
}
public function fetch($entry_name)
{
if(!$entry_name)
{
return FALSE;
}
return apc_fetch($entry_name);
}
public function delete($entry_name)
{
if($entry_name)
{
return apc_delete($entry_name);
}
}
public function reset_cache_stats()
{
$cache_stats = NULL;
apc_store('cache_stats', $cache_stats);
}
}
?> | <?php
class Better_PHP_Cache
{
private $cache_files_dir;
public function __construct($cache_files_dir)
{
if($cache_files_dir)
{
if(file_exists($cache_files_dir) && is_writable($cache_files_dir))
{
$this->cache_files_dir = $cache_files_dir;
}
}
}
public function store($entry_name, $entry_value, $time_to_live)
{
if(!($entry_name && $entry_value && $time_to_live))
{
return FALSE;
}
return apc_store($entry_name, $entry_value, $time_to_live);
}
public function fetch($entry_name)
{
if(!$entry_name)
{
return FALSE;
}
return apc_fetch($entry_name);
}
public function delete($entry_name)
{
if($entry_name)
{
return apc_delete($entry_name);
}
}
}
?> |
Remove type hinting broke by Promises | <?php
namespace Alchemy\expression;
use Exception;
/**
* Represent an UPDATE statment in SQL
*/
class Update extends Query {
protected $table;
protected $values = array();
/**
* Set the table into update
*
* @param Table $table
*/
public function table($table = null) {
if (is_null($table)) {
return $this->table;
}
$this->table = $table;
}
/**
* Set the given column to be equal to the given Value
*
* @param Column $column
* @param mixed $value
*/
public function set($column, $value) {
if (!$value instanceof Scalar) {
$value = new Scalar($value);
}
$this->values[] = array($column, $value);
}
/**
* Return an array of set operations to perform
*
* @return array
*/
public function sets() {
return $this->values;
}
/**
* Recursively get all scalar parameters used by this expression
*
* @return array array(Scalar, Scalar, ...)
*/
public function getParameters() {
$scalars = parent::getParameters();
foreach ($this->values as $value) {
$scalars[] = $value[1];
}
return $scalars;
}
}
| <?php
namespace Alchemy\expression;
use Exception;
/**
* Represent an UPDATE statment in SQL
*/
class Update extends Query {
protected $table;
protected $values = array();
/**
* Set the table into update
*
* @param Table $table
*/
public function table($table = null) {
if (is_null($table)) {
return $this->table;
}
$this->table = $table;
}
/**
* Set the given column to be equal to the given Value
*
* @param Column $column
* @param mixed $value
*/
public function set(Column $column, $value) {
if (!$value instanceof Scalar) {
$value = new Scalar($value);
}
$this->values[] = array($column, $value);
}
/**
* Return an array of set operations to perform
*
* @return array
*/
public function sets() {
return $this->values;
}
/**
* Recursively get all scalar parameters used by this expression
*
* @return array array(Scalar, Scalar, ...)
*/
public function getParameters() {
$scalars = parent::getParameters();
foreach ($this->values as $value) {
$scalars[] = $value[1];
}
return $scalars;
}
}
|
Clean up & comment language determination | const i18n = require('i18next')
const _ = require('underscore')
const path = require('path')
module.exports = {
setup(options = {}) {
const subdomainLang = options.subdomainLang || {}
const availableLngs = _.pluck(_.values(subdomainLang), 'lngCode')
i18n.init({
resGetPath: path.resolve(__dirname, '../../', 'locales/__lng__.json'),
saveMissing: true,
resSetPath: path.resolve(
__dirname,
'../../',
'locales/missing-__lng__.json'
),
sendMissingTo: 'fallback',
fallbackLng: options.defaultLng || 'en',
detectLngFromHeaders: true,
useCookie: false,
preload: availableLngs,
supportedLngs: availableLngs
})
const setLangBasedOnDomainMiddlewear = function(req, res, next) {
// Determine language from subdomain
const { host } = req.headers
if (host == null) {
return next()
}
const [subdomain] = host.split(/[.-]/)
const lang = subdomainLang[subdomain]
? subdomainLang[subdomain].lngCode
: null
// Unless setLng query param is set, use subdomain lang
if (!req.originalUrl.includes('setLng') && lang != null) {
req.i18n.setLng(lang)
}
if (req.language !== req.lng) {
req.showUserOtherLng = req.language
}
next()
}
return {
expressMiddlewear: i18n.handle,
setLangBasedOnDomainMiddlewear,
i18n
}
}
}
| const i18n = require('i18next')
const _ = require('underscore')
const path = require('path')
module.exports = {
setup(options = {}) {
const subdomainLang = options.subdomainLang || {}
const availableLngs = _.pluck(_.values(subdomainLang), 'lngCode')
i18n.init({
resGetPath: path.resolve(__dirname, '../../', 'locales/__lng__.json'),
saveMissing: true,
resSetPath: path.resolve(
__dirname,
'../../',
'locales/missing-__lng__.json'
),
sendMissingTo: 'fallback',
fallbackLng: options.defaultLng || 'en',
detectLngFromHeaders: true,
useCookie: false,
preload: availableLngs,
supportedLngs: availableLngs
})
const setLangBasedOnDomainMiddlewear = function(req, res, next) {
const { host } = req.headers
if (host == null) {
return next()
}
const parts = host.split(/[.-]/)
const subdomain = parts[0]
const lang = subdomainLang[subdomainLang]
? subdomainLang[subdomain].lngCode
: null
if (req.originalUrl.indexOf('setLng') === -1 && lang != null) {
req.i18n.setLng(lang)
}
if (req.language !== req.lng) {
req.showUserOtherLng = req.language
}
next()
}
return {
expressMiddlewear: i18n.handle,
setLangBasedOnDomainMiddlewear,
i18n
}
}
}
|
Fix : range output datas format validation | from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if (not isinstance(range_datas, (list, tuple)) or
any(not isinstance(pair, (list, tuple)) for pair in range_datas)):
raise ValueError("Range datas format not recognized")
return True
def __iter__(self):
return self.forward()
def forward(self):
current_item = 0
while (current_item < len(self._container)):
container = self._container[current_item]
current_item += 1
yield container
class Elevator(Client):
def Get(self, key):
return self.send(self.db_uid, 'GET', [key])
def MGet(self, keys):
return self.send(self.db_uid, 'MGET', [keys])
def Put(self, key, value):
return self.send(self.db_uid, 'PUT', [key, value])
def Delete(self, key):
return self.send(self.db_uid, 'DELETE', [key])
def Range(self, start=None, limit=None):
return self.send(self.db_uid, 'RANGE', [start, limit])
def RangeIter(self, key_from=None, key_to=None):
range_datas = self.Range(key_from, key_to)
return RangeIter(range_datas)
| from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if (not isinstance(range_datas, tuple) or
any(not isinstance(pair, tuple) for pair in range_datas)):
raise ValueError("Range datas format not recognized")
return True
def __iter__(self):
return self.forward()
def forward(self):
current_item = 0
while (current_item < len(self._container)):
container = self._container[current_item]
current_item += 1
yield container
class Elevator(Client):
def Get(self, key):
return self.send(self.db_uid, 'GET', [key])
def MGet(self, keys):
return self.send(self.db_uid, 'MGET', [keys])
def Put(self, key, value):
return self.send(self.db_uid, 'PUT', [key, value])
def Delete(self, key):
return self.send(self.db_uid, 'DELETE', [key])
def Range(self, start=None, limit=None):
return self.send(self.db_uid, 'RANGE', [start, limit])
def RangeIter(self, key_from=None, key_to=None):
range_datas = self.Range(key_from, key_to)
return RangeIter(range_datas)
|
Use debug module to print sql for debugging purposes | const BaseDataview = require('./base');
const debug = require('debug')('windshaft:dataview:list');
const TYPE = 'list';
const listSqlTpl = ctx => `select ${ctx._columns} from (${ctx._query}) as _cdb_list`;
/**
{
type: 'list',
options: {
columns: ['name', 'description']
}
}
*/
module.exports = class List extends BaseDataview {
constructor (query, options = {}) {
super();
this._checkOptions(options);
this.query = query;
this.columns = options.columns;
}
_checkOptions (options) {
if (!Array.isArray(options.columns)) {
throw new Error('List expects `columns` array in dataview options');
}
}
sql (psql, override, callback) {
if (!callback) {
callback = override;
}
const listSql = listSqlTpl({
_query: this.query,
_columns: this.columns.join(', ')
});
debug(listSql);
return callback(null, listSql);
}
format (result) {
return {
rows: result.rows
};
}
getType () {
return TYPE;
}
toString () {
return JSON.stringify({
_type: TYPE,
_query: this.query,
_columns: this.columns.join(', ')
});
};
}
| const BaseDataview = require('./base');
const TYPE = 'list';
const listSqlTpl = ctx => `select ${ctx._columns} from (${ctx._query}) as _cdb_list`;
/**
{
type: 'list',
options: {
columns: ['name', 'description']
}
}
*/
module.exports = class List extends BaseDataview{
constructor (query, options = {}) {
super();
this._checkOptions(options);
this.query = query;
this.columns = options.columns;
}
_checkOptions (options) {
if (!Array.isArray(options.columns)) {
throw new Error('List expects `columns` array in dataview options');
}
}
sql (psql, override, callback) {
if (!callback) {
callback = override;
}
const listSql = listSqlTpl({
_query: this.query,
_columns: this.columns.join(', ')
});
return callback(null, listSql);
}
format (result) {
return {
rows: result.rows
};
}
getType () {
return TYPE;
}
toString () {
return JSON.stringify({
_type: TYPE,
_query: this.query,
_columns: this.columns.join(', ')
});
};
}
|
Comment out problematic test for now | from __future__ import absolute_import, division, print_function
import os
import sys
import pytest
from mock import MagicMock
# At the moment it is not possible to have PyQt5 and PyQt4 installed
# simultaneously because one requires the Qt4 libraries while the other
# requires the Qt5 libraries
class TestQT5(object):
def setup_class(cls):
os.environ['QT_API'] = 'pyqt5'
import qt_helpers as qt
def _load_qt5(self):
import qt_helpers as qt
def test_main_import_qt5(self):
self._load_qt5()
from qt_helpers import QtCore
from qt_helpers import QtGui
from PyQt5 import QtCore as core, QtGui as gui
assert QtCore is core
assert QtGui is gui
# At the moment, PyQt5 does not run correctly on Travis so we can't run
# this without causing an Abort Trap.
# def test_load_ui_qt5(self):
# self._load_qt5()
# from qt_helpers import load_ui, get_qapp
# qpp = get_qapp()
# load_ui('test.ui')
def test_submodule_import_qt5(self):
self._load_qt5()
from qt_helpers.QtGui import QMessageBox
from qt_helpers.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox as qmb
from PyQt5.QtCore import Qt as _qt
assert qmb is QMessageBox
assert _qt is Qt
| from __future__ import absolute_import, division, print_function
import os
import sys
import pytest
from mock import MagicMock
# At the moment it is not possible to have PyQt5 and PyQt4 installed
# simultaneously because one requires the Qt4 libraries while the other
# requires the Qt5 libraries
class TestQT5(object):
def setup_class(cls):
print('-' * 72)
os.environ['QT_API'] = 'pyqt5'
import qt_helpers as qt
def _load_qt5(self):
import qt_helpers as qt
def test_main_import_qt5(self):
self._load_qt5()
from qt_helpers import QtCore
from qt_helpers import QtGui
from PyQt5 import QtCore as core, QtGui as gui
assert QtCore is core
assert QtGui is gui
def test_load_ui_qt5(self):
self._load_qt5()
from qt_helpers import load_ui, get_qapp
qpp = get_qapp()
load_ui('test.ui')
def test_submodule_import_qt5(self):
self._load_qt5()
from qt_helpers.QtGui import QMessageBox
from qt_helpers.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox as qmb
from PyQt5.QtCore import Qt as _qt
assert qmb is QMessageBox
assert _qt is Qt
def test_submodule_import_pyside(self):
self._load_pyside()
from qt_helpers.QtGui import QMessageBox
from qt_helpers.QtCore import Qt
from PySide.QtGui import QMessageBox as qmb
from PySide.QtCore import Qt as _qt
assert qmb is QMessageBox
assert _qt is Qt
|
Refactor - slightly more elegant way of splitting the template
Splitting the template into the button element and the popup. | /*
* Provide a search widget with a popup to enter and clear search terms.
* Test suite can get a handle on this for clean slate testing.
*/
tsbar.initSearchWidget = function(exports, $) {
function SearchWidget() {
this.$compiledTemplate = $(exports.tswidgets.templates['search.hbs'](Handlebars));
this.$el = this.$compiledTemplate.first();
this.$popup = this.$compiledTemplate.last();
this._widget = tsbar.Widget({
el: this.$el,
popup: this.$popup
});
}
SearchWidget.prototype.getWidget = function() {
return this._widget;
};
SearchWidget.prototype._registerListeners = function() {
this.$popup.find('#tsbar-search-button').click(this._doSearch);
this.$popup.find('#tsbar-clear-button').click(this._doClear);
};
SearchWidget.prototype._doSearch = function() {
var query = $('#tsbar-query-text').val();
$('#tsbar-search-results').load('/hsearch?q=' + query + ' #container');
};
SearchWidget.prototype._doClear = function() {
$('#tsbar-search-results').html('');
$('#tsbar-query-text').val('');
};
function main() {
var searchWidget = new SearchWidget();
searchWidget._registerListeners();
exports.tsbar.searchWidget = searchWidget.getWidget();
}
main();
};
(function(exports, $) {
tsbar.initSearchWidget(exports, $);
}(window, jQuery));
| /*
* Provide a search widget with a popup to enter and clear search terms.
* Test suite can get a handle on this for clean slate testing.
*/
tsbar.initSearchWidget = function(exports, $) {
function SearchWidget() {
this.$compiledTemplate = $(exports.tswidgets.templates['search.hbs'](Handlebars));
//TODO: this is a hack as the pre-compiled templates have carriage returns which confuses jquery
this.$el = $(this.$compiledTemplate[0]);
this.$popup = $(this.$compiledTemplate[2]);
this._widget = tsbar.Widget({
el: this.$el,
popup: this.$popup
});
}
SearchWidget.prototype.getWidget = function() {
return this._widget;
};
SearchWidget.prototype._registerListeners = function() {
this.$popup.find('#tsbar-search-button').click(this._doSearch);
this.$popup.find('#tsbar-clear-button').click(this._doClear);
};
SearchWidget.prototype._doSearch = function() {
var query = $('#tsbar-query-text').val();
$('#tsbar-search-results').load('/hsearch?q=' + query + ' #container');
};
SearchWidget.prototype._doClear = function() {
$('#tsbar-search-results').html('');
$('#tsbar-query-text').val('');
};
function main() {
var searchWidget = new SearchWidget();
searchWidget._registerListeners();
exports.tsbar.searchWidget = searchWidget.getWidget();
}
main();
};
(function(exports, $) {
tsbar.initSearchWidget(exports, $);
}(window, jQuery));
|
Fix missing username in test | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
| import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
Comment release by default to fix fatal | <?php
return [
/*
* This is your authorization key which you get from your profile.
* @ http://www.larabug.com
*/
'login_key' => env('LB_KEY', 'LB_KEY'),
/*
* This is your project key which you receive when creating a project
* @ http://www.larabug.com/projects
*/
'project_key' => env('LB_PROJECT_KEY', 'LB_PROJECT_KEY'),
/*
* Environments where LaraBug should report
*/
'environments' => [
'production'
],
/*
* How many lines to show near exception line.
*/
'lines_count' => 12,
/*
* Set the sleep time between duplicate exceptions.
*/
'sleep' => 5,
/*
* Define your path for your 500 errors.
*/
'errorView' => 'errors.500', // Refers to views/errors/500.blade.php
/*
* List of exceptions to skip sending.
*/
'except' => [
'Symfony\Component\HttpKernel\Exception\NotFoundHttpException',
],
/*
* Filter out these variables before sending them to larabug
*/
'blacklist' => [
'password',
'authorization'
],
/**
* Release git hash
*/
// 'release' => trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
];
| <?php
return [
/*
* This is your authorization key which you get from your profile.
* @ http://www.larabug.com
*/
'login_key' => env('LB_KEY', 'LB_KEY'),
/*
* This is your project key which you receive when creating a project
* @ http://www.larabug.com/projects
*/
'project_key' => env('LB_PROJECT_KEY', 'LB_PROJECT_KEY'),
/*
* Environments where LaraBug should report
*/
'environments' => [
'production'
],
/*
* How many lines to show near exception line.
*/
'lines_count' => 12,
/*
* Set the sleep time between duplicate exceptions.
*/
'sleep' => 5,
/*
* Define your path for your 500 errors.
*/
'errorView' => 'errors.500', // Refers to views/errors/500.blade.php
/*
* List of exceptions to skip sending.
*/
'except' => [
'Symfony\Component\HttpKernel\Exception\NotFoundHttpException',
],
/*
* Filter out these variables before sending them to larabug
*/
'blacklist' => [
'password',
'authorization'
],
/**
* Release git hash
*/
'release' => trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
];
|
Improve error description showing class name | <?php
/**
* DronePHP (http://www.dronephp.com)
*
* @link http://github.com/Pleets/DronePHP
* @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
* @license http://www.dronephp.com/license
*/
namespace Drone\Db;
abstract class Entity
{
/**
* @var string
*/
private $tableName;
/**
* Returns the tableName property
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Sets the tableName property
*
* @param string $tableName
*
* @param null
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
}
/**
* Sets all entity properties passed in the array
*
* @param array $data
*
* @return null
*/
public function exchangeArray($data)
{
$class = get_class($this);
foreach ($data as $prop => $value)
{
if (property_exists($this, $prop))
$this->$prop = $value;
else
throw new Exception("The property '$prop' does not exists in the class '$class'");
}
}
} | <?php
/**
* DronePHP (http://www.dronephp.com)
*
* @link http://github.com/Pleets/DronePHP
* @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
* @license http://www.dronephp.com/license
*/
namespace Drone\Db;
abstract class Entity
{
/**
* @var string
*/
private $tableName;
/**
* Returns the tableName property
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Sets the tableName property
*
* @param string $tableName
*
* @param null
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
}
/**
* Sets all entity properties passed in the array
*
* @param array $data
*
* @return null
*/
public function exchangeArray($data)
{
foreach ($data as $prop => $value)
{
if (property_exists($this, $prop))
$this->$prop = $value;
else
throw new Exception("The property '$prop' does not exists in the class!");
}
}
} |
Fix except handler raises immediately | import json
from django.core.serializers.base import DeserializationError
from django.core.serializers.json import (
DjangoJSONEncoder, PythonDeserializer, Serializer as JsonSerializer)
from prices import Money
MONEY_TYPE = 'Money'
class Serializer(JsonSerializer):
def _init_options(self):
super()._init_options()
self.json_kwargs['cls'] = CustomJsonEncoder
class CustomJsonEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Money):
return {
'_type': MONEY_TYPE, 'amount': obj.amount,
'currency': obj.currency}
return super().default(obj)
def object_hook(obj):
if '_type' in obj and obj['_type'] == MONEY_TYPE:
return Money(obj['amount'], obj['currency'])
return obj
def Deserializer(stream_or_string, **options):
"""Deserialize a stream or string of JSON data. This is a slightly modified
copy of Django implementation with additional argument <object_hook> in
json.loads"""
if not isinstance(stream_or_string, (bytes, str)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode()
try:
objects = json.loads(stream_or_string, object_hook=object_hook)
yield from PythonDeserializer(objects, **options)
except Exception as exc:
# ugly construction to overcome pylint's warning
# "The except handler raises immediately"
if isinstance(exc, GeneratorExit, DeserializationError):
raise
raise DeserializationError() from exc
| import json
from django.core.serializers.base import DeserializationError
from django.core.serializers.json import (
DjangoJSONEncoder, PythonDeserializer, Serializer as JsonSerializer)
from prices import Money
MONEY_TYPE = 'Money'
class Serializer(JsonSerializer):
def _init_options(self):
super()._init_options()
self.json_kwargs['cls'] = CustomJsonEncoder
class CustomJsonEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Money):
return {
'_type': MONEY_TYPE, 'amount': obj.amount,
'currency': obj.currency}
return super().default(obj)
def object_hook(obj):
if '_type' in obj and obj['_type'] == MONEY_TYPE:
return Money(obj['amount'], obj['currency'])
return obj
def Deserializer(stream_or_string, **options):
"""Deserialize a stream or string of JSON data. This is a copy of Django
implementation with additional argument <object_hook> in json.loads"""
if not isinstance(stream_or_string, (bytes, str)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode()
try:
objects = json.loads(stream_or_string, object_hook=object_hook)
yield from PythonDeserializer(objects, **options)
except (GeneratorExit, DeserializationError):
raise
except Exception as exc:
raise DeserializationError() from exc
|
Fix performance issue with publishing images | <?php
namespace JonoM\FocusPoint\Extensions;
use JonoM\FocusPoint\Dev\FocusPointMigrationTask;
use JonoM\FocusPoint\FieldType\DBFocusPoint;
use SilverStripe\Assets\Image;
use SilverStripe\Assets\Storage\DBFile;
/**
* FocusPoint Image extension.
* Extends Image to allow automatic cropping from a selected focus point.
*
* @extends DataExtension
* @property DBFocusPoint $FocusPoint
* @property Image|DBFile|FocusPointImageExtension $owner
*/
class FocusPointImageExtension extends FocusPointExtension
{
/**
* Describes the focus point coordinates on the image.
*/
private static $db = [
'FocusPoint' => DBFocusPoint::class,
];
public function requireDefaultRecords()
{
$autoMigrate = FocusPointMigrationTask::create();
$autoMigrate->up();
}
public function onBeforeWrite()
{
// Ensure that we saved the cached image width / height whenever we change the file hash
// This code ignores forceChange, since we only need to know if the underlying file is modified
$changes = $this->owner->getChangedFields(['FileHash']);
$fileHashChanged = isset($changes['FileHash']) && $changes['FileHash']['before'] !== $changes['FileHash']['after'];
if (
(
$fileHashChanged
|| empty($this->owner->FocusPoint->getField('Width'))
|| empty($this->owner->FocusPoint->getField('Height'))
) && $this->owner->exists()
) {
$this->owner->FocusPoint->Width = $this->owner->getWidth();
$this->owner->FocusPoint->Height = $this->owner->getHeight();
}
}
}
| <?php
namespace JonoM\FocusPoint\Extensions;
use JonoM\FocusPoint\Dev\FocusPointMigrationTask;
use JonoM\FocusPoint\FieldType\DBFocusPoint;
use SilverStripe\Assets\Image;
use SilverStripe\Assets\Storage\DBFile;
/**
* FocusPoint Image extension.
* Extends Image to allow automatic cropping from a selected focus point.
*
* @extends DataExtension
* @property DBFocusPoint $FocusPoint
* @property Image|DBFile|FocusPointImageExtension $owner
*/
class FocusPointImageExtension extends FocusPointExtension
{
/**
* Describes the focus point coordinates on the image.
*/
private static $db = [
'FocusPoint' => DBFocusPoint::class,
];
public function requireDefaultRecords()
{
$autoMigrate = FocusPointMigrationTask::create();
$autoMigrate->up();
}
public function onBeforeWrite()
{
// Ensure that we saved the cached image width / height whenever we change the file hash
if (
(
$this->owner->isChanged('FileHash')
|| empty($this->owner->FocusPoint->getField('Width'))
|| empty($this->owner->FocusPoint->getField('Height'))
) && $this->owner->exists()
) {
$this->owner->FocusPoint->Width = $this->owner->getWidth();
$this->owner->FocusPoint->Height = $this->owner->getHeight();
}
}
}
|
Implement new version of react-mdl's DataTable including TableHeader component. | import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, TableHeader, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
rows={rows}
className='law-list'
>
<TableHeader name='groupkey'>Ab­kür­zung</TableHeader>
<TableHeader name='title'>Be­zeich­nung</TableHeader>
<TableHeader name='action' />
</DataTable>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
| import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const columns = [
{ name: 'groupkey', label: <span>Ab­kür­zung</span> },
{ name: 'title', label: <span>Be­zeich­nung</span> },
{ name: 'action' },
];
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
columns={columns}
rows={rows}
className='law-list'
/>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
|
Make it cleaner to read | /* @flow */
var React = require('react');
var FlexCell: any = require('./FlexCell.react');
var FlexDetail = require('./FlexDetail.react');
class FlexGrid extends React.Component{
state: {detail: string};
render: Function;
constructor(): void {
super();
this.state = {detail:''};
this.render = this.render.bind(this);
}
handleDetailSelection(title: string) {
this.setState({detail:title});
}
handleDetailClosing(){
this.setState({detail:''});
}
render(): any {
if(this.state.detail){
return (<FlexDetail title={this.state.detail}
closeHandler={this.handleDetailClosing.bind(this)}/>);
} else {
return (
<main className="main">
{this.props.pokemon.map( p => {
if( p.name.indexOf(this.props.filterText.toLowerCase()) === -1){
return;
}
return <FlexCell
title={p.name}
key={p.name}
clickHandler={this.handleDetailSelection.bind(this)}/>
})}</main>);
}
}
};
module.exports = FlexGrid; | /* @flow */
var React = require('react');
var FlexCell: any = require('./FlexCell.react');
var FlexDetail = require('./FlexDetail.react');
class FlexGrid extends React.Component{
state: {detail: string};
render: Function;
constructor(): void {
super();
this.state = {detail:''};
this.render = this.render.bind(this);
}
handleDetailSelection(title: string) {
console.log(`You picked ${title}`);
this.setState({detail:title});
}
handleDetailClosing(){
this.setState({detail:''});
}
render(): any {
if(this.state.detail){
return (<FlexDetail title={this.state.detail}
closeHandler={this.handleDetailClosing.bind(this)}/>);
} else {
return (
<main className="main">
{this.props.pokemon.map( p => {
if( p.name.indexOf(this.props.filterText.toLowerCase()) === -1){
return;
}
return <FlexCell title={p.name} key={p.name} clickHandler={this.handleDetailSelection.bind(this)}/>
})}</main>);
}
}
};
module.exports = FlexGrid; |
Add MIT LICENSE. Fix test dir removing issue - re-raise exception after delete this dir. | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 'test'])
subprocess.call(['touch', 'test/rvv', 'test/max',
'test/bdv' ,'test/mail'])
#TODO create passwd test file
#TODO create shadow test file
#TODO create keys.txt file
def tearDown(self):
try:
if os.path.exists('test/rvv'):
raise Exception('test/rvv must not exist')
if not (os.path.exists('test/max') and
os.path.exists('test/bdv') and
os.path.exists('test/mail')):
raise Exception('File max, bdv or mail must exist!')
except:
subprocess.call(['rm', '-r', 'test/'])
raise
def test_passwd_change(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test')
def test_passwd_change_2(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test/')
suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test)
TextTestRunner(verbosity=2).run(suite)
| #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 'test'])
subprocess.call(['touch', 'test/rvv', 'test/max',
'test/mail'])
#TODO create passwd test file
#TODO create shadow test file
#TODO create keys.txt file
def tearDown(self):
if os.path.exists('test/rvv'):
raise Exception('test/rvv must not exist')
if not (os.path.exists('test/max') and
os.path.exists('test/bdv') and
os.path.exists('test/mail')):
raise Exception('File max, bdv or mail must exist!')
subprocess.call(['rm', '-r', 'test/'])
def test_passwd_change(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test')
def test_passwd_change_2(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test/')
suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test)
TextTestRunner(verbosity=2).run(suite)
|
Change the way gradle detects if task is needed to run | package org.graphwalker.gradle.plugin.task;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* @author Nils Olsson
*/
public class Clean extends TaskBase {
private final File outputDirectory = new File(getProject().getProjectDir(), "graphwalker");
@Override
public Task configure() {
getOutputs().upToDateWhen(new Spec<Task>() {
@Override
public boolean isSatisfiedBy(Task element) {
return !outputDirectory.exists();
}
});
return this;
}
@TaskAction
public void clean() {
Path directory = outputDirectory.toPath();
if (Files.exists(directory)) {
try {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| package org.graphwalker.gradle.plugin.task;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* @author Nils Olsson
*/
public class Clean extends TaskBase {
private final File outputDirectory = new File(getProject().getProjectDir(), "graphwalker");
@Override
public Task configure() {
onlyIf(new Spec<Task>() {
@Override
public boolean isSatisfiedBy(Task task) {
return outputDirectory.exists();
}
});
return this;
}
@TaskAction
public void clean() {
Path directory = outputDirectory.toPath();
if (Files.exists(directory)) {
try {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable | # -*- coding:utf-8 -*-
import numpy as np
class MaxHeap(object):
def __init__(self, sz, data):
self.sz = sz
self.heap = [0] * (sz + 1)
self.cnt = len(data)
self.heap[1: self.cnt + 1] = data
self.build_heap()
def build_heap(self):
last_non_leaf = self.cnt // 2
for x in range(last_non_leaf, 0, -1):
max_pos = x
i = x
while True:
if i <= self.cnt and self.heap[i] < self.heap[2 *i ]:
max_pos = 2 * i
if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]:
max_pos = 2 * i + 1
if max_pos == i:
break
self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i]
i = max_pos
if __name__ == '__main__':
data = np.random.randint(0, 100, 10)
print(data)
heap = MaxHeap(100, data)
print(heap.heap)
| # -*- coding:utf-8 -*-
import numpy as np
class ArrayHeap(object):
def __init__(self, sz, data = None):
self.sz = sz
self.cnt = 0
self.heap = [0 for i in range(sz + 1)]
if data is not None:
for i, val in enumerate(data):
self.heap[i + 1] = val
self.cnt = len(data)
self._build_heap()
def _build_heap(self):
last_non_leaf = self.cnt // 2
for x in range(last_non_leaf, 0, -1):
max_pos = x
i = x
while True:
if i <= self.cnt and self.heap[i] < self.heap[2 *i ]:
max_pos = 2 * i
if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]:
max_pos = 2 * i + 1
if max_pos == i:
break
self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i]
i = max_pos
if __name__ == '__main__':
data = np.random.randint(0, 100, 10)
print(data)
heap = ArrayHeap(100, data)
print(heap.heap)
|
Fix sorting of rooms in schedule | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
|
Add a default template attribute | 'use strict';
/*!
* angular-bootstrap-grid-list-toggle
* https://github.com/seblucas/angular-bootstrap-grid-list-toggle
* Copyright (c) 2015 ; Licensed MIT
*/
angular.module('seblucas.slGridListToggle', [])
.directive('slGridListToggle', function() {
return {
restrict: 'E',
require: '^ngModel',
scope: {
templatePrefix: '=',
defaultTemplate: '='
},
template:
'<div class="btn-group btn-group-lg pull-right"> \
<button ng-repeat="item in toggles" type="button" class="btn btn-default" ng-class="{active: isTemplateActive(item)}" ng-click="toggleTemplate(item)"> \
<span class="glyphicon glyphicon-{{item}}"></span> \
</button> \
</div>',
link: function(scope, element, attrs, ngModel) {
scope.toggles = ['th', 'list'];
ngModel.$render = function() {
scope.currentTemplate = ngModel.$modelValue;
};
scope.toggleTemplate = function(value) {
scope.currentTemplate = scope.templatePrefix + value +'.html';
ngModel.$setViewValue(scope.currentTemplate);
};
scope.isTemplateActive = function(value) {
return scope.currentTemplate.indexOf ('.' + value + '.html') > 0;
};
if (attrs.defaultTemplate) {
scope.toggleTemplate(scope.defaultTemplate);
}
}
};
}); | 'use strict';
/*!
* angular-bootstrap-grid-list-toggle
* https://github.com/seblucas/angular-bootstrap-grid-list-toggle
* Copyright (c) 2015 ; Licensed MIT
*/
angular.module('seblucas.slGridListToggle', [])
.directive('slGridListToggle', function() {
return {
restrict: 'E',
require: '^ngModel',
scope: {
templatePrefix: '='
},
template:
'<div class="btn-group btn-group-lg pull-right"> \
<button ng-repeat="item in toggles" type="button" class="btn btn-default" ng-class="{active: isTemplateActive(item)}" ng-click="toggleTemplate(item)"> \
<span class="glyphicon glyphicon-{{item}}"></span> \
</button> \
</div>',
link: function(scope, element, attrs, ngModel) {
scope.toggles = ['th', 'list'];
ngModel.$render = function() {
scope.currentTemplate = ngModel.$modelValue;
};
scope.toggleTemplate = function(value) {
scope.currentTemplate = scope.templatePrefix + value +'.html';
ngModel.$setViewValue(scope.currentTemplate);
};
scope.isTemplateActive = function(value) {
return scope.currentTemplate.indexOf ('.' + value + '.html') > 0;
};
}
};
}); |
Use instanceof instead of class_basename | <?php
declare(strict_types=1);
namespace Arcanedev\Localization\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Class LocaleCookieRedirect
*
* @package Arcanedev\Localization\Middleware
* @author ARCANEDEV <[email protected]>
*/
class LocaleCookieRedirect extends Middleware
{
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// If the request URL is ignored from localization.
if ($this->shouldIgnore($request) || $next($request) instanceof StreamedResponse) return $next($request);
$segment = $request->segment(1, null);
if ($this->localization->isLocaleSupported($segment))
return $next($request)->withCookie(cookie()->forever('locale', $segment));
$locale = $request->cookie('locale', null);
if ($locale !== null && ! $this->isDefaultLocaleHidden($locale)) {
if ( ! is_null($redirect = $this->getLocalizedRedirect($locale)))
return $redirect->withCookie(cookie()->forever('locale', $segment));
}
return $next($request);
}
}
| <?php
declare(strict_types=1);
namespace Arcanedev\Localization\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Class LocaleCookieRedirect
*
* @package Arcanedev\Localization\Middleware
* @author ARCANEDEV <[email protected]>
*/
class LocaleCookieRedirect extends Middleware
{
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// If the request URL is ignored from localization.
if ($this->shouldIgnore($request) || class_basename($next($request)) === 'StreamedResponse') return $next($request);
$segment = $request->segment(1, null);
if ($this->localization->isLocaleSupported($segment))
return $next($request)->withCookie(cookie()->forever('locale', $segment));
$locale = $request->cookie('locale', null);
if ($locale !== null && ! $this->isDefaultLocaleHidden($locale)) {
if ( ! is_null($redirect = $this->getLocalizedRedirect($locale)))
return $redirect->withCookie(cookie()->forever('locale', $segment));
}
return $next($request);
}
}
|
Use itertools.cycle for repeating digits | import itertools
from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
total = 0
for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)):
total += int(char) * digit
return total % 11 % 10 == int(check_digit)
class FedExGround96(FedEx):
barcode_pattern = r'^96\d{20}$'
@property
def tracking_number(self):
return self.barcode[7:]
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
odd = even = 0
for i, char in enumerate(reversed(chars)):
if i & 0x1:
odd += int(char)
else:
even += int(char)
check = ((even * 3) + odd) % 10
if check != 0:
check = 10 - check
return check == int(check_digit)
| from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
total = 0
for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)):
total += int(char) * digit
return total % 11 % 10 == int(check_digit)
class FedExGround96(FedEx):
barcode_pattern = r'^96\d{20}$'
@property
def tracking_number(self):
return self.barcode[7:]
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
odd = even = 0
for i, char in enumerate(reversed(chars)):
if i & 0x1:
odd += int(char)
else:
even += int(char)
check = ((even * 3) + odd) % 10
if check != 0:
check = 10 - check
return check == int(check_digit)
|
Raise exception on incorrect argument type | from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a callable function for the bandpass filter or decomposition method
corresponding to the given name.\n
Filter methods:
+-------------------+------------------------------------------------------+
| Name | Description |
+===================+======================================================+
| gaussian | implementation of a bandpass filter using Gaussian |
| | weights |
+-------------------+------------------------------------------------------+
| uniform | implementation of a filter where all weights are set |
| | to one |
+-------------------+------------------------------------------------------+
Decomposition methods:
+-------------------+------------------------------------------------------+
| Name | Description |
+===================+======================================================+
| fft | decomposition based on Fast Fourier Transform (FFT) |
| | and a bandpass filter |
+-------------------+------------------------------------------------------+
"""
if isinstance(name, str):
name = name.lower()
else:
raise TypeError("Only strings supported for the method's names.\n"
+ "Available names:"
+ str(list(_cascade_methods.keys()))) from None
try:
return _cascade_methods[name]
except KeyError:
raise ValueError("Unknown method {}\n".format(name)
+ "The available methods are:"
+ str(list(_cascade_methods.keys()))) from None
|
from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a callable function for the bandpass filter or decomposition method
corresponding to the given name.\n
Filter methods:
+-------------------+------------------------------------------------------+
| Name | Description |
+===================+======================================================+
| gaussian | implementation of a bandpass filter using Gaussian |
| | weights |
+-------------------+------------------------------------------------------+
| uniform | implementation of a filter where all weights are set |
| | to one |
+-------------------+------------------------------------------------------+
Decomposition methods:
+-------------------+------------------------------------------------------+
| Name | Description |
+===================+======================================================+
| fft | decomposition based on Fast Fourier Transform (FFT) |
| | and a bandpass filter |
+-------------------+------------------------------------------------------+
"""
if isinstance(name, str):
name = name.lower()
try:
return _cascade_methods[name]
except KeyError:
raise ValueError("Unknown method {}\n".format(name)
+ "The available methods are:"
+ str(list(_cascade_methods.keys()))) from None
|
Update links when it starts getting redirected | import os
import time
from constants import *
from dbhelper import *
from dbItemManagerV2 import DbItemManagerV2
from link import Link
LINK_EXPIRY_TIME_IN_DAYS = 80
class LinkManager(DbItemManagerV2):
"""
Manage links stored on AWS dynamo db database.
Contains functions for CRUD operations on the links stored
Following environment variables need to be set -
'LINKTAGSTABLE_CONNECTIONSTRING' : connection string of link tags table.
"""
def __init__(self):
"""
Instantiates the linkManager.
"""
DbItemManagerV2.__init__(self,
os.environ['LINKTAGSTABLE_CONNECTIONSTRING'])
def get(self, linkId):
"""
Put a new link.
"""
dbItem = DbItemManagerV2.get(self, linkId);
link = Link(linkId, dbItem.tags)
#handle the case when link starts gettting redirected to new url
if link.id != linkId:
self.delete(linkId)
self.put(link)
return link
def getStaleLinks(self):
"""
Returns a list of linkIds of stale links.
"""
linkExpiryCutoff = int(time.time()) - LINK_EXPIRY_TIME_IN_DAYS*24*60*60;
scanResults = DbItemManagerV2.scan(self, pubtime__lte = linkExpiryCutoff)
return (result.id for result in scanResults)
def getUnprocessedLinks(self):
return DbItemManagerV2.query_2(
self,
isProcessed__eq = 'false',
index = 'isProcessed-itemId-index')
| import os
import time
from constants import *
from dbhelper import *
from dbItemManagerV2 import DbItemManagerV2
from link import Link
LINK_EXPIRY_TIME_IN_DAYS = 80
class LinkManager(DbItemManagerV2):
"""
Manage links stored on AWS dynamo db database.
Contains functions for CRUD operations on the links stored
Following environment variables need to be set -
'LINKTAGSTABLE_CONNECTIONSTRING' : connection string of link tags table.
"""
def __init__(self):
"""
Instantiates the linkManager.
"""
DbItemManagerV2.__init__(self,
os.environ['LINKTAGSTABLE_CONNECTIONSTRING'])
def get(self, linkId):
"""
Put a new link.
"""
dbItem = DbItemManagerV2.get(self, linkId);
return Link(linkId, dbItem.tags)
def getStaleLinks(self):
"""
Returns a list of linkIds of stale links.
"""
linkExpiryCutoff = int(time.time()) - LINK_EXPIRY_TIME_IN_DAYS*24*60*60;
scanResults = DbItemManagerV2.scan(self, pubtime__lte = linkExpiryCutoff)
return (result.id for result in scanResults)
def getUnprocessedLinks(self):
return DbItemManagerV2.query_2(
self,
isProcessed__eq = 'false',
index = 'isProcessed-itemId-index')
|
Allow for modules without exports
They are undefined, so the seen[name] test would previously fail. | var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen.hasOwnProperty(name)) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
| var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
|
Drop requirement for urllib3 - it is part of requests. | from setuptools import setup, find_packages
setup(
name='ckanext-archiver',
version='0.1',
packages=find_packages(),
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==1.1.0',
'messytables>=0.1.4',
'flask==0.8' # flask needed for tests
],
author='Open Knowledge Foundation',
author_email='[email protected]',
description='Archive ckan resources',
long_description='Archive ckan resources',
license='MIT',
url='http://ckan.org/wiki/Extensions',
download_url='',
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points='''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
[ckan.plugins]
archiver = ckanext.archiver.plugin:ArchiverPlugin
[ckan.celery_task]
tasks = ckanext.archiver.celery_import:task_imports
'''
)
| from setuptools import setup, find_packages
setup(
name='ckanext-archiver',
version='0.1',
packages=find_packages(),
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==1.1.0',
'messytables>=0.1.4',
'urllib3==1.7',
'flask==0.8' # flask needed for tests
],
author='Open Knowledge Foundation',
author_email='[email protected]',
description='Archive ckan resources',
long_description='Archive ckan resources',
license='MIT',
url='http://ckan.org/wiki/Extensions',
download_url='',
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points='''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
[ckan.plugins]
archiver = ckanext.archiver.plugin:ArchiverPlugin
[ckan.celery_task]
tasks = ckanext.archiver.celery_import:task_imports
'''
)
|
Add pylint to installation requirements | """
Created on 21/03/2012
@author: losa, sortega
"""
import os
from setuptools import setup, find_packages
def find_files(path):
files = []
for dirname, subdirnames, filenames in os.walk(path):
for subdirname in subdirnames:
files.extend(find_files(os.path.join(dirname, subdirname)))
for filename in filenames:
files.append(os.path.join(dirname, filename))
return files
setup(
name = "bdp_fe",
version = "0.1.0",
description = "Big Data Platform Frontend",
long_description = ("This package is a web interface for the Big Data "
"Platform. Through this frontend, a user can lauch "
"Haddop jobs, read and interpret its results."),
author = "Telefonica Digital",
author_email = "[email protected]",
package_dir = {'': 'src'},
packages = find_packages('src'),
package_data = {'': ['templates/*']},
data_files = [('share/bdp_fe/static',
find_files('src/bdp_fe/jobconf/static/'))],
install_requires = [
'setuptools',
'pymongo',
'django',
'coverage',
'pylint',
'django-jenkins',
'thrift',
'flup',
'MySQL-python',
],
classifiers = [
"Development Status :: 3 - Alpha",
],
)
| """
Created on 21/03/2012
@author: losa, sortega
"""
import os
from setuptools import setup, find_packages
def find_files(path):
files = []
for dirname, subdirnames, filenames in os.walk(path):
for subdirname in subdirnames:
files.extend(find_files(os.path.join(dirname, subdirname)))
for filename in filenames:
files.append(os.path.join(dirname, filename))
return files
setup(
name = "bdp_fe",
version = "0.1.0",
description = "Big Data Platform Frontend",
long_description = ("This package is a web interface for the Big Data "
"Platform. Through this frontend, a user can lauch "
"Haddop jobs, read and interpret its results."),
author = "Telefonica Digital",
author_email = "[email protected]",
package_dir = {'': 'src'},
packages = find_packages('src'),
package_data = {'': ['templates/*']},
data_files = [('share/bdp_fe/static',
find_files('src/bdp_fe/jobconf/static/'))],
install_requires = [
'setuptools',
'pymongo',
'django',
'coverage',
'django-jenkins',
'thrift',
'flup',
'MySQL-python',
],
classifiers = [
"Development Status :: 3 - Alpha",
],
)
|
Rename visualize to viz in CDF | from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
super(CartoDataFrame, self).__init__(*args, **kwargs)
@staticmethod
def from_carto(*args, **kwargs):
from ..io.carto import read_carto
return read_carto(*args, **kwargs)
@classmethod
def from_file(cls, filename, **kwargs):
gdf = GeoDataFrame.from_file(filename, **kwargs)
return cls(gdf)
@classmethod
def from_features(cls, features, **kwargs):
gdf = GeoDataFrame.from_features(features, **kwargs)
return cls(gdf)
def to_carto(self, *args, **kwargs):
from ..io.carto import to_carto
return to_carto(self, *args, **kwargs)
def convert(self, index_column=None, geom_column=None, lnglat_columns=None,
drop_index=True, drop_geom=True, drop_lnglat=True):
# Magic function
generate_index(self, index_column, drop_index)
generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat)
return self
def viz(self, *args, **kwargs):
from ..viz import Map, Layer
return Map(Layer(self, *args, **kwargs))
| from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
super(CartoDataFrame, self).__init__(*args, **kwargs)
@staticmethod
def from_carto(*args, **kwargs):
from ..io.carto import read_carto
return read_carto(*args, **kwargs)
@classmethod
def from_file(cls, filename, **kwargs):
gdf = GeoDataFrame.from_file(filename, **kwargs)
return cls(gdf)
@classmethod
def from_features(cls, features, **kwargs):
gdf = GeoDataFrame.from_features(features, **kwargs)
return cls(gdf)
def to_carto(self, *args, **kwargs):
from ..io.carto import to_carto
return to_carto(self, *args, **kwargs)
def convert(self, index_column=None, geom_column=None, lnglat_columns=None,
drop_index=True, drop_geom=True, drop_lnglat=True):
# Magic function
generate_index(self, index_column, drop_index)
generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat)
return self
def visualize(self, *args, **kwargs):
from ..viz import Map, Layer
return Map(Layer(self, *args, **kwargs))
viz = visualize
|
Use base_url to form metrics url
Otherwise this ends up not working in cases where
the notebook is hosted (like JupyterHub) with a
different base_url | define(['jquery', 'base/js/utils'], function ($, utils) {
function createDisplayDiv() {
$('#maintoolbar-container').append(
$('<div>').attr('id', 'nbresuse-display')
.addClass('btn-group')
.addClass('pull-right')
.append(
$('<strong>').text('Mem: ')
).append(
$('<span>').attr('id', 'nbresuse-mem')
.attr('title', 'Actively used Memory (updates every 5s)')
)
);
}
var displayMetrics = function() {
$.getJSON(utils.get_body_data('baseUrl') + 'metrics', function(data) {
// FIXME: Proper setups for MB and GB. MB should have 0 things
// after the ., but GB should have 2.
var displayRSS = (data['rss'] / (1024 * 1024)).toFixed(0);
$('#nbresuse-mem').text(displayRSS + " MB");
});
}
var load_ipython_extension = function () {
createDisplayDiv();
displayMetrics();
// Update every five seconds, eh?
setInterval(displayMetrics, 1000 * 5);
};
return {
load_ipython_extension: load_ipython_extension,
};
});
| define(['jquery'], function ($) {
var displayDiv = null;
function createDisplayDiv() {
$('#maintoolbar-container').append(
$('<div>').attr('id', 'nbresuse-display')
.addClass('btn-group')
.addClass('pull-right')
.append(
$('<strong>').text('Mem: ')
).append(
$('<span>').attr('id', 'nbresuse-mem')
.attr('title', 'Actively used Memory (updates every 5s)')
)
);
}
var displayMetrics = function() {
$.getJSON('/metrics', function(data) {
// FIXME: Proper setups for MB and GB. MB should have 0 things
// after the ., but GB should have 2.
var displayRSS = (data['rss'] / (1024 * 1024)).toFixed(0);
$('#nbresuse-mem').text(displayRSS + " MB");
});
}
var load_ipython_extension = function () {
createDisplayDiv();
displayMetrics();
// Update every five seconds, eh?
setInterval(displayMetrics, 1000 * 5);
};
return {
load_ipython_extension: load_ipython_extension,
};
});
|
Return the module setup/teardown promises. | import { module as qunitModule } from 'qunit';
function beforeEachCallback(callbacks) {
if (typeof callbacks !== 'object') { return; }
if (!callbacks) { return; }
var beforeEach;
if (callbacks.setup) {
beforeEach = callbacks.setup;
delete callbacks.setup;
}
if (callbacks.beforeEach) {
beforeEach = callbacks.beforeEach;
delete callbacks.beforeEach;
}
return beforeEach;
}
function afterEachCallback(callbacks) {
if (typeof callbacks !== 'object') { return; }
if (!callbacks) { return; }
var afterEach;
if (callbacks.teardown) {
afterEach = callbacks.teardown;
delete callbacks.teardown;
}
if (callbacks.afterEach) {
afterEach = callbacks.afterEach;
delete callbacks.afterEach;
}
return afterEach;
}
export function createModule(Constructor, name, description, callbacks) {
var beforeEach = beforeEachCallback(callbacks || description);
var afterEach = afterEachCallback(callbacks || description);
var module = new Constructor(name, description, callbacks);
qunitModule(module.name, {
setup: function(assert) {
var done = assert.async();
return module.setup().then(function() {
if (beforeEach) {
beforeEach.call(module.context, assert);
}
})['finally'](done);
},
teardown: function(assert) {
if (afterEach) {
afterEach.call(module.context, assert);
}
var done = assert.async();
return module.teardown()['finally'](done);
}
});
}
| import { module as qunitModule } from 'qunit';
function beforeEachCallback(callbacks) {
if (typeof callbacks !== 'object') { return; }
if (!callbacks) { return; }
var beforeEach;
if (callbacks.setup) {
beforeEach = callbacks.setup;
delete callbacks.setup;
}
if (callbacks.beforeEach) {
beforeEach = callbacks.beforeEach;
delete callbacks.beforeEach;
}
return beforeEach;
}
function afterEachCallback(callbacks) {
if (typeof callbacks !== 'object') { return; }
if (!callbacks) { return; }
var afterEach;
if (callbacks.teardown) {
afterEach = callbacks.teardown;
delete callbacks.teardown;
}
if (callbacks.afterEach) {
afterEach = callbacks.afterEach;
delete callbacks.afterEach;
}
return afterEach;
}
export function createModule(Constructor, name, description, callbacks) {
var beforeEach = beforeEachCallback(callbacks || description);
var afterEach = afterEachCallback(callbacks || description);
var module = new Constructor(name, description, callbacks);
qunitModule(module.name, {
setup: function(assert) {
var done = assert.async();
module.setup().then(function() {
if (beforeEach) {
beforeEach.call(module.context, assert);
}
})['finally'](done);
},
teardown: function(assert) {
if (afterEach) {
afterEach.call(module.context, assert);
}
var done = assert.async();
module.teardown()['finally'](done);
}
});
}
|
Support for error and end events | const iterateObject = require("iterate-object")
, typpy = require("typpy")
, mapObject = require("map-o")
;
function prepareData(input) {
iterateObject(input, value => {
if (typpy(value.types, String)) {
value.types = { normal: [value.types] };
} else if (typpy(value.types, Array)) {
value.types = { normal: value.types };
}
value.types = Object(value.types);
mapObject(value.types, (value, name) => {
return {
char: value[0]
, icon: value[1] && ("&#x" + value[1])
};
});
});
return input;
}
var Coreconstructor_names = module.exports = prepareData({
listener: {
constructor_name: "Listener"
}
, data_handler: {
constructor_name: "DataHandler"
, types: {
normal: [":", "f087"]
, once: [".", "f087"]
}
}
, emit: {
constructor_name: "Emit"
, types: {
normal: [">>", "f087"]
, error: [undefined, "f02d"]
, end: [undefined, "f02d"]
}
}
, stream_data: {
constructor_name: "StreamHandler"
, types: {
normal: [">*", "f0c4"]
}
}
});
| const iterateObject = require("iterate-object")
, typpy = require("typpy")
, mapObject = require("map-o")
;
function prepareData(input) {
iterateObject(input, value => {
if (typpy(value.types, String)) {
value.types = { normal: [value.types] };
} else if (typpy(value.types, Array)) {
value.types = { normal: value.types };
}
value.types = Object(value.types);
mapObject(value.types, (value, name) => {
return {
char: value[0]
, icon: value[1]
};
});
});
return input;
}
var Coreconstructor_names = module.exports = prepareData({
listener: {
constructor_name: "Listener"
}
, data_handler: {
constructor_name: "DataHandler"
, types: {
normal: [":", "f087"]
, once: [".", "f087"]
}
}
, emit: {
constructor_name: "Emit"
, types: ">>"
, types: {
normal: [":", "f087"]
, once: [".", "f087"]
}
}
, stream: {
constructor_name: "StreamHandler"
, types: {
normal: ">*"
}
}
});
|
Revert "it's work!!! for tegEnity"
This reverts commit b66c557ffab584ed1f8083857fd67732fce21bc1. | package com.netcracker.students_project.entity;
import javax.persistence.*;
@Entity
@Table(name = "teg", schema = "netcracker", catalog = "nc_student_project")
public class TegEntity {
private int id;
private String text;
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TegEntity tegEntity = (TegEntity) o;
if (id != tegEntity.id) return false;
if (text != null ? !text.equals(tegEntity.text) : tegEntity.text != null) return false;
return true;
}
@Override
public String toString() {
return "TegEntity{" +
"id=" + id +
", text='" + text + '\'' +
'}';
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
}
| package com.netcracker.students_project.entity;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import javax.persistence.*;
@Entity
@Table(name = "teg", schema = "netcracker", catalog = "nc_student_project")
public class TegEntity {
private int id;
private String text;
@Id
@Column(name = "id", columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TegEntity tegEntity = (TegEntity) o;
if (id != tegEntity.id) return false;
if (text != null ? !text.equals(tegEntity.text) : tegEntity.text != null) return false;
return true;
}
@Override
public String toString() {
return "TegEntity{" +
"id=" + id +
", text='" + text + '\'' +
'}';
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
}
|
Use list comprehensions and consolidate error formatting where error details are either a list or a string. |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, str):
value = [value]
errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value])
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
|
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
|
Use same data processing for main and summary charts. | function example () {
var
container = document.getElementById('demo'),
H = Humble.Vis,
E = Flotr.EventAdapter,
data = [],
hash = window.location.hash,
amplitude = (hash ? .05 : .001),
mainOptions = {
height : 200,
width : 600,
data : data,
flotr : {}
},
summaryOptions = {
height : 200,
width : 600,
data : data,
flotr : {
handles : { show : true },
selection : { mode : 'x'}
}
},
vis, main, summary, interaction, i;
for (i = 0; i < 1e6; i++) {
data.push([i/10000, .2*Math.sin(i/10000) + i/100000 + amplitude * Math.sin(i/50)]);
}
if (hash !== '#minmax') {
mainOptions.processData = summaryOptions.processData = function (o) {
var
datum = o.datum;
datum
.bound(o.min, o.max)
.subsample(o.resolution);
}
}
vis = new H.Visualization();
main = new H.Child(mainOptions);
summary = new H.Child(summaryOptions);
interaction = new H.Interaction({leader : summary});
vis.add(main);
vis.add(summary);
vis.render(container);
interaction.add(H.Action.Selection);
interaction.follow(main);
}
| function example () {
var
container = document.getElementById('demo'),
H = Humble.Vis,
E = Flotr.EventAdapter,
data = [],
hash = window.location.hash,
amplitude = (hash ? .05 : .001),
mainOptions = {
height : 200,
width : 600,
data : data,
flotr : {}
},
summaryOptions = {
height : 200,
width : 600,
data : data,
flotr : {
handles : { show : true },
selection : { mode : 'x'}
}
},
vis, main, summary, interaction, i;
for (i = 0; i < 1e6; i++) {
data.push([i/10000, .2*Math.sin(i/10000) + i/100000 + amplitude * Math.sin(i/50)]);
}
if (hash !== '#minmax') {
mainOptions.processData = function (o) {
var
datum = o.datum;
datum
.bound(o.min, o.max)
.subsample(o.resolution);
}
}
vis = new H.Visualization();
main = new H.Child(mainOptions);
summary = new H.Child(summaryOptions);
interaction = new H.Interaction({leader : summary});
vis.add(main);
vis.add(summary);
vis.render(container);
interaction.add(H.Action.Selection);
interaction.follow(main);
}
|
Add an exception if ssh not configured | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
sshconfig = SSHConfig()
try:
sshconfig.parse(open(SSH_CONFIG))
except IOError:
print "your app needs to have a valid " \
"ssh config file location in settings.py"
sys.exit(1)
return sshconfig.lookup(self.server)
def runcmd(self, cmd):
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(self.conf['hostname'],
port = int(self.conf['port']),
username = self.conf['user'],
key_filename = self.conf['identityfile'],
password = None,)
stdin, stdout, stderr = client.exec_command(cmd)
return ''.join([i.rstrip('\r\n ').lstrip() for i in stdout.readlines()])
finally:
client.close() | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
sshconfig = SSHConfig()
sshconfig.parse(open(SSH_CONFIG))
return sshconfig.lookup(self.server)
def runcmd(self, cmd):
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(self.conf['hostname'],
port = int(self.conf['port']),
username = self.conf['user'],
key_filename = self.conf['identityfile'],
password = None,)
stdin, stdout, stderr = client.exec_command(cmd)
return ''.join([i.rstrip('\r\n ').lstrip() for i in stdout.readlines()])
finally:
client.close() |
Fix tab/space issues and use automatic name wildcard
- Using a regular query search allows ADS to automatically adjust author
name to hit multiple abstracts | #!/usr/bin/python
import sys, os
import ads
from nameparser import HumanName
reload(sys)
sys.setdefaultencoding('utf8')
names_file = open(sys.argv[1])
#Default abstract storage
abstract_directory = "abstracts"
if len(sys.argv) > 2:
abstract_directory = sys.argv[2]
if not os.path.exists(abstract_directory):
os.makedirs(abstract_directory)
number_abstracts = 4
if len(sys.argv) > 3:
number_abstracts = int(sys.argv[3])
author_num = 0
for line in names_file:
#Only names
if line[0]==',': continue
if len(line) < 4: continue
parsed_name = HumanName(line)
print "Author:", str(parsed_name)
papers = ads.SearchQuery(
q='author:"'+str(parsed_name)+'"',
sort='date',
fl=['abstract'])
abstract_file = open(abstract_directory+"/"+\
parsed_name.first+" "+parsed_name.last+".txt",'w')
j = 0
while True:
try:
for paper in papers:
abstract_file.write("Abstract "+str(j)+"\n")
try:
abstract_file.write(paper.abstract.encode('utf-8'))
except AttributeError:
pass
abstract_file.write("\n")
j += 1
if j > number_abstracts:
break
except ads.base.APIResponseError:
pass
else:
break
author_num+=1
| #!/usr/bin/python
import sys, os
import ads
from nameparser import HumanName
reload(sys)
sys.setdefaultencoding('utf8')
names_file = open(sys.argv[1])
#Default abstract storage
abstract_directory = "abstracts"
if len(sys.argv) > 2:
abstract_directory = sys.argv[2]
if not os.path.exists(abstract_directory):
os.makedirs(abstract_directory)
number_abstracts = 4
if len(sys.argv) > 3:
number_abstracts = int(sys.argv[3])
author_num = 0
for line in names_file:
#Only names
if line[0]==',': continue
if len(line) < 4: continue
print "Author", author_num
parsed_name = HumanName(line)
papers = ads.SearchQuery(
author=parsed_name.first+", "+parsed_name.last,
sort='date',
fl=['abstract'])
abstract_file = open(abstract_directory+"/"+\
parsed_name.first+" "+parsed_name.last+".txt",'w')
j = 0
try:
for paper in papers:
abstract_file.write("Abstract "+str(j)+"\n")
try:
abstract_file.write(paper.abstract.encode('utf-8'))
except AttributeError:
pass
abstract_file.write("\n")
j += 1
if j > number_abstracts: break
except ads.base.APIResponseError:
continue
author_num+=1
|
Fix mochaRunner:custom task's script and style paths | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Load the plugin's tasks
grunt.loadTasks('tasks');
grunt.initConfig({
jshint: {
options: {jshintrc: '.jshintrc'},
all: ['Gruntfile.js', 'tasks/*.js', 'test/tasks/*.test.js']
},
// the plugin's task to be run, then tested
mochaRunner: {
defaults: {
scripts: [
'test/fixtures/src/*.js',
'test/fixtures/spec/*.js'],
styles: ['test/fixtures/styles/*.css']
},
custom: {
options: {
port: 8001,
title: "Foo Bar",
ui: "tdd"
},
scripts: [
'test/fixtures/src/*.js',
'test/fixtures/spec/*.js'],
styles: ['test/fixtures/styles/*.css']
}
},
// an external plugin we use to run our tests
mochaTest: {
test: {src: ['test/tasks/mochaRunner.test.js']}
}
});
// Run the plugin's tasks, then test the result
grunt.registerTask('test', [
'mochaRunner',
'mochaTest'
]);
grunt.registerTask('default', [
'jshint',
'test'
]);
};
| module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Load the plugin's tasks
grunt.loadTasks('tasks');
grunt.initConfig({
jshint: {
options: {jshintrc: '.jshintrc'},
all: ['Gruntfile.js', 'tasks/*.js', 'test/tasks/*.test.js']
},
// the plugin's task to be run, then tested
mochaRunner: {
defaults: {
scripts: ['test/fixtures/src/*.js', 'test/fixtures/spec/*.js'],
styles: ['test/fixtures/styles/*.css']
},
custom: {
options: {
port: 8001,
title: "Foo Bar",
ui: "tdd"
},
src: ['<%= mochaRunner.defaults.src =>'],
spec: ['<%= mochaRunner.defaults.spec =>'],
styles: ['<%= mochaRunner.defaults.styles =>'],
}
},
// an external plugin we use to run our tests
mochaTest: {
test: {src: ['test/tasks/mochaRunner.test.js']}
}
});
// Run the plugin's tasks, then test the result
grunt.registerTask('test', [
'mochaRunner',
'mochaTest'
]);
grunt.registerTask('default', [
'jshint',
'test'
]);
};
|
Add a little function to make it easier to create users on-the-fly via NIS | from django.conf import settings
from django.contrib.auth.models import User, check_password
import crypt
import nis
class NISBackend:
"""
Authenticate against a user on an NIS server.
"""
def authenticate(self, username, password):
user = None
try:
passwd = nis.match(username, 'passwd').split(':')
original_crypted = passwd[1]
new_crypted = crypt.crypt(password, original_crypted[:2])
if original_crypted == new_crypted:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user.
first_name, last_name = passwd[4].split(' ', 2)
email = '%s@%s' % (username, settings.NIS_EMAIL_DOMAIN)
user = User(username=username,
password='',
first_name=first_name,
last_name=last_name,
email=email)
user.is_staff = False
user.is_superuser = False
user.save()
except nis.error:
pass
return user
def get_or_create_user(self, user_id):
# FIXME: remove duplication with authenticate()
user = self.get_user(user_id)
if not user:
try:
passwd = nis.match(username, 'passwd').split(':')
first_name, last_name = passwd[4].split(' ', 2)
email = '%s@%s' % (username, settings.NIS_EMAIL_DOMAIN)
user = User(username=username,
password='',
first_name=first_name,
last_name=last_name,
email=email)
user.is_staff = False
user.is_superuser = False
user.save()
except nis.error:
pass
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
| from django.conf import settings
from django.contrib.auth.models import User, check_password
import crypt
import nis
class NISBackend:
"""
Authenticate against a user on an NIS server.
"""
def authenticate(self, username, password):
user = None
try:
passwd = nis.match(username, 'passwd').split(':')
original_crypted = passwd[1]
new_crypted = crypt.crypt(password, original_crypted[:2])
if original_crypted == new_crypted:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user.
first_name, last_name = passwd[4].split(' ', 2)
email = '%s@%s' % (username, settings.NIS_EMAIL_DOMAIN)
user = User(username=username,
password='',
first_name=first_name,
last_name=last_name,
email=email)
user.is_staff = False
user.is_superuser = False
user.save()
except nis.error:
pass
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
|
[FIX] Define UTC as tz in get_working_days_of_date method | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_dt=None,
leaves=None, compute_leaves=False,
resource_id=None, default_interval=None,
context=None):
context = context or {}
context['tz'] = 'UTC'
if start_dt is None:
start_dt = datetime.now().replace(hour=0, minute=0, second=0)
if end_dt is None:
end_dt = datetime.now().replace(hour=23, minute=59, second=59)
days = 0
current = start_dt
while current <= end_dt:
if id is None:
days += 1
else:
end_day = current.replace(hour=23, minute=59, second=59)
end = end_dt if end_day > end_dt else end_day
working_intervals = self.get_working_intervals_of_day(
cr, uid, id, start_dt=current, end_dt=end, leaves=leaves,
compute_leaves=compute_leaves, resource_id=resource_id,
default_interval=default_interval, context=context)
if working_intervals:
days += 1
next = current + timedelta(days=1)
current = next
return days
| # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_dt=None,
leaves=None, compute_leaves=False,
resource_id=None, default_interval=None,
context=None):
if start_dt is None:
start_dt = datetime.now().replace(hour=0, minute=0, second=0)
if end_dt is None:
end_dt = datetime.now().replace(hour=23, minute=59, second=59)
days = 0
current = start_dt
while current <= end_dt:
if id is None:
days += 1
else:
end_day = current.replace(hour=23, minute=59, second=59)
end = end_dt if end_day > end_dt else end_day
working_intervals = self.get_working_intervals_of_day(
cr, uid, id, start_dt=current, end_dt=end, leaves=leaves,
compute_leaves=compute_leaves, resource_id=resource_id,
default_interval=default_interval, context=context)
if working_intervals:
days += 1
next = current + timedelta(days=1)
current = next
return days
|
Use clone() method from BaseModel to copy most recent fileversion |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
assert not parent or not parent.is_file, 'Parent must be a folder'
cloned = src.clone()
cloned.parent = parent
cloned.target = target_node
cloned.name = name or cloned.name
cloned.copied_from = src
cloned.save()
if src.is_file and src.versions.exists():
fileversions = src.versions.select_related('region').order_by('-created')
most_recent_fileversion = fileversions.first()
if most_recent_fileversion.region != target_node.osfstorage_region:
# add all original version except the most recent
cloned.versions.add(*fileversions[1:])
# create a new most recent version and update the region before adding
new_fileversion = most_recent_fileversion.clone()
new_fileversion.region = target_node.osfstorage_region
new_fileversion.save()
cloned.versions.add(new_fileversion)
else:
cloned.versions.add(*src.versions.all())
if not src.is_file:
for child in src.children:
copy_files(child, target_node, parent=cloned)
return cloned
| from osf.models.base import generate_object_id
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
assert not parent or not parent.is_file, 'Parent must be a folder'
cloned = src.clone()
cloned.parent = parent
cloned.target = target_node
cloned.name = name or cloned.name
cloned.copied_from = src
cloned.save()
if src.is_file and src.versions.exists():
fileversions = src.versions.select_related('region').order_by('-created')
most_recent_fileversion = fileversions.first()
if most_recent_fileversion.region != target_node.osfstorage_region:
# add all original version except the most recent
cloned.versions.add(*fileversions[1:])
# setting the id to None and calling save generates a new object
most_recent_fileversion.id = None
most_recent_fileversion._id = generate_object_id()
most_recent_fileversion.region = target_node.osfstorage_region
most_recent_fileversion.save()
cloned.versions.add(most_recent_fileversion)
else:
cloned.versions.add(*src.versions.all())
if not src.is_file:
for child in src.children:
copy_files(child, target_node, parent=cloned)
return cloned
|
Use a data-provider for tests. | <?php
namespace Tests;
use Dyrynda\Database\Support\GeneratesUuid;
use PHPUnit_Framework_TestCase;
class UuidResolversTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Dyrynda\Database\Support\GeneratesUuid
*/
protected $generator;
public function setUp()
{
$this->generator = $this->getMockForTrait(GeneratesUuid::class);
}
/**
* @see \Tests\UuidResolversTest::it_handles_uuid_versions
* @return array
*/
public function provider_for_it_handles_uuid_versions()
{
return [
['uuid1', 'uuid1'],
['uuid3', 'uuid3'],
['uuid4', 'uuid4'],
['uuid5', 'uuid5'],
['uuid999', 'uuid4'],
];
}
/**
* @test
* @param string $version
* @param string $resolved
*
* @dataProvider \Tests\UuidResolversTest::provider_for_it_handles_uuid_versions
*/
public function it_handles_uuid_versions($version, $resolved)
{
$this->generator->uuidVersion = $version;
$this->assertSame($resolved, $this->generator->resolveUuidVersion());
}
}
| <?php
namespace Tests;
use PHPUnit_Framework_TestCase;
use ReflectionClass;
class UuidResolversTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Dyrynda\Database\Support\GeneratesUuid
*/
protected $generator;
public function setUp()
{
$this->generator = $this->getMockForTrait('Dyrynda\Database\Support\GeneratesUuid');
}
/** @test */
public function it_handles_uuid_version_1()
{
$this->generator->uuidVersion = 'uuid1';
$this->assertSame('uuid1', $this->generator->resolveUuidVersion());
}
/** @test */
public function it_handles_uuid_version_3()
{
$this->generator->uuidVersion = 'uuid3';
$this->assertSame('uuid3', $this->generator->resolveUuidVersion());
}
/** @test */
public function it_handles_uuid_version_4()
{
$this->generator->uuidVersion = 'uuid4';
$this->assertSame('uuid4', $this->generator->resolveUuidVersion());
}
/** @test */
public function it_handles_uuid_version_5()
{
$this->generator->uuidVersion = 'uuid5';
$this->assertSame('uuid5', $this->generator->resolveUuidVersion());
}
/** @test */
public function it_defaults_to_uuid_version_4()
{
$this->generator->uuidVersion = 'uuid999';
$this->assertSame('uuid4', $this->generator->resolveUuidVersion());
}
}
|
Fix for randomly failing Welcome page tests
Change-Id: Icfa3aefc8753a3300b6e8e17850685a59bee1c0a | /*
* Copyright 2015 Mirantis, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
define(['../../helpers'], function() {
'use strict';
function WelcomePage(remote) {
this.remote = remote;
}
WelcomePage.prototype = {
constructor: WelcomePage,
skip: function(strictCheck) {
return this.remote
.waitForCssSelector('.welcome-page', 3000)
.then(function() {
return this.parent
.clickByCssSelector('.welcome-button-box button')
.waitForDeletedByCssSelector('.welcome-button-box button', 2000)
.then(
function() {return true},
function() {return !strictCheck}
);
},
function() {return !strictCheck}
);
}
};
return WelcomePage;
});
| /*
* Copyright 2015 Mirantis, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
define(['../../helpers'], function(Helpers) {
'use strict';
function WelcomePage(remote) {
this.remote = remote;
}
WelcomePage.prototype = {
constructor: WelcomePage,
skip: function(strictCheck) {
return this.remote
.getCurrentUrl()
.then(function(url) {
if (url == Helpers.serverUrl + '/#welcome') {
return this.parent
.clickByCssSelector('.welcome-button-box button')
.waitForDeletedByCssSelector('.welcome-button-box button', 2000)
.then(
function() {return true},
function() {return !strictCheck}
);
} else {
return true;
}
});
}
};
return WelcomePage;
});
|
Add cleaner error messages for single-string options | var request = require('request');
var Promise = require('bluebird');
var _ = require('lodash');
var internals = {
convertJSONSafe: function(s){
if(s && (typeof s === 'string')) {
try{
return JSON.parse(s);
} catch(e){
return s;
}
} else {
return s;
}
}
};
module.exports = function(_options, resolveAll) {
return new Promise(function(resolve, reject) {
request(_options, function(err, resp, data) {
if (err) {
if(typeof _options === 'string') {
err.message += ' while attempting ' + _options;
} else {
err.message += ' while attempting ' + JSON.stringify(_.omit(_options, 'auth'));
}
reject(new Error(err));
} else if (resolveAll) {
resolve({
statusCode: resp.statusCode,
data: internals.convertJSONSafe(data),
body: resp.body,
headers: resp.headers
});
} else if (resp.statusCode > 399) {
var msg = null;
data = internals.convertJSONSafe(data);
if (data) {
msg = data.message || data;
}
var rej = new Error('"'+JSON.stringify(msg)+'" while attempting ' + JSON.stringify(_.omit(_options, 'auth')));
rej.statusCode = resp.statusCode;
rej.data = data;
rej.request = _options;
reject(rej);
} else {
resolve(internals.convertJSONSafe(data));
}
});
});
};
| var request = require('request');
var Promise = require('bluebird');
var _ = require('lodash');
var internals = {
convertJSONSafe: function(s){
if(s && (typeof s === 'string')) {
try{
return JSON.parse(s);
} catch(e){
return s;
}
} else {
return s;
}
}
};
module.exports = function(_options, resolveAll) {
return new Promise(function(resolve, reject) {
request(_options, function(err, resp, data) {
if (err) {
err.message += ' while attempting ' + JSON.stringify(_.omit(_options, 'auth'));
reject(new Error(err));
} else if (resolveAll) {
resolve({
statusCode: resp.statusCode,
data: internals.convertJSONSafe(data),
body: resp.body,
headers: resp.headers
});
} else if (resp.statusCode > 399) {
var msg = null;
data = internals.convertJSONSafe(data);
if (data) {
msg = data.message || data;
}
var rej = new Error('"'+JSON.stringify(msg)+'" while attempting ' + JSON.stringify(_.omit(_options, 'auth')));
rej.statusCode = resp.statusCode;
rej.data = data;
rej.request = _options;
reject(rej);
} else {
resolve(internals.convertJSONSafe(data));
}
});
});
};
|
Add simple check to throw error if permissions exists | <?php
/**
* Created by PhpStorm.
* User: sonja
* Date: 1/26/18
* Time: 10:30 AM
*/
namespace AppBundle\API\Sharing;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Permissions;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
class Projects
{
private $manager;
const ERROR_NOT_LOGGED_IN = "Error. You are not logged in.";
const ERROR_PERMISSION_EXISTS = "Error. The permission for the user and the project exists.";
/**
* Projects constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
public function execute($email, $projectId, $action){
$user = $this->manager->getRepository(FennecUser::class)->findOneBy(array(
'email' => $email
));
$project = $this->manager->getRepository(WebuserData::class)->findOneBy(array(
'webuserDataId' => $projectId
));
$permission = $this->manager->getRepository(Permissions::class)->findOneBy(array(
'webuser' => $user->getId(),
'webuserData' => $projectId,
'permission' => $action
));
if($permission !== null){
return Projects::ERROR_PERMISSION_EXISTS;
}
$permission = new Permissions();
$permission->setWebuser($user);
$permission->setWebuserData($project);
$permission->setPermission($action);
$this->manager->persist($permission);
$this->manager->flush();
$message = "The permission '".$action."' of project ".$projectId." was granted to ".$user->getUsername()." successfully.";
return $message;
}
} | <?php
/**
* Created by PhpStorm.
* User: sonja
* Date: 1/26/18
* Time: 10:30 AM
*/
namespace AppBundle\API\Sharing;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Permissions;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
class Projects
{
private $manager;
const ERROR_NOT_LOGGED_IN = "Error. You are not logged in.";
/**
* Projects constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
public function execute($email, $projectId, $action){
$user = $this->manager->getRepository(FennecUser::class)->findOneBy(array(
'email' => $email
));
$project = $this->manager->getRepository(WebuserData::class)->findOneBy(array(
'webuserDataId' => $projectId
));
$permission = new Permissions();
$permission->setWebuser($user);
$permission->setWebuserData($project);
$permission->setPermission($action);
$this->manager->persist($permission);
$this->manager->flush();
$message = "The permission '".$action."' of project ".$projectId." was granted to ".$user->getUsername()." successfully.";
return $message;
}
} |
Fix lexer test error message | <?php
namespace igorw\edn;
class LexerTest extends \PHPUnit_Framework_TestCase {
/**
* @test
* @dataProvider provideInvalidEdn
* @expectedException Phlexy\LexingException
*/
function parseShouldRejectInvalidSyntax($edn) {
$data = tokenize($edn);
$this->fail(sprintf('Expected lexer to fail on %s, but got: %s', json_encode($edn), print_r($data, true)));
}
function provideInvalidEdn() {
return [
['##'],
['#:foo'],
[':#foo'],
[':{'],
[':}'],
[':{}'],
[':^'],
['^'],
['_:^'],
['.9'],
['/foo'],
['foo/'],
[':/foo'],
[':foo/'],
['#/foo'],
['#foo/'],
['foo/bar/baz'],
['foo/bar/baz/qux'],
['foo/bar/baz/qux/'],
['foo/bar/baz/qux/quux'],
['//'],
['///'],
['/foo//'],
['///foo'],
['\newline0.1'],
['\newline.'],
['.\newline'],
];
}
}
| <?php
namespace igorw\edn;
class LexerTest extends \PHPUnit_Framework_TestCase {
/**
* @test
* @dataProvider provideInvalidEdn
* @expectedException Phlexy\LexingException
*/
function parseShouldRejectInvalidSyntax($edn) {
$data = tokenize($edn);
$this->fail(sprintf('Expected parser to fail on %s, but got: %s', json_encode($edn), print_r($data, true)));
}
function provideInvalidEdn() {
return [
['##'],
['#:foo'],
[':#foo'],
[':{'],
[':}'],
[':{}'],
[':^'],
['^'],
['_:^'],
['.9'],
['/foo'],
['foo/'],
[':/foo'],
[':foo/'],
['#/foo'],
['#foo/'],
['foo/bar/baz'],
['foo/bar/baz/qux'],
['foo/bar/baz/qux/'],
['foo/bar/baz/qux/quux'],
['//'],
['///'],
['/foo//'],
['///foo'],
['\newline0.1'],
['\newline.'],
['.\newline'],
];
}
}
|
Clean unused default values for properties | <?php
/*
* Go! AOP framework
*
* @copyright Copyright 2013, Lisachenko Alexander <[email protected]>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Go\Aop\Framework;
use Go\Aop\IntroductionInfo;
/**
* Advice for introduction that holds list of traits and interfaces for the concrete class
*/
class TraitIntroductionInfo implements IntroductionInfo
{
/**
* Introduced interface
*
* @var string
*/
private $introducedInterface;
/**
* Trait to use
*
* @var string
*/
private $introducedTrait;
/**
* Create a DefaultIntroductionAdvisor for the given advice.
*
* @param string $introducedTrait Introduced trait
* @param string $introducedInterface Introduced interface
*/
public function __construct($introducedTrait, $introducedInterface)
{
$this->introducedTrait = $introducedTrait;
$this->introducedInterface = $introducedInterface;
}
/**
* Return the additional interface introduced by this Advisor or Advice.
*
* @return string The introduced interface or empty
*/
public function getInterface()
{
return $this->introducedInterface;
}
/**
* Return the additional trait with realization of introduced interface
*
* @return string The trait name to use or empty
*/
public function getTrait()
{
return $this->introducedTrait;
}
}
| <?php
/*
* Go! AOP framework
*
* @copyright Copyright 2013, Lisachenko Alexander <[email protected]>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Go\Aop\Framework;
use Go\Aop\IntroductionInfo;
/**
* Advice for introduction that holds list of traits and interfaces for the concrete class
*/
class TraitIntroductionInfo implements IntroductionInfo
{
/**
* Introduced interface
*
* @var string
*/
private $introducedInterface = '';
/**
* Trait to use
*
* @var string
*/
private $introducedTrait = '';
/**
* Create a DefaultIntroductionAdvisor for the given advice.
*
* @param string $introducedTrait Introduced trait
* @param string $introducedInterface Introduced interface
*/
public function __construct($introducedTrait, $introducedInterface)
{
$this->introducedTrait = $introducedTrait;
$this->introducedInterface = $introducedInterface;
}
/**
* Return the additional interface introduced by this Advisor or Advice.
*
* @return string The introduced interface or empty
*/
public function getInterface()
{
return $this->introducedInterface;
}
/**
* Return the additional trait with realization of introduced interface
*
* @return string The trait name to use or empty
*/
public function getTrait()
{
return $this->introducedTrait;
}
}
|
Make sure adapter is created correctly | <?php declare(strict_types=1);
namespace Imbo\Behat;
use Imbo\EventListener\ImageVariations;
use Imbo\EventListener\ImageVariations\Database\MongoDB;
use Imbo\EventListener\ImageVariations\Storage\GridFS;
/**
* Enable the image variations event listener
*/
return [
'eventListeners' => [
'imageVariationsListener' => [
'listener' => ImageVariations::class,
'params' => [
'database' => [
'adapter' => MongoDB::class,
'params' => ['databaseName' => 'imbo_testing'],
],
'storage' => [
'adapter' => fn() => new GridFS('imbo_testing'),
],
'widths' => [320],
'minWidth' => 100,
'maxWidth' => 2048,
'minDiff' => 100,
'autoScale' => true,
'lossless' => false,
'scaleFactor' => .5,
],
],
],
];
| <?php declare(strict_types=1);
namespace Imbo\Behat;
use Imbo\EventListener\ImageVariations;
use Imbo\EventListener\ImageVariations\Database\MongoDB;
use Imbo\EventListener\ImageVariations\Storage\GridFS;
/**
* Enable the image variations event listener
*/
return [
'eventListeners' => [
'imageVariationsListener' => [
'listener' => ImageVariations::class,
'params' => [
'database' => [
'adapter' => MongoDB::class,
'params' => ['databaseName' => 'imbo_testing'],
],
'storage' => [
'adapter' => GridFS::class,
'params' => ['databaseName' => 'imbo_testing'],
],
'widths' => [320],
'minWidth' => 100,
'maxWidth' => 2048,
'minDiff' => 100,
'autoScale' => true,
'lossless' => false,
'scaleFactor' => .5,
],
],
],
];
|
Update function name used in the streamtester | """
This file defines a general method for evaluating ftfy using data that arrives
in a stream. A concrete implementation of it is found in `twitter_tester.py`.
"""
from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
| """
This file defines a general method for evaluating ftfy using data that arrives
in a stream. A concrete implementation of it is found in `twitter_tester.py`.
"""
from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_text_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_text_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
|
Fix some bugs and better blueprint view | @extends('layouts.user.main')
@section('title')
{{trans('layout.zagros')}}::{{trans('layout.projects')}}
@stop
@section('projects-navbar')active @stop
@section('content')
<div class="col-md-6 col-md-offset-3">
<h2 class="text-center">Projects</h2>
@if (Session::has('message'))
<p class="text-info text-center">{{Session::get('message')}}</p>
@endif
@forelse ($projects as $project)
<div>
<h3>
<a href="{{URL::action('ProjectController@getIndex', $project->url)}}">{{$project->name}}</a>
@if (Auth::user()->admin)
<small class="pull-right"> <a href="{{URL::action('AdminController@getUpdateProject', $project->project_id)}}">Edit</a></small>
@endif
</h3>
<small>{{$project->description}}</small>
<hr>
</div>
@empty
<h4 class="text-info text-center">{{trans('messages.no_project')}}</h4>
@endforelse
</div>
@stop
| @extends('layouts.user.main')
@section('title')
{{trans('layout.zagros')}}::{{trans('layout.prjs')}}
@stop
@section('projects-navbar')active @stop
@section('content')
<div class="col-md-6 col-md-offset-3">
<h2 class="text-center">Projects</h2>
@if (Session::has('message'))
<p class="text-info text-center">{{Session::get('message')}}</p>
@endif
@forelse ($projects as $project)
<div>
<h3>
<a href="{{URL::action('ProjectController@getIndex', $project->url)}}">{{$project->name}}</a>
@if (Auth::user()->admin)
<small class="pull-right"> <a href="{{URL::action('AdminController@getUpdateProject', $project->project_id)}}">Edit</a></small>
@endif
</h3>
<small>{{$project->description}}</small>
<hr>
</div>
@empty
<h4 class="text-info text-center">{{trans('messages.no_project')}}</h4>
@endforelse
</div>
@stop
|
BAP-3724: Add email owners to search index
- Fix cs | <?php
namespace Oro\Bundle\EmailBundle\EventListener;
use Symfony\Component\Security\Core\User\UserInterface;
use Oro\Bundle\SearchBundle\Event\PrepareEntityMapEvent;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailRecipient;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationAwareInterface;
class SearchListener
{
const EMAIL_CLASS_NAME = 'Oro\Bundle\EmailBundle\Entity\Email';
const EMPTY_ORGANIZATION_ID = 0;
/**
* @param PrepareEntityMapEvent $event
*/
public function prepareEntityMapEvent(PrepareEntityMapEvent $event)
{
$data = $event->getData();
$className = $event->getClassName();
if ($className === self::EMAIL_CLASS_NAME) {
/** @var $entity Email */
$entity = $event->getEntity();
$organizationsId = [];
$recipients = $entity->getRecipients();
/** @var $recipient EmailRecipient */
foreach ($recipients as $recipient) {
$owner = $recipient->getEmailAddress()->getOwner();
if ($owner instanceof UserInterface && $owner instanceof OrganizationAwareInterface) {
$organizationsId[] = $owner->getOrganization()->getId();
}
}
if (!isset ($data['integer'])) {
$data['integer'] = [];
}
if (!empty($organizationsId)) {
$data['integer']['organization'] = array_unique($organizationsId);
} else {
$data['integer']['organization'] = self::EMPTY_ORGANIZATION_ID;
}
}
$event->setData($data);
}
}
| <?php
namespace Oro\Bundle\EmailBundle\EventListener;
use Symfony\Component\Security\Core\User\UserInterface;
use Oro\Bundle\SearchBundle\Event\PrepareEntityMapEvent;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailRecipient;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationAwareInterface;
class SearchListener
{
const EMAIL_CLASS_NAME = 'Oro\Bundle\EmailBundle\Entity\Email';
/**
* @param PrepareEntityMapEvent $event
*/
public function prepareEntityMapEvent(PrepareEntityMapEvent $event)
{
$data = $event->getData();
$className = $event->getClassName();
if ($className === self::EMAIL_CLASS_NAME) {
/** @var $entity Email */
$entity = $event->getEntity();
$organizationsId = [];
$recipients = $entity->getRecipients();
/** @var $recipient EmailRecipient */
foreach ($recipients as $recipient) {
$owner = $recipient->getEmailAddress()->getOwner();
if ($owner instanceof UserInterface && $owner instanceof OrganizationAwareInterface) {
$organizationsId[] = $owner->getOrganization()->getId();
}
}
if (!empty($organizationsId)) {
$data['integer']['organization'] = array_unique($organizationsId);
} else {
$data['integer']['organization'] = 0;
}
}
$event->setData($data);
}
}
|
fix(props): Convert GroupedActivityFeed length to number in jsx | const React = require("react");
const {connect} = require("react-redux");
const {GroupedActivityFeed} = require("components/ActivityFeed/ActivityFeed");
const Spotlight = require("components/Spotlight/Spotlight");
const TimelinePage = React.createClass({
render() {
const props = this.props;
const navItems = [
{title: "All", active: true, icon: "fa-firefox"},
{title: "Bookmarks", icon: "fa-star"}
];
return (<main className="timeline">
<nav className="sidebar">
<ul>
{navItems.map(item => {
return (<li key={item.title}>
<a className={item.active ? "active" : ""}>
<span className={`fa ${item.icon}`} /> {item.title}
</a>
</li>);
})}
</ul>
</nav>
<section className="content">
<div className="wrapper">
<Spotlight sites={props.History.rows} />
<GroupedActivityFeed title="Just now" sites={props.History.rows} length={20} />
</div>
</section>
</main>);
}
});
function select(state) {
return state;
}
module.exports = connect(select)(TimelinePage);
module.exports.TimelinePage = TimelinePage;
| const React = require("react");
const {connect} = require("react-redux");
const {GroupedActivityFeed} = require("components/ActivityFeed/ActivityFeed");
const Spotlight = require("components/Spotlight/Spotlight");
const TimelinePage = React.createClass({
render() {
const props = this.props;
const navItems = [
{title: "All", active: true, icon: "fa-firefox"},
{title: "Bookmarks", icon: "fa-star"}
];
return (<main className="timeline">
<nav className="sidebar">
<ul>
{navItems.map(item => {
return (<li key={item.title}>
<a className={item.active ? "active" : ""}>
<span className={`fa ${item.icon}`} /> {item.title}
</a>
</li>);
})}
</ul>
</nav>
<section className="content">
<div className="wrapper">
<Spotlight sites={props.History.rows} />
<GroupedActivityFeed title="Just now" sites={props.History.rows} length="20" />
</div>
</section>
</main>);
}
});
function select(state) {
return state;
}
module.exports = connect(select)(TimelinePage);
module.exports.TimelinePage = TimelinePage;
|
Make it not expect json | $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: false,
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
| $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: "json",
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
console.log( res );
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
|
Add a TODO for ascii filter | var core = require('../../core');
// TODO (cengler) - The Y is flipped in this shader for some reason.
/**
* @author Vico @vicocotea
* original shader : https://www.shadertoy.com/view/lssGDj by @movAX13h
*/
/**
* An ASCII filter.
*
* @class
* @extends AbstractFilter
* @namespace PIXI.filters
*/
function AsciiFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
require('fs').readFileSync(__dirname + '/ascii.frag', 'utf8'),
// custom uniforms
{
dimensions: { type: '4fv', value: new Float32Array([0, 0, 0, 0]) },
pixelSize: { type: '1f', value: 8 }
}
);
}
AsciiFilter.prototype = Object.create(core.AbstractFilter.prototype);
AsciiFilter.prototype.constructor = AsciiFilter;
module.exports = AsciiFilter;
Object.defineProperties(AsciiFilter.prototype, {
/**
* The pixel size used by the filter.
*
* @member {number}
* @memberof AsciiFilter#
*/
size: {
get: function ()
{
return this.uniforms.pixelSize.value;
},
set: function (value)
{
this.uniforms.pixelSize.value = value;
}
}
});
| var core = require('../../core');
/**
* @author Vico @vicocotea
* original shader : https://www.shadertoy.com/view/lssGDj by @movAX13h
*/
/**
* An ASCII filter.
*
* @class
* @extends AbstractFilter
* @namespace PIXI.filters
*/
function AsciiFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
require('fs').readFileSync(__dirname + '/ascii.frag', 'utf8'),
// custom uniforms
{
dimensions: { type: '4fv', value: new Float32Array([0, 0, 0, 0]) },
pixelSize: { type: '1f', value: 8 }
}
);
}
AsciiFilter.prototype = Object.create(core.AbstractFilter.prototype);
AsciiFilter.prototype.constructor = AsciiFilter;
module.exports = AsciiFilter;
Object.defineProperties(AsciiFilter.prototype, {
/**
* The pixel size used by the filter.
*
* @member {number}
* @memberof AsciiFilter#
*/
size: {
get: function ()
{
return this.uniforms.pixelSize.value;
},
set: function (value)
{
this.uniforms.pixelSize.value = value;
}
}
});
|
Fix indices with multiple key hits in same file. | package com.jetbrains.python.psi.search;
import com.intellij.openapi.project.Project;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.util.Processor;
import com.intellij.util.QueryExecutor;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.stubs.PySuperClassIndex;
import java.util.Collection;
/**
* @author yole
*/
public class PyClassInheritorsSearchExecutor implements QueryExecutor<PyClass, PyClassInheritorsSearch.SearchParameters> {
public boolean execute(final PyClassInheritorsSearch.SearchParameters queryParameters, final Processor<PyClass> consumer) {
PyClass superClass = queryParameters.getSuperClass();
Project project = superClass.getProject();
final Collection<PyClass> candidates = StubIndex.getInstance().get(PySuperClassIndex.KEY, superClass.getName(), project,
ProjectScope.getAllScope(project));
for(PyClass candidate: candidates) {
final PyClass[] classes = candidate.getSuperClasses();
if (classes != null) {
for(PyClass superClassCandidate: classes) {
if (superClassCandidate.isEquivalentTo(superClass)) {
if (!consumer.process(candidate)) {
return false;
}
else {
break;
}
}
}
}
}
return true;
}
}
| package com.jetbrains.python.psi.search;
import com.intellij.openapi.project.Project;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.util.Processor;
import com.intellij.util.QueryExecutor;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.stubs.PySuperClassIndex;
import java.util.Collection;
/**
* @author yole
*/
public class PyClassInheritorsSearchExecutor implements QueryExecutor<PyClass, PyClassInheritorsSearch.SearchParameters> {
public boolean execute(final PyClassInheritorsSearch.SearchParameters queryParameters, final Processor<PyClass> consumer) {
PyClass superClass = queryParameters.getSuperClass();
Project project = superClass.getProject();
final Collection<PyClass> candidates = StubIndex.getInstance().get(PySuperClassIndex.KEY, superClass.getName(), project,
ProjectScope.getAllScope(project));
for(PyClass candidate: candidates) {
final PyClass[] classes = candidate.getSuperClasses();
if (classes != null) {
for(PyClass superClassCandidate: classes) {
if (superClassCandidate.isEquivalentTo(superClass)) {
if (!consumer.process(superClassCandidate)) return false;
}
}
}
}
return true;
}
}
|
Fix crash tasks with unicode string name (like name: héhé). | class Formatter(object):
def format(self, match):
formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
match.line)
class QuietFormatter(object):
def format(self, match):
formatstr = u"[{0}] {1}:{2}"
return formatstr.format(match.rule.id, match.filename,
match.linenumber)
class ParseableFormatter(object):
def format(self, match):
formatstr = u"{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
match.rule.id,
match.message,
)
| class Formatter(object):
def format(self, match):
formatstr = "[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
match.line)
class QuietFormatter(object):
def format(self, match):
formatstr = "[{0}] {1}:{2}"
return formatstr.format(match.rule.id, match.filename,
match.linenumber)
class ParseableFormatter(object):
def format(self, match):
formatstr = "{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
match.rule.id,
match.message,
)
|
Use dimension shape instead of coordinate system type | define(function (require) {
return function (seriesType, ecModel) {
ecModel.eachSeriesByType(seriesType, function (seriesModel) {
var data = seriesModel.getData();
var coordSys = seriesModel.coordinateSystem;
if (coordSys) {
var dims = coordSys.dimensions;
if (dims.length === 1) {
data.each(dims[0], function (x, idx) {
// Also {Array.<number>}, not undefined to avoid if...else... statement
data.setItemLayout(idx, isNaN(x) ? [NaN, NaN] : coordSys.dataToPoint(x));
});
}
else if (dims.length === 2) {
data.each(dims, function (x, y, idx) {
// Also {Array.<number>}, not undefined to avoid if...else... statement
data.setItemLayout(
idx, (isNaN(x) || isNaN(y)) ? [NaN, NaN] : coordSys.dataToPoint([x, y])
);
}, true);
}
}
});
};
}); | define(function (require) {
return function (seriesType, ecModel) {
ecModel.eachSeriesByType(seriesType, function (seriesModel) {
var data = seriesModel.getData();
var coordSys = seriesModel.coordinateSystem;
if (coordSys) {
var dims = coordSys.dimensions;
if (coordSys.type === 'singleAxis') {
data.each(dims[0], function (x, idx) {
// Also {Array.<number>}, not undefined to avoid if...else... statement
data.setItemLayout(idx, isNaN(x) ? [NaN, NaN] : coordSys.dataToPoint(x));
});
}
else {
data.each(dims, function (x, y, idx) {
// Also {Array.<number>}, not undefined to avoid if...else... statement
data.setItemLayout(
idx, (isNaN(x) || isNaN(y)) ? [NaN, NaN] : coordSys.dataToPoint([x, y])
);
}, true);
}
}
});
};
}); |
Fix calling to wrong Utility class | <?php
/**
* @file
*
* @package In2pire
* @subpackage Cli
* @author Nhat Tran <[email protected]>
*/
namespace In2pire\Cli\Question;
use In2pire\Component\Utility\String;
final class Container
{
public static function create($question, $command)
{
static $cache = [];
$cacheKey = $question;
if (isset($cache[$cacheKey])) {
$class = $cache[$cacheKey]['class'];
$question = $cache[$cacheKey]['question'];
} else {
if (false === strpos($question, '.')) {
// Not FQCN
$class = __NAMESPACE__ . '\\' . String::convertToCamelCase($question);
} else {
// FQCN
$class = explode('.', $question);
$class = array_map(array('In2pire\\Component\\Utility\\String', 'convertToCamelCase'), $class);
$class = implode('\\', $class);
$question = substr($question, strrpos($question, '.') + 1);
}
$cache[$cacheKey] = [
'class' => $class,
'question' => $question
];
}
if (!class_exists($class)) {
throw new \RuntimeException('Unknow question ' . $cacheKey);
}
return new $class($command);
}
}
| <?php
/**
* @file
*
* @package In2pire
* @subpackage Cli
* @author Nhat Tran <[email protected]>
*/
namespace In2pire\Cli\Question;
use In2pire\Component\Utility\String;
final class Container
{
public static function create($question, $command)
{
static $cache = [];
$cacheKey = $question;
if (isset($cache[$cacheKey])) {
$class = $cache[$cacheKey]['class'];
$question = $cache[$cacheKey]['question'];
} else {
if (false === strpos($question, '.')) {
// Not FQCN
$class = __NAMESPACE__ . '\\' . String::convertToCamelCase($question);
} else {
// FQCN
$class = explode('.', $question);
$class = array_map(array('In2pire\\Component\\Utility\\String', 'convertToCamelCase'), $class);
$class = implode('\\', $class);
$question = substr($question, strrpos($question, '.') + 1);
}
$cache[$cacheKey] = [
'class' => $class,
'question' => $question
];
}
$class = __NAMESPACE__ . '\\' . Utility::convertToCamelCase($question);
if (!class_exists($class)) {
throw new \RuntimeException('Unknow question ' . $cacheKey);
}
return new $class($command);
}
}
|
Add priority option to send_queued | __version__ = '2.0.0'
def get_account(using=None):
from django.conf import settings
accounts = settings.SMSGATEWAY_ACCOUNTS
if using is not None:
return accounts[using]
else:
return accounts[accounts['__default__']]
def send(to, msg, signature, using=None, reliable=False):
"""
Send an SMS message immediately.
* 'to' is a semicolon separated list of phone numbers with an international
prefix (+32... etc).
* 'msg' is the message itself as a unicode object (max 160 characters).
* 'signature' is where the message comes from. Depends on the backend in use.
* 'using' is an optional parameter where you can specify a specific account
to send messages from.
"""
from smsgateway.backends import get_backend
from smsgateway.sms import SMSRequest
account_dict = get_account(using)
backend = get_backend(account_dict['backend'])
sms_request = SMSRequest(to, msg, signature, reliable=reliable)
return backend.send(sms_request, account_dict)
def send_queued(to, msg, signature, using=None, reliable=False, priority=None):
"""
Place SMS message in queue to be sent.
"""
from smsgateway.models import QueuedSMS
queued_sms = QueuedSMS(
to=to,
content=msg,
signature=signature,
using=using if using is not None else '__none__',
reliable=reliable
)
if priority is not None:
queued_sms.priority = priority
queued_sms.save()
| __version__ = '2.0.0'
def get_account(using=None):
from django.conf import settings
accounts = settings.SMSGATEWAY_ACCOUNTS
if using is not None:
return accounts[using]
else:
return accounts[accounts['__default__']]
def send(to, msg, signature, using=None, reliable=False):
"""
Send an SMS message immediately.
* 'to' is a semicolon separated list of phone numbers with an international
prefix (+32... etc).
* 'msg' is the message itself as a unicode object (max 160 characters).
* 'signature' is where the message comes from. Depends on the backend in use.
* 'using' is an optional parameter where you can specify a specific account
to send messages from.
"""
from smsgateway.backends import get_backend
from smsgateway.sms import SMSRequest
account_dict = get_account(using)
backend = get_backend(account_dict['backend'])
sms_request = SMSRequest(to, msg, signature, reliable=reliable)
return backend.send(sms_request, account_dict)
def send_queued(to, msg, signature, using=None, reliable=False):
"""
Place SMS message in queue to be sent.
"""
from smsgateway.models import QueuedSMS
QueuedSMS.objects.create(
to=to,
content=msg,
signature=signature,
using=using if using is not None else '__none__',
reliable=reliable
)
|
Change method data to view | <?php
namespace Hook;
class Navigation
{
public function view($data)
{
return [
'nav' => [
[
[
'url'=>'user/signin',
'img'=>'user48.png',
'text'=>'Sign In / Sign Up'
]
],
[
[
'url'=>'',
'img'=>'home48.png',
'text'=>'Home'
],
[
'url'=>'manga/directory',
'img'=>'directory48.png',
'text'=>'Manga Directory'
],
[
'url'=>'manga/directory/hot',
'img'=>'hot48.png',
'text'=>'Popular Manga'
],
[
'url'=>'manga/directory/latest',
'img'=>'news48.png',
'text'=>'Latest Updated'
]
]
]
];
}
}
?>
| <?php
namespace Hook;
class Navigation
{
public function data($data)
{
return [
'nav' => [
[
[
'url'=>'user/signin',
'img'=>'user48.png',
'text'=>'Sign In / Sign Up'
]
],
[
[
'url'=>'',
'img'=>'home48.png',
'text'=>'Home'
],
[
'url'=>'manga/directory',
'img'=>'directory48.png',
'text'=>'Manga Directory'
],
[
'url'=>'manga/directory/hot',
'img'=>'hot48.png',
'text'=>'Popular Manga'
],
[
'url'=>'manga/directory/latest',
'img'=>'news48.png',
'text'=>'Latest Updated'
]
]
]
];
}
}
?>
|
ENH: Make ID3Lab allow attr to be pluggable | import IPython
import ts_charting.lab.lab as tslab
import ipycli.standalone as sa
from workbench import sharedx
class ID3Lab(tslab.Lab):
_html_obj = None
def __init__(self, draw=False, html_obj=None):
super(ID3Lab, self).__init__(draw=draw)
if html_obj is None:
html_obj = sharedx
self._html_obj = html_obj
def get_varname(self):
"""
Try to get the variable that this lab is
bound to in the IPython kernel
"""
inst = IPython.InteractiveShell._instance
for k,v in inst.user_ns.iteritems():
if v is self and not k.startswith('_'):
return k
def link(self):
name = self.get_varname()
return sa.link(name)
def _repr_javascript_(self):
"""
Output:
stations:
AAPL
IBM
<link>
Note:
Uses Javascript because sa.link() returns javascript. This is
because sa.link needs to use the location.href to get the notebook_id
since we cannot grab that from within the notebook kernel.
"""
js = """
element.append('{0}');
container.show();
"""
station_text = '<strong>stations:</strong> <br />'
station_text += '<br />'.join(self.stations.keys())
out = js.format(station_text)
link = self.link().data
out += 'element.append("<br />");' + link
return out
@property
def html_obj(self):
return self._html_obj
def __str__(self):
return
| import IPython
import ts_charting.lab.lab as tslab
import ipycli.standalone as sa
from workbench import sharedx
class ID3Lab(tslab.Lab):
def get_varname(self):
"""
Try to get the variable that this lab is
bound to in the IPython kernel
"""
inst = IPython.InteractiveShell._instance
for k,v in inst.user_ns.iteritems():
if v is self and not k.startswith('_'):
return k
def link(self):
name = self.get_varname()
return sa.link(name)
def _repr_javascript_(self):
"""
Output:
stations:
AAPL
IBM
<link>
Note:
Uses Javascript because sa.link() returns javascript. This is
because sa.link needs to use the location.href to get the notebook_id
since we cannot grab that from within the notebook kernel.
"""
js = """
element.append('{0}');
container.show();
"""
station_text = '<strong>stations:</strong> <br />'
station_text += '<br />'.join(self.stations.keys())
out = js.format(station_text)
link = self.link().data
out += 'element.append("<br />");' + link
return out
@property
def html_obj(self):
# for now default to sharedx
return sharedx
def __str__(self):
return
|
Rename method and param to better describe what is happening | <?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
array(
new RoutedApplication(
array(
array('POST', '/form', $html)))));
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
private function htmlHasClass($html, $class)
{
$crawler = new Crawler($html);
return $crawler->filter($class)->count() > 0;
}
private function responseBodyHasClass($response, $class)
{
return $this->htmlHasClass($response['body'], $class);
}
public function testFormErrorShouldBeShown()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, '.error'));
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
}
}
| <?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
array(
new RoutedApplication(
array(
array('POST', '/form', $html)))));
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
private function filterNotEmpty($html, $filter)
{
$crawler = new Crawler($html);
return $crawler->filter($filter)->count() > 0;
}
private function responseBodyHasClass($response, $class)
{
return $this->filterNotEmpty($response['body'], $class);
}
public function testFormErrorShouldBeShown()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, '.error'));
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
}
}
|
Fix errors in set_welcome and update for http_client | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
_completion)
def set_welcome(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/thread_settings',
'POST',
message.to_json(),
_completion)
| from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient()
def send_message(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
_completion)
def set_welcome(self, message, completion):
url = "/me/thread_settings?access_token=%s" % (self.access_token)
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
url,
'POST'
message.to_json(),
_completion)
|
Add option for launching server
There was no option to start the server and you had to do it manually.
Now it can be started with:
1) -s with default configuration
2) --server <PORT> for manual port choice | import argparse
"""
usage: mfh.py [-h] [-c | --client [PORT]] [-u] [-v]
Serve some sweet honey to the ubiquitous bots!
optional arguments:
-h, --help show this help message and exit
-c launch client with on port defined in settings
--client [PORT] port to start a client on
-u, --updater enable self updating
-v, --verbose increase output verbosity
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that`s how you`d detect a sneaky chinese bot.',
prog='mfh.py',
)
client_group = parser.add_mutually_exclusive_group()
client_group.add_argument(
'-c',
action='store_true',
help='launch client with on port defined in settings',
)
client_group.add_argument(
'--client',
help='port to start a client on',
metavar='PORT',
nargs='?',
type=int,
)
server_group = parser.add_mutually_exclusive_group()
server_group.add_argument(
'-s',
action='store_true',
help='launch server with on port defined in settings',
)
server_group.add_argument(
'--server',
help='port to start a server on',
metavar='PORT',
nargs='?',
type=int,
)
parser.add_argument(
'-u',
'--updater',
action='store_true',
help='enable self updating',
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help='increase output verbosity',
)
return parser.parse_args()
| import argparse
"""
usage: mfh.py [-h] [-c | --client [PORT]] [-u] [-v]
Serve some sweet honey to the ubiquitous bots!
optional arguments:
-h, --help show this help message and exit
-c launch client with on port defined in settings
--client [PORT] port to start a client on
-u, --updater enable self updating
-v, --verbose increase output verbosity
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that`s how you`d detect a sneaky chinese bot.',
prog='mfh.py',
)
client_group = parser.add_mutually_exclusive_group()
client_group.add_argument(
'-c',
action='store_true',
help='launch client with on port defined in settings',
)
client_group.add_argument(
'--client',
help='port to start a client on',
metavar='PORT',
nargs='?',
type=int,
)
parser.add_argument(
'-u',
'--updater',
action='store_true',
help='enable self updating',
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help='increase output verbosity',
)
return parser.parse_args()
|
Adjust cURL headers to avoid certain bot-blockers | <?php
namespace Craft;
use Guzzle\Http\Client;
class VzUrl_ValidationService extends BaseApplicationComponent
{
public function check($url)
{
if (empty($url)) {
return false;
}
// Store the original, so we can pass it back in the response
$originalUrl = $url;
if (substr($url, 0, 1) == '/') {
// Local URL, add the current domain
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$host = $protocol . "://" . $_SERVER['HTTP_HOST'];
$url = $host . $url;
}
try {
// Make the request
$client = new Client();
$client->setUserAgent('VzUrl/1.0 (CraftCMS)');
$request = $client->get($url, null, array(
'headers' => array(
'Accept' => 'text/html,*/*',
'Cache-Control' => 'no-cache',
),
'timeout' => 10,
'connect_timeout' => 2,
'verify' => false,
));
$response = $request->send();
// Get the data we need
$code = $response->getStatusCode();
$final = $response->getEffectiveUrl();
if (isset($host)) {
$final = str_replace($host, '', $final);
}
return array(
'original' => $originalUrl,
'final_url' => $final,
'http_code' => $code
);
} catch (\Exception $e) {
return false;
}
}
}
| <?php
namespace Craft;
use Guzzle\Http\Client;
class VzUrl_ValidationService extends BaseApplicationComponent
{
public function check($url)
{
if (empty($url)) {
return false;
}
// Store the original, so we can pass it back in the response
$originalUrl = $url;
if (substr($url, 0, 1) == '/') {
// Local URL, add the current domain
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$host = $protocol . "://" . $_SERVER['HTTP_HOST'];
$url = $host . $url;
}
try {
// Make the request
$client = new Client();
$response = $client->get($url)->send();
// Get the data we need
$code = $response->getStatusCode();
$final = $response->getEffectiveUrl();
if (isset($host)) {
$final = str_replace($host, '', $final);
}
return array(
'original' => $originalUrl,
'final_url' => $final,
'http_code' => $code
);
} catch (\Exception $e) {
return false;
}
}
}
|
Change import order to satisfy pylint. | """Tests for crabigator.wanikani."""
from __future__ import print_function
import os
from unittest import TestCase
from crabigator.wanikani import WaniKani, WaniKaniError
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestCase):
"""Unit test cases for the WaniKani API wrapper."""
@classmethod
def test_wanikani(cls):
"""Test all public methods in crabigator.wanikani."""
wanikani = WaniKani(os.environ['WANIKANI_API_KEY'])
print(wanikani.user_information)
print(wanikani.study_queue)
print(wanikani.level_progression)
print(wanikani.srs_distribution)
print(wanikani.recent_unlocks)
print(wanikani.get_recent_unlocks(3))
print(wanikani.critical_items)
print(wanikani.get_recent_unlocks(65))
print(wanikani.radicals)
print(wanikani.get_radicals([1, 2]))
print(wanikani.kanji)
print(wanikani.get_kanji([1, 2]))
print(wanikani.vocabulary)
print(wanikani.get_vocabulary([1, 2]))
try:
wanikani.get_vocabulary([9999])
except WaniKaniError as ex:
print(ex)
| """Tests for crabigator.wanikani."""
from __future__ import print_function
from crabigator.wanikani import WaniKani, WaniKaniError
import os
from unittest import TestCase
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestCase):
"""Unit test cases for the WaniKani API wrapper."""
@classmethod
def test_wanikani(cls):
"""Test all public methods in crabigator.wanikani."""
wanikani = WaniKani(os.environ['WANIKANI_API_KEY'])
print(wanikani.user_information)
print(wanikani.study_queue)
print(wanikani.level_progression)
print(wanikani.srs_distribution)
print(wanikani.recent_unlocks)
print(wanikani.get_recent_unlocks(3))
print(wanikani.critical_items)
print(wanikani.get_recent_unlocks(65))
print(wanikani.radicals)
print(wanikani.get_radicals([1, 2]))
print(wanikani.kanji)
print(wanikani.get_kanji([1, 2]))
print(wanikani.vocabulary)
print(wanikani.get_vocabulary([1, 2]))
try:
wanikani.get_vocabulary([9999])
except WaniKaniError as ex:
print(ex)
|
Add one more component test | <?php
namespace Xu\Tests\Foundation;
use Xu\Foundation\Foundation;
class Foundation_Test extends \WP_UnitTestCase {
public function test_component() {
$this->assertTrue( xu( '' ) instanceof Foundation );
$this->assertEquals( Foundation::VERSION, xu( 'xu' )->version() );
}
public function test_fn_method() {
$this->assertEquals( 'xu-dashify', \xu()->fn( 'xu_dashify', ['xu_dashify'] ) );
$this->assertEquals( 'xu-dashify', \xu()->fn( 'dashify', 'xu_dashify' ) );
}
public function test_component_method() {
try {
\xu()->component( null );
} catch ( \Exception $e ) {
$this->assertEquals( 'Invalid argument. `$component` must be string.', $e->getMessage() );
}
try {
\xu()->component( 'frozzare.tank.container' );
} catch ( \Exception $e ) {
$this->assertEquals( '`Xu\\Components\\Frozzare\\Tank\\Container` class does not exists.', $e->getMessage() );
}
try {
\xu()->component( 'test' );
} catch ( \Exception $e ) {
$this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
}
try {
\xu()->component( 'Test\\Test' );
} catch ( \Exception $e ) {
$this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
}
}
}
| <?php
namespace Xu\Tests\Foundation;
use Xu\Foundation\Foundation;
class Foundation_Test extends \WP_UnitTestCase {
public function test_component() {
$this->assertTrue( xu( '' ) instanceof Foundation );
$this->assertEquals( Foundation::VERSION, xu( 'xu' )->version() );
}
public function test_fn_method() {
$this->assertEquals( 'xu-dashify', \xu()->fn( 'xu_dashify', ['xu_dashify'] ) );
$this->assertEquals( 'xu-dashify', \xu()->fn( 'dashify', 'xu_dashify' ) );
}
public function test_component_method() {
try {
\xu()->component( null );
} catch ( \Exception $e ) {
$this->assertEquals( 'Invalid argument. `$component` must be string.', $e->getMessage() );
}
try {
\xu()->component( 'frozzare.tank.container' );
} catch ( \Exception $e ) {
$this->assertEquals( '`Xu\\Components\\Frozzare\\Tank\\Container` class does not exists.', $e->getMessage() );
}
try {
\xu()->component( 'test' );
} catch ( \Exception $e ) {
$this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
}
}
}
|
Mark runserver as a plumbing command | """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
This command is named to mirror its equivalent in Django. It configures
the WSGI app and serves it through Werkzeug's simple serving mechanism,
with a debugger attached, and auto-reloading.
"""
plumbing = True
help = "run a (local, debug) server"
def add_arguments(self, parser):
"""Add argparse arguments."""
parser.add_argument(
'-p',
'--port',
type=int,
default=1212,
help="port to bind to",
)
parser.add_argument(
'-b',
'--bind',
type=str,
default='::1',
help="address to bind to",
)
def handle(self, config, options):
"""Run command."""
app = get_wsgi_app(config)
werkzeug.serving.run_simple(
options.bind,
options.port,
app,
use_reloader=True,
use_debugger=True,
use_evalex=True,
threaded=False,
processes=1,
)
| """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
This command is named to mirror its equivalent in Django. It configures
the WSGI app and serves it through Werkzeug's simple serving mechanism,
with a debugger attached, and auto-reloading.
"""
help = "run a (local, debug) server"
def add_arguments(self, parser):
"""Add argparse arguments."""
parser.add_argument(
'-p',
'--port',
type=int,
default=1212,
help="port to bind to",
)
parser.add_argument(
'-b',
'--bind',
type=str,
default='::1',
help="address to bind to",
)
def handle(self, config, options):
"""Run command."""
app = get_wsgi_app(config)
werkzeug.serving.run_simple(
options.bind,
options.port,
app,
use_reloader=True,
use_debugger=True,
use_evalex=True,
threaded=False,
processes=1,
)
|
Fix Google Authenticator unit test | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\Bundle\QABundle\Tests;
class SonataUserTwoStepVerificationCommandTest extends CommandTestCase
{
/**
* @expectedException \RuntimeException
*/
public function testMissingArguments()
{
$client = self::createClient();
$this->runCommand($client, "sonata:user:two-step-verification");
}
public function testReset()
{
$client = self::createClient();
$output = $this->runCommand($client, "sonata:user:two-step-verification --reset secure");
$this->assertContains("Url : https://chart.googleapis.com/", $output);
$user = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
'username' => 'secure'
));
$this->assertContains($user->getTwoStepVerificationCode(), $output);
}
public function testGenerateOnGenerateUser()
{
$client = self::createClient();
$output = $this->runCommand($client, "sonata:user:two-step-verification secure");
$code = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
'username' => 'secure'
))->getTwoStepVerificationCode();
$this->assertContains($code, $output);
}
} | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\Bundle\QABundle\Tests;
class SonataUserTwoStepVerificationCommandTest extends CommandTestCase
{
/**
* @expectedException \RuntimeException
*/
public function testMissingArguments()
{
$client = self::createClient();
$this->runCommand($client, "sonata:user:two-step-verification");
}
public function testReset()
{
$client = self::createClient();
$output = $this->runCommand($client, "sonata:user:two-step-verification --reset secure");
$this->assertContains("Url : https://www.google.com/", $output);
$user = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
'username' => 'secure'
));
$this->assertContains($user->getTwoStepVerificationCode(), $output);
}
public function testGenerateOnGenerateUser()
{
$client = self::createClient();
$output = $this->runCommand($client, "sonata:user:two-step-verification secure");
$code = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
'username' => 'secure'
))->getTwoStepVerificationCode();
$this->assertContains($code, $output);
}
} |
Remove console logs from files... | angular.module('events.events.filter', [])
.filter('showEvents', function () {
return function (events, filter) {
var result = [];
function filterIsSet () {
return typeof filter !== 'undefined' && (typeof filter.topics !== 'undefined' || typeof filter.searchText !== 'undefined');
}
function topicsFilterIsSet () {
return typeof filter.topics !== 'undefined' && filter.topics.length > 0 && filter.topics instanceof Array;
}
function withinTopicsFilter (topics) {
var ts = topics.map(function (topic) {
return topic.term_slug;
});
for (var i = 0, l = ts.length; i < l; i++){
if (filter.topics.indexOf(ts[i]) > -1) {
return true;
}
}
return false;
}
function filterByTopics () {
events.map(function (event) {
if (!withinTopicsFilter(event.topics)) {
event.hide = true;
}
else {
event.hide = false;
}
});
}
function showAll () {
events.map(function (event) {
event.hide = false;
});
}
function filterEvents () {
if (filterIsSet() && topicsFilterIsSet()){
filterByTopics();
} else {
showAll();
}
return events;
}
return filterEvents();
};
});
| angular.module('events.events.filter', [])
.filter('showEvents', function () {
return function (events, filter) {
var result = [];
function filterIsSet () {
return typeof filter !== 'undefined' && (typeof filter.topics !== 'undefined' || typeof filter.searchText !== 'undefined');
}
function topicsFilterIsSet () {
return typeof filter.topics !== 'undefined' && filter.topics.length > 0 && filter.topics instanceof Array;
}
function withinTopicsFilter (topics) {
var ts = topics.map(function (topic) {
return topic.term_slug;
});
for (var i = 0, l = ts.length; i < l; i++){
if (filter.topics.indexOf(ts[i]) > -1) {
return true;
}
}
return false;
}
function filterByTopics () {
events.map(function (event) {
if (!withinTopicsFilter(event.topics)) {
event.hide = true;
}
else {
event.hide = false;
}
});
}
function showAll () {
events.map(function (event) {
event.hide = false;
});
}
function filterEvents () {
if (filterIsSet() && topicsFilterIsSet()){
console.log( 'filter' );
filterByTopics();
} else {
console.log('show all');
showAll();
}
return events;
}
return filterEvents();
};
});
|
Change name of module made by cython to rk4cython to test. | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import configuration
ext_modules = [Extension("sourceterm.srccython", ["sourceterm/srccython.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
Extension("romberg", ["romberg.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
Extension("rk4cython", ["rk4.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
#Extension("cythontesting", ["cythontesting.pyx"],
#extra_compile_args=["-g"],
#extra_link_args=["-g"],
#include_dirs=[numpy.get_include()])
]
setup_args = dict(name=configuration.PROGRAM_NAME,
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules)
if __name__ == "__main__":
setup(**setup_args)
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import configuration
ext_modules = [Extension("sourceterm.srccython", ["sourceterm/srccython.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
Extension("romberg", ["romberg.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
Extension("rk4", ["rk4.pyx"],
extra_compile_args=["-g"],
extra_link_args=["-g"],
include_dirs=[numpy.get_include()]),
#
#Extension("cythontesting", ["cythontesting.pyx"],
#extra_compile_args=["-g"],
#extra_link_args=["-g"],
#include_dirs=[numpy.get_include()])
]
setup_args = dict(name=configuration.PROGRAM_NAME,
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules)
if __name__ == "__main__":
setup(**setup_args)
|
Remove string replace in favor of sprintf | <?php
class Philwinkle_Fixerio_Model_Import extends Mage_Directory_Model_Currency_Import_Abstract
{
protected $_url = 'http://api.fixer.io/latest?base=%1$s&symbols=%2$s';
protected $_messages = array();
/**
* HTTP client
*
* @var Varien_Http_Client
*/
protected $_httpClient;
public function __construct()
{
$this->_httpClient = new Varien_Http_Client();
}
protected function _convert($currencyFrom, $currencyTo, $retry = 0)
{
$url = sprintf($this->_url, $currencyFrom, $currencyTo);
try {
$response = $this->_httpClient
->setUri($url)
->setConfig(array('timeout' => Mage::getStoreConfig('currency/fixerio/timeout')))
->request('GET')
->getBody();
$converted = json_decode($response);
$xml = new SimpleXmlElement("<double>{$converted->rates->$currencyTo}</double>");
if( !$xml ) {
$this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
return null;
}
return (float) $xml;
}
catch (Exception $e) {
if( $retry == 0 ) {
$this->_convert($currencyFrom, $currencyTo, 1);
} else {
$this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
}
}
}
}
| <?php
class Philwinkle_Fixerio_Model_Import extends Mage_Directory_Model_Currency_Import_Abstract
{
protected $_url = 'http://api.fixer.io/latest?base={{CURRENCY_FROM}}&symbols={{CURRENCY_TO}}';
protected $_messages = array();
/**
* HTTP client
*
* @var Varien_Http_Client
*/
protected $_httpClient;
public function __construct()
{
$this->_httpClient = new Varien_Http_Client();
}
protected function _convert($currencyFrom, $currencyTo, $retry=0)
{
$url = str_replace('{{CURRENCY_FROM}}', $currencyFrom, $this->_url);
$url = str_replace('{{CURRENCY_TO}}', $currencyTo, $url);
try {
$response = $this->_httpClient
->setUri($url)
->setConfig(array('timeout' => Mage::getStoreConfig('currency/fixerio/timeout')))
->request('GET')
->getBody();
$converted = json_decode($response);
$xml = new SimpleXmlElement("<double>{$converted->rates->$currencyTo}</double>");
if( !$xml ) {
$this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
return null;
}
return (float) $xml;
}
catch (Exception $e) {
if( $retry == 0 ) {
$this->_convert($currencyFrom, $currencyTo, 1);
} else {
$this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
}
}
}
}
|
Fix position of curly brace | package annotations.util;
/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/
/**
* {@link Strings} provides useful static methods related to strings.
*/
public abstract class Strings {
private Strings() {}
/**
* Returns the given string, escaped and quoted according to Java
* conventions. Currently, only newlines, backslashes, tabs, and
* single and double quotes are escaped. Perhaps nonprinting
* characters should also be escaped somehow.
*/
public static String escape(String in) {
StringBuilder out = new StringBuilder("\"");
for (int pos = 0; pos < in.length(); pos++) {
switch (in.charAt(pos)) {
case '\n':
out.append("\\n");
break;
case '\t':
out.append("\\t");
break;
case '\\':
out.append("\\\\");
break;
case '\'':
out.append("\\\'");
break;
case '\"':
out.append("\\\"");
break;
default:
out.append(in.charAt(pos));
}
}
out.append('\"');
return out.toString();
}
}
| package annotations.util;
/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/
/**
* {@link Strings} provides useful static methods related to strings.
*/
public abstract class Strings {
private Strings() {}
/**
* Returns the given string, escaped and quoted according to Java
* conventions. Currently, only newlines, backslashes, tabs, and
* single and double quotes are escaped. Perhaps nonprinting
* characters should also be escaped somehow.
*/
public static String escape(String in) {
StringBuilder out = new StringBuilder("\"");
for (int pos = 0; pos < in.length(); pos++) {
switch (in.charAt(pos)) {
case '\n':
out.append("\\n");
break;
case '\t':
out.append("\\t");
break;
case '\\':
out.append("\\\\");
break;
case '\'':
out.append("\\\'");
break;
case '\"':
out.append("\\\"");
break;
default:
out.append(in.charAt(pos));
}
out.append('\"');
return out.toString();
}
}
}
|
Fix checking for posting providers. | <?php
namespace Borfast\Socializr;
class Socializr
{
protected $config = array();
protected $login_providers = array('Google', 'Facebook');
protected $posting_providers = array('Twitter', 'Facebook');
public function __construct($config)
{
$this->config = $config;
}
/**
* Post the given content to the given provider, using the given credentials.
*/
public function post($content, $provider, $auth)
{
// Only allow configured providers.
if (!in_array($provider, array_keys($this->config['posting_providers']))) {
throw new \Exception('Unknown provider');
}
// Only create a new ProviderEngine instance if necessary.
if (empty($this->posting_providers[$provider])) {
$provider_engine = '\\Borfast\\Socializr\\'.$provider.'Engine';
$provider_config = $this->config['providers'][$provider];
$provider_config['oauth_access_token'] = $auth['oauth_access_token'];
$provider_config['oauth_access_token_secret'] = $auth['oauth_access_token_secret'];
$this->posting_providers[$provider] = new $provider_engine($provider_config, $auth);
}
return $this->posting_providers[$provider]->post($content);
}
/**
* Gets the list of supported login service providers.
*/
public static function getLoginProviders()
{
$login_providers = array('Google', 'Facebook');
return $login_providers;
}
/**
* Tries to authorize the user against the given provider.
*/
public function authorize($provider)
{
}
}
| <?php
namespace Borfast\Socializr;
class Socializr
{
protected $config = array();
protected $login_providers = array('Google', 'Facebook');
protected $posting_providers = array('Twitter', 'Facebook');
public function __construct($config)
{
$this->config = $config;
}
/**
* Post the given content to the given provider, using the given credentials.
*/
public function post($content, $provider, $auth)
{
// Only allow configured providers.
if (!in_array($provider, array_keys($this->config['providers']))) {
throw new \Exception('Unknown provider');
}
// Only create a new ProviderEngine instance if necessary.
if (empty($this->providers[$provider])) {
$provider_engine = '\\Borfast\\Socializr\\'.$provider.'Engine';
$provider_config = $this->config['providers'][$provider];
$provider_config['oauth_access_token'] = $auth['oauth_access_token'];
$provider_config['oauth_access_token_secret'] = $auth['oauth_access_token_secret'];
$this->posting_providers[$provider] = new $provider_engine($provider_config, $auth);
}
return $this->posting_providers[$provider]->post($content);
}
/**
* Gets the list of supported login service providers.
*/
public static function getLoginProviders()
{
$login_providers = array('Google', 'Facebook');
return $login_providers;
}
/**
* Tries to authorize the user against the given provider.
*/
public function authorize($provider)
{
}
}
|
Remove id attribute from input fix | <?php
namespace Banklink\Request;
/**
* Generic request representation
*
* @author Roman Marintsenko <[email protected]>
* @since 31.10.2012
*/
abstract class Request
{
protected $requestUrl;
protected $requestData = array();
/**
* @param string $requestUrl
* @param array $requestData
*/
public function __construct($requestUrl, array $requestData)
{
$this->requestUrl = $requestUrl;
$this->requestData = $requestData;
}
/**
* Get request data which should be sent to desired bank
*
* @return array
*/
public function getRequestData()
{
return $this->requestData;
}
/**
* Generates HTML view for request <input> fields
* NB! This does not generate actual <form> element, it must be rendered manually
*
* @return string
*/
public function buildRequestHtml()
{
$output = '';
foreach ($this->requestData as $key => $value) {
$output .= sprintf('<input name="%s" value="%s" type="hidden" />', $key, $value);
}
return $output;
}
/**
* Get URL to where request data should be sent (most likely via POST method)
*
* @return string
*/
public function getRequestUrl()
{
return $this->requestUrl;
}
} | <?php
namespace Banklink\Request;
/**
* Generic request representation
*
* @author Roman Marintsenko <[email protected]>
* @since 31.10.2012
*/
abstract class Request
{
protected $requestUrl;
protected $requestData = array();
/**
* @param string $requestUrl
* @param array $requestData
*/
public function __construct($requestUrl, array $requestData)
{
$this->requestUrl = $requestUrl;
$this->requestData = $requestData;
}
/**
* Get request data which should be sent to desired bank
*
* @return array
*/
public function getRequestData()
{
return $this->requestData;
}
/**
* Generates HTML view for request <input> fields
* NB! This does not generate actual <form> element, it must be rendered manually
*
* @return string
*/
public function buildRequestHtml()
{
$output = '';
foreach ($this->requestData as $key => $value) {
$output .= sprintf('<input name="%s" value="%s" type="hidden" />', strtolower($key), $key, $value);
}
return $output;
}
/**
* Get URL to where request data should be sent (most likely via POST method)
*
* @return string
*/
public function getRequestUrl()
{
return $this->requestUrl;
}
} |
Add DOB field to User entity (JANUS-40)
* Fix DOB form definition. | <?php
namespace Ice\ExternalUserBundle\Form\Type;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UpdateFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array(
'description' => 'Email address. Must be unique.',
'required' => true,
))
->add('title', 'text', array(
'description' => 'Salutation.',
'required' => true,
))
->add('firstNames', 'text', array(
'description' => 'First name(s).',
'required' => true,
))
->add('middleNames', 'text', array(
'description' => 'Middle name(s).',
'required' => false,
))
->add('lastNames', 'text', array(
'description' => 'Last name.',
'required' => true,
))
->add('dob', 'birthday', array(
'widget' => 'single_text',
'description' => 'Date of birth.',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ice\ExternalUserBundle\Entity\User',
'csrf_protection' => false,
'validation_groups' => array('rest_update'),
));
}
public function getName()
{
return '';
}
}
| <?php
namespace Ice\ExternalUserBundle\Form\Type;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UpdateFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array(
'description' => 'Email address. Must be unique.',
'required' => true,
))
->add('title', 'text', array(
'description' => 'Salutation.',
'required' => true,
))
->add('firstNames', 'text', array(
'description' => 'First name(s).',
'required' => true,
))
->add('middleNames', 'text', array(
'description' => 'Middle name(s).',
'required' => false,
))
->add('lastNames', 'text', array(
'description' => 'Last name.',
'required' => true,
))
->add('dob', 'text', array(
'widget' => 'single_text',
'description' => 'Date of birth.',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ice\ExternalUserBundle\Entity\User',
'csrf_protection' => false,
'validation_groups' => array('rest_update'),
));
}
public function getName()
{
return '';
}
}
|
Revert "fix scroll low framerate"
This reverts commit 1ad82adaec7893b2478dd75de4d5a171ea58a015. | 'use strict';
$(function () {
// Handler for .ready() called.
$('[data-scrollToLink]').each(function (i, l) {
var $link = $(l);
$link.on('click', function () {
$('body').scrollTo('#' + $link.attr('data-scrollToLink'), 500, {offset: {top: -50} });
});
});
$("#owl-example").owlCarousel({
items: 7, //10 items above 1000px browser width
itemsDesktop: [1000, 5], //5 items between 1000px and 901px
itemsDesktopSmall: [900, 4], // betweem 900px and 601px
itemsTablet: [600, 2], //2 items between 600 and 0
itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
autoPlay: 3000,
stopOnHover: true,
lazyLoad: true,
afterInit: function () {
$("[title]").tooltip();
}
});
}); | 'use strict';
$(function () {
// Handler for .ready() called.
$('[data-scrollToLink]').each(function (i, l) {
var $link = $(l);
$link.on('click', function () {
$('body').scrollTo('#' + $link.attr('data-scrollToLink'), 500, {offset: {top: -50} });
});
});
$(window).on('scroll', function() {
window.requestAnimationFrame(scrollHandler);
});
$("#owl-example").owlCarousel({
items: 7, //10 items above 1000px browser width
itemsDesktop: [1000, 5], //5 items between 1000px and 901px
itemsDesktopSmall: [900, 4], // betweem 900px and 601px
itemsTablet: [600, 2], //2 items between 600 and 0
itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
autoPlay: 3000,
stopOnHover: true,
lazyLoad: true,
afterInit: function () {
$("[title]").tooltip();
}
});
}); |
Update line by default, compute x1 and x2. | ;(function() {
var isInited = false;
var marker = null;
SVG.extend(SVG.Element, {
connectable: function(options, elmTarget) {
if (elmTarget === undefined) {
elmTarget = options;
options = {};
}
var elmSource = this;
var line = options.container.line().attr("marker-end", "url(#triangle)");
var markers = options.markers;
// Source and target positions
var sPos = {};
var tPos = {};
function updateLine() {
sPos = elmSource.transform();
tPos = elmTarget.transform();
var x1 = sPos.x;
var y1 = sPos.y;
var x2 = tPos.x;
var y2 = tPos.y;
if (x2 > x1) {
x2 -= 30;
x1 += 25;
} else {
x1 -= 25;
x2 += 30;
}
line.attr({
x1: x1,
y1: y1,
x2: x2,
y2: y2
});
}
if (isInited === false) {
marker = markers.marker(10, 10);
marker.attr({
id: "triangle",
viewBox: "0 0 10 10",
refX: "0",
refY: "5",
markerUnits: "strokeWidth",
markerWidth: "4",
markerHeight: "5"
});
marker.path().attr({
d: "M 0 0 L 10 5 L 0 10 z"
});
isInited = true;
}
updateLine();
elmSource.dragmove = updateLine;
elmTarget.dragmove = updateLine;
return elmSource;
}
});
}).call(this);
| ;(function() {
var isInited = false;
var marker = null;
SVG.extend(SVG.Element, {
connectable: function(options, elmTarget) {
if (elmTarget === undefined) {
elmTarget = options;
options = {};
}
var elmSource = this;
var line = options.container.line();
var markers = options.markers;
// Source and target positions
var sPos = {};
var tPos = {};
function updateLine() {
sPos = elmSource.transform();
tPos = elmTarget.transform();
line.attr({
x1: sPos.x,
y1: sPos.y,
x2: tPos.x,
y2: tPos.y
});
}
if (isInited === false) {
marker = markers.marker();
marker.attr({
id: "triangle",
viewBox: "0 0 10 10",
refX: "0",
refY: "5",
markerUnits: "strokeWidth",
markerWidth: "4",
markerHeight: "5",
orient: "auto"
});
marker.path().attr({
d: "M 0 0 L 10 5 L 0 10 z"
});
isInited = true;
}
elmSource.dragmove = updateLine;
elmTarget.dragmove = updateLine;
return elmSource;
}
});
}).call(this);
|
Put a ref for item editor. | import { Component } from 'substance'
import CardComponent from '../shared/CardComponent'
export default class CollectionEditor extends Component {
getActionHandlers () {
return {
'remove-item': this._removeCollectionItem
}
}
render ($$) {
const model = this.props.model
let items = model.getItems()
let el = $$('div').addClass('sc-collection-editor')
items.forEach(item => {
let ItemEditor = this._getItemComponentClass(item)
el.append(
$$(CardComponent).append(
$$(ItemEditor, {
model: item,
// LEGACY
// TODO: try to get rid of this
node: item._node
}).ref(item.id)
)
)
})
return el
}
_getItemComponentClass (item) {
let ItemComponent = this.getComponent(item.type, true)
if (!ItemComponent) {
// try to find a component registered for a parent type
if (item._node) {
ItemComponent = this._getParentTypeComponent(item._node)
}
}
return ItemComponent || this.getComponent('entity')
}
_getParentTypeComponent (node) {
let superTypes = node.getSchema().getSuperTypes()
for (let type of superTypes) {
let NodeComponent = this.getComponent(type, true)
if (NodeComponent) return NodeComponent
}
}
_removeCollectionItem (item) {
const model = this.props.model
model.removeItem(item)
// TODO: this is only necessary for fake collection models
// i.e. models that are only virtual, which I'd like to avoid
this.rerender()
}
}
| import { Component } from 'substance'
import CardComponent from '../shared/CardComponent'
export default class CollectionEditor extends Component {
getActionHandlers () {
return {
'remove-item': this._removeCollectionItem
}
}
render ($$) {
const model = this.props.model
let items = model.getItems()
let el = $$('div').addClass('sc-collection-editor')
items.forEach(item => {
let ItemEditor = this._getItemComponentClass(item)
el.append(
$$(CardComponent).append(
$$(ItemEditor, {
model: item,
// LEGACY
// TODO: try to get rid of this
node: item._node
})
)
)
})
return el
}
_getItemComponentClass (item) {
let ItemComponent = this.getComponent(item.type, true)
if (!ItemComponent) {
// try to find a component registered for a parent type
if (item._node) {
ItemComponent = this._getParentTypeComponent(item._node)
}
}
return ItemComponent || this.getComponent('entity')
}
_getParentTypeComponent (node) {
let superTypes = node.getSchema().getSuperTypes()
for (let type of superTypes) {
let NodeComponent = this.getComponent(type, true)
if (NodeComponent) return NodeComponent
}
}
_removeCollectionItem (item) {
const model = this.props.model
model.removeItem(item)
// TODO: this is only necessary for fake collection models
// i.e. models that are only virtual, which I'd like to avoid
this.rerender()
}
}
|
Use HTTPS for JCenter repository | package com.kantenkugel.discordbot.versioncheck;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum RepoType
{
JCENTER("https://jcenter.bintray.com/", Pair.of("jcenter()", null), "bintray"),
MAVENCENTRAL("https://repo.maven.apache.org/maven2/", null, "central", "maven");
private final String repoBase;
private final Pair<String, String> gradleImport;
private final List<String> aliases;
RepoType(String repoBase, Pair<String, String> gradleImport, String... aliases)
{
this.repoBase = repoBase;
this.gradleImport = gradleImport;
this.aliases = Arrays.asList(aliases);
}
public String getRepoBase()
{
return repoBase;
}
public Pair<String, String> getGradleImport()
{
return gradleImport;
}
public List<String> getAliases()
{
return Collections.unmodifiableList(aliases);
}
public static RepoType fromString(String value)
{
value = value.toLowerCase();
for (RepoType repoType : RepoType.values())
{
if (repoType.toString().equals(value) || repoType.aliases.contains(value))
{
return repoType;
}
}
return null;
}
@Override
public String toString()
{
return name().toLowerCase();
}
}
| package com.kantenkugel.discordbot.versioncheck;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum RepoType
{
JCENTER("http://jcenter.bintray.com/", Pair.of("jcenter()", null), "bintray"),
MAVENCENTRAL("https://repo.maven.apache.org/maven2/", null, "central", "maven");
private final String repoBase;
private final Pair<String, String> gradleImport;
private final List<String> aliases;
RepoType(String repoBase, Pair<String, String> gradleImport, String... aliases)
{
this.repoBase = repoBase;
this.gradleImport = gradleImport;
this.aliases = Arrays.asList(aliases);
}
public String getRepoBase()
{
return repoBase;
}
public Pair<String, String> getGradleImport()
{
return gradleImport;
}
public List<String> getAliases()
{
return Collections.unmodifiableList(aliases);
}
public static RepoType fromString(String value)
{
value = value.toLowerCase();
for (RepoType repoType : RepoType.values())
{
if (repoType.toString().equals(value) || repoType.aliases.contains(value))
{
return repoType;
}
}
return null;
}
@Override
public String toString()
{
return name().toLowerCase();
}
}
|
Add title bar event listener | const settings = require('electron-settings')
var alpha = document.getElementById('alpha');
var remote = require('electron').remote;
// Listen for checkbox click
alpha.addEventListener('click', function(event) {
if (event.target.type === 'checkbox') {
if (event.target.parentElement.classList.contains('beta')) {
handleSelection(event.target)
}
}
})
document.getElementById("min-btn").addEventListener("click", function (e) {
console.log('btn clicked!')
var window = remote.getCurrentWindow();
window.minimize();
});
document.getElementById("exit-btn").addEventListener("click", function (e) {
console.log('btn clicked!')
var window = remote.getCurrentWindow();
window.close();
});
function handleSelection(beta) {
if (beta.checked) {
// Change section background when selected
beta.closest('.ui.message').classList.add('selected')
// Save cuerrent state
settings.set(beta.id, beta.id)
console.log(settings.getAll())
} else {
// Change background back to default when unselected
beta.closest('.ui.message').classList.remove('selected')
// save current state
settings.delete(beta.id)
console.log(settings.getAll())
}
// Hide input field if hideable
if (beta.parentElement.classList.contains('omega')) {
$(beta).parent().next().slideToggle("fast")
}
// Disable input field
$(beta).parent().next().toggleClass('disabled')
}
// Initial view based on last usage
console.log(settings.getAll())
var state = settings.getAll()
for (var i in state) {
document.getElementById(i).click()
}
| const settings = require('electron-settings')
var alpha = document.getElementById('alpha');
// Listen for checkbox click
alpha.addEventListener('click', function(event) {
if (event.target.type === 'checkbox') {
if (event.target.parentElement.classList.contains('beta')) {
handleSelection(event.target)
}
}
})
function handleSelection(beta) {
if (beta.checked) {
// Change section background when selected
beta.closest('.ui.message').classList.add('selected')
// Save cuerrent state
settings.set(beta.id, beta.id)
console.log(settings.getAll())
} else {
// Change background back to default when unselected
beta.closest('.ui.message').classList.remove('selected')
// save current state
settings.delete(beta.id)
console.log(settings.getAll())
}
// Hide input field if hideable
if (beta.parentElement.classList.contains('omega')) {
$(beta).parent().next().slideToggle("fast")
}
// Disable input field
$(beta).parent().next().toggleClass('disabled')
}
// Initial view based on last usage
console.log(settings.getAll())
var state = settings.getAll()
for (var i in state) {
document.getElementById(i).click()
}
|
Test port config definition for hapi-auth-hawk | /**
* Created by Omnius on 6/15/16.
*/
'use strict';
const Boom = require('boom');
exports.register = (server, options, next) => {
server.auth.strategy('hawk-login-auth-strategy', 'hawk', {
getCredentialsFunc: (sessionId, callback) => {
const redis = server.app.redis;
const methods = server.methods;
const dao = methods.dao;
const userCredentialDao = dao.userCredentialDao;
userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => {
if (err) {
server.log(err);
return callback(Boom.serverUnavailable(err));
}
if (!Object.keys(dbCredentials).length) {
return callback(Boom.forbidden());
}
const credentials = {
hawkSessionToken: dbCredentials.hawkSessionToken,
algorithm: dbCredentials.algorithm,
userId: dbCredentials.userId,
key: dbCredentials.key,
id: dbCredentials.id
};
return callback(null, credentials);
});
},
hawk: {
port: process.env.PORT || 8088
}
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
| /**
* Created by Omnius on 6/15/16.
*/
'use strict';
const Boom = require('boom');
exports.register = (server, options, next) => {
server.auth.strategy('hawk-login-auth-strategy', 'hawk', {
getCredentialsFunc: (sessionId, callback) => {
const redis = server.app.redis;
const methods = server.methods;
const dao = methods.dao;
const userCredentialDao = dao.userCredentialDao;
userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => {
if (err) {
server.log(err);
return callback(Boom.serverUnavailable(err));
}
if (!Object.keys(dbCredentials).length) {
return callback(Boom.forbidden());
}
const credentials = {
hawkSessionToken: dbCredentials.hawkSessionToken,
algorithm: dbCredentials.algorithm,
userId: dbCredentials.userId,
key: dbCredentials.key,
id: dbCredentials.id
};
return callback(null, credentials);
});
},
hawk: {
port: 443
}
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
[Glitch] Fix crash if a notification contains an unprocessed media attachment
Port 0c24c865b785a557f43125c976090e271247a2b1 to glitch-soc
Signed-off-by: Claire <[email protected]> | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import Icon from 'flavours/glitch/components/icon';
const filename = url => url.split('/').pop().split('#')[0].split('?')[0];
export default class AttachmentList extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.list.isRequired,
compact: PropTypes.bool,
};
render () {
const { media, compact } = this.props;
return (
<div className={classNames('attachment-list', { compact })}>
{!compact && (
<div className='attachment-list__icon'>
<Icon id='link' />
</div>
)}
<ul className='attachment-list__list'>
{media.map(attachment => {
const displayUrl = attachment.get('remote_url') || attachment.get('url');
return (
<li key={attachment.get('id')}>
<a href={displayUrl} target='_blank' rel='noopener noreferrer'>
{compact && <Icon id='link' />}
{compact && ' ' }
{displayUrl ? filename(displayUrl) : <FormattedMessage id='attachments_list.unprocessed' defaultMessage='(unprocessed)' />}
</a>
</li>
);
})}
</ul>
</div>
);
}
}
| import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Icon from 'flavours/glitch/components/icon';
const filename = url => url.split('/').pop().split('#')[0].split('?')[0];
export default class AttachmentList extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.list.isRequired,
compact: PropTypes.bool,
};
render () {
const { media, compact } = this.props;
if (compact) {
return (
<div className='attachment-list compact'>
<ul className='attachment-list__list'>
{media.map(attachment => {
const displayUrl = attachment.get('remote_url') || attachment.get('url');
return (
<li key={attachment.get('id')}>
<a href={displayUrl} target='_blank' rel='noopener noreferrer'><Icon id='link' /> {filename(displayUrl)}</a>
</li>
);
})}
</ul>
</div>
);
}
return (
<div className='attachment-list'>
<div className='attachment-list__icon'>
<Icon id='link' />
</div>
<ul className='attachment-list__list'>
{media.map(attachment => {
const displayUrl = attachment.get('remote_url') || attachment.get('url');
return (
<li key={attachment.get('id')}>
<a href={displayUrl} target='_blank' rel='noopener noreferrer'>{filename(displayUrl)}</a>
</li>
);
})}
</ul>
</div>
);
}
}
|
Fix issue where PHP would try to escape slashes in a string in json_encode | <?php
class FacebookJS {
private $_initOptions = array(
"status" => true,
"cookie" => true,
"oauth" => true,
"xfbml" => true
);
public function setAppId($appId){
if (!is_null($appId)){
$this->_initOptions["appid"] = $appId;
}
}
public function setChannelUrl($channelUrl = ''){
if (!empty($channelUrl)){
$this->_initOptions["channelURL"] = $channelUrl;
}
}
public function asyncScript(){
return "<script>\n"
. "(function(d){\n"
. "var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}\n"
. "js = d.createElement('script'); js.id = id; js.async = true;\n"
. "js.src = '//connect.facebook.net/en_US/all.js'\n;"
. " d.getElementsByTagName('head')[0].appendChild(js);\n"
. " }(document));\n"
. "</script>";
}
public function getFbInit(){
return "<div id='fb-root'></div>\n"
."<script>\n"
." window.fbAsyncInit = function() {\n"
."FB.init(\n"
. stripslashes(json_encode((object) $this->_initOptions))
. "\n);};</script>";
}
} | <?php
class FacebookJS {
private $_initOptions = array(
"status" => true,
"cookie" => true,
"oauth" => true,
"xfbml" => true
);
public function setAppId($appId){
if (!is_null($appId)){
$this->_initOptions["appid"] = $appId;
}
}
public function setChannelUrl($channelUrl){
if (!is_null($channelUrl)){
$this->_initOptions["channelURL"] = $channelUrl;
}
}
public function asyncScript(){
return "<script>\n"
. "(function(d){\n"
. "var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}\n"
. "js = d.createElement('script'); js.id = id; js.async = true;\n"
. "js.src = '//connect.facebook.net/en_US/all.js'\n;"
. " d.getElementsByTagName('head')[0].appendChild(js);\n"
. " }(document));\n"
. "</script>";
}
public function getFbInit(){
return "<div id='fb-root'></div>\n"
."<script>\n"
." window.fbAsyncInit = function() {\n"
."FB.init(\n"
. json_encode((object) $this->_initOptions)
. "\n);};</script>";
}
} |
Fix to work with Hive13
Reviewers: jeff, JamesGreenhill
Reviewed By: JamesGreenhill
Differential Revision: http://phabricator.local.disqus.net/D13528 | package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(TypeEntryShim.stringType);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
| package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(PrimitiveObjectInspectorUtils.stringTypeEntry);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
|
Use wrapped object for presenter | <?php
namespace Lio\Forum\Replies;
use Input;
use McCool\LaravelAutoPresenter\BasePresenter;
use Misd\Linkify\Linkify;
use Request;
class ReplyPresenter extends BasePresenter
{
public function url()
{
$slug = $this->getWrappedObject()->thread->slug;
$threadUrl = action('Forum\ForumThreadsController@getShowThread', $slug);
return $threadUrl . app(ReplyQueryStringGenerator::class)->generate($this->getWrappedObject());
}
public function created_ago()
{
return $this->getWrappedObject()->created_at->diffForHumans();
}
public function updated_ago()
{
return $this->getWrappedObject()->updated_at->diffForHumans();
}
public function body()
{
$body = $this->getWrappedObject()->body;
$body = $this->convertMarkdown($body);
$body = $this->formatGists($body);
$body = $this->linkify($body);
return $body;
}
private function convertMarkdown($content)
{
return app('Lio\Markdown\HtmlMarkdownConvertor')->convertMarkdownToHtml($content);
}
private function formatGists($content)
{
return app('Lio\Github\GistEmbedFormatter')->format($content);
}
private function linkify($content)
{
$linkify = new Linkify();
return $linkify->process($content);
}
}
| <?php
namespace Lio\Forum\Replies;
use App;
use Input;
use McCool\LaravelAutoPresenter\BasePresenter;
use Request;
class ReplyPresenter extends BasePresenter
{
public function url()
{
$slug = $this->thread->slug;
$threadUrl = action('Forum\ForumThreadsController@getShowThread', [$slug]);
return $threadUrl . \App::make('Lio\Forum\Replies\ReplyQueryStringGenerator')->generate($this->getWrappedObject());
}
public function created_ago()
{
return $this->getWrappedObject()->created_at->diffForHumans();
}
public function updated_ago()
{
return $this->getWrappedObject()->updated_at->diffForHumans();
}
public function body()
{
$body = $this->getWrappedObject()->body;
$body = $this->convertMarkdown($body);
$body = $this->formatGists($body);
$body = $this->linkify($body);
return $body;
}
// ------------------- //
private function convertMarkdown($content)
{
return App::make('Lio\Markdown\HtmlMarkdownConvertor')->convertMarkdownToHtml($content);
}
private function formatGists($content)
{
return App::make('Lio\Github\GistEmbedFormatter')->format($content);
}
private function linkify($content)
{
$linkify = new \Misd\Linkify\Linkify();
return $linkify->process($content);
}
}
|
Add 'One For All' Queue Id (Valorant) | package no.stelar7.api.r4j.basic.constants.types.val;
import no.stelar7.api.r4j.basic.constants.types.CodedEnum;
import java.util.Optional;
import java.util.stream.Stream;
public enum GameQueueType implements CodedEnum<GameQueueType>
{
COMPETITIVE("competitive"),
DEATHMATCH("deathmatch"),
SPIKE_RUSH("spikerush"),
UNRATED("unrated"),
CUSTOM_GAME(""),
TOURNAMENT_MODE("tournamentmode"),
ONE_FOR_ALL("onefa"),
;
private final String queue;
/**
* Constructor for MapType
*
* @param code the mapId
*/
GameQueueType(final String code)
{
this.queue = code;
}
/**
* Gets from code.
*
* @param mapId the map id
* @return the from code
*/
public Optional<GameQueueType> getFromCode(final String mapId)
{
return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
}
@Override
public String prettyName()
{
switch (this)
{
default:
return "This enum does not have a pretty name";
}
}
/**
* Gets id.
*
* @return the id
*/
public String getId()
{
return this.queue;
}
/**
* Used internaly in the api...
*
* @return the value
*/
public String getValue()
{
return getId();
}
}
| package no.stelar7.api.r4j.basic.constants.types.val;
import no.stelar7.api.r4j.basic.constants.types.CodedEnum;
import java.util.Optional;
import java.util.stream.Stream;
public enum GameQueueType implements CodedEnum<GameQueueType>
{
COMPETITIVE("competitive"),
DEATHMATCH("deathmatch"),
SPIKE_RUSH("spikerush"),
UNRATED("unrated"),
CUSTOM_GAME(""),
TOURNAMENT_MODE("tournamentmode"),
;
private final String queue;
/**
* Constructor for MapType
*
* @param code the mapId
*/
GameQueueType(final String code)
{
this.queue = code;
}
/**
* Gets from code.
*
* @param mapId the map id
* @return the from code
*/
public Optional<GameQueueType> getFromCode(final String mapId)
{
return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
}
@Override
public String prettyName()
{
switch (this)
{
default:
return "This enum does not have a pretty name";
}
}
/**
* Gets id.
*
* @return the id
*/
public String getId()
{
return this.queue;
}
/**
* Used internaly in the api...
*
* @return the value
*/
public String getValue()
{
return getId();
}
}
|
Add chalk to file to copie | module.exports = function(grunt) {
var config = {
copy: {
src: {
files: [{
expand: true,
src: [
'node_modules/socket.io/**/*',
'node_modules/fast-http/**/*',
'node_modules/opn/**/*',
'node_modules/chalk/**/*',
'*.html',
'source/',
'vendor/**/*.*',
'package.json',
'.gitignore',
'server.js'
],
dest: 'dist/'
}]
}
},
useminPrepare: {
html: '*.html'
},
usemin: {
html: 'dist/*.html'
},
uglify: {
options : {
mangle : false
}
},
uncss: {
dist: {
files: {
'dist/vendor/css/styles.css': ['dist/index.html']
}
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'dist/index.html',
'dist/404.html': 'dist/404.html',
'dist/500.html': 'dist/500.html'
}
}
}
};
grunt.initConfig(config);
// Load all Grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('default', ['copy', 'useminPrepare', 'concat', 'cssmin', 'uglify', 'usemin', 'htmlmin', 'uncss']);
};
| module.exports = function(grunt) {
var config = {
copy: {
src: {
files: [{
expand: true,
src: [
'node_modules/socket.io/**/*',
'node_modules/fast-http/**/*',
'node_modules/opn/**/*',
'*.html',
'source/',
'vendor/**/*.*',
'package.json',
'.gitignore',
'server.js'
],
dest: 'dist/'
}]
}
},
useminPrepare: {
html: '*.html'
},
usemin: {
html: 'dist/*.html'
},
uglify: {
options : {
mangle : false
}
},
uncss: {
dist: {
files: {
'dist/vendor/css/styles.css': ['dist/index.html']
}
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'dist/index.html',
'dist/404.html': 'dist/404.html',
'dist/500.html': 'dist/500.html'
}
}
}
};
grunt.initConfig(config);
// Load all Grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('default', ['copy', 'useminPrepare', 'concat', 'cssmin', 'uglify', 'usemin', 'htmlmin', 'uncss']);
};
|
Fix bug with automatic date transformations | /**
* convert json dates to date objects
* for all requests using the $http service
*
* @return callback for app.config()
*/
define([], function () {
'use strict';
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;
function convertDateStringsToDates(input) {
// Ignore things that aren't objects.
if (typeof input !== "object") {
return input;
}
for (var key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
var value = input[key];
var match;
// Check for string properties which look like dates.
if (typeof value === "string" && (match = value.match(regexIso8601))) {
if (!match[1] || !match[2] || !match[3] || !match[4] || !match[5] || !match[6]) {
// Require at least year mont day hour minute second
continue;
}
var milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
} else if (typeof value === "object") {
// Recurse into object
convertDateStringsToDates(value);
}
}
}
return function($httpProvider) {
$httpProvider.defaults.transformResponse.push(function(responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
};
});
| /**
* convert json dates to date objects
* for all requests using the $http service
*
* @return callback for app.config()
*/
define([], function () {
'use strict';
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;
function convertDateStringsToDates(input) {
// Ignore things that aren't objects.
if (typeof input !== "object") {
return input;
}
for (var key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
var value = input[key];
var match;
// Check for string properties which look like dates.
if (typeof value === "string" && (match = value.match(regexIso8601))) {
var milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
} else if (typeof value === "object") {
// Recurse into object
convertDateStringsToDates(value);
}
}
}
return function($httpProvider) {
$httpProvider.defaults.transformResponse.push(function(responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
};
});
|
Allow runtime toggling of mocks | var config = require('../lib/config'),
cors = require('../lib/cors'),
fs = require('fs');
var paths = [],
len = 0;
exports.init = function() {
if (config.mocksEnabled) {
console.log("Mock server enabled");
}
var pathSource = require('./paths');
for (var name in pathSource) {
paths.push({
regex: new RegExp(name),
source: pathSource[name]
});
}
len = paths.length;
};
exports.provider = function(req, res, next) {
if (config.mocksEnabled) {
var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?');
for (var i = 0; i < len; i++) {
var path = paths[i];
if (path.regex.test(replaceUrl)) {
console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback'));
cors.applyCORS(req.headers.host, res);
if (req.method !== 'HEAD') {
req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking
}
if (typeof path.source === 'function') {
res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1)));
} else {
res.sendfile(__dirname + '/' + path.source);
}
return;
}
}
}
next();
};
| var config = require('../lib/config'),
cors = require('../lib/cors'),
fs = require('fs');
var paths = [],
len = 0;
exports.init = function() {
if (config.mocksEnabled) {
console.log("Mock server enabled");
var pathSource = require('./paths');
for (var name in pathSource) {
paths.push({
regex: new RegExp(name),
source: pathSource[name]
});
}
len = paths.length;
}
};
exports.provider = function(req, res, next) {
if (config.mocksEnabled) {
var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?');
for (var i = 0; i < len; i++) {
var path = paths[i];
if (path.regex.test(replaceUrl)) {
console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback'));
cors.applyCORS(req.headers.host, res);
if (req.method !== 'HEAD') {
req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking
}
if (typeof path.source === 'function') {
res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1)));
} else {
res.sendfile(__dirname + '/' + path.source);
}
return;
}
}
}
next();
};
|
Add filter by state (SAAS-635) | 'use strict';
(function() {
angular.module('ncsaas')
.service('customersService', ['baseServiceClass', '$q', 'agreementsService', customersService]);
function customersService(baseServiceClass, $q, agreementsService) {
var ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init:function() {
this._super();
this.endpoint = '/customers/';
},
getPersonalOrFirstCustomer: function(username) {
var deferred = $q.defer();
/*jshint camelcase: false */
this.getList().then(
function(customers) {
for(var i = 0; i < customers.length; i++) {
if (customers[i].name === username) {
deferred.resolve(customers[i]);
}
}
if (customers.length !== 0) {
deferred.resolve(customers[0]);
} else {
deferred.resolve(undefined);
}
}
);
return deferred.promise;
},
getCurrentPlan: function(customer) {
var deferred = $q.defer();
agreementsService.getList({customer: customer.uuid, state: 'active'}).then(function(response) {
if (response.length > 0) {
deferred.resolve(response[0]);
} else {
deferred.reject();
}
});
return deferred.promise;
}
});
return new ServiceClass();
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('customersService', ['baseServiceClass', '$q', 'agreementsService', customersService]);
function customersService(baseServiceClass, $q, agreementsService) {
var ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init:function() {
this._super();
this.endpoint = '/customers/';
},
getPersonalOrFirstCustomer: function(username) {
var deferred = $q.defer();
/*jshint camelcase: false */
this.getList().then(
function(customers) {
for(var i = 0; i < customers.length; i++) {
if (customers[i].name === username) {
deferred.resolve(customers[i]);
}
}
if (customers.length !== 0) {
deferred.resolve(customers[0]);
} else {
deferred.resolve(undefined);
}
}
);
return deferred.promise;
},
getCurrentPlan: function(customer) {
var deferred = $q.defer(),
error = true;
agreementsService.getList({customer: customer.uuid}).then(function(response) {
if (response) {
for (var i = 0; i < response.length; i++) {
if (response[i].customer == customer.url && response[i].state == 'active') {
deferred.resolve(response[i]);
error = false;
break;
}
}
}
if (error) {
deferred.reject();
}
});
return deferred.promise;
}
});
return new ServiceClass();
}
})();
|
Add try accept block for bs4 features | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
import bs4
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
try:
s = BeautifulSoup(handle, features='html5lib')
except bs4.FeatureNotFound:
s = BeautifulSoup(handle, features='html.parser')
return s
if __name__ == '__main__':
pass
| from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
|
Use the Controllers namespace rather than Http | <?php
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\API';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$directories = new \DirectoryIterator(app_path('API'));
foreach ($directories as $directory) {
if (! $directory->isDir() || $directory->isDot() || $directory->isFile()) {
continue;
}
$router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Controllers', 'prefix' => $directory.'/api'], function ($router) use ($directory) {
require app_path('API/'.$directory.'/routes.php');
});
}
}
}
| <?php
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\API';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$directories = new \DirectoryIterator(app_path('API'));
foreach ($directories as $directory) {
if (! $directory->isDir() || $directory->isDot() || $directory->isFile()) {
continue;
}
$router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Http', 'prefix' => $directory.'/api'], function ($router) use ($directory) {
require app_path('API/'.$directory.'/routes.php');
});
}
}
}
|
Change support requirement to key | <?php
namespace LinkValue\MobileNotifBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Collect all mobile clients and store it to application domain.
*/
class MobileClientCompilerPass implements CompilerPassInterface
{
/**
* @{inherit_doc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('link_value_mobile_notif.mobile_notif')) {
return;
}
$definition = $container->getDefinition('link_value_mobile_notif.mobile_notif');
$tagged = $container->findTaggedServiceIds('link_value_mobile_notif.mobile_client');
foreach ($tagged as $serviceId => $attributes) {
foreach ($attributes as $attribute) {
if (empty($attribute['key'])) {
throw new \InvalidArgumentException(sprintf('"link_value_mobile_notif.mobile_client" tag must define "key" key.'));
}
$definition->addMethodCall('addMobileClient', array(
$attribute['key'],
new Reference($serviceId),
));
}
}
}
}
| <?php
namespace LinkValue\MobileNotifBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Collect all mobile clients and store it to application domain.
*/
class MobileClientCompilerPass implements CompilerPassInterface
{
/**
* @{inherit_doc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('link_value_mobile_notif.mobile_notif')) {
return;
}
$definition = $container->getDefinition('link_value_mobile_notif.mobile_notif');
$tagged = $container->findTaggedServiceIds('link_value_mobile_notif.mobile_client');
foreach ($tagged as $serviceId => $attributes) {
foreach ($attributes as $attribute) {
if (empty($attribute['support'])) {
throw new \InvalidArgumentException(sprintf('"link_value_mobile_notif.mobile_client" tag must define "support" key.'));
}
$definition->addMethodCall('addMobileClient', array(
$attribute['support'],
new Reference($serviceId),
));
}
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.