text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix status codes of handled responses | from flask import Flask, url_for, Response, json, request
class MonitorApp(object):
def __init__(self, monitor):
self.app = Flask(__name__)
self.app.monitor = monitor
self.setup()
def setup(self):
@self.app.route('/anomaly', methods = ['POST'])
def api_anomaly():
data = request.json
if request.headers['Content-Type'] == 'application/json':
success = self.app.monitor.process_anomaly_data(data)
return self.handle_response(success, data)
else:
return Response("Unsupported media type\n" + data, status=415)
@self.app.route('/monitor', methods = ['POST'])
def api_monitor():
data = request.json
if request.headers['Content-Type'] == 'application/json':
success = self.app.monitor.process_monitor_flows(data)
return self.handle_response(success, data)
else:
return Response("Unsupported media type\n" + data, status=415)
def handle_response(self, success, data):
json_data = json.dumps(data)
if success:
return Response("OK\n" + json_data, status=200)
else:
return Response("BAD REQUEST\n" + json_data, status=400)
| from flask import Flask, url_for, Response, json, request
class MonitorApp(object):
def __init__(self, monitor):
self.app = Flask(__name__)
self.app.monitor = monitor
self.setup()
def setup(self):
@self.app.route('/anomaly', methods = ['POST'])
def api_anomaly():
data = request.json
if request.headers['Content-Type'] == 'application/json':
success = self.app.monitor.process_anomaly_data(data)
return handle_response(success)
else:
return Response("Unsupported media type\n" + data, status=415)
@self.app.route('/monitor', methods = ['POST'])
def api_monitor():
data = request.json
if request.headers['Content-Type'] == 'application/json':
success = self.app.monitor.process_monitor_flows(data)
return handle_response(success)
else:
return Response("Unsupported media type\n" + data, status=415)
def handle_response(self, success):
if success:
return Response("OK\n" + data, status=status)
else:
return Response("BAD REQUEST\n" + data, status=status)
|
Use XDG directory for caching | import os
from catchy import HttpCacher, xdg_directory_cacher, NoCachingStrategy
from .installer import Installer
from .sources import PackageSourceFetcher
from .providers import CachingPackageProvider
from .deployer import PackageDeployer
def create(caching):
if not caching.enabled:
cacher = NoCachingStrategy()
elif caching.http_cache_url is not None:
# TODO: add DirectoryCacher in front of HttpCacher
cacher = HttpCacher(caching.http_cache_url, caching.http_cache_key)
else:
cacher = xdg_directory_cacher("whack/builds")
package_source_fetcher = PackageSourceFetcher()
package_provider = CachingPackageProvider(cacher)
deployer = PackageDeployer()
installer = Installer(package_source_fetcher, package_provider, deployer)
return Operations(installer)
class Operations(object):
def __init__(self, installer):
self._installer = installer
def install(self, package_name, install_dir, params):
return self._installer.install(package_name, install_dir, params)
def build(self, package_name, install_dir, params):
return self._installer.build(package_name, install_dir, params)
def install(package, install_dir, caching, params):
operations = create(caching)
operations.install(package, install_dir, params)
def build(command, package, install_dir, caching, params):
operations = create(caching)
operations.build(package, install_dir, params)
| import os
from catchy import HttpCacher, DirectoryCacher, NoCachingStrategy
from .installer import Installer
from .sources import PackageSourceFetcher
from .providers import CachingPackageProvider
from .deployer import PackageDeployer
def create(caching):
if not caching.enabled:
cacher = NoCachingStrategy()
elif caching.http_cache_url is not None:
# TODO: add DirectoryCacher in front of HttpCacher
cacher = HttpCacher(caching.http_cache_url, caching.http_cache_key)
else:
cacher = DirectoryCacher(os.path.expanduser("~/.cache/whack/builds"))
package_source_fetcher = PackageSourceFetcher()
package_provider = CachingPackageProvider(cacher)
deployer = PackageDeployer()
installer = Installer(package_source_fetcher, package_provider, deployer)
return Operations(installer)
class Operations(object):
def __init__(self, installer):
self._installer = installer
def install(self, package_name, install_dir, params):
return self._installer.install(package_name, install_dir, params)
def build(self, package_name, install_dir, params):
return self._installer.build(package_name, install_dir, params)
def install(package, install_dir, caching, params):
operations = create(caching)
operations.install(package, install_dir, params)
def build(command, package, install_dir, caching, params):
operations = create(caching)
operations.build(package, install_dir, params)
|
Change Default Setting For User_Id_Type
According to the default setting in Laravel | <?php
return [
/*
|--------------------------------------------------------------------------
| Users Model
|--------------------------------------------------------------------------
|
| We need to know which model are you using to authenticate your users,
| so we can run the autorization rules on them. It is set to whatever
| setting you have in your auth config file.
|
*/
'user_model' => Config::get('auth.model'),
/*
|--------------------------------------------------------------------------
| Users ID Type
|--------------------------------------------------------------------------
|
| Here you can select if you are using a UUID string or an incremenenting
| integer (Laravel default). The possible options are
|
| - "uuid": sets the foreign key to string('user_id' '36')
| - everything else: sets the foreign key to integer('user_id')->unsigned()
|
*/
'user_id_type' => 'id',
/*
|--------------------------------------------------------------------------
| Database tables
|--------------------------------------------------------------------------
|
| Here you can rename the 4 table names that are used in the migrations, if
| you do not like the defaults or you are using them for something else.
|
| You also need to specify the 'users' table name, since it is used in one
| of the models to define the relationship. It is set to whatever
| setting you have in your auth config file.
|
*/
'tables' => [
'roles' => 'roles',
'permissions' => 'permissions',
'permission_role' => 'permission_role',
'role_user' => 'role_user',
'users' => Config::get('auth.table'),
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Users Model
|--------------------------------------------------------------------------
|
| We need to know which model are you using to authenticate your users,
| so we can run the autorization rules on them. It is set to whatever
| setting you have in your auth config file.
|
*/
'user_model' => Config::get('auth.model'),
/*
|--------------------------------------------------------------------------
| Users ID Type
|--------------------------------------------------------------------------
|
| Here you can select if you are using a UUID string or an incremenenting
| integer (Laravel default). The possible options are
|
| - "uuid": sets the foreign key to string('user_id' '36')
| - everything else: sets the foreign key to integer('user_id')->unsigned()
|
*/
'user_id_type' => 'uuid',
/*
|--------------------------------------------------------------------------
| Database tables
|--------------------------------------------------------------------------
|
| Here you can rename the 4 table names that are used in the migrations, if
| you do not like the defaults or you are using them for something else.
|
| You also need to specify the 'users' table name, since it is used in one
| of the models to define the relationship. It is set to whatever
| setting you have in your auth config file.
|
*/
'tables' => [
'roles' => 'roles',
'permissions' => 'permissions',
'permission_role' => 'permission_role',
'role_user' => 'role_user',
'users' => Config::get('auth.table'),
],
];
|
Increment rc version to rc3 | from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
pytest.main(self.test_args)
setup(
name="gevent-socketio",
version="0.3.5-rc3",
description=(
"SocketIO server based on the Gevent pywsgi server, "
"a Python network library"),
author="Jeffrey Gelens",
author_email="[email protected]",
maintainer="Alexandre Bourget",
maintainer_email="[email protected]",
license="BSD",
url="https://github.com/abourget/gevent-socketio",
download_url="https://github.com/abourget/gevent-socketio",
install_requires=("gevent-websocket",),
setup_requires=('versiontools >= 1.7'),
cmdclass = {'test': PyTest},
tests_require=['pytest', 'mock'],
packages=find_packages(exclude=["examples", "tests"]),
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
],
)
| from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
pytest.main(self.test_args)
setup(
name="gevent-socketio",
version="0.3.5-rc2",
description=(
"SocketIO server based on the Gevent pywsgi server, "
"a Python network library"),
author="Jeffrey Gelens",
author_email="[email protected]",
maintainer="Alexandre Bourget",
maintainer_email="[email protected]",
license="BSD",
url="https://github.com/abourget/gevent-socketio",
download_url="https://github.com/abourget/gevent-socketio",
install_requires=("gevent-websocket",),
setup_requires=('versiontools >= 1.7'),
cmdclass = {'test': PyTest},
tests_require=['pytest', 'mock'],
packages=find_packages(exclude=["examples", "tests"]),
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
],
)
|
Use hash_equals for constant-time string comparison | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Crypt;
/**
* Tools for cryptography
*/
class Utils
{
/**
* Compare two strings to avoid timing attacks
*
* C function memcmp() internally used by PHP, exits as soon as a difference
* is found in the two buffers. That makes possible of leaking
* timing information useful to an attacker attempting to iteratively guess
* the unknown string (e.g. password).
* The length will leak.
*
* @param string $expected
* @param string $actual
* @return bool
*/
public static function compareStrings($expected, $actual)
{
$expected = (string) $expected;
$actual = (string) $actual;
if (function_exists('hash_equals')) {
return hash_equals($expected, $actual);
}
$lenExpected = strlen($expected);
$lenActual = strlen($actual);
$len = min($lenExpected, $lenActual);
$result = 0;
for ($i = 0; $i < $len; $i++) {
$result |= ord($expected[$i]) ^ ord($actual[$i]);
}
$result |= $lenExpected ^ $lenActual;
return ($result === 0);
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Crypt;
/**
* Tools for cryptography
*/
class Utils
{
/**
* Compare two strings to avoid timing attacks
*
* C function memcmp() internally used by PHP, exits as soon as a difference
* is found in the two buffers. That makes possible of leaking
* timing information useful to an attacker attempting to iteratively guess
* the unknown string (e.g. password).
*
* @param string $expected
* @param string $actual
* @return bool
*/
public static function compareStrings($expected, $actual)
{
$expected = (string) $expected;
$actual = (string) $actual;
$lenExpected = strlen($expected);
$lenActual = strlen($actual);
$len = min($lenExpected, $lenActual);
$result = 0;
for ($i = 0; $i < $len; $i++) {
$result |= ord($expected[$i]) ^ ord($actual[$i]);
}
$result |= $lenExpected ^ $lenActual;
return ($result === 0);
}
}
|
Change laravel 5 to Suyabay Reloaded | <!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 96px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">SUYABAY RELOADED</div>
</div>
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 96px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Laravel 5</div>
</div>
</div>
</body>
</html>
|
Fix version is not removed correctly
When executed by ./gradlew bootRun, it works,
but when executed by java -jar, it doesn't work
because of duplicate separator(/). | package com.example.spring.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.resource.VersionPathStrategy;
@Slf4j
public class MiddleVersionPathStrategy implements VersionPathStrategy {
private final String prefix;
private final String version;
public MiddleVersionPathStrategy(String prefix, String version) {
this.prefix = prefix;
this.version = version;
}
@Override
public String extractVersion(String requestPath) {
if (requestPath.startsWith(this.prefix)) {
String prefixRemoved = requestPath.substring(this.prefix.length());
if (prefixRemoved.startsWith(this.version)) {
return this.version;
}
}
return null;
}
@Override
public String removeVersion(String requestPath, String version) {
return this.prefix + requestPath.substring((this.prefix + this.version + "/").length());
}
@Override
public String addVersion(String path, String version) {
log.info("addVersion: {}", path);
if (path.startsWith(".")) {
return path;
} else {
String p = path;
if (p.startsWith("/")) {
p = p.substring(1);
}
if (p.startsWith(this.prefix)) {
return this.prefix + this.version + "/" + p.substring(this.prefix.length());
} else {
return path;
}
}
}
}
| package com.example.spring.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.resource.VersionPathStrategy;
@Slf4j
public class MiddleVersionPathStrategy implements VersionPathStrategy {
private final String prefix;
private final String version;
public MiddleVersionPathStrategy(String prefix, String version) {
this.prefix = prefix;
this.version = version;
}
@Override
public String extractVersion(String requestPath) {
if (requestPath.startsWith(this.prefix)) {
String prefixRemoved = requestPath.substring(this.prefix.length());
if (prefixRemoved.startsWith(this.version)) {
return this.version;
}
}
return null;
}
@Override
public String removeVersion(String requestPath, String version) {
return this.prefix + requestPath.substring(this.prefix.length() + this.version.length());
}
@Override
public String addVersion(String path, String version) {
log.info("addVersion: {}", path);
if (path.startsWith(".")) {
return path;
} else {
String p = path;
if (p.startsWith("/")) {
p = p.substring(1);
}
if (p.startsWith(this.prefix)) {
return this.prefix + this.version + "/" + p.substring(this.prefix.length());
} else {
return path;
}
}
}
}
|
Exit as soon as KeyboardInterrupt catched | # coding: utf-8
import sys
import errno
import logging
from .base import Gor
from tornado import gen, ioloop, queues
import contextlib
from tornado.stack_context import StackContext
@contextlib.contextmanager
def die_on_error():
try:
yield
except Exception:
logging.error("exception in asynchronous operation", exc_info=True)
sys.exit(1)
class TornadoGor(Gor):
def __init__(self, *args, **kwargs):
super(TornadoGor, self).__init__(*args, **kwargs)
self.q = queues.Queue()
self.concurrency = kwargs.get('concurrency', 2)
@gen.coroutine
def _process(self):
line = yield self.q.get()
try:
msg = self.parse_message(line)
if msg:
self.emit(msg, line)
finally:
self.q.task_done()
@gen.coroutine
def _worker(self):
while True:
yield self._process()
@gen.coroutine
def _run(self):
for _ in range(self.concurrency):
self._worker()
while True:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
ioloop.IOLoop.instance().stop()
break
self.q.put(line)
yield
def run(self):
with StackContext(die_on_error):
self.io_loop = ioloop.IOLoop.current()
self.io_loop.run_sync(self._run)
sys.exit(errno.EINTR)
| # coding: utf-8
import os, sys
from .base import Gor
from tornado import gen, ioloop, queues
class TornadoGor(Gor):
def __init__(self, *args, **kwargs):
super(TornadoGor, self).__init__(*args, **kwargs)
self.q = queues.Queue()
self.concurrency = kwargs.get('concurrency', 2)
@gen.coroutine
def _process(self):
line = yield self.q.get()
try:
msg = self.parse_message(line)
if msg:
self.emit(msg, line)
finally:
self.q.task_done()
@gen.coroutine
def _worker(self):
while True:
yield self._process()
@gen.coroutine
def _run(self):
for _ in range(self.concurrency):
self._worker()
while True:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
try:
sys.exit(0)
except SystemExit:
os._exit(0)
self.q.put(line)
yield
def run(self):
self.io_loop = ioloop.IOLoop.current()
self.io_loop.run_sync(self._run)
|
Add class method to check if PC is a Mac | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_is_macintosh()
def select_applications(self):
"""
Allow user to select an application they want
not to appear on the Dock
"""
pass
def load_dodger_filer(self):
"""
Load the file to modify for the application
chosen by the user in `select_applications`
The file to be loaded for is `info.plist`
"""
pass
def dodge_application(self):
"""
Remive the application from the Dock
"""
pass
@classmethod
def pc_is_macintosh(cls):
"""
Check if it is an `Apple Computer` i.e a Mac
@return bool
"""
system = platform.system().lower()
sys_version = int((platform.mac_ver())[0].replace(".", ""))
allowed_version = int(cls.allowed_version.replace(".", ""))
if (system == "darwin") and (sys_version >= allowed_version):
return True
else:
print("\nSorry :(")
print("FAILED. OsX-dock-dodger is only applicable to computers " +
"running OS X {} or higher".format(cls.allowed_version))
return False
dodge = OSXDodger("/Applications/")
dodge.load_applications()
| import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
pass
def select_applications(self):
"""
Allow user to select an application they want
not to appear on the Dock
"""
pass
def load_dodger_filer(self):
"""
Load the file to modify for the application
chosen by the user in `select_applications`
The file to be loaded for is `info.plist`
"""
pass
def dodge_application(self):
"""
Remive the application from the Dock
"""
pass
@classmethod
def pc_is_macintosh(cls):
"""
Check if it is an `Apple Computer` i.e a Mac
@return bool
"""
system = platform.system().lower()
sys_version = int((platform.mac_ver())[0].replace(".", ""))
allowed_version = int(cls.allowed_version.replace(".", ""))
if (system == "darwin") and (sys_version >= allowed_version):
return True
else:
print("\nSorry :(")
print("FAILED. OsX-dock-dodger is only applicable to computers " +
"running OS X {} or higher".format(cls.allowed_version))
return False
dodge = OSXDodger("/Applications/")
dodge.pc_is_macintosh()
|
Fix classname for filter list | var React = require('react');
var classNames = require('classnames');
var FilterItem = React.createClass({
propTypes: {
selected: React.PropTypes.bool,
href: React.PropTypes.string,
className: React.PropTypes.string,
count: React.PropTypes.number,
onClick: React.PropTypes.func
},
getDefaultProps: function() {
return {
selected: false,
href: '#'
};
},
onClick: function(e) {
if (!this.props.onClick) {
return;
}
e.preventDefault();
this.props.onClick();
},
render: function() {
var className = classNames('filter-item', this.props.className, {
selected: this.props.selected
});
var count = this.props.count;
var inner = '';
if (typeof count !== 'undefined') {
inner = <span className="count">{count}</span>;
}
return (
<li>
<a className={className} onClick={this.onClick}>
{inner}
{this.props.children}
</a>
</li>
);
}
});
var FilterList = React.createClass({
render: function() {
return (
<ul className="filter-list">
{this.props.children}
</ul>
);
}
});
module.exports = FilterList;
module.exports.Item = FilterItem;
| var React = require('react');
var classNames = require('classnames');
var FilterItem = React.createClass({
propTypes: {
selected: React.PropTypes.bool,
href: React.PropTypes.string,
className: React.PropTypes.string,
count: React.PropTypes.number,
onClick: React.PropTypes.func
},
getDefaultProps: function() {
return {
selected: false,
href: '#'
};
},
onClick: function(e) {
if (!this.props.onClick) {
return;
}
e.preventDefault();
this.props.onClick();
},
render: function() {
var className = classNames('filter-item', this.props.className, {
selected: this.props.selected
});
var count = this.props.count;
var inner = '';
if (typeof count !== 'undefined') {
inner = <span className="count">{count}</span>;
}
return (
<li className={className}>
{inner}
<a onClick={this.onClick}>{this.props.children}</a>
</li>
);
}
});
var FilterList = React.createClass({
render: function() {
return (
<ul className="filter-list">
{this.props.children}
</ul>
);
}
});
module.exports = FilterList;
module.exports.Item = FilterItem;
|
Fix :bug: with assets watch deletion. | import collections
import os
import re
import time
def watch(folders, on_change, pattern=None, sleep_time=0.1):
pattern = re.compile(pattern) if pattern else None
watched = collections.defaultdict(lambda: -1)
def walk():
walked = []
for folder in folders:
for current, _, files, in os.walk(folder):
for f in files:
if pattern and not pattern.search(f):
continue
path = os.path.join(current, f)
info = os.stat(path)
new_time = info.st_mtime
if new_time > watched[path] > 0:
on_change(path, new_time, False)
watched[path] = new_time
walked.append(path)
# Look for deleted files
for w in [x for x in watched.keys() if x not in walked]:
del watched[w]
on_change(w, -1, True)
while True:
walk()
time.sleep(sleep_time)
| import collections
import os
import re
import time
def watch(folders, on_change, pattern=None, sleep_time=0.1):
pattern = re.compile(pattern) if pattern else None
watched = collections.defaultdict(lambda: -1)
def walk():
walked = []
for folder in folders:
for current, _, files, in os.walk(folder):
for f in files:
if pattern and not pattern.search(f):
continue
path = os.path.join(current, f)
info = os.stat(path)
new_time = info.st_mtime
if new_time > watched[path] > 0:
on_change(path, new_time, False)
watched[path] = new_time
walked.append(path)
# Look for deleted files
for w in (x for x in watched.keys() if x not in walked):
del watched[w]
on_change(w, -1, True)
while True:
walk()
time.sleep(sleep_time)
|
Remove the Membership special case. We want everything correlated. | # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
ctype = ContentType.objects.get_for_model(instance.sender)
defaults = {
'timestamp': timestamp,
'julian': timestamp.timetuple().tm_yday,
'year': timestamp.year,
'month': timestamp.month,
'day': timestamp.day,
}
correlation, created = self.get_or_create(
content_type=ctype,
object_id=instance._get_pk_val(),
identifier=instance._meta.model_name,
date_field=attribute,
defaults=defaults
)
for key, value in defaults.iteritems():
setattr(correlation, key, value)
correlation.save()
return
def get_query_set(self):
qs = super(CorrelationManager, self).get_query_set()
return qs #.prefetch_related('content_object')
def today(self):
qs = self.get_query_set()
return qs.filter(julian=date.today().timetuple().tm_yday)
| # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
# Membership is a special case. Since most groups are static
# (or non-generational), the date the group is formed is the same as
# the date its members joined. So if those two values are equal, stop
# the process.
if not timestamp or (instance._meta.model_name == 'membership'
and instance.started == instance.group.started):
return
ctype = ContentType.objects.get_for_model(instance.sender)
defaults = {
'timestamp': timestamp,
'julian': timestamp.timetuple().tm_yday,
'year': timestamp.year,
'month': timestamp.month,
'day': timestamp.day,
}
correlation, created = self.get_or_create(
content_type=ctype,
object_id=instance._get_pk_val(),
identifier=instance._meta.model_name,
date_field=attribute,
defaults=defaults
)
for key, value in defaults.iteritems():
setattr(correlation, key, value)
correlation.save()
return
def get_query_set(self):
qs = super(CorrelationManager, self).get_query_set()
return qs #.prefetch_related('content_object')
def today(self):
qs = self.get_query_set()
return qs.filter(julian=date.today().timetuple().tm_yday)
|
Correct type hinting for $input_headers. | <?php
namespace Meng\Soap;
class Interpreter
{
private $soap;
private $lastFunction;
private $lastArguments;
public function __construct($wsdl, array $options = [])
{
$this->soap = new Soap($wsdl, $options);
}
/**
* Interpret SOAP method and arguments to a request envelope.
*
* @param string $function_name
* @param array $arguments
* @param array $options
* @param mixed $input_headers
* @return array
*/
public function request($function_name, array $arguments, array $options = null, $input_headers = null)
{
$this->soap->feedRequest($function_name, $arguments, $options, $input_headers);
$this->lastFunction = $function_name;
$this->lastArguments = $arguments;
return [
'Endpoint' => $this->soap->getEndpoint(),
'SoapAction' => $this->soap->getSoapAction(),
'Version' => $this->soap->getVersion(),
'Envelope' => $this->soap->getRequest()
];
}
/**
* Interpret a response envelope to PHP objects.
*
* @param string $response
* @param array $output_headers
* @return mixed
*/
public function response($response, array &$output_headers = null)
{
$this->soap->feedResponse($response);
$response = $this->soap->__soapCall($this->lastFunction, $this->lastArguments, null, null, $output_headers);
$this->soap->feedResponse(null);
return $response;
}
} | <?php
namespace Meng\Soap;
class Interpreter
{
private $soap;
private $lastFunction;
private $lastArguments;
public function __construct($wsdl, array $options = [])
{
$this->soap = new Soap($wsdl, $options);
}
/**
* Interpret SOAP method and arguments to a request envelope.
*
* @param string $function_name
* @param array $arguments
* @param array $options
* @param array $input_headers
* @return array
*/
public function request($function_name, array $arguments, array $options = null, $input_headers = null)
{
$this->soap->feedRequest($function_name, $arguments, $options, $input_headers);
$this->lastFunction = $function_name;
$this->lastArguments = $arguments;
return [
'Endpoint' => $this->soap->getEndpoint(),
'SoapAction' => $this->soap->getSoapAction(),
'Version' => $this->soap->getVersion(),
'Envelope' => $this->soap->getRequest()
];
}
/**
* Interpret a response envelope to PHP objects.
*
* @param string $response
* @param array $output_headers
* @return mixed
*/
public function response($response, array &$output_headers = null)
{
$this->soap->feedResponse($response);
$response = $this->soap->__soapCall($this->lastFunction, $this->lastArguments, null, null, $output_headers);
$this->soap->feedResponse(null);
return $response;
}
} |
Allow null as defining class.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1736 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | /*
* Copyright (C) 2008, 2010 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
if ((declaringClass == null && field.declaringClass != null)
|| (declaringClass != null && field.declaringClass == null)) {
return false;
}
return name.equals(field.getName())
&& (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
}
return false;
}
public int hashCode() {
return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
}
public String toString() {
return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
}
} | /*
* Copyright (C) 2008 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
return name.equals(field.getName())
&& declaringClass.equals(field.getDeclaringClass());
}
return false;
}
public int hashCode() {
return name.hashCode() ^ declaringClass.hashCode();
}
public String toString() {
return declaringClass.getName() + "[" + name + "]";
}
} |
Fix error when tiles aren't selected | (() => {
const tools = [];
DTile.Tool = class DTileTool {
static register() {
tools.push(new this());
}
static get allTools() { return tools; }
static get store() { return DTile.store; }
static get state() { return DTileTool.store.getState(); }
get currentMap() {
const state = DTileTool.state;
return state.entities.maps[state.ui.currentMapId].present;
}
get currentLayerIndex() {
return DTileTool.state.ui.currentLayerIndex;
}
get currentLayer() {
return this.currentMap.layers[this.currentLayerIndex];
}
get layerAsTileArea() {
if (!this.currentLayer) return;
const map = this.currentMap;
return {
width: map.width,
height: map.height,
tiles: this.currentLayer.tiles
};
}
get tileArea() {
return DTileTool.state.ui.currentTileArea || {
width: 0,
height: 0,
tiles: []
};
}
getTileMeta(tilesetId, tileId) {
if (tilesetId < 0 || tileId < 0) return {};
return DTileTool.state.entities.tilesets[tilesetId].tileMeta[tileId] || {};
}
onMove() {}
onTap() {}
onTrack() {}
};
})();
| (() => {
const tools = [];
DTile.Tool = class DTileTool {
static register() {
tools.push(new this());
}
static get allTools() { return tools; }
static get store() { return DTile.store; }
static get state() { return DTileTool.store.getState(); }
get currentMap() {
const state = DTileTool.state;
return state.entities.maps[state.ui.currentMapId].present;
}
get currentLayerIndex() {
return DTileTool.state.ui.currentLayerIndex;
}
get currentLayer() {
return this.currentMap.layers[this.currentLayerIndex];
}
get layerAsTileArea() {
if (!this.currentLayer) return;
const map = this.currentMap;
return {
width: map.width,
height: map.height,
tiles: this.currentLayer.tiles
};
}
get tileArea() {
return DTileTool.state.ui.currentTileArea;
}
getTileMeta(tilesetId, tileId) {
if (tilesetId < 0 || tileId < 0) return {};
return DTileTool.state.entities.tilesets[tilesetId].tileMeta[tileId] || {};
}
onMove() {}
onTap() {}
onTrack() {}
};
})();
|
Move the CURRENT_USER_STORAGE_KEY constant to SessionManager | 'use strict';
var React = require('react-native');
var Constants = require('./constants');
var { AsyncStorage } = React;
const CURRENT_USER_STORAGE_KEY = 'currentUser';
var SessionManager = {
login: function(user) {
return new Promise(function(resolve, reject) {
var url = Constants.APP_SERVER_HOST + '/users/register';
fetch(url, {
method: 'post',
body: JSON.stringify({user: user}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => {
if(response.ok) {
return response.json();
} else {
reject(new Error(JSON.parse(response._bodyText).error)); //FixIt - Shoudn't be using the quasi private method
}
})
.then(response => {
var user = {
name: response.user.name,
email: response.user.email,
avatar: response.user.gravatar_url
}
console.log(user);
AsyncStorage
.setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
.catch(error => reject(error));
});
},
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
resolve(JSON.parse(value));
});
});
}
};
module.exports = SessionManager;
| 'use strict';
var React = require('react-native');
var Constants = require('./constants');
var { AsyncStorage } = React;
var SessionManager = {
login: function(user) {
return new Promise(function(resolve, reject) {
var url = Constants.APP_SERVER_HOST + '/users/register';
fetch(url, {
method: 'post',
body: JSON.stringify({user: user}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => {
if(response.ok) {
return response.json();
} else {
reject(new Error(JSON.parse(response._bodyText).error)); //FixIt - Shoudn't be using the quasi private method
}
})
.then(response => {
var user = {
name: response.user.name,
email: response.user.email,
avatar: response.user.gravatar_url
}
console.log(user);
AsyncStorage
.setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
.catch(error => reject(error));
});
},
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
resolve(JSON.parse(value));
});
});
}
};
module.exports = SessionManager;
|
Add log info in webpack to troubleshoot Travis issue | // Karma configuration
module.exports = function karmaConfig(config) {
config.set({
client: {
captureConsole: true
},
frameworks: ['mocha'],
files: [
'./test/*/**.js'
],
// Preprocess matching files before serving them to the browser
// Available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// Add webpack as preprocessor
'./src/**/*.js': ['webpack', 'sourcemap'],
'./test/**/*.js': ['webpack', 'sourcemap']
},
// Test results reporter to use
// Available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots'],
logLevel: config.LOG_INFO,
browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['PhantomJS'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
// Tell Karma with webpack config to use
// eslint-disable-next-line global-require
webpack: require('./webpack/configs/config.test'),
// webpackMiddleware: {
// noInfo: true
// },
//
// webpackServer: {
// noInfo: true
// },
// Tell karma all the plugins we're going to be using to prevent warnings
plugins: [
'karma-mocha',
'karma-webpack',
// launchers
// 'karma-chrome-launcher',
'karma-phantomjs-launcher',
// preprocessors
// 'karma-coverage',
'karma-sourcemap-loader'
]
});
};
| // Karma configuration
module.exports = function karmaConfig(config) {
config.set({
client: {
captureConsole: true
},
frameworks: ['mocha'],
files: [
'./test/*/**.js'
],
// Preprocess matching files before serving them to the browser
// Available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// Add webpack as preprocessor
'./src/**/*.js': ['webpack', 'sourcemap'],
'./test/**/*.js': ['webpack', 'sourcemap']
},
// Test results reporter to use
// Available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots'],
logLevel: config.LOG_ERROR,
browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['PhantomJS'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
// Tell Karma with webpack config to use
// eslint-disable-next-line global-require
webpack: require('./webpack/configs/config.test'),
webpackMiddleware: {
noInfo: true
},
webpackServer: {
noInfo: true
},
// Tell karma all the plugins we're going to be using to prevent warnings
plugins: [
'karma-mocha',
'karma-webpack',
// launchers
// 'karma-chrome-launcher',
'karma-phantomjs-launcher',
// preprocessors
// 'karma-coverage',
'karma-sourcemap-loader'
]
});
};
|
Add slug transform from name. | "use strict";
const
_ = require('lodash'),
xss = require('xss'),
router = require('koa-router')(),
auth = require('../auth/auth.service'),
params = require('../lib/params'),
Term = require('../model/term.model');
_.map([
{ path: '/categories', type: 'category' },
{ path: '/tags', type: 'tag' },
{ path: '/menus', type: 'menu' }
], item => {
router.get(item.path, getByType(item.type));
router.post(item.path, auth.isAuthenticated, params({
body: 'name'
}), addByType(item.type));
});
function getByType (type) {
return async function (ctx) {
const terms = await Term.find({ taxonomy: type });
ctx.body = { value: terms };
};
}
function addByType (type) {
return async function (ctx) {
const params = ctx.request.body;
try {
await Term.create({
name: params.name,
slug: params.slug || params.name.toLowerCase().replace(/\s/g, '-'),
description: params.description,
taxonomy: type
});
ctx.body = { value: 'success' };
} catch (err) {
ctx.throw(400, err.message);
}
}
}
module.exports = router; | "use strict";
const
_ = require('lodash'),
xss = require('xss'),
router = require('koa-router')(),
auth = require('../auth/auth.service'),
params = require('../lib/params'),
Term = require('../model/term.model');
_.map([
{ path: '/categories', type: 'category' },
{ path: '/tags', type: 'tag' },
{ path: '/menus', type: 'menu' }
], item => {
router.get(item.path, getByType(item.type));
router.post(item.path, auth.isAuthenticated, params({
body: 'name'
}), addByType(item.type));
});
function getByType (type) {
return async function (ctx) {
const terms = await Term.find({ taxonomy: type });
ctx.body = { value: terms };
};
}
function addByType (type) {
return async function (ctx) {
const params = ctx.request.body;
try {
await Term.create({
name: params.name,
slug: params.slug || params.name,
description: params.description,
taxonomy: type
});
ctx.body = { value: 'success' };
} catch (err) {
ctx.throw(400, err.message);
}
}
}
module.exports = router; |
Update Tapastic plugin for 1.7.9 compatibility | <?php
class Af_Tapastic extends Plugin {
function about() {
return array(0.1, "Fetch image from comics hosted at tapastic.com", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (strpos($article["link"], "tapastic.com") !== FALSE) {
if (strpos($article["plugin_data"], "tapastic,$owner_uid:") === FALSE) {
$doc = new DOMDocument();
$doc->loadHTML(fetch_file_contents($article["link"]));
if ($doc) {
$xpath = new DOMXPath($doc);
$imgnode = $xpath->query('//img[@class="art-image"]')->item(0);
if (is_null($imgnode)) {
return $article;
}
$article["content"] = $doc->saveHTML($imgnode);
$article["plugin_data"] = "tapastic,$owner_uid:" . $article["plugin_data"];
}
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
function api_version() {
return 2;
}
}
?>
| <?php
class Af_Tapastic extends Plugin {
function about() {
return array(0.1, "Fetch image from comics hosted at tapastic.com", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (strpos($article["link"], "tapastic.com") !== FALSE) {
if (strpos($article["plugin_data"], "tapastic,$owner_uid:") === FALSE) {
$doc = new DOMDocument();
$doc->loadHTML(fetch_file_contents($article["link"]));
if ($doc) {
$xpath = new DOMXPath($doc);
$imgnode = $xpath->query('//img[@class="art-image"]')->item(0);
if (is_null($imgnode)) {
return $article;
}
$article["content"] = $doc->saveHTML($imgnode);
$article["plugin_data"] = "tapastic,$owner_uid:" . $article["plugin_data"];
}
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
}
?>
|
Define class with `class`, not `def`
I don't make calsses much, can you tell? | from __future__ import print_function
from twisted.internet import reactor, protocol, threads, defer
from twisted.protocols.basic import LineReceiver
from nethud.proto.client import NethackFactory
class TelnetConnection(LineReceiver):
def __init__(self, users):
self.users = users
self.uname = ''
def connectionLost(self, reason):
if NethackFactory.client:
NethackFactory.client.deassoc_client(self.uname)
if self.uname in self.users:
del self.users[self.uname]
self.uname = ''
print(reason)
def lineReceived(self, line):
msg_split = line.split()
if msg_split[0] == 'AUTH':
if len(msg_split) != 2:
self.sendLine("ERR 406 Invalid Parameters.")
return
self.handle_auth(msg_split[1])
elif msg_split[0] == 'QUIT':
self.transport.loseConnection()
else:
self.sendLine("ERR 452 Invalid Command")
def handle_auth(self, uname):
self.users[uname] = self
self.uname = uname
if NethackFactory.client:
NethackFactory.client.assoc_client(uname, self)
class TelnetFactory(protocol.Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return TelnetConnection(users = self.users)
| from __future__ import print_function
from twisted.internet import reactor, protocol, threads, defer
from twisted.protocols.basic import LineReceiver
from nethud.proto.client import NethackFactory
class TelnetConnection(LineReceiver):
def __init__(self, users):
self.users = users
self.uname = ''
def connectionLost(self, reason):
if NethackFactory.client:
NethackFactory.client.deassoc_client(self.uname)
if self.uname in self.users:
del self.users[self.uname]
self.uname = ''
print(reason)
def lineReceived(self, line):
msg_split = line.split()
if msg_split[0] == 'AUTH':
if len(msg_split) != 2:
self.sendLine("ERR 406 Invalid Parameters.")
return
self.handle_auth(msg_split[1])
elif msg_split[0] == 'QUIT':
self.transport.loseConnection()
else:
self.sendLine("ERR 452 Invalid Command")
def handle_auth(self, uname):
self.users[uname] = self
self.uname = uname
if NethackFactory.client:
NethackFactory.client.assoc_client(uname, self)
def TelnetFactory(protocol.Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return TelnetConnection(users = self.users)
|
Fix install_requires to limit Django version <2.0. | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-djaken',
version='2.0.1',
packages=['djaken'],
include_package_data=True,
license='BSD License',
description='Djaken is a complete web-based notes application for Django.',
long_description=README,
url='https://github.com/ethoms/django-djaken/',
author='Euan Thoms',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['Django>=1.9,<2.0','docutils>=0.12', 'pycrypto>=2.6', ],
keywords='django notes markdown encrypt',
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-djaken',
version='2.0.1',
packages=['djaken'],
include_package_data=True,
license='BSD License',
description='Djaken is a complete web-based notes application for Django.',
long_description=README,
url='https://github.com/ethoms/django-djaken/',
author='Euan Thoms',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['Django>=1.9','docutils>=0.12', 'pycrypto>=2.6', ],
keywords='django notes markdown encrypt',
)
|
Fix month in list name. | angular.module('shoppingList').controller(
'ShoppingListController', ['$scope', '$window', function($scope, $window) {
'use strict';
var blankItem = {
name: '',
category: '',
quantity: '',
unit: '',
notes: ''
};
$scope.categories = [
'Baking',
'Beverages',
'Bread/Bakery',
'Canned Goods',
'Cereal/Breakfast',
'Condiments',
'Dairy',
'Deli',
'Frozen Foods',
'Meats',
'Non-Food',
'Pasta/Rice',
'Produce',
'Snacks',
'Spices'
];
$scope.categories.sort();
$scope.isEditing = true;
var now = new Date();
$scope.name = 'Shopping ' + (now.getMonth() + 1) + '/' + now.getDate() + '/' + now.getFullYear();
$scope.listItems = [
angular.copy(blankItem)
];
$scope.addItem = function() {
$scope.listItems.push(angular.copy(blankItem));
};
$scope.removeItem = function(index) {
if ($window.confirm('Delete this item?')) {
$scope.listItems.splice(index, 1);
}
};
$scope.setEditMode = function(bool) {
$scope.isEditing = !!bool;
};
}]
);
| angular.module('shoppingList').controller(
'ShoppingListController', ['$scope', '$window', function($scope, $window) {
'use strict';
var blankItem = {
name: '',
category: '',
quantity: '',
unit: '',
notes: ''
};
$scope.categories = [
'Baking',
'Beverages',
'Bread/Bakery',
'Canned Goods',
'Cereal/Breakfast',
'Condiments',
'Dairy',
'Deli',
'Frozen Foods',
'Meats',
'Non-Food',
'Pasta/Rice',
'Produce',
'Snacks',
'Spices'
];
$scope.categories.sort();
$scope.isEditing = true;
var now = new Date();
$scope.name = 'Shopping ' + now.getMonth() + '/' + now.getDate() + '/' + now.getFullYear();
$scope.listItems = [
angular.copy(blankItem)
];
$scope.addItem = function() {
$scope.listItems.push(angular.copy(blankItem));
};
$scope.removeItem = function(index) {
if ($window.confirm('Delete this item?')) {
$scope.listItems.splice(index, 1);
}
};
$scope.setEditMode = function(bool) {
$scope.isEditing = !!bool;
};
}]
);
|
Change default zoom level to 8. | var app = angular.module('am');
app.directive('googleMap', ['$timeout', function($timeout) {
return {
scope: {
'center': '='
},
controller: function() {
this.map = undefined;
},
compile: function(el, attrs) {
return {
pre: function(scope, el, attrs, ctrl) {
var div, map, center = scope.center;
div = angular.element('<div>').css({width: '100%', height: '100%'});
el.prepend(div);
map = new google.maps.Map(div[0], {
zoom: 9,
center: new google.maps.LatLng(center.lat, center.lng),
disableDefaultUI: true,
zoomControl: true
});
ctrl.map = map;
},
post: function(scope, el, attrs, ctrl) {
var map = ctrl.map;
google.maps.event.addListener(map, 'dragend', function() {
var center = map.getCenter();
$timeout(function() {
scope.center = {
lat: center.lat(),
lng: center.lng()
};
});
});
}
};
}
};
}]);
| var app = angular.module('am');
app.directive('googleMap', ['$timeout', function($timeout) {
return {
scope: {
'center': '='
},
controller: function() {
this.map = undefined;
},
compile: function(el, attrs) {
return {
pre: function(scope, el, attrs, ctrl) {
var div, map, center = scope.center;
div = angular.element('<div>').css({width: '100%', height: '100%'});
el.prepend(div);
map = new google.maps.Map(div[0], {
zoom: 8,
center: new google.maps.LatLng(center.lat, center.lng),
disableDefaultUI: true,
zoomControl: true
});
ctrl.map = map;
},
post: function(scope, el, attrs, ctrl) {
var map = ctrl.map;
google.maps.event.addListener(map, 'dragend', function() {
var center = map.getCenter();
$timeout(function() {
scope.center = {
lat: center.lat(),
lng: center.lng()
};
});
});
}
};
}
};
}]);
|
Introduce new Detections stream type | package stroom.data.store.impl.fs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
class StreamTypeExtensions {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
private static final Map<String, String> EXTENSION_MAP = new HashMap<>();
static {
EXTENSION_MAP.put("Manifest", "mf");
EXTENSION_MAP.put("Raw Events", "revt");
EXTENSION_MAP.put("Raw Reference", "rref");
EXTENSION_MAP.put("Events", "evt");
EXTENSION_MAP.put("Reference", "ref");
EXTENSION_MAP.put("Test Events", "tevt");
EXTENSION_MAP.put("Test Reference", "tref");
EXTENSION_MAP.put("Segment Index", "seg");
EXTENSION_MAP.put("Boundary Index", "bdy");
EXTENSION_MAP.put("Meta Data", "meta");
EXTENSION_MAP.put("Error", "err");
EXTENSION_MAP.put("Context", "ctx");
EXTENSION_MAP.put("Detections", "dtxn");
}
static String getExtension(final String streamType) {
String extension = EXTENSION_MAP.get(streamType);
if (extension == null) {
LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
extension = "dat";
}
return extension;
}
}
| package stroom.data.store.impl.fs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
class StreamTypeExtensions {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
private static final Map<String, String> EXTENSION_MAP = new HashMap<>();
static {
EXTENSION_MAP.put("Manifest", "mf");
EXTENSION_MAP.put("Raw Events", "revt");
EXTENSION_MAP.put("Raw Reference", "rref");
EXTENSION_MAP.put("Events", "evt");
EXTENSION_MAP.put("Reference", "ref");
EXTENSION_MAP.put("Test Events", "tevt");
EXTENSION_MAP.put("Test Reference", "tref");
EXTENSION_MAP.put("Segment Index", "seg");
EXTENSION_MAP.put("Boundary Index", "bdy");
EXTENSION_MAP.put("Meta Data", "meta");
EXTENSION_MAP.put("Error", "err");
EXTENSION_MAP.put("Context", "ctx");
}
static String getExtension(final String streamType) {
String extension = EXTENSION_MAP.get(streamType);
if (extension == null) {
LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
extension = "dat";
}
return extension;
}
}
|
Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook | import inspect
import socket
import sys
from io import BytesIO, StringIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import eye, PY2
from birdseye.server import app
fake_stream = BytesIO if PY2 else StringIO
thread_proxies = {}
def stream_proxy(original):
def p():
frame = inspect.currentframe()
while frame:
if frame.f_code == ThreadingMixIn.process_request_thread.__code__:
return fake_stream()
frame = frame.f_back
return thread_proxies.get(currentThread().ident,
original)
return LocalProxy(p)
sys.stderr = stream_proxy(sys.stderr)
sys.stdout = stream_proxy(sys.stdout)
def run_server():
thread_proxies[currentThread().ident] = fake_stream()
try:
app.run(
debug=True,
port=7777,
host='127.0.0.1',
use_reloader=False,
)
except socket.error:
pass
def cell_magic(_line, cell):
Thread(target=run_server).start()
call_id = eye.exec_ipython_cell(cell)
html = HTML('<iframe '
' src="http://localhost:7777/ipython_call/%s"' % call_id +
' style="width: 100%"'
' height="500"'
'/>')
# noinspection PyTypeChecker
display(html)
| import inspect
import socket
import sys
from io import BytesIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import server, eye
thread_proxies = {}
def stream_proxy(original):
def p():
frame = inspect.currentframe()
while frame:
if frame.f_code == ThreadingMixIn.process_request_thread.__code__:
return BytesIO()
frame = frame.f_back
return thread_proxies.get(currentThread().ident,
original)
return LocalProxy(p)
sys.stderr = stream_proxy(sys.stderr)
sys.stdout = stream_proxy(sys.stdout)
def run_server():
thread_proxies[currentThread().ident] = BytesIO()
try:
server.main([])
except socket.error:
pass
def cell_magic(_line, cell):
Thread(target=run_server).start()
call_id = eye.exec_ipython_cell(cell)
html = HTML('<iframe '
' src="http://localhost:7777/ipython_call/%s"' % call_id +
' style="width: 100%"'
' height="500"'
'/>')
# noinspection PyTypeChecker
display(html)
|
Fix header nav selected key issue | import React from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon, Popover } from 'antd'
import { Link } from 'dva/router'
import uri from 'utils/uri'
import { l } from 'utils/localization'
import styles from './Header.less'
import { classnames } from 'utils'
function createMenu(items, handleClick, mode = 'horizontal') {
let current = uri.current().split('/')[1]
return (
<Menu onClick={handleClick} selectedKeys={[current]} mode={mode}>
{items.map(item => (<Menu.Item key={item.path.split('/')[1]}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))}
</Menu>
)
}
const HeaderNav = React.createClass({
getInitialState() {
return {
current: uri.current().split('/')[1],
}
},
handleClick(e) {
this.setState({
current: e.key,
})
},
render() {
return (<div>
<div className={styles.headerNavItems}>
{createMenu(this.props.items, this.handleClick)}
</div>
<Popover content={createMenu(this.props.items, this.handleClick, 'inline')} trigger="click" overlayClassName={styles.headerNavMenus}>
<div className={classnames(styles.headerNavDropdown, this.props.barClassName)}>
<Icon type="bars" />
</div>
</Popover>
</div>
)
},
})
export default HeaderNav
| import React from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon, Popover } from 'antd'
import { Link } from 'dva/router'
import uri from 'utils/uri'
import { l } from 'utils/localization'
import styles from './Header.less'
import { classnames } from 'utils'
function createMenu(items, handleClick, mode = 'horizontal') {
let current = uri.current().split('/')[1]
return (
<Menu onClick={handleClick} selectedKeys={[current]} mode={mode}>
{items.map(item => (<Menu.Item key={item.name}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))}
</Menu>
)
}
const HeaderNav = React.createClass({
getInitialState() {
return {
current: uri.current().split('/')[1],
}
},
handleClick(e) {
this.setState({
current: e.key,
})
},
render() {
return (<div>
<div className={styles.headerNavItems}>
{createMenu(this.props.items, this.handleClick)}
</div>
<Popover content={createMenu(this.props.items, this.handleClick, 'inline')} trigger="click" overlayClassName={styles.headerNavMenus}>
<div className={classnames(styles.headerNavDropdown, this.props.barClassName)}>
<Icon type="bars" />
</div>
</Popover>
</div>
)
},
})
export default HeaderNav
|
Include "filecache" and "alembicarchive" selection. | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
## Description
"""
Define file for Cache Manager Tool.
"""
#-------------------------------------------------------------------------------
# Define Cache Nodes to deal with this script
CACHE_NODES = [
"file",
"filecache",
"alembic",
"alembicarchive"
]
# Define Houdini Environment Varialbes. This will also be used for displaying.
ENV_TYPE = [
'-',
'HIP',
'JOB'
]
# Define Header Items
CACHE_ITEMS = [
{ "key": "name", "display": "Name", "width": 100, "visible": False},
{ "key": "node", "display": "Node", "width": 200, "visible": True},
{ "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True},
{ "key": "srcStatus", "display": "Status", "width": 50, "visible": True},
{ "key": "env", "display": "Env", "width": 50, "visible": False},
{ "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False},
{ "key": "color", "display": "Color", "width": None, "visible": False}
]
# Menu Items
MENU_HELP = "Help"
MENU_RELOAD = "Reload"
#-------------------------------------------------------------------------------
# EOF
#-------------------------------------------------------------------------------
| # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
## Description
"""
Define file for Cache Manager Tool.
"""
#-------------------------------------------------------------------------------
# Define Cache Nodes to deal with this script
CACHE_NODES = [
"file",
"filecache"
"alembic",
# "alembicarchive"
]
# Define Houdini Environment Varialbes. This will also be used for displaying.
ENV_TYPE = [
'-',
'HIP',
'JOB'
]
# Define Header Items
CACHE_ITEMS = [
{ "key": "name", "display": "Name", "width": 100, "visible": False},
{ "key": "node", "display": "Node", "width": 200, "visible": True},
{ "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True},
{ "key": "srcStatus", "display": "Status", "width": 50, "visible": True},
{ "key": "env", "display": "Env", "width": 50, "visible": False},
{ "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False},
{ "key": "color", "display": "Color", "width": None, "visible": False}
]
# Menu Items
MENU_HELP = "Help"
MENU_RELOAD = "Reload"
#-------------------------------------------------------------------------------
# EOF
#-------------------------------------------------------------------------------
|
Improve method name for search input change | import { updateQuery, fetchQuery, addSearch, isSearching } from '../actions';
import { search } from '../actions/SearchAPI';
import Icon from './Icon';
export default class SearchForm extends React.Component {
constructor() {
super()
this._debouncedSearch = _.debounce(this._debouncedSearch, 300)
}
render() {
return (
<form onSubmit={e => e.preventDefault()}>
<div className='relative'>
<input onChange={this._handleInputChange.bind(this)}
id='Search'
type='text'
autoComplete='off'
placeholder='Search Wikipedia'
defaultValue={this.props.Search.queries[this.props.index]}
className='field border-bottom search__input'/>
<div className='search-icon'><Icon size="18px" icon="search" fill={'silver'} /></div>
</div>
</form>
);
}
_handleInputChange(e) {
e.persist()
this._debouncedSearch(e.target.value.trim())
}
_debouncedSearch(query) {
const {dispatch, index} = this.props;
dispatch(updateQuery(index, query))
dispatch(isSearching(true))
if (query) {
search(query, this._handleResults.bind(this));
} else {
this._handleResults([])
}
}
_handleResults(results) {
this.props.dispatch(addSearch(results, this.props.index))
this.props.dispatch(isSearching(false))
}
}
| import { updateQuery, fetchQuery, addSearch, isSearching } from '../actions';
import { search } from '../actions/SearchAPI';
import Icon from './Icon';
export default class SearchForm extends React.Component {
constructor() {
super()
this._debouncedSearch = _.debounce(this._debouncedSearch, 300)
}
render() {
return (
<form onSubmit={e => e.preventDefault()}>
<div className='relative'>
<input onChange={this._handleKeyUp.bind(this)}
id='Search'
type='text'
autoComplete='off'
placeholder='Search Wikipedia'
defaultValue={this.props.Search.queries[this.props.index]}
className='field border-bottom search__input'/>
<div className='search-icon'><Icon size="18px" icon="search" fill={'silver'} /></div>
</div>
</form>
);
}
_handleKeyUp(e) {
e.persist()
this._debouncedSearch(e.target.value.trim())
}
_debouncedSearch(query) {
const {dispatch, index} = this.props;
dispatch(updateQuery(index, query))
dispatch(isSearching(true))
if (query) {
search(query, this._handleResults.bind(this));
} else {
this._handleResults([])
}
}
_handleResults(results) {
this.props.dispatch(addSearch(results, this.props.index))
this.props.dispatch(isSearching(false))
}
}
|
Change encoding of URL parser | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible urls. If a url is found then
route the url to a corresponding module to handle.
"""
def __init__(self, *args, **kwargs):
"""Constructor."""
Module.__init__(self, kwargs=kwargs)
self.url_patterns = [
Twitter,
Youtube,
Bitly,
]
self.url_pattern = re.compile("http://(.*?)")
def _register_events(self):
self.add_event('pubmsg', 'parse_message')
def parse_message(self, event):
nick = event['nick']
# make sure the message contains a url before checking
# the other handlers patterns
try:
for handler in self.url_patterns:
m = handler.pattern.search(event['message'])
if m:
handler_instance = handler()
msg = handler_instance.handle(event=event, match=m)
if msg:
self.server.privmsg(event['target'], msg)
break
except:
print "<<Error>> in Urlparser"
print traceback.print_exc()
| from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible urls. If a url is found then
route the url to a corresponding module to handle.
"""
def __init__(self, *args, **kwargs):
"""Constructor."""
Module.__init__(self, kwargs=kwargs)
self.url_patterns = [
Twitter,
Youtube,
Bitly,
]
self.url_pattern = re.compile("http://(.*?)")
def _register_events(self):
self.add_event('pubmsg', 'parse_message')
def parse_message(self, event):
nick = event['nick']
# make sure the message contains a url before checking
# the other handlers patterns
try:
for handler in self.url_patterns:
m = handler.pattern.search(event['message'])
if m:
handler_instance = handler()
msg = handler_instance.handle(event=event, match=m)
if msg:
self.server.privmsg(event['target'], msg.encode('utf-8'))
break
except:
print "<<Error>> in Urlparser"
print traceback.print_exc()
|
Fix fetch keys refresh condition | /*
* Copyright 2018 Expedia Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import axios from 'axios';
import {observable, action} from 'mobx';
import {ErrorHandlingStore} from '../../../../stores/errorHandlingStore';
export class SearchableKeysStore extends ErrorHandlingStore {
@observable keys = {};
@action fetchKeys() {
if (Object.keys(this.keys).length > 3) { // traceId, serviceName and operationName are default
return; // don't re-trigger if other keys are available
}
axios
.get('/api/traces/searchableKeys')
.then((response) => {
this.keys = response.data;
if (this.keys.error) {
this.keys.error.values = ['true', 'false'];
}
})
.catch((result) => {
SearchableKeysStore.handleError(result);
}
);
}
}
export default new SearchableKeysStore();
| /*
* Copyright 2018 Expedia Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import axios from 'axios';
import {observable, action} from 'mobx';
import {ErrorHandlingStore} from '../../../../stores/errorHandlingStore';
export class SearchableKeysStore extends ErrorHandlingStore {
@observable keys = {};
@action fetchKeys() {
if (Object.keys(this.keys).length > 2) { // serviceName and operationName are default
return; // don't re-trigger if other keys are available
}
axios
.get('/api/traces/searchableKeys')
.then((response) => {
this.keys = response.data;
if (this.keys.error) {
this.keys.error.values = ['true', 'false'];
}
})
.catch((result) => {
SearchableKeysStore.handleError(result);
}
);
}
}
export default new SearchableKeysStore();
|
Change the source map and minimise the source | /* eslint import/no-extraneous-dependencies: 0 */
var webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
module.exports = {
watch: false,
devtool: 'cheap-source-map',
entry: ['./src/js/L.PM.js'],
output: {
filename: 'leaflet.pm.min.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader',
}),
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
},
],
},
plugins: [
new ExtractTextPlugin('leaflet.pm.css'),
new webpack.optimize.UglifyJsPlugin(),
],
};
| /* eslint import/no-extraneous-dependencies: 0 */
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
module.exports = {
watch: false,
devtool: 'cheap-eval-source-map',
entry: ['./src/js/L.PM.js'],
output: {
filename: 'leaflet.pm.min.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader',
}),
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
},
],
},
plugins: [
new ExtractTextPlugin('leaflet.pm.css'),
],
};
|
Return entire corpus from corenlp analysis | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
proc = None
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their own element.
For readability's sake, it would be nice to pair all of the information
for a given word with that word, making a list of words with their
part of speech tags
"""
def jsonCleanup(self, data, analysisTypes):
for corpus in data:
res = StanfordCoreNLP.proc.parse_doc(corpus.contents)
words = []
for sentence in res["sentences"]:
for index, token in enumerate(sentence["tokens"]):
word = {}
word["token"] = sentence["tokens"][index]
for atype in analysisTypes:
word[atype] = sentence[atype][index]
words.append(word)
return words
def __init__(self, analysisType):
self.analysisType = analysisType
if StanfordCoreNLP.proc == None:
StanfordCoreNLP.proc = CoreNLP(configdict={'annotators':'tokenize, ssplit, pos, lemma, ner'},
corenlp_jars=[os.path.join(os.path.dirname(__file__), '../../lib/*')])
def run(self, data):
return self.jsonCleanup(data, self.analysisType)
| #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
proc = None
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their own element.
For readability's sake, it would be nice to pair all of the information
for a given word with that word, making a list of words with their
part of speech tags
"""
def jsonCleanup(self, data, analysisTypes):
for corpus in data:
res = StanfordCoreNLP.proc.parse_doc(corpus.contents)
print(str(res));
for sentence in res["sentences"]:
words = []
for index, token in enumerate(sentence["tokens"]):
word = {}
word["token"] = sentence["tokens"][index]
for atype in analysisTypes:
word[atype] = sentence[atype][index]
words.append(word)
return words
def __init__(self, analysisType):
self.analysisType = analysisType
if StanfordCoreNLP.proc == None:
StanfordCoreNLP.proc = CoreNLP(configdict={'annotators':'tokenize, ssplit, pos, lemma, ner'},
corenlp_jars=[os.path.join(os.path.dirname(__file__), '../../lib/*')])
def run(self, data):
return self.jsonCleanup(data, self.analysisType)
|
Add default async filter in split chunks
Using all chunks was causing conflict order issues in the css extraction | const os = require('os');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
/**
* parallel doesn't work yet for WSL (GNU/Linux on Windows)
* cf https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
* https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/302
* @return {Boolean} true if WSL
*/
const isWSL = () => {
if (process.platform === 'linux' && os.release().includes('Microsoft')) {
return true;
}
return false;
};
module.exports = ({ isProduction }) => ({
// Needs to be single because we embed two entry points
runtimeChunk: 'single',
minimize: isProduction,
minimizer: [
new TerserPlugin({
// openpgp and elliptic are written into assets with WriteWebpackPlugin and get minified
exclude: /\/node_modules\/(?!(asmcrypto\.js|pmcrypto))|openpgp|elliptic/,
extractComments: false,
parallel: !isWSL(),
terserOptions: {
keep_classnames: isProduction,
keep_fnames: isProduction,
},
}),
new CssMinimizerPlugin(),
],
splitChunks: {
chunks(chunk) {
// This is the default "async" filter provided by webpack
const async = !chunk.canBeInitial();
return chunk.name !== 'crypto-worker' && async;
},
},
});
| const os = require('os');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
/**
* parallel doesn't work yet for WSL (GNU/Linux on Windows)
* cf https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
* https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/302
* @return {Boolean} true if WSL
*/
const isWSL = () => {
if (process.platform === 'linux' && os.release().includes('Microsoft')) {
return true;
}
return false;
};
module.exports = ({ isProduction }) => ({
// Needs to be single because we embed two entry points
runtimeChunk: 'single',
minimize: isProduction,
minimizer: [
new TerserPlugin({
// openpgp and elliptic are written into assets with WriteWebpackPlugin and get minified
exclude: /\/node_modules\/(?!(asmcrypto\.js|pmcrypto))|openpgp|elliptic/,
extractComments: false,
parallel: !isWSL(),
terserOptions: {
keep_classnames: isProduction,
keep_fnames: isProduction,
},
}),
new CssMinimizerPlugin(),
],
splitChunks: {
chunks(chunk) {
return chunk.name !== 'crypto-worker';
},
},
});
|
Fix typo in dependency name | var webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './js/index.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'bundle')
},
resolve: {
alias: {
'css': path.resolve(__dirname, 'css/'),
'bootstrap': path.resolve(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
'js': path.resolve(__dirname, 'js/'),
'vue': path.resolve(__dirname, 'node_modules/vue/dist/vue.esm.js'),
'vuex:': path.resolve(__dirname, 'node_modules/vuex/dist/vuex.sm.js'),
'jquery': path.resolve(__dirname, 'node_modules/jquery/src/jquery.js'),
'jquery.qrcode': path.resolve(__dirname, 'node_modules/jquery.qrcode/jquery.qrcode.min.js'),
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
}; | var webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './js/index.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'bundle')
},
resolve: {
alias: {
'css': path.resolve(__dirname, 'css/'),
'bootstrap': path.resolve(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
'js': path.resolve(__dirname, 'js/'),
'vue': path.resolve(__dirname, 'node_modules/vue/dist/vue.esm.js'),
'vuex:': path.resolve(__dirname, 'node_modules/vuex/dist/vuex.sm.js'),
'jquery': path.resolve(__dirname, 'node_modules/jquery/src/jquery.js'),
'jquery.qrcode': path.resolve(__dirname, 'node_modules/jquery-qrcode/jquery.qrcode.min.js'),
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
}; |
Replace outdated deprecating comments with a proper doc string. | from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
| # This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
Fix error in template context | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the flawless ' + chalk.red('Angular ES6 Webpack') + ' generator!'
));
var prompts = [
{
type: 'input',
name: 'appName',
message: 'What is the applications name?',
default: ''
},
{
type: 'input',
name: 'ngVersion',
message: 'What version of Angular would you like to use?',
default: '1.4.7'
}
];
this.prompt(prompts, function (props) {
this.appName = props.appName;
this.ngVersion = props.ngVersion;
done();
}.bind(this));
},
writing: {
app: function () {
var context = {
ngVersion: this.ngVersion,
appName: this.appName,
};
this.template('_package.json', 'package.json', context);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
}
},
install: function () {
this.npmInstall();
}
});
| 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the flawless ' + chalk.red('Angular ES6 Webpack') + ' generator!'
));
var prompts = [
{
type: 'input',
name: 'appName',
message: 'What is the applications name?',
default: ''
},
{
type: 'input',
name: 'ngVersion',
message: 'What version of Angular would you like to use?',
default: '1.4.7'
}
];
this.prompt(prompts, function (props) {
this.appName = props.appName;
this.ngVersion = props.ngVersion;
done();
}.bind(this));
},
writing: {
app: function () {
var context = {
this.ngVersion: '1.4.8',
this.appName: 'Test App',
};
this.template('_package.json', 'package.json', context);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
}
},
install: function () {
this.npmInstall();
}
});
|
DEICH-329: Fix resetting page parameter when using search filters | import { replace } from 'react-router-redux'
export function toggleParameter (queryParamName, inputLocationQuery) {
return (dispatch, getState) => {
const pathname = getState().routing.locationBeforeTransitions.pathname
const locationQuery = inputLocationQuery || { ...getState().routing.locationBeforeTransitions.query }
const queryParam = locationQuery[ queryParamName ]
if (queryParam !== undefined) {
delete locationQuery[ queryParamName ]
} else {
locationQuery[ queryParamName ] = null // null enables the parameter
}
return dispatch(replace({ pathname: pathname, query: locationQuery }))
}
}
export function toggleParameterValue (queryParamName, value, inputLocationQuery, shouldRemoveInBackString = false, nameToReplace) {
return (dispatch, getState) => {
const pathname = getState().routing.locationBeforeTransitions.pathname
const locationQuery = inputLocationQuery || { ...getState().routing.locationBeforeTransitions.query }
let queryParam = locationQuery[ queryParamName ] || []
if (shouldRemoveInBackString) {
locationQuery[ queryParamName ] = queryParam.replace(`${nameToReplace}=${value}&`, '')
} else {
if (!Array.isArray(queryParam)) {
queryParam = [ queryParam ]
}
if (queryParam.includes(value)) {
queryParam = queryParam.filter(queryParamValue => queryParamValue !== value)
} else {
queryParam.push(value)
}
if (queryParam.length === 0) {
delete locationQuery[ queryParamName ]
} else {
locationQuery[ queryParamName ] = queryParam
}
}
return dispatch(replace({ pathname: pathname, query: locationQuery }))
}
}
| import { replace } from 'react-router-redux'
export function toggleParameter (queryParamName, locationQuery) {
return (dispatch, getState) => {
const pathname = getState().routing.locationBeforeTransitions.pathname
const locationQuery = locationQuery || { ...getState().routing.locationBeforeTransitions.query }
const queryParam = locationQuery[ queryParamName ]
if (queryParam !== undefined) {
delete locationQuery[ queryParamName ]
} else {
locationQuery[ queryParamName ] = null // null enables the parameter
}
return dispatch(replace({ pathname: pathname, query: locationQuery }))
}
}
export function toggleParameterValue (queryParamName, value, locationQuery, shouldRemoveInBackString = false, nameToReplace) {
return (dispatch, getState) => {
const pathname = getState().routing.locationBeforeTransitions.pathname
const locationQuery = locationQuery || { ...getState().routing.locationBeforeTransitions.query }
let queryParam = locationQuery[ queryParamName ] || []
if (shouldRemoveInBackString) {
locationQuery[ queryParamName ] = queryParam.replace(`${nameToReplace}=${value}&`, '')
} else {
if (!Array.isArray(queryParam)) {
queryParam = [ queryParam ]
}
if (queryParam.includes(value)) {
queryParam = queryParam.filter(queryParamValue => queryParamValue !== value)
} else {
queryParam.push(value)
}
if (queryParam.length === 0) {
delete locationQuery[ queryParamName ]
} else {
locationQuery[ queryParamName ] = queryParam
}
}
return dispatch(replace({ pathname: pathname, query: locationQuery }))
}
}
|
Use bower components from dist subfolder | module.exports = function Gruntfile(grunt) {
'use strict';
require('load-grunt-tasks')(grunt);
grunt.initConfig(
{
babel: {
options: {
modules: 'system',
sourceMap: true
},
dist: {
files: [
{
expand: true,
cwd: 'src/',
src: ['**/*.js'],
dest: 'dist/'
}
]
}
},
clean: ["dist"],
copy: {
markup: {
files: [
{
expand: true,
cwd: 'src/',
src: ['**/*.html'],
dest: 'dist/'
}
]
}
},
eslint: {
target: ['src/**.js']
},
wiredep: {
task: {
src: ['dist/**/*.html'],
ignorePath: /\.\.\//
}
}
}
);
grunt.registerTask(
'build', [
'clean',
'babel',
'copy',
'wiredep'
]
);
grunt.registerTask(
'test', [
'eslint'
]
);
grunt.registerTask(
'default', [
'test',
'build'
]
);
};
| module.exports = function Gruntfile(grunt) {
'use strict';
require('load-grunt-tasks')(grunt);
grunt.initConfig(
{
babel: {
options: {
modules: 'system',
sourceMap: true
},
dist: {
files: [
{
expand: true,
cwd: 'src/',
src: ['**/*.js'],
dest: 'dist/'
}
]
}
},
clean: ["dist"],
copy: {
markup: {
files: [
{
expand: true,
cwd: 'src/',
src: ['**/*.html'],
dest: 'dist/'
}
]
}
},
eslint: {
target: ['src/**.js']
},
wiredep: {
task: {
src: ['dist/**/*.html']
}
}
}
);
grunt.registerTask(
'build', [
'clean',
'babel',
'copy',
'wiredep'
]
);
grunt.registerTask(
'test', [
'eslint'
]
);
grunt.registerTask(
'default', [
'test',
'build'
]
);
};
|
Support multiple @var tags and also no @var tags at all | <?php
namespace BetterReflection\TypesFinder;
use PhpParser\Node\Stmt\Property as PropertyNode;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\ContextFactory;
use BetterReflection\Reflection\ReflectionProperty;
class FindPropertyType
{
/**
* Given a property, attempt to find the type of the property
*
* @param PropertyNode $node
* @param ReflectionProperty $reflectionProperty
* @return Type[]
*/
public function __invoke(PropertyNode $node, ReflectionProperty $reflectionProperty)
{
$contextFactory = new ContextFactory();
$context = $contextFactory->createFromReflector($reflectionProperty);
/* @var \PhpParser\Comment\Doc $comment */
if (!$node->hasAttribute('comments')) {
return [];
}
$comment = $node->getAttribute('comments')[0];
$docBlock = new DocBlock(
$comment->getReformattedText(),
new DocBlock\Context(
$reflectionProperty->getDeclaringClass()->getNamespaceName()
)
);
/* @var \phpDocumentor\Reflection\DocBlock\Tag\VarTag $varTag */
$resolvedTypes = [];
$varTags = $docBlock->getTagsByName('var');
foreach ($varTags as $varTag) {
$resolvedTypes = array_merge(
$resolvedTypes,
(new ResolveTypes())->__invoke($varTag->getTypes(), $context)
);
}
return $resolvedTypes;
}
}
| <?php
namespace BetterReflection\TypesFinder;
use PhpParser\Node\Stmt\Property as PropertyNode;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\ContextFactory;
use BetterReflection\Reflection\ReflectionProperty;
class FindPropertyType
{
/**
* Given a property, attempt to find the type of the property
*
* @param PropertyNode $node
* @param ReflectionProperty $reflectionProperty
* @return Type[]
*/
public function __invoke(PropertyNode $node, ReflectionProperty $reflectionProperty)
{
$contextFactory = new ContextFactory();
$context = $contextFactory->createFromReflector($reflectionProperty);
/* @var \PhpParser\Comment\Doc $comment */
if (!$node->hasAttribute('comments')) {
return [];
}
$comment = $node->getAttribute('comments')[0];
$docBlock = new DocBlock(
$comment->getReformattedText(),
new DocBlock\Context(
$reflectionProperty->getDeclaringClass()->getNamespaceName()
)
);
/* @var \phpDocumentor\Reflection\DocBlock\Tag\VarTag $varTag */
$varTag = $docBlock->getTagsByName('var')[0];
return (new ResolveTypes())->__invoke($varTag->getTypes(), $context);
}
}
|
Improve logic in showing userRoom | const db = require('../db.js');
const Rooms = require('../models/roomModel.js');
const UsersRooms = require('../models/userRoomModel.js');
module.exports = (user1Id, user2Id) => { //user1 is the one trying to start a conversation
const queryStr = `
SELECT ur_1.ur1_id FROM (
(
SELECT user_id AS user1_id, room_id AS ur1_id FROM users_rooms
WHERE user_id = '${user1Id}'
) AS ur_1
INNER JOIN
(
SELECT user_id AS user2_id, room_id AS ur2_id FROM users_rooms
WHERE user_id = '${user2Id}'
) AS ur_2
ON ur_1.ur1_id = ur_2.ur2_id
)
`; //checks whether or not they already have a room in common
return db.query(queryStr).spread((results) => {
if (results.length > 0) {
return db.query(
`UPDATE users_rooms
SET \`show\` = true
WHERE room_id = '${results[0].id}' AND user_id = '${user1Id}'
`
)
.spread(data => data);
}
return Rooms.create({
number_active_participants: 2,
})
.then(room => (
UsersRooms.bulkCreate([
{
user_id: user1Id,
room_id: room.id,
show: true,
},
{
user_id: user2Id,
room_id: room.id,
show: true,
},
])
.then(() => (
[room]
))
));
});
};
| const db = require('../db.js');
const Rooms = require('../models/roomModel.js');
const UsersRooms = require('../models/userRoomModel.js');
module.exports = (user1Id, user2Id) => {
const queryStr = `
SELECT ur_1.ur1_id FROM (
(
SELECT user_id AS user1_id, room_id AS ur1_id FROM users_rooms
WHERE user_id = '${user1Id}'
) AS ur_1
INNER JOIN
(
SELECT user_id AS user2_id, room_id AS ur2_id FROM users_rooms
WHERE user_id = '${user2Id}'
) AS ur_2
ON ur_1.ur1_id = ur_2.ur2_id
)
`;
return db.query(queryStr).spread((results) => {
if (results.length > 0) {
return db.query(
`UPDATE users_rooms
SET \`show\` = true
WHERE room_id = '${results[0].id}'
`
)
.spread(data => data);
}
return Rooms.create({
number_active_participants: 2,
})
.then(room => (
UsersRooms.bulkCreate([
{
user_id: user1Id,
room_id: room.id,
show: true,
},
{
user_id: user2Id,
room_id: room.id,
show: true,
},
])
.then(() => (
[room]
))
));
});
};
|
Switch date labels to make them human friendly | <table class="table table-condensed table-hover">
<tr>
<th>{{ trans('manager.vacancies.table.th.date') }}</th>
@foreach ($business->services as $service)
<th>{{ $service->name }}</th>
@endforeach
</tr>
@foreach ($dates as $date => $vacancies)
<tr>
<td title="{{ $date }}">{{ Carbon::parse($date)->formatLocalized('%A %d %B') }}</td>
@foreach ($business->services as $service)
@if(count($vacancies) > 0 && array_key_exists($service->slug, $vacancies))
<td> {!! Form::text("vacancy[$date][$service->id]", $vacancies[$service->slug]->capacity, array('class'=>'form-control', 'type' => 'numeric', 'step' => '1', 'placeholder'=> "$date {$service->name} ({$vacancies[$service->slug]->capacity})" )) !!} </td>
@else
<td> {!! Form::text("vacancy[$date][$service->id]", null, array('class'=>'form-control', 'placeholder'=> "$date {$service->name}" )) !!} </td>
@endif
@endforeach
</tr>
@endforeach
</table>
@if (!$business->services->isEmpty())
<div class="row">
<div class="form-group col-sm-12">
{!! Button::primary(trans('manager.businesses.btn.update'))->block()->large()->submit() !!}
</div>
</div>
@endif
| <table class="table table-condensed table-hover">
<tr>
<th>{{ trans('manager.vacancies.table.th.date') }}</th>
@foreach ($business->services as $service)
<th>{{ $service->name }}</th>
@endforeach
</tr>
@foreach ($dates as $date => $vacancies)
<tr>
<td title="{{ Carbon::parse($date)->formatLocalized('%A %d %B') }}">{{ $date }}</td>
@foreach ($business->services as $service)
@if(count($vacancies) > 0 && array_key_exists($service->slug, $vacancies))
<td> {!! Form::text("vacancy[$date][$service->id]", $vacancies[$service->slug]->capacity, array('class'=>'form-control', 'type' => 'numeric', 'step' => '1', 'placeholder'=> "$date {$service->name} ({$vacancies[$service->slug]->capacity})" )) !!} </td>
@else
<td> {!! Form::text("vacancy[$date][$service->id]", null, array('class'=>'form-control', 'placeholder'=> "$date {$service->name}" )) !!} </td>
@endif
@endforeach
</tr>
@endforeach
</table>
@if (!$business->services->isEmpty())
<div class="row">
<div class="form-group col-sm-12">
{!! Button::primary(trans('manager.businesses.btn.update'))->block()->large()->submit() !!}
</div>
</div>
@endif
|
Increase transition time for slideshow images from 3 seconds to 5 seconds | (function () {
'use strict';
mare.views.Home = Backbone.View.extend({
el: 'body',
initialize: function() {
// DOM cache any commonly used elements to improve performance
this.$featuredPanelOverlay = $( '.panel-overlay' );
// initialize the owl carousel and make any needed modifications to slideshow image loading
this.initializeSlideshow();
},
/* initializes the slideshow */
initializeSlideshow: function initializeSlideshow() {
// initialize the slideshow default settings
$( '#slideshow' ).owlCarousel({
autoPlay : 5000,
singleItem : true,
lazyLoad : true,
lazyEffect: 'fade',
autoHeight: true,
transitionStyle : 'fade'
});
// prevents the slideshow image descriptions from loading in before the images do
// TODO: This doesn't seem to be working as well as it needs to.
$( '#slideshow img' ).load(function() {
$(this).siblings( '.slideshow__description' ).removeClass( 'hidden' );
});
}
});
}()); | (function () {
'use strict';
mare.views.Home = Backbone.View.extend({
el: 'body',
initialize: function() {
// DOM cache any commonly used elements to improve performance
this.$featuredPanelOverlay = $( '.panel-overlay' );
// initialize the owl carousel and make any needed modifications to slideshow image loading
this.initializeSlideshow();
},
/* initializes the slideshow */
initializeSlideshow: function initializeSlideshow() {
// initialize the slideshow default settings
$( '#slideshow' ).owlCarousel({
autoPlay : 3000,
singleItem : true,
lazyLoad : true,
lazyEffect: 'fade',
autoHeight: true,
transitionStyle : 'fade'
});
// prevents the slideshow image descriptions from loading in before the images do
// TODO: This doesn't seem to be working as well as it needs to.
$( '#slideshow img' ).load(function() {
$(this).siblings( '.slideshow__description' ).removeClass( 'hidden' );
});
}
});
}()); |
Increment version number for release | <?php
namespace Concrete\Package\CommunityStoreStripe;
use Package;
use Whoops\Exception\ErrorException;
use \Concrete\Package\CommunityStore\Src\CommunityStore\Payment\Method as PaymentMethod;
defined('C5_EXECUTE') or die(_("Access Denied."));
class Controller extends Package
{
protected $pkgHandle = 'community_store_stripe';
protected $appVersionRequired = '5.7.2';
protected $pkgVersion = '1.0.5';
public function on_start()
{
require __DIR__ . '/vendor/autoload.php';
}
public function getPackageDescription()
{
return t("Stripe Payment Method for Community Store");
}
public function getPackageName()
{
return t("Stripe Payment Method");
}
public function install()
{
$installed = Package::getInstalledHandles();
if(!(is_array($installed) && in_array('community_store',$installed)) ) {
throw new ErrorException(t('This package requires that Community Store be installed'));
} else {
$pkg = parent::install();
$pm = new PaymentMethod();
$pm->add('community_store_stripe','Stripe',$pkg);
}
}
public function uninstall()
{
$pm = PaymentMethod::getByHandle('community_store_stripe');
if ($pm) {
$pm->delete();
}
$pkg = parent::uninstall();
}
}
?> | <?php
namespace Concrete\Package\CommunityStoreStripe;
use Package;
use Whoops\Exception\ErrorException;
use \Concrete\Package\CommunityStore\Src\CommunityStore\Payment\Method as PaymentMethod;
defined('C5_EXECUTE') or die(_("Access Denied."));
class Controller extends Package
{
protected $pkgHandle = 'community_store_stripe';
protected $appVersionRequired = '5.7.2';
protected $pkgVersion = '1.0.4';
public function on_start()
{
require __DIR__ . '/vendor/autoload.php';
}
public function getPackageDescription()
{
return t("Stripe Payment Method for Community Store");
}
public function getPackageName()
{
return t("Stripe Payment Method");
}
public function install()
{
$installed = Package::getInstalledHandles();
if(!(is_array($installed) && in_array('community_store',$installed)) ) {
throw new ErrorException(t('This package requires that Community Store be installed'));
} else {
$pkg = parent::install();
$pm = new PaymentMethod();
$pm->add('community_store_stripe','Stripe',$pkg);
}
}
public function uninstall()
{
$pm = PaymentMethod::getByHandle('community_store_stripe');
if ($pm) {
$pm->delete();
}
$pkg = parent::uninstall();
}
}
?> |
Add Support for boolean as to string into yaml extension | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Yaml\Dumper as YamlDumper;
/**
* Provides integration of the Yaml component with Twig.
*
* @author Fabien Potencier <[email protected]>
*/
class YamlExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters()
{
return array(
'yaml_encode' => new \Twig_Filter_Method($this, 'encode'),
'yaml_dump' => new \Twig_Filter_Method($this, 'dump'),
);
}
public function encode($input, $inline = 0)
{
static $dumper;
if (null === $dumper) {
$dumper = new YamlDumper();
}
return $dumper->dump($input, $inline);
}
public function dump($value)
{
if (is_resource($value)) {
return '%Resource%';
}
if (is_array($value) || is_object($value)) {
return '%'.gettype($value).'% '.$this->encode($value);
}
return $this->encode($value);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'yaml';
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Yaml\Dumper as YamlDumper;
/**
* Provides integration of the Yaml component with Twig.
*
* @author Fabien Potencier <[email protected]>
*/
class YamlExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters()
{
return array(
'yaml_encode' => new \Twig_Filter_Method($this, 'encode'),
'yaml_dump' => new \Twig_Filter_Method($this, 'dump'),
);
}
public function encode($input, $inline = 0)
{
static $dumper;
if (null === $dumper) {
$dumper = new YamlDumper();
}
return $dumper->dump($input, $inline);
}
public function dump($value)
{
if (is_resource($value)) {
return '%Resource%';
}
if (is_array($value) || is_object($value)) {
return '%'.gettype($value).'% '.$this->encode($value);
}
return $value;
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'yaml';
}
}
|
Update meta. Bump minor version. | from setuptools import setup
def readme():
with open('README.rst', encoding='utf-8') as f:
return f.read()
setup(name='Clashogram',
version='0.1.24',
description='Clash of Clans war moniting for telegram channels.',
long_description=readme(),
author='Mehdi Sadeghi',
author_email='[email protected]',
url='https://github.com/mehdisadeghi/clashogram',
py_modules=['clashogram'],
scripts=['clashogram.py'],
entry_points={
'console_scripts': ['clashogram=clashogram:main']
},
license='MIT',
platforms='any',
install_requires=['babel',
'requests',
'jdatetime',
'pytz',
'python-dateutil',
'click'],
keywords=['games', 'telegram', 'coc', 'notification', 'clash of clans'],
classifiers=['Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: Persian',
'Natural Language :: English',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'])
| from setuptools import setup
def readme():
with open('README.rst', encoding='utf-8') as f:
return f.read()
setup(name='Clashogram',
version='0.1.23',
description='Clash of Clans war moniting for telegram channels.',
long_description=readme(),
author='Mehdi Sadeghi',
author_email='[email protected]',
url='https://github.com/mehdisadeghi/clashogram',
py_modules=['clashogram'],
scripts=['clashogram.py'],
entry_points={
'console_scripts': ['clashogram=clashogram:main']
},
license='MIT',
platforms='any',
install_requires=['babel',
'requests',
'jdatetime',
'pytz',
'python-dateutil',
'click'],
keywords=['games', 'telegram', 'coc', 'notification', 'clash of clans'],
classifiers=['Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: Persian',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'])
|
Update config with Boston IDs | angular.module('gdgXBoomerang')
.factory('Config', function () {
return {
// TODO Modify these to configure your app
'name' : 'GDG Boston',
'id' : '104210617698082698436',
'googleApi' : 'AIzaSyBsAbuRRTugYJHNour-If818LLAL0cPNNc',
'pwaId' : '', // Picasa Web Album id, must belong to Google+ id above
'domain' : 'http://www.gdgboston.org',
'twitter' : 'BostonGDG',
'facebook' : '',
'meetup' : 'gdg-boston',
// Change to 'EEEE, MMMM d, y - H:mm' for 24 hour time format.
'dateFormat' : 'EEEE, MMMM d, y - h:mm a',
'cover' : {
title: 'Worldwide GDG Events',
subtitle: 'Directory of developer events organized by tags and displayed on a global map.',
button: {
text: 'Find local events',
url: 'http://gdg.events/'
}
},
'activities': {
techTalks: true,
codeLabs: true,
hackathons: true,
devFests: true,
appClinics: true,
panels: true,
designSprints: true,
roundTables: true
}
// To update the snippet which is used for sharing, see the TODO in the index.html.
};
});
| angular.module('gdgXBoomerang')
.factory('Config', function () {
return {
// TODO Modify these to configure your app
'name' : 'GDG Space Coast',
'id' : '103959793061819610212',
'googleApi' : '<insert your API key here>',
'pwaId' : '5915725140705884785', // Picasa Web Album id, must belong to Google+ id above
'domain' : 'http://www.gdgspacecoast.org',
'twitter' : 'gdgspacecoast',
'facebook' : 'gdgspacecoast',
'meetup' : 'gdgspacecoast',
// Change to 'EEEE, MMMM d, y - H:mm' for 24 hour time format.
'dateFormat' : 'EEEE, MMMM d, y - h:mm a',
'cover' : {
title: 'Worldwide GDG Events',
subtitle: 'Directory of developer events organized by tags and displayed on a global map.',
button: {
text: 'Find local events',
url: 'http://gdg.events/'
}
},
'activities': {
techTalks: true,
codeLabs: true,
hackathons: true,
devFests: true,
appClinics: true,
panels: true,
designSprints: true,
roundTables: true
}
// To update the snippet which is used for sharing, see the TODO in the index.html.
};
});
|
QS-1249: Replace history state when clicking on toolbar links | import React, { PropTypes, Component } from 'react';
import connectToStores from '../../utils/connectToStores';
import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function';
import LoginStore from '../../stores/LoginStore';
function getState() {
const isGuest = LoginStore.isGuest();
return {isGuest};
}
@connectToStores([LoginStore], getState)
export default class ToolBar extends Component {
static propTypes = {
links : PropTypes.array.isRequired,
activeLinkIndex: PropTypes.number.isRequired,
arrowUpLeft : PropTypes.string.isRequired,
// Injected by @connectToStores:
isGuest : PropTypes.bool
};
static contextTypes = {
history: PropTypes.object.isRequired
};
shouldComponentUpdate = shouldPureComponentUpdate;
render() {
let {activeLinkIndex, links, arrowUpLeft, isGuest} = this.props;
let className = isGuest ? "toolbar toolbar-guest" : "toolbar";
return (
<div id="toolbar-bottom" className={className}>
<div className="arrow-up" style={{ left: arrowUpLeft }}></div>
<div className="toolbar-inner">
{links.map((link, index) => {
return (
<div key={index} className="toolbar-link-wrapper" onClick={() => this.context.history.replace(link.url)}>
<a href="javascript:void(0)">{activeLinkIndex === index ? <strong>{link.text}</strong> : link.text}</a>
</div>
);
})}
</div>
</div>
);
}
}
| import React, { PropTypes, Component } from 'react';
import connectToStores from '../../utils/connectToStores';
import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function';
import LoginStore from '../../stores/LoginStore';
function getState() {
const isGuest = LoginStore.isGuest();
return {isGuest};
}
@connectToStores([LoginStore], getState)
export default class ToolBar extends Component {
static propTypes = {
links : PropTypes.array.isRequired,
activeLinkIndex: PropTypes.number.isRequired,
arrowUpLeft : PropTypes.string.isRequired,
// Injected by @connectToStores:
isGuest : PropTypes.bool
};
static contextTypes = {
history: PropTypes.object.isRequired
};
shouldComponentUpdate = shouldPureComponentUpdate;
render() {
let {activeLinkIndex, links, arrowUpLeft, isGuest} = this.props;
let className = isGuest ? "toolbar toolbar-guest" : "toolbar";
return (
<div id="toolbar-bottom" className={className}>
<div className="arrow-up" style={{ left: arrowUpLeft }}></div>
<div className="toolbar-inner">
{links.map((link, index) => {
return (
<div key={index} className="toolbar-link-wrapper" onClick={() => this.context.history.pushState(null, link.url)}>
<a href="javascript:void(0)">{activeLinkIndex === index ? <strong>{link.text}</strong> : link.text}</a>
</div>
);
})}
</div>
</div>
);
}
}
|
Resolve scope issues with save function callback | angular.module('ChillaxApp', [])
.controller("ChillaxController", function () {
var chillax = this;
chillax.init = function() {
chillax.nextNotification="Chillax loaded!";
chillax.retrieveSettings();
};
chillax.retrieveSettings = function() {
var settings = {};
settings["enabled"] = "";
settings["reminderInterval"] = "";
settings["breakInterval"] = "";
settings["sound"] = "";
chillax.enabled = true;
chrome.storage.sync.get(settings, function(obj) {
console.log("Settings loaded: " + obj["enabled"]);
this.chillax.reminderInterval = obj["reminderInterval"];
chillax.breakInterval = settings["breakInterval"];
chillax.sound = settings["sound"];
});
};
chillax.playSound = function () {
chillax.nextNotification="Is enabled: " + chillax.enabled;
console.log("Play misty for me");
};
chillax.saveSettings = function () {
console.log("Attempting to auto save the settings");
// Prepare setting values to save
var settings = {};
settings["enabled"] = chillax.enabled;
settings["reminderInterval"] = chillax.reminderInterval;
settings["breakInterval"] = chillax.breakInterval;
settings["sound"] = chillax.sound;
// Output settings
console.log(settings);
chrome.storage.sync.set(settings, function() {
console.log("Settings have been stored successfully");
});
};
}); | angular.module('ChillaxApp', [])
.controller("ChillaxController", function () {
var chillax = this;
chillax.init = function() {
chillax.nextNotification="Chillax loaded!";
chillax.retrieveSettings();
};
chillax.retrieveSettings = function() {
var settings = {};
settings["enabled"] = "";
settings["reminderInterval"] = "";
settings["breakInterval"] = "";
settings["sound"] = "";
chillax.enabled = true;
chrome.storage.sync.get(settings, function(obj) {
console.log("Settings loaded: " + obj["enabled"]);
chillax.reminderInterval = obj["reminderInterval"];
chillax.breakInterval = settings["breakInterval"];
chillax.sound = settings["sound"];
});
};
chillax.playSound = function () {
chillax.nextNotification="Is enabled: " + chillax.enabled;
console.log("Play misty for me");
};
chillax.saveSettings = function () {
console.log("Attempting to auto save the settings");
// Prepare setting values to save
var settings = {};
settings["enabled"] = chillax.enabled;
settings["reminderInterval"] = chillax.reminderInterval;
settings["breakInterval"] = chillax.breakInterval;
settings["sound"] = chillax.sound;
// Output settings
console.log(settings);
chrome.storage.sync.set(settings, function() {
console.log("Settings have been stored successfully");
});
};
}); |
Fix executors for retrofit request and callback | package com.drivemode.spotify.rest;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
/**
* @author KeishinYokomaku
*/
public class RestAdapterFactory {
public static final String TAG = RestAdapterFactory.class.getSimpleName();
public static final String SPOTIFY_WEB_API_ENDPOINT = "https://api.spotify.com/v1";
public static final String SPOTIFY_AUTHENTICATE_ENDPOINT = "https://accounts.spotify.com/";
private final OkClient mOkClient;
public RestAdapterFactory() {
mOkClient = new OkClient(new OkHttpClient());
}
public RestAdapter provideWebApiAdapter(RequestInterceptor interceptor) {
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(mOkClient)
.setEndpoint(SPOTIFY_WEB_API_ENDPOINT)
.setRequestInterceptor(interceptor)
.build();
}
public RestAdapter provideAuthenticateApiAdapter() {
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(mOkClient)
.setEndpoint(SPOTIFY_AUTHENTICATE_ENDPOINT)
.build();
}
}
| package com.drivemode.spotify.rest;
import com.squareup.okhttp.OkHttpClient;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
/**
* @author KeishinYokomaku
*/
public class RestAdapterFactory {
public static final String TAG = RestAdapterFactory.class.getSimpleName();
public static final String SPOTIFY_WEB_API_ENDPOINT = "https://api.spotify.com/v1";
public static final String SPOTIFY_AUTHENTICATE_ENDPOINT = "https://accounts.spotify.com/";
private final OkClient mOkClient;
private final Executor mExecutor;
public RestAdapterFactory() {
mOkClient = new OkClient(new OkHttpClient());
mExecutor = Executors.newSingleThreadExecutor();
}
public RestAdapter provideWebApiAdapter(RequestInterceptor interceptor) {
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(mOkClient)
.setExecutors(mExecutor, mExecutor)
.setEndpoint(SPOTIFY_WEB_API_ENDPOINT)
.setRequestInterceptor(interceptor)
.build();
}
public RestAdapter provideAuthenticateApiAdapter() {
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(mOkClient)
.setExecutors(mExecutor, mExecutor)
.setEndpoint(SPOTIFY_AUTHENTICATE_ENDPOINT)
.build();
}
}
|
Add create method to Todo Api | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
create: function(todo, success, failure) {
$.ajax({
url: BASE_URL,
type: 'POST',
dataType: 'json',
data: todo,
success: function() {
success();
},
error: function() {
failure();
}
});
},
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; |
Use the exit code constant | <?php
namespace Padam87\CronBundle\Command;
use Doctrine\Common\Annotations\AnnotationReader;
use Padam87\CronBundle\Util\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DumpCommand extends ConfigurationAwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->setName('cron:dump')
->setDescription('Dumps jobs to a crontab file')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->dump($input);
return self::SUCCESS;
}
protected function dump(InputInterface $input): string
{
$reader = new AnnotationReader();
$helper = new Helper($this->getApplication(), $reader);
$tab = $helper->createTab($input, $this->getConfiguration());
$path = strtolower(
sprintf(
'%s.crontab',
$this->getApplication()->getName()
)
);
file_put_contents($path, (string) $tab);
return $path;
}
}
| <?php
namespace Padam87\CronBundle\Command;
use Doctrine\Common\Annotations\AnnotationReader;
use Padam87\CronBundle\Util\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DumpCommand extends ConfigurationAwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->setName('cron:dump')
->setDescription('Dumps jobs to a crontab file')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->dump($input);
return 0;
}
protected function dump(InputInterface $input): string
{
$reader = new AnnotationReader();
$helper = new Helper($this->getApplication(), $reader);
$tab = $helper->createTab($input, $this->getConfiguration());
$path = strtolower(
sprintf(
'%s.crontab',
$this->getApplication()->getName()
)
);
file_put_contents($path, (string) $tab);
return $path;
}
}
|
Fix Chrome headless when root on Linux
Fix Chrome headless when running as root by adding --no-sandbox. | // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
const puppeteer = require("puppeteer");
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function (config) {
config.set({
autoWatch: false,
concurrency: Infinity,
browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: ["--no-sandbox"]
}
},
frameworks: ["jasmine", "karma-typescript"],
files: [
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
"assets/scripts/**/*.ts"
],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
htmlDetailed: {
splitResults: false
},
plugins: [
"karma-appveyor-reporter",
"karma-chrome-launcher",
"karma-html-detailed-reporter",
"karma-jasmine",
"karma-typescript"
],
reporters: [
"progress",
"appveyor",
"karma-typescript"
]
});
};
| // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
const puppeteer = require("puppeteer");
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function (config) {
config.set({
autoWatch: false,
concurrency: Infinity,
browsers: ["ChromeHeadless"],
frameworks: ["jasmine", "karma-typescript"],
files: [
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
"assets/scripts/**/*.ts"
],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
htmlDetailed: {
splitResults: false
},
plugins: [
"karma-appveyor-reporter",
"karma-chrome-launcher",
"karma-html-detailed-reporter",
"karma-jasmine",
"karma-typescript"
],
reporters: [
"progress",
"appveyor",
"karma-typescript"
]
});
};
|
Disable torcache for now.
Randomize order torrent cache mirrors are added to urls list.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@2874 3942dd89-8c5d-46d7-aeed-044bccf3e60c | import logging
import re
import random
from flexget.plugin import register_plugin, priority
log = logging.getLogger('torrent_cache')
MIRRORS = ['http://torrage.com/torrent/',
# Now using a landing page instead of going directly to the torrent
# TODO: May be fixable by setting the referer
#'http://torcache.net/torrent/',
'http://zoink.it/torrent/',
'http://torrage.ws/torrent/']
class TorrentCache(object):
"""Adds urls to torrent cache sites to the urls list."""
@priority(-255)
def on_feed_filter(self, feed, config):
for entry in feed.accepted:
info_hash = None
if entry['url'].startswith('magnet:'):
info_hash_search = re.search('btih:([0-9a-f]+)', entry['url'], re.IGNORECASE)
if info_hash_search:
info_hash = info_hash_search.group(1)
elif entry.get('torrent_info_hash'):
info_hash = entry['torrent_info_hash']
if info_hash:
# Add the mirrors in random order
random.shuffle(MIRRORS)
entry.setdefault('urls', [entry['url']])
entry['urls'].extend(host + info_hash.upper() + '.torrent' for host in MIRRORS)
register_plugin(TorrentCache, 'torrent_cache', api_ver=2, builtin=True)
| import logging
import re
from flexget.plugin import register_plugin, priority
log = logging.getLogger('torrent_cache')
MIRRORS = ['http://torrage.com/torrent/',
'http://torcache.net/torrent/',
'http://zoink.it/torrent/',
'http://torrage.ws/torrent/']
class TorrentCache(object):
"""Adds urls to torrent cache sites to the urls list."""
@priority(-255)
def on_feed_filter(self, feed, config):
for entry in feed.accepted:
info_hash = None
if entry['url'].startswith('magnet:'):
info_hash_search = re.search('btih:([0-9a-f]+)', entry['url'], re.IGNORECASE)
if info_hash_search:
info_hash = info_hash_search.group(1)
elif entry.get('torrent_info_hash'):
info_hash = entry['torrent_info_hash']
if info_hash:
entry.setdefault('urls', [entry['url']])
entry['urls'].extend(host + info_hash.upper() + '.torrent' for host in MIRRORS)
register_plugin(TorrentCache, 'torrent_cache', api_ver=2, builtin=True)
|
Change the development status to Beta | import distutils.core
import sys
from rabbitpy import __version__
tests_require = ['nose', 'mock']
if sys.version_info < (2, 7, 0):
tests_require.append('unittest2')
desc = 'A minimalistic & pythonic AMQP library focused on supporting RabbitMQ'
distutils.core.setup(name='rabbitpy',
version=__version__,
description=desc,
long_description=open('README.md').read(),
author='Gavin M. Roy',
author_email='[email protected]',
url='http://rabbitpy.readthedocs.org',
packages=['rabbitpy'],
package_data={'': ['LICENSE', 'README.md']},
include_package_data=True,
install_requires=['pamqp>=1.2.0'],
tests_require=tests_require,
test_suite='nose.collector',
license=open('LICENSE').read(),
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: Software Development :: Libraries'],
zip_safe=True)
| import distutils.core
import sys
from rabbitpy import __version__
tests_require = ['nose', 'mock']
if sys.version_info < (2, 7, 0):
tests_require.append('unittest2')
desc = 'A minimalistic & pythonic AMQP library focused on supporting RabbitMQ'
distutils.core.setup(name='rabbitpy',
version=__version__,
description=desc,
long_description=open('README.md').read(),
author='Gavin M. Roy',
author_email='[email protected]',
url='http://rabbitpy.readthedocs.org',
packages=['rabbitpy'],
package_data={'': ['LICENSE', 'README.md']},
include_package_data=True,
install_requires=['pamqp>=1.2.0'],
tests_require=tests_require,
test_suite='nose.collector',
license=open('LICENSE').read(),
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: Software Development :: Libraries'],
zip_safe=True)
|
Fix some curious issue on SQL Record insertion | 'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('dns_records', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
type: {
type: Sequelize.ENUM('A', 'CNAME', 'MX', 'SOA', 'TXT', 'NS'),
allowNull: false
},
name: {
type: Sequelize.STRING(64),
allowNull: false
},
ipv4address: {
type: Sequelize.STRING(15)
},
ipv6address: {
type: Sequelize.STRING(39)
},
cname: {
type: Sequelize.STRING(255)
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
UserId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('dns_records');
}
};
| 'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('dns_records', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
type: {
type: Sequelize.STRING(4),
allowNull: false
},
name: {
type: Sequelize.STRING(64),
allowNull: false
},
ipv4address: {
type: Sequelize.STRING(15)
},
ipv6address: {
type: Sequelize.STRING(39)
},
cname: {
type: Sequelize.STRING(255)
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
UserId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('dns_records');
}
};
|
Fix the search class not found | <?php
namespace AstritZeqiri\LaravelSearchable\Traits;
use AstritZeqiri\LaravelSearchable\Search;
use AstritZeqiri\LaravelSearchable\Exceptions\SearchException;
trait Searchable
{
/**
* Search on multiple database fields on eloquent models.
*
* @param Illuminate\Database\Eloquent\Builder $query
* @param string $search
* @param array $fields
* @param boolean $exact
*
* @throws SearchException [if the search fields are not set on the model or they are not given on the method]
* @return Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch($query, $search = "", $fields = [], $exact = false)
{
if (! $search) {
return $query;
}
if (! $fields && ! property_exists(static::class, 'searchOn')) {
throw SearchException::searchOnOrFieldsNotFound();
}
$fields = $fields ?: static::$searchOn;
if (! is_array($fields)) {
$fields = [$fields];
}
if (empty($fields)) {
return $query;
}
return (new Search($query))
->className(static::class)
->searchFor($search)
->onFields($fields)
->exactSearch($exact)
->build();
}
}
| <?php
namespace AstritZeqiri\LaravelSearchable\Traits;
use AstritZeqiri\LaravelSearchable\Exceptions\SearchException;
trait Searchable
{
/**
* Search on multiple database fields on eloquent models.
*
* @param Illuminate\Database\Eloquent\Builder $query
* @param string $search
* @param array $fields
* @param boolean $exact
*
* @throws SearchException [if the search fields are not set on the model or they are not given on the method]
* @return Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch($query, $search = "", $fields = [], $exact = false)
{
if (! $search) {
return $query;
}
if (! $fields && ! property_exists(static::class, 'searchOn')) {
throw SearchException::searchOnOrFieldsNotFound();
}
$fields = $fields ?: static::$searchOn;
if (! is_array($fields)) {
$fields = [$fields];
}
if (empty($fields)) {
return $query;
}
return (new Search($query))
->className(static::class)
->searchFor($search)
->onFields($fields)
->exactSearch($exact)
->build();
}
}
|
Add HTML fragment to test sample | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = (
"Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expected, **kwargs):
self.assertEqual(self.func(source, **kwargs), expected)
def test_empty(self):
self.check("", "")
def test_ascii(self):
self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n")
def test_non_ascii(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>. И другие штуки.</p>\n"
"<p>Test of <em>HTML</em>.</p>\n"))
def test_breaks(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"
"<p>Test of <em>HTML</em>.</p>\n"),
breaks=True)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expected, **kwargs):
self.assertEqual(self.func(source, **kwargs), expected)
def test_empty(self):
self.check("", "")
def test_ascii(self):
self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n")
def test_non_ascii(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>. И другие штуки.</p>\n"))
def test_breaks(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"),
breaks=True)
|
Fix map marker and zoom map in center | /* global google:false */
export function VenueDirective () {
'ngInject';
return {
restrict: 'E',
templateUrl: 'app/components/venue/venue.html',
scope: {},
controller: VenueController,
controllerAs: 'vm',
bindToController: true
};
}
class VenueController {
constructor () {
'ngInject';
this.map = {
center: {latitude: 56.946333, longitude: 24.116870},
zoom: 16,
options: {
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeControl: false,
streetViewControl: false,
panControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [
{
"stylers": [{"hue": "#00aaff"}, {"saturation": -23}, {"gamma": 1.37}, {"lightness": -5}]
}
]
}
};
this.marker = {
idKey: 'place',
position: {latitude: 56.946333, longitude: 24.116870},
options: {
title: 'Riga Dev Day 2016',
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
labelContent: 'Kino Citadele',
labelAnchor: "46 -5",
labelClass: 'map-label'
}
}
}
}
| /* global google:false */
export function VenueDirective () {
'ngInject';
return {
restrict: 'E',
templateUrl: 'app/components/venue/venue.html',
scope: {},
controller: VenueController,
controllerAs: 'vm',
bindToController: true
};
}
class VenueController {
constructor () {
'ngInject';
let center = {latitude: 56.946333, longitude: 24.116870};
this.map = {
center: center,
zoom: 13,
options: {
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeControl: false,
streetViewControl: false,
panControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [
{
"stylers": [{"hue": "#00aaff"}, {"saturation": -23}, {"gamma": 1.37}, {"lightness": -5}]
}
]
}
};
this.marker = {
idKey: 'place',
position: center,
options: {
title: 'Riga Dev Day 2016',
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
labelContent: 'Kino Citadele',
labelAnchor: "46 -5",
labelClass: 'map-label'
}
}
}
}
|
Add Navbar dropdown menu. Under username there are Settings and Log out | import React from 'react';
import {Link} from 'react-router-dom';
import {NavDropdown} from 'react-bootstrap';
class NavbarUserInfo extends React.Component {
constructor(props) {
super(props);
}
logOut() {
}
render() {
if (!this.props.secret) {
return (
<ul className="nav navbar-nav navbar-right">
<li>
<Link to='/login'>
Log in
</Link>
</li>
</ul>
);
}
return (
<span>
<ul className="nav navbar-nav navbar-right">
<li>
<Link to='/add_book'>Add Book</Link>
</li>
<li>
<Link to='/admin'>Admin</Link>
</li>
<NavDropdown eventKey={3} title={this.props.signum} id="basic-nav-dropdown">
<li>
<Link to='/settings'>Settings</Link>
<a href="/books" onClick={this.props.logOut}>Log out</a>
</li>
</NavDropdown>
</ul>
</span>
);
}
}
export default NavbarUserInfo;
| import React from 'react';
import {Link} from 'react-router-dom';
class NavbarUserInfo extends React.Component {
constructor(props) {
super(props);
}
logOut() {
}
render() {
if (!this.props.secret) {
return (
<ul className="nav navbar-nav navbar-right">
<li>
<Link to='/login'>
Log in
</Link>
</li>
</ul>
);
}
return (
<span>
<ul className="nav navbar-nav navbar-right">
<li>
<Link to='/add_book'>Add Book</Link>
</li>
<li>
<Link to='/admin'>Admin</Link>
</li>
<li>
<a href="/books" onClick={this.props.logOut}>Logout</a>
</li>
</ul>
<p className="nav navbar-nav navbar-right navbar-text">Signed in as
<a className="navbar-link"> {this.props.signum}</a>
</p>
</span>
);
}
}
export default NavbarUserInfo;
|
Send editied file back to phoenix | <?php
namespace Rogue\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Rogue\Services\Phoenix;
use Rogue\Models\Reportback;
class SendReportbackToPhoenix extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $reportback;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Reportback $reportback)
{
$this->reportback = $reportback;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$phoenix = new Phoenix;
$reportbackItem = $this->reportback->items()->orderBy('created_at', 'desc')->first();
$body = [
'uid' => $this->reportback->drupal_id,
'nid' => $this->reportback->campaign_id,
'quantity' => $this->reportback->quantity,
'why_participated' => $this->reportback->why_participated,
'file_url' => $reportbackItem->edited_file_url,
'caption' => $reportbackItem->caption,
'source' => $reportbackItem->source,
];
$phoenix->postReportback($this->reportback->campaign_id, $body);
}
}
| <?php
namespace Rogue\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Rogue\Services\Phoenix;
use Rogue\Models\Reportback;
class SendReportbackToPhoenix extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $reportback;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Reportback $reportback)
{
$this->reportback = $reportback;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$phoenix = new Phoenix;
$reportbackItem = $this->reportback->items()->orderBy('created_at', 'desc')->first();
$body = [
'uid' => $this->reportback->drupal_id,
'nid' => $this->reportback->campaign_id,
'quantity' => $this->reportback->quantity,
'why_participated' => $this->reportback->why_participated,
'file_url' => $reportbackItem->file_url,
'caption' => $reportbackItem->caption,
'source' => $reportbackItem->source,
];
$phoenix->postReportback($this->reportback->campaign_id, $body);
}
}
|
Fix the file extensions for the bundles | const path = require('path');
const webpack = require('webpack');
module.exports = [{
entry: path.join(__dirname, 'src', 'Flatline.ts'),
output: {
path: path.join(__dirname, 'build'),
filename: "flatline-browser.min.js",
library: "Flatline",
libraryTarget: "var"
},
resolve: {
extensions: [".ts", ".tsx"]
},
module: {
rules: [{
test: /\.tsx?$/,
include: [
path.join(__dirname, 'src')
],
loader: 'ts-loader'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, dead_code: true },
mangle: true,
sourceMap: true,
beautify: false
})
]
}, {
entry: path.join(__dirname, 'src', 'Flatline.ts'),
output: {
path: path.join(__dirname, 'build'),
filename: "flatline-common.min.js",
libraryTarget: "commonjs"
},
resolve: {
extensions: [".ts", ".tsx"]
},
module: {
rules: [{
test: /\.tsx?$/,
include: [
path.join(__dirname, 'src')
],
loader: 'ts-loader'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, dead_code: true },
mangle: true,
sourceMap: true,
beautify: false
})
]
}] | const path = require('path');
const webpack = require('webpack');
module.exports = [{
entry: path.join(__dirname, 'src', 'Flatline.ts'),
output: {
path: path.join(__dirname, 'build'),
filename: "flatline-browser.js",
library: "Flatline",
libraryTarget: "var"
},
resolve: {
extensions: [".ts", ".tsx"]
},
module: {
rules: [{
test: /\.tsx?$/,
include: [
path.join(__dirname, 'src')
],
loader: 'ts-loader'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, dead_code: true },
mangle: true,
sourceMap: true,
beautify: false
})
]
}, {
entry: path.join(__dirname, 'src', 'Flatline.ts'),
output: {
path: path.join(__dirname, 'build'),
filename: "flatline-common.js",
libraryTarget: "commonjs"
},
resolve: {
extensions: [".ts", ".tsx"]
},
module: {
rules: [{
test: /\.tsx?$/,
include: [
path.join(__dirname, 'src')
],
loader: 'ts-loader'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, dead_code: true },
mangle: true,
sourceMap: true,
beautify: false
})
]
}] |
Fix missing --no-wait option on integration:delete | <?php
namespace Platformsh\Cli\Command\Integration;
use Platformsh\Cli\Command\PlatformCommand;
use Platformsh\Cli\Util\ActivityUtil;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class IntegrationDeleteCommand extends PlatformCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('integration:delete')
->addArgument('id', InputArgument::REQUIRED, 'The integration ID')
->setDescription('Delete an integration from a project');
$this->addProjectOption()->addNoWaitOption();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$id = $input->getArgument('id');
$integration = $this->getSelectedProject()
->getIntegration($id);
if (!$integration) {
$this->stdErr->writeln("Integration not found: <error>$id</error>");
return 1;
}
$type = $integration->getProperty('type');
$confirmText = "Delete the integration <info>$id</info> (type: $type)?";
if (!$this->getHelper('question')->confirm($confirmText, $input, $this->stdErr)) {
return 1;
}
$result = $integration->delete();
$this->stdErr->writeln("Deleted integration <info>$id</info>");
if (!$input->getOption('no-wait')) {
ActivityUtil::waitMultiple($result->getActivities(), $this->stdErr);
}
return 0;
}
}
| <?php
namespace Platformsh\Cli\Command\Integration;
use Platformsh\Cli\Command\PlatformCommand;
use Platformsh\Cli\Util\ActivityUtil;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class IntegrationDeleteCommand extends PlatformCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('integration:delete')
->addArgument('id', InputArgument::REQUIRED, 'The integration ID')
->setDescription('Delete an integration from a project');
$this->addProjectOption();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$id = $input->getArgument('id');
$integration = $this->getSelectedProject()
->getIntegration($id);
if (!$integration) {
$this->stdErr->writeln("Integration not found: <error>$id</error>");
return 1;
}
$type = $integration->getProperty('type');
$confirmText = "Delete the integration <info>$id</info> (type: $type)?";
if (!$this->getHelper('question')->confirm($confirmText, $input, $this->stdErr)) {
return 1;
}
$result = $integration->delete();
$this->stdErr->writeln("Deleted integration <info>$id</info>");
if (!$input->getOption('no-wait')) {
ActivityUtil::waitMultiple($result->getActivities(), $this->stdErr);
}
return 0;
}
}
|
Hide Drag-Drop when no ElementDetails | import React, {Component} from 'react';
import {DragDropContext} from 'react-dnd';
import {Col} from 'react-bootstrap';
import HTML5Backend from 'react-dnd-html5-backend';
import List from './List';
import ElementDetails from './ElementDetails';
import ElementStore from './stores/ElementStore';
class Elements extends Component {
constructor(props) {
super(props);
this.state = {
currentElement: null,
};
this.handleOnChange = this.handleOnChange.bind(this)
}
componentDidMount() {
ElementStore.listen(this.handleOnChange);
}
componentWillUnmount() {
ElementStore.unlisten(this.handleOnChange);
}
handleOnChange(state) {
const { currentElement } = state;
this.setState({ currentElement });
}
render() {
const { currentElement } = this.state;
const showReport = (currentElement || []).type === 'report'
let list = (
<Col md={12} style={{paddingLeft: "10px"}}>
<List overview={true} showReport={showReport}/>
</Col>
)
let page = (<span />)
if (currentElement) {
list = (
<Col md={4}>
<List overview={false} showReport={showReport}/>
</Col>
)
page = (
<Col md={8}>
<ElementDetails currentElement={currentElement} />
</Col>
)
}
return (
<div>
{list}
{page}
</div>
);
}
}
export default DragDropContext(HTML5Backend)(Elements);
| import React, {Component} from 'react';
import {DragDropContext} from 'react-dnd';
import {Col} from 'react-bootstrap';
import HTML5Backend from 'react-dnd-html5-backend';
import List from './List';
import ElementDetails from './ElementDetails';
import ElementStore from './stores/ElementStore';
class Elements extends Component {
constructor(props) {
super(props);
this.state = {
currentElement: null,
};
this.handleOnChange = this.handleOnChange.bind(this)
}
componentDidMount() {
ElementStore.listen(this.handleOnChange);
}
componentWillUnmount() {
ElementStore.unlisten(this.handleOnChange);
}
handleOnChange(state) {
const { currentElement } = state;
this.setState({ currentElement });
}
render() {
const { currentElement } = this.state;
const showReport = (currentElement || []).type === 'report'
let list = (
<Col md={12} style={{paddingLeft: "10px"}}>
<List overview={false} showReport={showReport}/>
</Col>
)
let page = (<span />)
if (currentElement) {
list = (
<Col md={4}>
<List overview={false} showReport={showReport}/>
</Col>
)
page = (
<Col md={8}>
<ElementDetails currentElement={currentElement} />
</Col>
)
}
return (
<div>
{list}
{page}
</div>
);
}
}
export default DragDropContext(HTML5Backend)(Elements);
|
Remove unnecessary lock on context creation | package com.mudalov.safe.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* API Entry point, links commands and execution contexts
*
* User: mudalov
* Date: 22/01/15
* Time: 23:57
*/
public class SafeCommands {
private static final ConcurrentHashMap<String, GroupExecutionContext> groupContexts = new ConcurrentHashMap<String, GroupExecutionContext>();
private static final String DefaultGroup = "DefaultGroup";
private SafeCommands() {
}
public static <T> CommandRef<T> create(AbstractCommand<T> command, String group) {
GroupExecutionContext groupContext = getGroupContext(group);
command.setContext(groupContext);
return new CommandRef<T>(groupContext, command);
}
public static <T> CommandRef<T> create(AbstractCommand<T> command) {
return create(command, DefaultGroup);
}
private static GroupExecutionContext getGroupContext(String groupName) {
GroupExecutionContext context = groupContexts.get(groupName);
if (context != null) {
return context;
}
context = new GroupExecutionContext(groupName);
GroupExecutionContext prevContext = groupContexts.putIfAbsent(groupName, context);
if (prevContext == null) {
return context;
} else {
return prevContext;
}
}
}
| package com.mudalov.safe.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* API Entry point, links commands and execution contexts
*
* User: mudalov
* Date: 22/01/15
* Time: 23:57
*/
public class SafeCommands {
private static final Logger log = LoggerFactory.getLogger(SafeCommands.class);
private static final ReentrantLock groupContextLock = new ReentrantLock();
private static final Map<String, GroupExecutionContext> groupContexts = new ConcurrentHashMap<String, GroupExecutionContext>();
private static final String DefaultGroup = "DefaultGroup";
private SafeCommands() {
}
public static <T> CommandRef<T> create(AbstractCommand<T> command, String group) {
GroupExecutionContext groupContext = getGroupContext(group);
command.setContext(groupContext);
return new CommandRef<T>(groupContext, command);
}
public static <T> CommandRef<T> create(AbstractCommand<T> command) {
return create(command, DefaultGroup);
}
private static GroupExecutionContext getGroupContext(String groupName) {
GroupExecutionContext context = groupContexts.get(groupName);
if (context != null) {
return context;
}
groupContextLock.lock();
try {
context = groupContexts.get(groupName);
if (context != null) {
return context;
}
context = new GroupExecutionContext(groupName);
groupContexts.put(groupName, context);
return context;
} finally {
groupContextLock.unlock();
}
}
}
|
Make atom from filename before throwing an error in get_source. | import os
import sys
from prolog.interpreter.error import throw_existence_error
from prolog.interpreter.term import Callable
path = os.path.dirname(__file__)
path = os.path.join(path, "..", "prolog_modules")
def get_source(filename):
try:
fd = os.open(filename, os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(os.path.join(path, filename), os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(filename + ".pl", os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(os.path.join(path, filename + ".pl"), os.O_RDONLY, 0777)
except OSError, e:
throw_existence_error("source_sink", Callable.build(filename))
assert 0, "unreachable" # make the flow space happy
try:
content = []
while 1:
s = os.read(fd, 4096)
if not s:
break
content.append(s)
file_content = "".join(content)
finally:
os.close(fd)
return file_content
| import os
import sys
import py
from prolog.interpreter.error import throw_existence_error
path = os.path.dirname(__file__)
path = os.path.join(path, "..", "prolog_modules")
def get_source(filename):
try:
fd = os.open(filename, os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(os.path.join(path, filename), os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(filename + ".pl", os.O_RDONLY, 0777)
except OSError, e:
try:
fd = os.open(os.path.join(path, filename + ".pl"), os.O_RDONLY, 0777)
except OSError, e:
throw_existence_error("source_sink", filename)
assert 0, "unreachable" # make the flow space happy
try:
content = []
while 1:
s = os.read(fd, 4096)
if not s:
break
content.append(s)
file_content = "".join(content)
finally:
os.close(fd)
return file_content
|
Use decorator to patch git repository is not exist | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
def without_git_repository(func):
def inner(*args, **kwargs):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
return func(*args, **kwargs)
return inner
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
@without_git_repository
def test_is_repository_without_repository(self):
self.assertEqual(self.client.is_repository(), True)
| import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
def _patch_without_repository(self, func):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
def test_is_repository_without_repository(self):
def _func(_check_output):
self.assertEqual(self.client.is_repository(), False)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
self._patch_without_repository(_func)
|
Fix broken spec tests in Laravel Session implementation | <?php
namespace spec\Omniphx\Forrest\Providers\Laravel;
use Illuminate\Config\Repository as Config;
use Illuminate\Contracts\Session\Session as Session;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class LaravelSessionSpec extends ObjectBehavior
{
public function let(Config $config, Session $session)
{
$this->beConstructedWith($config, $session);
}
public function it_is_initializable(Config $config)
{
$config->get(Argument::any())->shouldBeCalled();
$this->shouldHaveType('Omniphx\Forrest\Providers\Laravel\LaravelSession');
}
public function it_should_allow_a_get(Session $session)
{
$session->has(Argument::any())->shouldBeCalled()->willReturn(true);
$session->get(Argument::any())->shouldBeCalled();
$this->get('test');
}
public function it_should_allow_a_put(Session $session)
{
$session->put(Argument::any(), Argument::any())->shouldBeCalled();
$this->put('test', 'value');
}
public function it_should_allow_a_has(Session $session)
{
$session->has(Argument::any())->shouldBeCalled();
$this->has('test');
}
public function it_should_throw_an_exception_if_token_does_not_exist(Session $session)
{
$session->has(Argument::any())->shouldBeCalled()->willReturn(false);
$this->shouldThrow('\Omniphx\Forrest\Exceptions\MissingKeyException')->duringGet('test');
}
} | <?php
namespace spec\Omniphx\Forrest\Providers\Laravel;
use Illuminate\Config\Repository as Config;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class LaravelSessionSpec extends ObjectBehavior
{
public function let(Config $config, SessionInterface $session)
{
$this->beConstructedWith($config, $session);
}
public function it_is_initializable(Config $config)
{
$config->get(Argument::any())->shouldBeCalled();
$this->shouldHaveType('Omniphx\Forrest\Providers\Laravel\LaravelSession');
}
public function it_should_allow_a_get(SessionInterface $session)
{
$session->has(Argument::any())->shouldBeCalled()->willReturn(true);
$session->get(Argument::any())->shouldBeCalled();
$this->get('test');
}
public function it_should_allow_a_put(SessionInterface $session)
{
$session->set(Argument::any(), Argument::any())->shouldBeCalled();
$this->put('test', 'value');
}
public function it_should_allow_a_has(SessionInterface $session)
{
$session->has(Argument::any())->shouldBeCalled();
$this->has('test');
}
public function it_should_throw_an_exception_if_token_does_not_exist(SessionInterface $session)
{
$session->has(Argument::any())->shouldBeCalled()->willReturn(false);
$this->shouldThrow('\Omniphx\Forrest\Exceptions\MissingKeyException')->duringGet('test');
}
} |
Fix emplorrs demo salary db error | from django import forms
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department')
super(ChangeManagerForm, self).__init__(*args, **kwargs)
def save(self):
new_manager = self.cleaned_data['manager']
DeptManager.objects.filter(
department=self.department
).set(
department=self.department,
employee=new_manager
)
class ChangeTitleForm(forms.Form):
position = forms.CharField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeTitleForm, self).__init__(*args, **kwargs)
def save(self):
new_title = self.cleaned_data['position']
Title.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
title=new_title
)
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField(max_value=1000000)
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeSalaryForm, self).__init__(*args, **kwargs)
def save(self):
new_salary = self.cleaned_data['salary']
Salary.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
salary=new_salary,
)
| from datetime import date
from django import forms
from django.utils import timezone
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department')
super(ChangeManagerForm, self).__init__(*args, **kwargs)
def save(self):
new_manager = self.cleaned_data['manager']
DeptManager.objects.filter(
department=self.department
).set(
department=self.department,
employee=new_manager
)
class ChangeTitleForm(forms.Form):
position = forms.CharField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeTitleForm, self).__init__(*args, **kwargs)
def save(self):
new_title = self.cleaned_data['position']
Title.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
title=new_title
)
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeSalaryForm, self).__init__(*args, **kwargs)
def save(self):
new_salary = self.cleaned_data['salary']
Salary.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
salary=new_salary,
)
|
Add polib as a dependency. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
try:
from pypandoc import convert
long_description = convert('README.md', 'rst')
except IOError:
print("warning: README.md not found")
long_description = ""
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
long_description = ""
setup(
name="pybossa-pbs",
version="1.4",
author="Daniel Lombraña González",
author_email="[email protected]",
description="PyBossa command line client",
long_description=long_description,
license="AGPLv3",
url="https://github.com/PyBossa/pbs",
classifiers = ['Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',],
py_modules=['pbs', 'helpers'],
install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage',
'rednose', 'pypandoc', 'simplejson', 'jsonschema', 'polib'],
entry_points='''
[console_scripts]
pbs=pbs:cli
'''
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
try:
from pypandoc import convert
long_description = convert('README.md', 'rst')
except IOError:
print("warning: README.md not found")
long_description = ""
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
long_description = ""
setup(
name="pybossa-pbs",
version="1.4",
author="Daniel Lombraña González",
author_email="[email protected]",
description="PyBossa command line client",
long_description=long_description,
license="AGPLv3",
url="https://github.com/PyBossa/pbs",
classifiers = ['Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',],
py_modules=['pbs', 'helpers'],
install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage',
'rednose', 'pypandoc', 'simplejson', 'jsonschema'],
entry_points='''
[console_scripts]
pbs=pbs:cli
'''
)
|
Load external and internal IPs [WAL-542] | const resourceVmsList = {
controller: ProjectVirtualMachinesListController,
controllerAs: 'ListController',
templateUrl: 'views/partials/filtered-list.html',
};
export default resourceVmsList;
function ProjectVirtualMachinesListController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.VirtualMachines;
this._super();
this.rowFields.push('internal_ips');
this.rowFields.push('external_ips');
this.rowFields.push('floating_ips');
this.rowFields.push('internal_ips_set');
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no virtual machines yet';
options.noMatchesText = 'No virtual machines found matching filter.';
options.columns.push({
title: gettext('Internal IP'),
render: function(row) {
if (row.internal_ips.length === 0) {
return '–';
}
return row.internal_ips.join(', ');
}
});
options.columns.push({
title: gettext('External IP'),
render: function(row) {
if (row.external_ips.length === 0) {
return '–';
}
return row.external_ips.join(', ');
}
});
return options;
},
getImportTitle: function() {
return 'Import virtual machine';
},
getCreateTitle: function() {
return 'Add virtual machine';
},
});
controllerScope.__proto__ = new ResourceController();
}
| const resourceVmsList = {
controller: ProjectVirtualMachinesListController,
controllerAs: 'ListController',
templateUrl: 'views/partials/filtered-list.html',
};
export default resourceVmsList;
function ProjectVirtualMachinesListController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.VirtualMachines;
this._super();
this.rowFields.push('internal_ips');
this.rowFields.push('external_ips');
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no virtual machines yet';
options.noMatchesText = 'No virtual machines found matching filter.';
options.columns.push({
title: gettext('Internal IP'),
render: function(row) {
if (row.internal_ips.length === 0) {
return '–';
}
return row.internal_ips.join(', ');
}
});
options.columns.push({
title: gettext('External IP'),
render: function(row) {
if (row.external_ips.length === 0) {
return '–';
}
return row.external_ips.join(', ');
}
});
return options;
},
getImportTitle: function() {
return 'Import virtual machine';
},
getCreateTitle: function() {
return 'Add virtual machine';
},
});
controllerScope.__proto__ = new ResourceController();
}
|
Hide actions after key deletion | define('app/views/key_list', [
'text!app/templates/key_list.html',
'ember'
],
/**
*
* Key list page
*
* @returns Class
*/
function(key_list_html) {
return Ember.View.extend({
tagName: false,
init: function() {
this._super();
this.set('template', Ember.Handlebars.compile(key_list_html));
},
deleteKey: function(){
var keys = this.getSelectedKeys();
var plural = false;
if(keys.length == 0){
return;
} else if(keys.length > 1){
plural = true;
}
Mist.confirmationController.set("title", 'Delete Key' + (plural ? 's' : ''));
var names = '';
keys.forEach(function(key){
names = names + ' ' + key.name;
});
Mist.confirmationController.set("text", 'Are you sure you want to delete' +
names +'?');
Mist.confirmationController.set("callback", function(){
keys.forEach(function(key){
key.deleteKey();
window.history.go(-1);
$('#keys .keys-footer').fadeOut(200);
});
});
Mist.confirmationController.set("fromDialog", true);
Mist.confirmationController.show();
},
getSelectedKeys: function(){
var keys = new Array();
Mist.keysController.forEach(function(key){
if(key.selected){
keys.push(key);
}
});
return keys;
},
});
}
);
| define('app/views/key_list', [
'text!app/templates/key_list.html',
'ember'
],
/**
*
* Key list page
*
* @returns Class
*/
function(key_list_html) {
return Ember.View.extend({
tagName: false,
init: function() {
this._super();
this.set('template', Ember.Handlebars.compile(key_list_html));
},
deleteKey: function(){
var keys = this.getSelectedKeys();
var plural = false;
if(keys.length == 0){
return;
} else if(keys.length > 1){
plural = true;
}
Mist.confirmationController.set("title", 'Delete Key' + (plural ? 's' : ''));
var names = '';
keys.forEach(function(key){
names = names + ' ' + key.name;
});
Mist.confirmationController.set("text", 'Are you sure you want to delete' +
names +'?');
Mist.confirmationController.set("callback", function(){
keys.forEach(function(key){
key.deleteKey();
window.history.go(-1);
});
});
Mist.confirmationController.set("fromDialog", true);
Mist.confirmationController.show();
},
getSelectedKeys: function(){
var keys = new Array();
Mist.keysController.forEach(function(key){
if(key.selected){
keys.push(key);
}
});
return keys;
},
});
}
);
|
Add slave option support to the master-slave inputs JS. | $(document).ready(function () {
var showSlave = function ($master, showOn) {
if ($master.is(':checkbox')) {
return (+$master.is(':checked')).toString() === showOn;
}
var value = $master.val().toString();
if ($master.is('select') && $master.prop('multiple')) {
return value.indexOf(showOn) >= 0;
}
return value === showOn;
};
var toggleSlaveContainer = function ($slaveContainer, $master, showOn) {
$master.val() && showSlave($master, showOn) ? $slaveContainer.show() : $slaveContainer.hide();
if ($slaveContainer.is('option')) {
$slaveContainer.closest('select').trigger('chosen:updated');
}
};
$('.slave_input').each(function () {
var $slave = $(this);
var $slaveContainer = $slave.is('option') ? $slave : $slave.closest('.table_row');
var masterSelector = $slave.data('master');
var showOn = $slave.data('show-on').toString();
var $context = $slave.closest('[class*="_a2lix_translationsFields-"]');
var $master = $context.find(masterSelector).first();
if (!$master.length) {
$context = $slave.closest('form');
$master = $context.find(masterSelector).first();
}
toggleSlaveContainer($slaveContainer, $master, showOn);
$context.on('change', masterSelector, function () {
toggleSlaveContainer($slaveContainer, $(this), showOn);
});
});
});
| $(document).ready(function () {
var showSlave = function ($master, showOn) {
if ($master.is(':checkbox')) {
return (+$master.is(':checked')).toString() === showOn;
}
var value = $master.val().toString();
if ($master.is('select') && $master.prop('multiple')) {
return value.indexOf(showOn) >= 0;
}
return value === showOn;
};
var toggleSlaveContainer = function ($slaveContainer, $master, showOn) {
$master.val() && showSlave($master, showOn) ? $slaveContainer.show() : $slaveContainer.hide();
};
$('.slave_input').each(function () {
var $slave = $(this);
var $slaveContainer = $slave.closest('.table_row');
var masterSelector = $slave.data('master');
var showOn = $slave.data('show-on').toString();
var $context = $slave.closest('[class*="_a2lix_translationsFields-"]');
var $master = $context.find(masterSelector).first();
if (!$master.length) {
$context = $slave.closest('form');
$master = $context.find(masterSelector).first();
}
toggleSlaveContainer($slaveContainer, $master, showOn);
$context.on('change', masterSelector, function () {
toggleSlaveContainer($slaveContainer, $(this), showOn);
});
});
});
|
Create a gulp task to run pipeline once | 'use strict';
const gulp = require('gulp'),
fs = require('fs'),
plumber = require('gulp-plumber');
const options = {
source: 'templates',
dist: 'dist',
workingDir: 'tmp',
src: function plumbedSrc() {
return gulp.src.apply(gulp, arguments).pipe(plumber());
}
};
/**
* Load tasks from the '/tasks' directory.
*/
const build = require('./tasks/build')(options);
const checkDeps = require('./tasks/check-deps')(options);
const dupe = require('./tasks/dupe')(options);
const less = require('./tasks/less')(options);
const lint = require('./tasks/lint')(options);
const postcss = require('./tasks/postcss')(options);
const sass = require('./tasks/sass')(options);
/* Runs the entire pipeline once. */
gulp.task('run-pipeline', gulp.series('dupe', 'less', 'sass', 'postcss', 'lint', 'build'));
/* By default templates will be built into '/dist'. */
gulp.task(
'default',
gulp.series(
'run-pipeline',
() => {
/* gulp will watch for changes in '/templates'. */
gulp.watch(
[
options.source + '/**/*.html',
options.source + '/**/*.css',
options.source + '/**/*.scss',
options.source + '/**/*.less',
options.source + '/**/conf.json'
],
{ delay: 500 },
gulp.series('run-pipeline')
)
}
)
);
| 'use strict';
const gulp = require('gulp'),
fs = require('fs'),
plumber = require('gulp-plumber');
const options = {
source: 'templates',
dist: 'dist',
workingDir: 'tmp',
src: function plumbedSrc() {
return gulp.src.apply(gulp, arguments).pipe(plumber());
}
};
/**
* Load tasks from the '/tasks' directory.
*/
const build = require('./tasks/build')(options);
const checkDeps = require('./tasks/check-deps')(options);
const dupe = require('./tasks/dupe')(options);
const less = require('./tasks/less')(options);
const lint = require('./tasks/lint')(options);
const postcss = require('./tasks/postcss')(options);
const sass = require('./tasks/sass')(options);
/* By default templates will be built into '/dist' */
gulp.task(
'default',
gulp.series(
('dupe', 'less', 'sass', 'postcss', 'lint', 'build'),
() => {
/* gulp will watch for changes in '/templates'. */
gulp.watch(
[
options.source + '/**/*.html',
options.source + '/**/*.css',
options.source + '/**/*.scss',
options.source + '/**/*.less',
options.source + '/**/conf.json'
],
{ delay: 500 },
gulp.series('dupe', 'less', 'sass', 'postcss', 'lint', 'build')
)
}
)
);
|
Make getImage non-static, correct default path | <?php
/**
* @package Mautic
* @copyright 2014 Mautic, NP. All rights reserved.
* @author Mautic
* @link http://mautic.com
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Templating\Helper;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Helper\UrlHelper;
use Symfony\Component\Templating\Helper\Helper;
class GravatarHelper extends Helper
{
private static $devMode;
public function __construct(MauticFactory $factory)
{
self::$devMode = $factory->getEnvironment() == 'dev';
}
public function getImage($email, $size = '250', $default = null)
{
$localDefault = 'media/images/avatar.png';
$url = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s='.$size;
if ($default !== false && !self::$devMode) {
if ($default === null) {
$default = $localDefault;
}
$default = (strpos($default, '.') !== false && strpos($default, 'http') !== 0) ? UrlHelper::rel2abs($default) : $default;
$url .= '&d=' . urlencode($default);
}
return $url;
}
public function getName()
{
return 'gravatar';
}
}
| <?php
/**
* @package Mautic
* @copyright 2014 Mautic, NP. All rights reserved.
* @author Mautic
* @link http://mautic.com
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Templating\Helper;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Helper\UrlHelper;
use Symfony\Component\Templating\Helper\Helper;
class GravatarHelper extends Helper
{
private static $devMode;
public function __construct(MauticFactory $factory)
{
self::$devMode = $factory->getEnvironment() == 'dev';
}
static public function getImage($email, $size = '250', $default = null)
{
$localDefault = 'assets/images/avatar.png';
$url = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s='.$size;
if ($default !== false && !self::$devMode) {
if ($default === null) {
$default = $localDefault;
}
$default = (strpos($default, '.') !== false && strpos($default, 'http') !== 0) ? UrlHelper::rel2abs($default) : $default;
$url .= '&d=' . urlencode($default);
}
return $url;
}
public function getName()
{
return 'gravatar';
}
} |
Allow project to live in non-root directory. | <?php
require_once './vendor/autoload.php';
use Turbine\Application;
$config = [
'baseDirectory' => '/PlexRSSFeed'
];
$app = new Application($config);
if (getenv('DEVELOPMENT') === 'true') {
$app->getErrorHandler()->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$app->setConfig('error', true);
}
$container = $app->getContainer();
$app->getContainer()->share(\Zend\Diactoros\Response\EmitterInterface::class, \PlexRSSFeed\RSSEmitter::class);
$container->share('\Suin\RSSWriter\Feed');
$container->add('\Suin\RSSWriter\Channel');
$container->add('\Suin\RSSWriter\Item');
$container->add('\PlexRSSFeed\Factory\ChannelFactory')
->withMethodCall(
'setContainer',
[new League\Container\Argument\RawArgument($container)]
);
$container->add('\PlexRSSFeed\Factory\ItemFactory')
->withMethodCall(
'setContainer',
[new League\Container\Argument\RawArgument($container)]
);
$container->add('\PlexRSSFeed\Controller\FeedController')
->withArguments([
'\Suin\RSSWriter\Feed',
'\PlexRSSFeed\Factory\ChannelFactory',
'\PlexRSSFeed\Factory\ItemFactory'
]);
$app->get($config['baseDirectory'] . '/{feed}/{items}', '\PlexRSSFeed\Controller\FeedController::__invoke');
$app->run();
| <?php
require_once './vendor/autoload.php';
use Turbine\Application;
$config = [];
$app = new Application($config);
if (getenv('DEVELOPMENT') === 'true') {
$app->getErrorHandler()->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$app->setConfig('error', true);
}
$container = $app->getContainer();
$app->getContainer()->share(\Zend\Diactoros\Response\EmitterInterface::class, \PlexRSSFeed\RSSEmitter::class);
$container->share('\Suin\RSSWriter\Feed');
$container->add('\Suin\RSSWriter\Channel');
$container->add('\Suin\RSSWriter\Item');
$container->add('\PlexRSSFeed\Factory\ChannelFactory')
->withMethodCall(
'setContainer',
[new League\Container\Argument\RawArgument($container)]
);
$container->add('\PlexRSSFeed\Factory\ItemFactory')
->withMethodCall(
'setContainer',
[new League\Container\Argument\RawArgument($container)]
);
$container->add('\PlexRSSFeed\Controller\FeedController')
->withArguments([
'\Suin\RSSWriter\Feed',
'\PlexRSSFeed\Factory\ChannelFactory',
'\PlexRSSFeed\Factory\ItemFactory'
]);
$app->get('/{feed}/{items}', '\PlexRSSFeed\Controller\FeedController::__invoke');
$app->run();
|
Fix a JS error in ContactActions | var ContactActions = {
getDrawerFingerprints : function(jid) {
var store = new ChatOmemoStorage();
store.getLocalRegistrationId().then(deviceId => {
ContactActions_ajaxGetDrawerFingerprints(jid, deviceId);
});
},
morePictures(button, jid, page) {
button.remove();
ContactActions_ajaxHttpGetPictures(jid, page);
},
moreLinks(button, jid, page) {
button.remove();
ContactActions_ajaxHttpGetLinks(jid, page);
},
resolveSessionsStates : function(jid) {
var store = new ChatOmemoStorage();
store.getSessionsIds(jid).map(id => {
store.getSessionState(jid + '.' + id).then(state => {
if (state) {
let icon = document.querySelector('span#sessionicon_' + id);
if (icon) {
icon.classList.remove('blue');
icon.classList.add('blue');
}
let checkbox = document.querySelector('input[name=sessionstate_' + id + ']');
if (checkbox) {
checkbox.checked = true;
}
}
})
});
store.getContactState(jid).then(enabled => {
if (!enabled) {
document.querySelector('#omemo_fingerprints ul.list').classList.add('disabled');
}
});
},
toggleFingerprintState : function(checkbox) {
var store = new ChatOmemoStorage();
store.setSessionState(checkbox.dataset.identifier, checkbox.checked);
}
} | var ContactActions = {
getDrawerFingerprints : function(jid) {
var store = new ChatOmemoStorage();
store.getLocalRegistrationId().then(deviceId => {
ContactActions_ajaxGetDrawerFingerprints(jid, deviceId);
});
},
morePictures(button, jid, page) {
button.remove();
ContactActions_ajaxHttpGetPictures(jid, page);
},
moreLinks(button, jid, page) {
button.remove();
ContactActions_ajaxHttpGetLinks(jid, page);
},
resolveSessionsStates : function(jid) {
var store = new ChatOmemoStorage();
store.getSessionsIds(jid).map(id => {
store.getSessionState(jid + '.' + id).then(state => {
if (state) {
let icon = document.querySelector('span#sessionicon_' + id);
icon.classList.remove('blue');
icon.classList.add('blue');
let checkbox = document.querySelector('input[name=sessionstate_' + id + ']');
checkbox.checked = true;
}
})
});
store.getContactState(jid).then(enabled => {
if (!enabled) {
document.querySelector('#omemo_fingerprints ul.list').classList.add('disabled');
}
});
},
toggleFingerprintState : function(checkbox) {
var store = new ChatOmemoStorage();
store.setSessionState(checkbox.dataset.identifier, checkbox.checked);
}
} |
Fix: Remove unintended POST request when loading subtitles | /**
* Moovie: an advanced HTML5 video player for MooTools.
* @copyright 2010 Colin Aarts
* @license MIT
*/
import { WebSRT } from './WebSRT.js';
import { WebVTT } from 'vtt.js';
/**
* Loads and parses the track based on the filetype.
* @type {Class}
*/
const Loader = new Class({
initialize: function (url, srclang, onCue) {
this.url = url;
this.srclang = srclang;
this.onCue = onCue;
this.sendRequest();
},
sendRequest: function () {
const request = new Request({
method: 'GET',
url: this.url,
onSuccess: (data) => {
const parser = this.getParser(this.url.split('.').pop());
parser.oncue = (cue) => {
this.onCue(cue);
};
parser.parse(data);
parser.flush();
}
});
request.send();
},
getParser: function (ext) {
if (ext === 'srt') {
return new WebSRT.Parser();
} else if (ext === 'vtt') {
return new WebVTT.Parser(window, WebVTT.StringDecoder());
}
throw new Error(`Unsupported file type: ${ext}`);
}
});
export default Loader;
| /**
* Moovie: an advanced HTML5 video player for MooTools.
* @copyright 2010 Colin Aarts
* @license MIT
*/
import { WebSRT } from './WebSRT.js';
import { WebVTT } from 'vtt.js';
/**
* Loads and parses the track based on the filetype.
* @type {Class}
*/
const Loader = new Class({
initialize: function (url, srclang, onCue) {
this.url = url;
this.srclang = srclang;
this.onCue = onCue;
this.sendRequest();
},
sendRequest: function () {
const request = new Request({
url: this.url,
onSuccess: (data) => {
const parser = this.getParser(this.url.split('.').pop());
parser.oncue = (cue) => {
this.onCue(cue);
};
parser.parse(data);
parser.flush();
}
});
request.send();
},
getParser: function (ext) {
if (ext === 'srt') {
return new WebSRT.Parser();
} else if (ext === 'vtt') {
return new WebVTT.Parser(window, WebVTT.StringDecoder());
}
throw new Error(`Unsupported file type: ${ext}`);
}
});
export default Loader;
|
Include correct documentation URL in error message | import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
| import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
Update user to be confirmed by default. | <?php
class UsersTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
$users = array(
array(
'username' => 'admin',
'email' => '[email protected]',
'password' => Hash::make('admin'),
'confirmed' => 1,
'confirmation_code' => md5(microtime().Config::get('app.key')),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'username' => 'user',
'email' => '[email protected]',
'password' => Hash::make('user'),
'confirmed' => 1,
'confirmation_code' => md5(microtime().Config::get('app.key')),
'created_at' => new DateTime,
'updated_at' => new DateTime,
)
);
DB::table('users')->insert( $users );
}
}
| <?php
class UsersTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
$users = array(
array(
'username' => 'admin',
'email' => '[email protected]',
'password' => Hash::make('admin'),
'confirmed' => 0,
'confirmation_code' => md5(microtime().Config::get('app.key')),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'username' => 'user',
'email' => '[email protected]',
'password' => Hash::make('user'),
'confirmed' => 0,
'confirmation_code' => md5(microtime().Config::get('app.key')),
'created_at' => new DateTime,
'updated_at' => new DateTime,
)
);
DB::table('users')->insert( $users );
}
}
|
ZON-3178: Update test, the article now starts with a default value for `template` (belongs to commit:95a001d) | # coding: utf8
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', 'Artikel')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
| # coding: utf8
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', '(nothing selected)')
s.assertNotVisible('css=.fieldname-header_layout')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
|
Use LocalDisk as data storage | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
connection: 'localDiskDb',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'alter'
};
| /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
// connection: 'localDiskDb',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
// migrate: 'alter'
};
|
Fix incorrect property name for getUserHomeDirectory()
Change-Id: I34f209afae4d5ab2373aef8174bbee0d2fcfca6b | package ru.linachan.yggdrasil.common;
import java.io.File;
public class SystemInfo {
public static File getWorkingDirectory() {
return new File(System.getProperty("user.dir"));
}
public static String getUser() {
return System.getProperty("user.name");
}
public static File getUserHomeDirectory() {
return new File(System.getProperty("user.home"));
}
public static String getUserLanguage() {
return System.getProperty("user.language");
}
public static String getOSName() {
return System.getProperty("os.name");
}
public static OSType getOSType() {
String osName = System.getProperty("os.name");
if (osName.contains("win"))
return OSType.WINDOWS;
if (osName.contains("mac"))
return OSType.OSX;
if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix"))
return OSType.UNIX;
return OSType.OTHER;
}
public static OSArch getOSArch() {
String osArch = System.getProperty("os.arch");
if (osArch.contains("64"))
return OSArch.X64;
if (osArch.contains("86"))
return OSArch.X86;
return OSArch.OTHER;
}
public static String getOSVersion() {
return System.getProperty("os.version");
}
public enum OSType {
WINDOWS, UNIX, OSX, OTHER, ALL
}
public enum OSArch {
X64, X86, OTHER, ALL
}
}
| package ru.linachan.yggdrasil.common;
import java.io.File;
public class SystemInfo {
public static File getWorkingDirectory() {
return new File(System.getProperty("user.dir"));
}
public static String getUser() {
return System.getProperty("user.name");
}
public static File getUserHomeDirectory() {
return new File(System.getProperty("user.dir"));
}
public static String getUserLanguage() {
return System.getProperty("user.language");
}
public static String getOSName() {
return System.getProperty("os.name");
}
public static OSType getOSType() {
String osName = System.getProperty("os.name");
if (osName.contains("win"))
return OSType.WINDOWS;
if (osName.contains("mac"))
return OSType.OSX;
if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix"))
return OSType.UNIX;
return OSType.OTHER;
}
public static OSArch getOSArch() {
String osArch = System.getProperty("os.arch");
if (osArch.contains("64"))
return OSArch.X64;
if (osArch.contains("86"))
return OSArch.X86;
return OSArch.OTHER;
}
public static String getOSVersion() {
return System.getProperty("os.version");
}
public enum OSType {
WINDOWS, UNIX, OSX, OTHER, ALL
}
public enum OSArch {
X64, X86, OTHER, ALL
}
}
|
Document reason for class instead of free function | from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
# functions using database (extraction_order) must be instance methods of a class
# -> free functions will not work: database connection error
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
| from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
|
Fix missing Halis Book font on website | /* global window */
/* @jsx createElement */
// @flow
// eslint-disable-next-line no-unused-vars
import { createElement } from 'jsx-dom';
import { watch } from '../core';
// $FlowFixMe
import cardInfoHeader from '../assets/tooltip-header-sprite.png';
// $FlowFixMe
import cardInfoBackground from '../assets/tooltip-text-background.png';
// $FlowFixMe
import Gwent from '../assets/fonts/hinted-GWENT-ExtraBold.woff2';
// $FlowFixMe
import HalisGRRegular from '../assets/fonts/hinted-HalisGR-Regular.woff2';
// $FlowFixMe
import HalisGRBold from '../assets/fonts/hinted-HalisGR-Bold.woff2';
// $FlowFixMe importing so that it is copied to the font folder
import '../assets/fonts/hinted-HalisGR-Book.woff2';
// Setup the homepage
async function onLoad() {
// fetch card data
const { cards, dictionary } = await fetchJson('./data.json');
// Start watching the whole body for card names.
watch(
window.document.body,
{
cards,
dictionary,
assets: {
cardInfoHeader,
cardInfoBackground,
Gwent,
HalisGRRegular,
HalisGRBold
}
},
{ shouldUnderline: true }
);
}
async function fetchJson(src: string): Promise<Object> {
const response = await window.fetch(src);
const json = await response.json();
return json;
}
onLoad();
| /* global window */
/* @jsx createElement */
// @flow
// eslint-disable-next-line no-unused-vars
import { createElement } from 'jsx-dom';
import { watch } from '../core';
// $FlowFixMe
import cardInfoHeader from '../assets/tooltip-header-sprite.png';
// $FlowFixMe
import cardInfoBackground from '../assets/tooltip-text-background.png';
// $FlowFixMe
import Gwent from '../assets/fonts/hinted-GWENT-ExtraBold.woff2';
// $FlowFixMe
import HalisGRRegular from '../assets/fonts/hinted-HalisGR-Regular.woff2';
// $FlowFixMe
import HalisGRBold from '../assets/fonts/hinted-HalisGR-Bold.woff2';
// Setup the homepage
async function onLoad() {
// fetch card data
const { cards, dictionary } = await fetchJson('./data.json');
// Start watching the whole body for card names.
watch(
window.document.body,
{
cards,
dictionary,
assets: {
cardInfoHeader,
cardInfoBackground,
Gwent,
HalisGRRegular,
HalisGRBold
}
},
{ shouldUnderline: true }
);
}
async function fetchJson(src: string): Promise<Object> {
const response = await window.fetch(src);
const json = await response.json();
return json;
}
onLoad();
|
Check function and branch coverage | module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation + "/coverage",
check: {
lines: 100,
statements: 100,
branches: 100,
functions: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
| module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation + "/coverage",
check: {
lines: 100,
statements: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
|
:racehorse: Fix memory leak in Image component prefetch | import React, { Component } from 'react';
import './image.css';
import placeholderImg from './placeholder.png';
import { prefetch } from '@utils/image.utils';
class Image extends Component {
static defaultProps = {
alt: '',
placeholder: placeholderImg,
extraClasses: '',
};
state = {
prefetchedSource: placeholderImg,
isLoaded: false,
isError: false
};
prefetchImage = () => {
const { src, timeout } = this.props;
prefetch(src, timeout)
.then(this.handlePrefetchSuccess)
.catch(this.handlePrefetchError);
};
handlePrefetchSuccess = (img) => {
if (!this._mounted) return;
const { src, onLoad } = this.props;
this.setState({
prefetchedSource: src,
isLoaded: true,
isError: false,
});
onLoad && onLoad(img);
};
handlePrefetchError = (img) => {
if (!this._mounted) return;
const { onError, placeholder } = this.props;
this.setState({
prefetchedSource: placeholder,
isLoaded: true,
isError: false,
});
onError && onError(img);
};
componentWillUnmount() {
this._mounted = false;
}
componentDidMount() {
this._mounted = true;
this.prefetchImage();
}
render() {
const {
alt,
placeholder,
extraClasses
} = this.props;
const {
prefetchedSource,
isLoaded,
isError
} = this.state;
const imageSource = isLoaded ? prefetchedSource : placeholder;
const isLoadingClass = !isLoaded && !isError ? 'image__loading' : '';
return (
<img
className={ `image ${isLoadingClass} ${extraClasses}` }
src={ imageSource }
alt={ alt } />
);
}
}
export default Image;
| import React, { Component } from 'react';
import './image.css';
import placeholderImg from './placeholder.png';
import { prefetch } from '@utils/image.utils';
class Image extends Component {
static defaultProps = {
alt: '',
placeholder: placeholderImg,
extraClasses: '',
onLoad: x => x,
onError: x => x
};
state = {
isLoaded: false,
isError: false
};
componentDidMount() {
const {
src,
timeout,
onLoad,
onError
} = this.props;
prefetch(src, timeout)
.then(img => {
this.setState({
isLoaded: true,
isError: false
});
onLoad(img);
})
.catch(img => {
this.setState({
isLoaded: false,
isError: true
});
onError(img);
});
}
render() {
const {
src,
alt,
placeholder,
extraClasses
} = this.props;
const {
isLoaded,
isError
} = this.state;
const imageSource = isLoaded ? src : placeholder;
const isLoadingClass = !isLoaded && !isError ? 'image__loading' : '';
return (
<img
className={ `image ${isLoadingClass} ${extraClasses}` }
src={ imageSource }
alt={ alt } />
);
}
}
export default Image;
|
Use index context manager for sync | # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
def add_arguments(self, parser):
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
default=False,
help='Delete existing index',
)
def handle(self, delete, *args, **options):
indices = registered_indices()
connection = connections.get_connection()
hues.info('Using connection', connection)
if len(indices):
hues.info('Discovered', len(indices), 'Indexes')
else:
hues.warn('No search index found')
for i, index in enumerate(indices, 1):
hues.info('==> Initializing', index.__name__)
with index().ensure_closed_and_reopened() as ix:
if delete:
hues.warn('Deleting existing index.')
ix.delete()
ix.init()
hues.success('--> Done {0}/{1}'.format(i, len(indices)))
| # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch import exceptions
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
def add_arguments(self, parser):
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
default=False,
help='Delete existing index',
)
def handle(self, delete, *args, **options):
indices = registered_indices()
connection = connections.get_connection()
hues.info('Using connection', connection)
if len(indices):
hues.info('Discovered', len(indices), 'Indexes')
else:
hues.warn('No search index found')
for i, index in enumerate(indices, 1):
hues.info('==> Initializing', index.__name__)
index_name = index._doc_type.index
try:
connection.indices.close(index_name)
if delete:
hues.warn('Deleting existing index.')
connection.indices.delete(index_name)
except exceptions.NotFoundError:
pass
index.init()
connection.indices.open(index_name)
hues.success('--> Done {0}/{1}'.format(i, len(indices)))
|
Change component category to media | <?php
class Kwc_Basic_FullWidthImage_Component extends Kwc_TextImage_ImageEnlarge_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['componentName'] = trlKwfStatic('Picture 100% width');
$ret['componentCategory'] = 'media';
$ret['componentPriority'] = 50;
$ret['showHelpText'] = true;
$ret['defineWidth'] = false;
$ret['dimensions'] = array(
'default'=>array(
'text' => trlKwfStatic('full width'),
'width' => self::CONTENT_WIDTH,
'height' => 0,
'cover' => true
),
'16to9'=>array(
'text' => trlKwfStatic('full width').' 16:9',
'width' => self::CONTENT_WIDTH,
'cover' => true,
'aspectRatio' => 9/16
),
'4to3'=>array(
'text' => trlKwfStatic('full width').' 4:3',
'width' => self::CONTENT_WIDTH,
'cover' => true,
'aspectRatio' => 3/4
)
);
return $ret;
}
}
| <?php
class Kwc_Basic_FullWidthImage_Component extends Kwc_TextImage_ImageEnlarge_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['componentName'] = trlKwfStatic('Picture 100% width');
$ret['componentCategory'] = 'content';
$ret['componentPriority'] = 50;
$ret['showHelpText'] = true;
$ret['defineWidth'] = false;
$ret['dimensions'] = array(
'default'=>array(
'text' => trlKwfStatic('full width'),
'width' => self::CONTENT_WIDTH,
'height' => 0,
'cover' => true
),
'16to9'=>array(
'text' => trlKwfStatic('full width').' 16:9',
'width' => self::CONTENT_WIDTH,
'cover' => true,
'aspectRatio' => 9/16
),
'4to3'=>array(
'text' => trlKwfStatic('full width').' 4:3',
'width' => self::CONTENT_WIDTH,
'cover' => true,
'aspectRatio' => 3/4
)
);
return $ret;
}
}
|
Clean up duplicate code in controllers | package org.apereo.cas.web.report;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;
import java.util.Map;
/**
* This is {@link ControllerUtils}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
final class ControllerUtils {
private ControllerUtils() {
}
/**
* Configure model map for config server cloud bus endpoints.
*
* @param busProperties the bus properties
* @param configServerProperties the config server properties
* @param path the path
* @param model the model
*/
public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
final ConfigServerProperties configServerProperties,
final String path,
final Map model) {
if (busProperties != null && busProperties.isEnabled()) {
model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
model.put("refreshMethod", "GET");
} else {
model.put("refreshEndpoint", path + "/status/refresh");
model.put("refreshMethod", "POST");
}
}
}
| package org.apereo.cas.web.report;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;
import java.util.Map;
/**
* This is {@link ControllerUtils}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
public final class ControllerUtils {
private ControllerUtils() {
}
/**
* Configure model map for config server cloud bus endpoints.
*
* @param busProperties the bus properties
* @param configServerProperties the config server properties
* @param path the path
* @param model the model
*/
public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
final ConfigServerProperties configServerProperties,
final String path,
final Map model) {
if (busProperties != null && busProperties.isEnabled()) {
model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
model.put("refreshMethod", "GET");
} else {
model.put("refreshEndpoint", path + "/status/refresh");
model.put("refreshMethod", "POST");
}
}
}
|
[TASK] Change name of uuid to fingerprint in command | <?php
namespace Flowpack\SingleSignOn\Client\Command;
/* *
* This script belongs to the TYPO3 Flow package "Flowpack.SingleSignOn.Client". *
* */
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Cli\CommandController;
/**
* Command controller for the SSO key management
*
* @Flow\Scope("singleton")
*/
class SsoKeyCommandController extends CommandController {
/**
* @var \TYPO3\Flow\Security\Cryptography\RsaWalletServiceInterface
* @Flow\Inject
*/
protected $rsaWalletService;
/**
* Generate key pair command
*
* Creates a new key pair and imports it into the wallet.
* Used by SSO client and server.
*
* @return void
*/
public function generateKeyPairCommand() {
$publicKeyFingerprint = $this->rsaWalletService->generateNewKeypair();
$this->outputLine('Created key with fingerprint: ' . $publicKeyFingerprint);
}
/**
* Export a public key
*
* @param string $publicKeyFingerprint
* @return void
*/
public function exportPublicKeyCommand($publicKeyFingerprint) {
$publicKey = $this->rsaWalletService->getPublicKey($publicKeyFingerprint);
$this->output($publicKey->getKeyString());
}
}
?> | <?php
namespace Flowpack\SingleSignOn\Client\Command;
/* *
* This script belongs to the TYPO3 Flow package "Flowpack.SingleSignOn.Client". *
* */
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Cli\CommandController;
/**
* Command controller for the SSO key management
*
* @Flow\Scope("singleton")
*/
class SsoKeyCommandController extends CommandController {
/**
* @var \TYPO3\Flow\Security\Cryptography\RsaWalletServiceInterface
* @Flow\Inject
*/
protected $rsaWalletService;
/**
* Generate key pair command
*
* Creates a new key pair and imports it into the wallet.
* Used by SSO client and server.
*
* @return void
*/
public function generateKeyPairCommand() {
$keyUuid = $this->rsaWalletService->generateNewKeypair();
$this->outputLine('Created key with uuid: ' . $keyUuid);
}
/**
* Export a public key
*
* @param string $publicKeyFingerprint
* @return void
*/
public function exportPublicKeyCommand($publicKeyFingerprint) {
$publicKey = $this->rsaWalletService->getPublicKey($publicKeyFingerprint);
$this->output($publicKey->getKeyString());
}
}
?> |
Fix an issue with grid post rendering. | import React from 'react'
import { parsePost } from '../parsers/PostParser'
class PostsAsGrid extends React.Component {
static propTypes = {
posts: React.PropTypes.object,
json: React.PropTypes.object,
currentUser: React.PropTypes.object,
gridColumnCount: React.PropTypes.number,
}
renderColumn(posts, index) {
const { json, currentUser } = this.props
return (
<div className="Column" key={`column_${index}`}>
{posts.map((post) => {
return (
<article ref={`postGrid_${post.id}`} key={post.id} className="Post PostGrid">
{parsePost(post, json, currentUser)}
</article>
)
})}
</div>
)
}
render() {
const { posts, gridColumnCount } = this.props
if (!gridColumnCount) { return null }
const columns = []
for (let i = 0; i < gridColumnCount; i++) {
columns.push([])
}
for (const index in posts.data) {
if (posts.data[index]) {
columns[index % gridColumnCount].push(posts.data[index])
}
}
return (
<div className="Posts asGrid">
{columns.map((column, index) => {
return this.renderColumn(column, index)
})}
</div>
)
}
}
export default PostsAsGrid
| import React from 'react'
import { parsePost } from '../parsers/PostParser'
class PostsAsGrid extends React.Component {
static propTypes = {
posts: React.PropTypes.object,
json: React.PropTypes.object,
currentUser: React.PropTypes.object,
gridColumnCount: React.PropTypes.number,
}
renderColumn(posts) {
const { json, currentUser } = this.props
return (
<div className="Column">
{posts.map((post) => {
return (
<article ref={`postGrid_${post.id}`} key={post.id} className="Post PostGrid">
{parsePost(post, json, currentUser)}
</article>
)
})}
</div>
)
}
render() {
const { posts, gridColumnCount } = this.props
if (!gridColumnCount) { return null }
const columns = []
for (let i = 0; i < gridColumnCount; i++) {
columns.push([])
}
for (const index in posts.data) {
if (posts.data[index]) {
columns[index % gridColumnCount].push(posts.data[index])
}
}
return (
<div className="Posts asGrid">
{columns.map((column) => {
return this.renderColumn(column)
})}
</div>
)
}
}
export default PostsAsGrid
|
Fix issue with has meta to match get meta | <?php
namespace Coreplex\Meta\Eloquent;
use Coreplex\Meta\Contracts\Variant;
trait HasMetaData
{
/**
* Retrieve the meta data for this model
*
* @param Variant $variant
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function meta(Variant $variant = null)
{
if ( ! $variant) {
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
}
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
->where('variant_id', $variant->getKey())
->where('variant_type', $variant->getType());
}
/**
* Check if the meta has been set for the metable item, if a variant is
* passed then check if it is set for the variant.
*
* @param Variant|null $variant
* @return bool
*/
public function hasMeta(Variant $variant = null)
{
if (! empty($variant)) {
return $this->meta($variant)->exists();
}
$this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
}
/**
* Get the meta data for the metable item.
*
* @param Variant|null $variant
* @return mixed
*/
public function getMeta(Variant $variant = null)
{
if ($variant) {
return $this->meta($variant)->getResults();
}
return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
}
}
| <?php
namespace Coreplex\Meta\Eloquent;
use Coreplex\Meta\Contracts\Variant;
trait HasMetaData
{
/**
* Retrieve the meta data for this model
*
* @param Variant $variant
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function meta(Variant $variant = null)
{
if ( ! $variant) {
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
}
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
->where('variant_id', $variant->getKey())
->where('variant_type', $variant->getType());
}
/**
* Check if the meta has been set for the metable item, if a variant is
* passed then check if it is set for the variant.
*
* @param Variant|null $variant
* @return bool
*/
public function hasMeta(Variant $variant = null)
{
return $this->meta($variant)->exists();
}
/**
* Get the meta data for the metable item.
*
* @param Variant|null $variant
* @return mixed
*/
public function getMeta(Variant $variant = null)
{
if ($variant) {
return $this->meta($variant)->getResults();
}
return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
}
}
|
Clean up enumerations in Bats Hotspot FIX Proxy 4.0 | package com.paritytrading.philadelphia.hotspot;
/**
* Enumerations for Bats Hotspot FIX Proxy 4.0.
*/
public class HotspotEnumerations {
/**
* Values for CxlRejReason(102).
*/
public static class HotspotCxlRejReasonValues {
public static final int TooLateToCancel = 0;
public static final int UnknownOrder = 1;
public static final int OrderAlreadyInPendingStatus = 3;
public static final int DuplicateClOrdID = 6;
public static final int Other = 99;
private HotspotCxlRejReasonValues() {
}
}
/**
* Values for ExecType(150).
*/
public static class HotspotExecTypeValues {
public static final char New = '0';
public static final char DoneForDay = '3';
public static final char Canceled = '4';
public static final char Replace = '5';
public static final char PendingCancel = '6';
public static final char Rejected = '8';
public static final char Expired = 'C';
public static final char AcceptedForPidding = 'D';
public static final char PendingReplace = 'E';
public static final char Trade = 'F';
public static final char Status = 'I';
private HotspotExecTypeValues() {
}
}
private HotspotEnumerations() {
}
}
| package com.paritytrading.philadelphia.hotspot;
/**
* Enumerations for Bats Hotspot FIX Proxy 4.0.
*/
public class HotspotEnumerations {
/**
* Values for CxlRejReason(102).
*/
public static class HotspotCxlRejReasonValues {
public static final int TooLateToCancel = 0;
public static final int UnknownOrder = 1;
public static final int OrderAlreadyInPendingStatus = 3;
public static final int DuplicateClOrdID = 6;
public static final int Other = 99;
private HotspotCxlRejReasonValues() {
}
}
/**
* Values for ExecType(150).
*/
public static class HotspotExecTypeValues {
public static final char New = '0';
public static final char DoneForDay = '3';
public static final char Canceled = '4';
public static final char Replace = '5';
public static final char PendingCancel = '6';
public static final char Rejected = '8';
public static final char Expired = 'C';
public static final char AcceptedForPidding = 'D';
public static final char PendingReplace = 'E';
public static final char Trade = 'F';
public static final char Status = 'I';
private HotspotExecTypeValues() {
}
}
}
|
Fix NPE while creating tests. | package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.db.TestPlan;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import org.openide.util.Utilities;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setTestPlan(Utilities.actionsGlobalContext().lookup(TestPlan.class));
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
| package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
|
Add Python 3 Only classifier and python_requires >= 3.5
in setup.py | #!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path) as f:
return f.read()
setup(
name='pytest-testdox',
version='1.2.1',
description='A testdox format reporter for pytest',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='[email protected]',
url='https://github.com/renanivo/pytest-testdox',
keywords='pytest testdox test report bdd',
install_requires=[
'pytest>=3.7.0',
],
packages=['pytest_testdox'],
python_requires=">=3.5",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
],
entry_points={
'pytest11': [
'testdox = pytest_testdox.plugin',
],
},
)
| #!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path) as f:
return f.read()
setup(
name='pytest-testdox',
version='1.2.1',
description='A testdox format reporter for pytest',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='[email protected]',
url='https://github.com/renanivo/pytest-testdox',
keywords='pytest testdox test report bdd',
install_requires=[
'pytest>=3.7.0',
],
packages=['pytest_testdox'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Pytest',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
entry_points={
'pytest11': [
'testdox = pytest_testdox.plugin',
],
},
)
|
Create APIServer view on notification
used to json render | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
from django.http import StreamingHttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from opps.api.views.generic.list import ListView as ListAPIView
from opps.views.generic.detail import DetailView
from opps.db import Db
from .models import Notification
class AsyncServer(DetailView):
model = Notification
def _queue(self):
_db = Db(self.get_object.get_absolute_url(),
self.get_object().id)
pubsub = _db.object().pubsub()
pubsub.subscribe(_db.key)
while True:
for m in pubsub.listen():
if m['type'] == 'message':
yield u"data: {}\n\n".format(m['data'])
yield u"data: {}\n\n".format(json.dumps({"action": "ping"}))
time.sleep(0.5)
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
response = StreamingHttpResponse(self._queue(),
mimetype='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Software'] = 'opps-liveblogging'
response['Access-Control-Allow-Origin'] = '*'
response.flush()
return response
class APIServer(ListAPIView):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
from django.http import StreamingHttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from opps.views.generic.detail import DetailView
from opps.db import Db
from .models import Notification
class AsyncServer(DetailView):
model = Notification
def _queue(self):
_db = Db(self.get_object.get_absolute_url(),
self.get_object().id)
pubsub = _db.object().pubsub()
pubsub.subscribe(_db.key)
while True:
for m in pubsub.listen():
if m['type'] == 'message':
yield u"data: {}\n\n".format(m['data'])
yield u"data: {}\n\n".format(json.dumps({"action": "ping"}))
time.sleep(0.5)
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
response = StreamingHttpResponse(self._queue(),
mimetype='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Software'] = 'opps-liveblogging'
response['Access-Control-Allow-Origin'] = '*'
response.flush()
return response
|
Fix syntax error in PHP 5.3 | <?php
namespace Concise\Matcher;
class UrlHasPart extends AbstractMatcher
{
public function supportedSyntaxes()
{
return array(
'url ?:string has scheme ?:string' => 'URL has scheme.',
'url ?:string has host ?:string' => 'URL has host.',
'url ?:string has port ?:int' => 'URL has port.',
'url ?:string has user ?:string' => 'URL has user.',
'url ?:string has password ?:string' => 'URL has password.',
'url ?:string has path ?:string' => 'URL has path.',
'url ?:string has query ?:string' => 'URL has query.',
'url ?:string has fragment ?:string' => 'URL has fragment.',
);
}
public function match($syntax, array $data = array())
{
$parts = array(
'port' => PHP_URL_PORT,
'host' => PHP_URL_HOST,
'user' => PHP_URL_USER,
'password' => PHP_URL_PASS,
'path' => PHP_URL_PATH,
'query' => PHP_URL_QUERY,
'fragment' => PHP_URL_FRAGMENT,
);
$url = parse_url($data[0]);
foreach ($parts as $kw => $part) {
if (strpos($syntax, $kw)) {
return parse_url($data[0], $part) == $data[1];
}
}
return parse_url($data[0], PHP_URL_SCHEME) == $data[1];
}
public function getTags()
{
return array(Tag::URLS);
}
}
| <?php
namespace Concise\Matcher;
class UrlHasPart extends AbstractMatcher
{
public function supportedSyntaxes()
{
return array(
'url ?:string has scheme ?:string' => 'URL has scheme.',
'url ?:string has host ?:string' => 'URL has host.',
'url ?:string has port ?:int' => 'URL has port.',
'url ?:string has user ?:string' => 'URL has user.',
'url ?:string has password ?:string' => 'URL has password.',
'url ?:string has path ?:string' => 'URL has path.',
'url ?:string has query ?:string' => 'URL has query.',
'url ?:string has fragment ?:string' => 'URL has fragment.',
);
}
public function match($syntax, array $data = array())
{
$parts = [
'port' => PHP_URL_PORT,
'host' => PHP_URL_HOST,
'user' => PHP_URL_USER,
'password' => PHP_URL_PASS,
'path' => PHP_URL_PATH,
'query' => PHP_URL_QUERY,
'fragment' => PHP_URL_FRAGMENT,
];
$url = parse_url($data[0]);
foreach ($parts as $kw => $part) {
if (strpos($syntax, $kw)) {
return parse_url($data[0], $part) == $data[1];
}
}
return parse_url($data[0], PHP_URL_SCHEME) == $data[1];
}
public function getTags()
{
return array(Tag::URLS);
}
}
|
Stop the view indicating if the command is first | @extends('layout')
@section('content')
<div class="row">
@include('commands._partials.list', [ 'step' => 'Before' ])
@include('commands._partials.list', [ 'step' => 'After' ])
</div>
@include('dialogs.command')
<script type="text/template" id="command-template">
<td>
<div class="btn-group">
<% if (!first) { %>
<button type="button" class="btn btn-xs btn-link pull-left"><i class="fa fa-long-arrow-up"></i></button>
<% } %>
<% if (!last) { %>
<button type="button" class="btn btn-xs btn-link pull-right"><i class="fa fa-long-arrow-down"></i></button>
<% } %>
</div>
</td>
<td><%- name %></td>
<td><%- user %></td>
<td>
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-edit" title="Edit the command" data-toggle="modal" data-target="#command"><i class="fa fa-edit"></i></button>
</div>
</td>
</script>
@stop
@section('javascript')
<script type="text/javascript">
new app.CommandsTab();
app.Commands.add({!! $commands->toJson() !!});
</script>
@stop
| @extends('layout')
@section('content')
<div class="row">
@include('commands._partials.list', [ 'step' => 'Before' ])
@include('commands._partials.list', [ 'step' => 'After' ])
</div>
@include('dialogs.command')
<script type="text/template" id="command-template">
<td>
<div class="btn-group">
<% if (!first) { %>
<button type="button" class="btn btn-xs btn-link pull-left"><i class="fa fa-long-arrow-up"></i></button>
<% } %>
<% if (!last) { %>
<button type="button" class="btn btn-xs btn-link pull-right"><i class="fa fa-long-arrow-down"></i></button>
<% } %>
</div>
</td>
<td><%- name %> <%- first %></td>
<td><%- user %></td>
<td>
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-edit" title="Edit the command" data-toggle="modal" data-target="#command"><i class="fa fa-edit"></i></button>
</div>
</td>
</script>
@stop
@section('javascript')
<script type="text/javascript">
new app.CommandsTab();
app.Commands.add({!! $commands->toJson() !!});
</script>
@stop
|
Add image_handler for link harvester | import logging
import re
import socket
import urllib
import http.client
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile(r"^https?://(www\.)?wurstball\.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "description",
"human_readable_type"]}
def wurstball_handler(metadata):
if not WURSTBALL_RE.match(metadata.url):
return None
ret = default_handler(metadata)
soup = BeautifulSoup(metadata.buf)
img_url = soup.find(id="content-main").img["src"]
try:
response = urllib.request.urlopen(img_url, timeout=5)
img_data = response.read()
except (socket.timeout,
urllib.error.URLError,
urllib.error.HTTPError) as err:
logger.warn("Could not download Wurstball image: {}".format(err))
return ret
mime_type = response.getheader("Content-Type")
ret.update({"image_mime_type": mime_type,
"image_buffer": img_data,
"image_url": img_url,
"title": None,
"description": None})
return ret
def image_handler(metadata):
if not metadata.mime_type.startswith("image/"):
return None
ret = default_handler(metadata)
try:
img_data = metadata.buf + metadata.response.read()
except http.client.IncompleteRead as err:
logger.warn("Could not download image: {}".format(err))
return ret
ret.update({"image_mime_type": metadata.mime_type,
"image_buffer": img_data,
"image_url": metadata.url})
return ret
| import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile(r"^https?://(www\.)?wurstball\.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "description",
"human_readable_type"]}
def wurstball_handler(metadata):
if not WURSTBALL_RE.match(metadata.url):
return None
ret = default_handler(metadata)
soup = BeautifulSoup(metadata.buf)
img_url = soup.find(id="content-main").img["src"]
try:
response = urllib.request.urlopen(img_url, timeout=5)
img_data = response.read()
except (socket.timeout,
urllib.error.URLError,
urllib.error.HTTPError) as err:
logger.warn("Could not download Wurstball image: {}".format(err))
return ret
mime_type = response.getheader("Content-Type")
ret.update({"image_mime_type": mime_type,
"image_buffer": img_data,
"image_url": img_url,
"title": None,
"description": None})
return ret
|
Check if js registry is null | @inject('registry', 'Despark\Cms\Javascript\Contracts\RegistryContract')
<script type="text/javascript">
if (typeof Despark == 'undefined') {
Despark = {};
}
Despark.js = Despark.js || {};
Despark.js.registry = {
'values': {!! json_encode($registry->getRegistry()) !!},
'get': function (namespace, key) {
if (this.values && typeof this.values[namespace] != 'undefined') {
if (typeof key != 'undefined') {
if (typeof this.values[namespace][key] != 'undefined') {
return this.values[namespace][key]
}
var keys = key.split('.');
var found = this.values[namespace];
for (var i in keys) {
if (typeof found[keys[i]] != 'undefined') {
found = found[keys[i]];
} else {
return null;
}
}
return found;
} else {
return this.values[namespace];
}
}
}
};
</script> | @inject('registry', 'Despark\Cms\Javascript\Contracts\RegistryContract')
<script type="text/javascript">
if (typeof Despark == 'undefined') {
Despark = {};
}
Despark.js = Despark.js || {};
Despark.js.registry = {
'values': {!! json_encode($registry->getRegistry()) !!},
'get': function (namespace, key) {
if (typeof this.values[namespace] != 'undefined') {
if (typeof key != 'undefined') {
if (typeof this.values[namespace][key] != 'undefined') {
return this.values[namespace][key]
}
var keys = key.split('.');
var found = this.values[namespace];
for (var i in keys) {
if (typeof found[keys[i]] != 'undefined') {
found = found[keys[i]];
} else {
return null;
}
}
return found;
} else {
return this.values[namespace];
}
}
}
};
</script> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.