text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add method to create resource | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = subdomain
self.api_key = api_key
self.base_url = 'https://%s.fulfil.io/api/v1' % self.subdomain
self.session = requests.Session()
self.session.headers.update({'x-api-key': api_key})
def model(self, name):
return Model(self, name)
class Model(object):
def __init__(self, client, model_name):
self.client = client
self.model_name = model_name
@property
def path(self):
return '%s/model/%s' % (self.client.base_url, self.model_name)
def get(self, id):
return loads(
self.client.session.get(
self.path + '/%d' % id
).content
)
def search(self, filter, page=1, per_page=10, fields=None):
response = self.client.session.get(
self.path,
params={
'filter': dumps(filter or []),
'page': page,
'per_page': per_page,
'field': fields,
}
)
return loads(response.content)
def create(self, data):
response = self.client.session.post(
self.path,
data=dumps(data)
)
return loads(response.content)
| import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = subdomain
self.api_key = api_key
self.base_url = 'https://%s.fulfil.io/api/v1' % self.subdomain
self.session = requests.Session()
self.session.headers.update({'x-api-key': api_key})
def model(self, name):
return Model(self, name)
class Model(object):
def __init__(self, client, model_name):
self.client = client
self.model_name = model_name
@property
def path(self):
return '%s/model/%s' % (self.client.base_url, self.model_name)
def get(self, id):
return loads(
self.client.session.get(
self.path + '/%d' % id
).content
)
def search(self, filter, page=1, per_page=10, fields=None):
response = self.client.session.get(
self.path,
params={
'filter': dumps(filter or []),
'page': page,
'per_page': per_page,
'field': fields,
}
)
return loads(response.content)
|
Add default value to entity in constructor | <?php
namespace HiPay\Wallet\Mirakl\Vendor\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Class CheckAvailability
* Event object used when the event 'before.availability.check'
* is dispatched from the processor.
*
* @author Ivanis Kouamé <[email protected]>
* @copyright 2015 Smile
*/
class CheckAvailability extends Event
{
protected $email;
protected $entity;
/**
* CheckAvailability constructor.
*
* @param $email
* @param $entity
*/
public function __construct($email, $entity = false)
{
$this->email = $email;
$this->entity = $entity;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*
* @return $this
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return mixed
*/
public function getEntity()
{
return $this->entity;
}
/**
* @param mixed $entity
*
* @return $this
*/
public function setEntity($entity)
{
$this->entity = $entity;
return $this;
}
}
| <?php
namespace HiPay\Wallet\Mirakl\Vendor\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Class CheckAvailability
* Event object used when the event 'before.availability.check'
* is dispatched from the processor.
*
* @author Ivanis Kouamé <[email protected]>
* @copyright 2015 Smile
*/
class CheckAvailability extends Event
{
protected $email;
protected $entity;
/**
* CheckAvailability constructor.
*
* @param $email
* @param $entity
*/
public function __construct($email, $entity)
{
$this->email = $email;
$this->entity = $entity;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*
* @return $this
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return mixed
*/
public function getEntity()
{
return $this->entity;
}
/**
* @param mixed $entity
*
* @return $this
*/
public function setEntity($entity)
{
$this->entity = $entity;
return $this;
}
}
|
Add function for getting installed plugins | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment variables
starts from it.
Default - 'SHELDON_'. So, environment
variables will be looking like:
'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY'
:return:
"""
# Bot config variables
self.variables = {}
for variable in os.environ:
if variable.startswith(prefix):
self.variables[variable] = os.environ[variable]
def get(self, variable, default_value):
"""
Get variable value from environment
:param variable: string, needed variable
:param default_value: string, value that returns if
variable is not set
:return: variable value
"""
if variable not in self.variables:
return default_value
return self.variables[variable]
def get_installed_plugins(self):
"""
Return list of installed plugins from installed_plugins.txt
:return: list of strings with names of plugins
"""
plugins_file = open('installed_plugins.txt')
return plugins_file.readlines()
| # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment variables
starts from it.
Default - 'SHELDON_'. So, environment
variables will be looking like:
'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY'
:return:
"""
# Bot config variables
self.variables = {}
for variable in os.environ:
if variable.startswith(prefix):
self.variables[variable] = os.environ[variable]
def get(self, variable, default_value):
"""
:param variable: string, needed variable
:param default_value: string, value that returns if
variable is not set
:return:
"""
if variable not in self.variables:
return default_value
return self.variables[variable]
|
Remove use of ipify.org service | module.exports = function geoip (ip) {
return (state, emitter) => {
state.geoip = {
ip: ip,
isLoading: false
}
emitter.on('geoip:fetch', () => {
if (state.geoip.isLoading) return
state.geoip.isLoading = true
window.fetch('https://freegeoip.net/json/').then(body => {
return body.json().then(data => {
Object.assign(state.geoip, data, {
isLoading: false,
precision: 'city'
})
emitter.emit('render')
})
}).catch(err => {
state.geoip.isLoading = false
emitter.emit('error', err)
})
})
emitter.on('geoip:getPosition', () => {
state.geoip.isLoading = true
emitter.emit('render')
navigator.geolocation.getCurrentPosition(position => {
state.geoip.latitude = position.coords.latitude
state.geoip.longitude = position.coords.longitude
state.geoip.precision = 'exact'
state.geoip.isLoading = false
emitter.emit('render')
}, err => emitter.emit('error', err))
})
}
}
| module.exports = function geoip (ip) {
return (state, emitter) => {
state.geoip = {
ip: ip,
isLoading: false
}
emitter.on('geoip:fetch', () => {
if (state.geoip.isLoading) return
state.geoip.isLoading = true
window.fetch('//api.ipify.org?format=json')
.then(body => body.json())
.then(resp => window.fetch(`//freegeoip.net/json/${resp.ip}`))
.then(body => body.json())
.then(data => {
Object.assign(state.geoip, data, {
isLoading: false,
precision: 'city'
})
emitter.emit('render')
}, err => {
state.geoip.isLoading = false
emitter.emit('error', err)
})
})
emitter.on('geoip:getPosition', () => {
state.geoip.isLoading = true
emitter.emit('render')
navigator.geolocation.getCurrentPosition(position => {
state.geoip.latitude = position.coords.latitude
state.geoip.longitude = position.coords.longitude
state.geoip.precision = 'exact'
state.geoip.isLoading = false
emitter.emit('render')
}, err => emitter.emit('error', err))
})
}
}
|
Stop the repl test on an error, making sure all Pipes are closed |
from tests.util.pipe import Pipe
from threading import Thread
from pycell.repl import repl
from tests.util.system_test import system_test
from tests.util.all_examples import all_sessions
def _validate_line(exp_line, strin, strout):
expprompt = exp_line[:4]
if expprompt in (">>> ", "... "):
prompt = strout.read(4)
if prompt != exp_line[:4]:
raise Exception(
"Prompt was '%s' but we expected '%s'." % (
prompt, exp_line[:4])
)
strin.write(exp_line[4:])
else:
output = strout.readline()
if output != exp_line:
raise Exception("Output was '%s' but we expected '%s'" % (
output, exp_line)
)
def _validate_session(f):
with Pipe() as strin, Pipe() as strout, Pipe() as strerr:
replthread = Thread(target=repl, args=(strin, strout, strerr))
replthread.start()
for exp_line in f:
_validate_line(exp_line, strin, strout)
replthread.join()
@system_test
def All_example_repl_sessions_are_correct():
for example in all_sessions():
with open(example, encoding="ascii") as f:
_validate_session(f)
|
from tests.util.pipe import Pipe
from threading import Thread
from pycell.repl import repl
from tests.util.system_test import system_test
from tests.util.all_examples import all_sessions
def _validate_session(f):
strin = Pipe()
strout = Pipe()
strerr = Pipe()
replthread = Thread(target=repl, args=(strin, strout, strerr))
replthread.start()
for exp_line in f:
expprompt = exp_line[:4]
if expprompt in (">>> ", "... "):
prompt = strout.read(4)
if prompt != exp_line[:4]:
raise Exception(
"Prompt was '%s' but we expected '%s'." % (
prompt, exp_line[:4]))
strin.write(exp_line[4:])
else:
output = strout.readline()
if output != exp_line:
raise Exception("Output was '%s' but we expected '%s'" % (
output, exp_line))
strerr.close()
strout.close()
strin.close()
replthread.join()
@system_test
def All_example_repl_sessions_are_correct():
from pycell.chars_in_file import chars_in_file
for example in all_sessions():
with open(example, encoding="ascii") as f:
_validate_session(f)
|
Fix subject getter to support subject alts
git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3722 8555b757-d854-4b86-925a-82fd84c90ff4 | <div class="box">
<?php
if(!Config::get('lang_selector_enabled')) {
$opts = array();
$code = Lang::getCode();
foreach(Lang::getAvailableLanguages() as $id => $dfn) {
$selected = ($id == $code) ? 'selected="selected"' : '';
$opts[] = '<option value="'.$id.'" '.$selected.'>'.Utilities::sanitizeOutput($dfn['name']).'</option>';
}
echo '<div class="buttons"><select id="language_selector">'.implode('', $opts).'</select></div>';
}
if(!array_key_exists('token', $_REQUEST))
throw new TokenIsMissingException();
$token = $_REQUEST['token'];
if(!Utilities::isValidUID($token))
throw new TokenHasBadFormatException($token);
$translatable = TranslatableEmail::fromToken($token);
$translation = $translatable->translate();
/*
* Do not call Template::sanitizeOutput on email contents after that because
* TranslatableEmail::translate calls Translation::replace which itself calls
* Utilities::sanitizeOutput, use Template::sanitize instead !
*/
$subject = array_filter($translation->subject->out());
?>
<dl>
<dt data-property="subject">{tr:subject} :</dt>
<dd data-property="subject"><?php echo Template::sanitize(array_pop($subject)) ?></dd>
<dt data-property="message">{tr:message}</dt>
<dd data-property="message"><?php echo Template::sanitize($translation->html) ?></dd>
</dl>
</div>
| <div class="box">
<?php
if(!Config::get('lang_selector_enabled')) {
$opts = array();
$code = Lang::getCode();
foreach(Lang::getAvailableLanguages() as $id => $dfn) {
$selected = ($id == $code) ? 'selected="selected"' : '';
$opts[] = '<option value="'.$id.'" '.$selected.'>'.Utilities::sanitizeOutput($dfn['name']).'</option>';
}
echo '<div class="buttons"><select id="language_selector">'.implode('', $opts).'</select></div>';
}
if(!array_key_exists('token', $_REQUEST))
throw new TokenIsMissingException();
$token = $_REQUEST['token'];
if(!Utilities::isValidUID($token))
throw new TokenHasBadFormatException($token);
$translatable = TranslatableEmail::fromToken($token);
$translation = $translatable->translate();
/*
* Do not call Template::sanitizeOutput on email contents after that because
* TranslatableEmail::translate calls Translation::replace which itself calls
* Utilities::sanitizeOutput, use Template::sanitize instead !
*/
?>
<dl>
<dt data-property="subject">{tr:subject} :</dt>
<dd data-property="subject"><?php echo Template::sanitize($translation->subject) ?></dd>
<dt data-property="message">{tr:message}</dt>
<dd data-property="message"><?php echo Template::sanitize($translation->html) ?></dd>
</dl>
</div>
|
Use 50 times the page size for faceting | "use strict";
var search = require('../lib/search');
module.exports = function (input, callback) {
if (typeof input.query.plan !== 'undefined' && typeof input.query.plan.esquery !== 'undefined') {
input.query.plan.esquery.from = input.query.offset || 0;
if (input.query.plan.esonly) {
input.query.plan.esquery.size = input.query.perpage;
} else {
input.query.plan.esquery.size = Math.max(1000, input.query.perpage * 50);
}
}
search(input.query, function (results) {
if (results.records) {
callback({
records: results.records,
count: results.count,
summary: 'Search: ' + input.query.canonical
});
} else if (results.pipe) {
var records = results.pipe.range(input.query.offset, input.query.offset + input.query.size).toJSON();
var count = input.query.offset + records.length;
if (records.length > input.query.size) {
records.pop();
}
callback({
records: records,
count: count,
summary: 'Search: ' + input.query.canonical
});
}
});
};
module.exports.message = 'search';
| "use strict";
var search = require('../lib/search');
module.exports = function (input, callback) {
if (typeof input.query.plan !== 'undefined' && typeof input.query.plan.esquery !== 'undefined') {
input.query.plan.esquery.from = input.query.offset || 0;
if (input.query.plan.esonly) {
input.query.plan.esquery.size = input.query.perpage;
} else {
input.query.plan.esquery.size = Math.max(1000, input.query.perpage * 4);
}
}
search(input.query, function (results) {
if (results.records) {
callback({
records: results.records,
count: results.count,
summary: 'Search: ' + input.query.canonical
});
} else if (results.pipe) {
var records = results.pipe.range(input.query.offset, input.query.offset + input.query.size).toJSON();
var count = input.query.offset + records.length;
if (records.length > input.query.size) {
records.pop();
}
callback({
records: records,
count: count,
summary: 'Search: ' + input.query.canonical
});
}
});
};
module.exports.message = 'search';
|
Add dynamic database name to getColumns() | <?php
namespace UserControlSkeleton\Models\Database;
use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;
class MysqlAdapter implements AdapterInterface
{
protected $user;
protected $pass;
protected $host;
protected $port;
protected $name;
protected $driver;
public function __construct()
{
$this->user = getenv('DATABASE_USER');
$this->pass = getenv('DATABASE_PASS');
$this->host = getenv('DATABASE_HOST');
$this->port = getenv('DATABASE_PORT');
$this->name = getenv('DATABASE_NAME');
$this->driver = getenv('DATABASE_DRIVER');
}
public function connect()
{
try {
$link = new PDO($this->driver.':host='.$this->host.';port='.$this->port.';dbname='.$this->name.';charset=UTF8;', $this->user, $this->pass);
return $link;
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
public function getColumns()
{
$databaseName = getenv('DATABASE_NAME');
$statement = $this->connect();
$statement = $statement->prepare('
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = "$databaseName"
AND TABLE_NAME = "users"
');
$statement->execute();
$statement->fetch(PDO::FETCH_ASSOC);
return $statement;
}
}
| <?php
namespace UserControlSkeleton\Models\Database;
use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;
class MysqlAdapter implements AdapterInterface
{
protected $user;
protected $pass;
protected $host;
protected $port;
protected $name;
protected $driver;
public function __construct()
{
$this->user = getenv('DATABASE_USER');
$this->pass = getenv('DATABASE_PASS');
$this->host = getenv('DATABASE_HOST');
$this->port = getenv('DATABASE_PORT');
$this->name = getenv('DATABASE_NAME');
$this->driver = getenv('DATABASE_DRIVER');
}
public function connect()
{
try {
$link = new PDO($this->driver.':host='.$this->host.';port='.$this->port.';dbname='.$this->name.';charset=UTF8;', $this->user, $this->pass);
return $link;
} catch (\PDOException $e) {
echo $e->getMessage();
die();
}
}
public function getColumns()
{
$statement = $this->connect();
$statement = $statement->prepare('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "user_control_skeleton" AND TABLE_NAME = "users"');
$statement->execute();
$statement->fetch(PDO::FETCH_ASSOC);
return $statement;
}
}
|
Handle multiple receiver domain properly | import datetime
import smtpd
from email.parser import Parser
from mailchute import db
from mailchute import settings
from mailchute.model import RawMessage, IncomingEmail
from logbook import Logger
logger = Logger(__name__)
class MessageProcessor(object):
def _should_persist(self, recipient):
recipient_domain = recipient.split('@')[1].lower()
allowed_receiver_domains = settings.RECEIVER_DOMAIN
if allowed_receiver_domains:
allowed_receiver_domains = allowed_receiver_domains.split(',')
return (allowed_receiver_domains is None
or recipient_domain in allowed_receiver_domains)
def __call__(self, peer, mailfrom, recipients, data):
try:
mailfrom = mailfrom.lower()
recipients = list(map(str.lower, recipients))
logger.info(
"Incoming message from {0} to {1}".format(mailfrom, recipients))
email = Parser().parsestr(data)
raw_message = RawMessage(message=data)
for recipient in recipients:
if self._should_persist(recipient):
incoming_email = IncomingEmail(
sender=mailfrom, recipient=recipient,
raw_message=raw_message,
subject=email['subject'],
created_at=datetime.datetime.now(),
)
db.session.add(incoming_email)
else:
logger.info('{} is not an allowed recipient. Skip.'.format(
recipient))
db.session.commit()
logger.info("Message saved")
except Exception as e: # pragma: no cover
logger.exception(e)
db.session.rollback()
class MailchuteSMTPServer(smtpd.SMTPServer):
process_message = MessageProcessor()
| import datetime
import smtpd
from email.parser import Parser
from mailchute import db
from mailchute import settings
from mailchute.model import RawMessage, IncomingEmail
from logbook import Logger
logger = Logger(__name__)
class MessageProcessor(object):
def _should_persist(self, recipient):
allowed_receiver_domain = settings.RECEIVER_DOMAIN
recipient_domain = recipient.split('@')[1].lower()
return (allowed_receiver_domain is None
or recipient_domain == settings.RECEIVER_DOMAIN)
def __call__(self, peer, mailfrom, recipients, data):
try:
mailfrom = mailfrom.lower()
recipients = list(map(str.lower, recipients))
logger.info(
"Incoming message from {0} to {1}".format(mailfrom, recipients))
email = Parser().parsestr(data)
raw_message = RawMessage(message=data)
for recipient in recipients:
if self._should_persist(recipient):
incoming_email = IncomingEmail(
sender=mailfrom, recipient=recipient,
raw_message=raw_message,
subject=email['subject'],
created_at=datetime.datetime.now(),
)
db.session.add(incoming_email)
else:
logger.info('{} is not an allowed recipient. Skip.'.format(
recipient))
db.session.commit()
logger.info("Message saved")
except Exception as e: # pragma: no cover
logger.exception(e)
db.session.rollback()
class MailchuteSMTPServer(smtpd.SMTPServer):
process_message = MessageProcessor()
|
Fix spacing and conditional braces | package seedu.todo.ui;
import seedu.todo.controllers.*;
public class InputHandler {
Controller handlingController = null;
public boolean processInput(String input) {
if (this.handlingController != null) {
handlingController.process(input);
} else {
Controller[] controllers = instantiateAllControllers();
// Define the controller which returns the maximum confidence.
Controller maxController = null;
// Get controller which has the maximum confidence.
float maxConfidence = Integer.MIN_VALUE;
for (int i = 0; i < controllers.length; i++) {
float confidence = controllers[i].inputConfidence(input);
// Don't consider controllers with non-positive confidence.
if (confidence <= 0) {
continue;
}
if (confidence > maxConfidence) {
maxConfidence = confidence;
maxController = controllers[i];
}
}
// No controller exists with confidence > 0.
if (maxController == null) {
return false;
}
// Process using best-matched controller.
maxController.process(input);
}
return true;
}
private Controller[] instantiateAllControllers() {
return new Controller[] { new AddController(),
new ListController(),
new DestroyController(),
new UpdateController() };
}
}
| package seedu.todo.ui;
import seedu.todo.controllers.*;
public class InputHandler {
Controller handlingController = null;
public boolean processInput(String input) {
if (this.handlingController != null) {
handlingController.process(input);
} else {
Controller[] controllers = instantiateAllControllers();
// Define the controller which returns the maximum confidence.
Controller maxController = null;
// Get controller which has the maximum confidence.
float maxConfidence = Integer.MIN_VALUE;
for (int i = 0; i < controllers.length; i++) {
float confidence = controllers[i].inputConfidence(input);
// Don't consider controllers with non-positive confidence.
if (confidence <= 0)
continue;
if (confidence > maxConfidence) {
maxConfidence = confidence;
maxController = controllers[i];
}
}
// No controller exists with confidence > 0.
if (maxController == null)
return false;
// Process using best-matched controller.
maxController.process(input);
}
return true;
}
private Controller[] instantiateAllControllers() {
return new Controller[] { new AddController(),
new ListController(),
new DestroyController(),
new UpdateController() };
}
}
|
Add missing `await` to outer iterator `next` call.
Closes #73. | module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
}
const next = await iterator.next()
if (next.done) {
return { done: true }
}
const gathered = []
ITEMS: for (const item of next.value) {
switch (filter(item)) {
case -1:
break
case 0:
gathered.push(item)
break
case 1:
done = true
break ITEMS
}
}
return { done: false, value: gathered }
}
}
}
| module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
}
const next = iterator.next()
if (next.done) {
return { done: true }
}
const gathered = []
ITEMS: for (const item of next.value) {
switch (filter(item)) {
case -1:
break
case 0:
gathered.push(item)
break
case 1:
done = true
break ITEMS
}
}
return { done: false, value: gathered }
}
}
}
|
Use initial value from api | import {div, header, footer, button, p, hJSX} from '@cycle/dom'
import isolate from '@cycle/isolate'
import AceEditor from 'cyclejs-ace-editor'
let {Observable} = require('rx')
function intent({DOM, context}) {
const buttonClicks$ = DOM.select('.submit-button').events('click')
const initialCodeValue$ = context.map(json => {
return json.initialCode || ''
})
return {
buttonClicks$,
initialCodeValue$
}
}
function view(subjectCodeEditor) {
return Observable
.just(
<div id="code">
<header>
<div className="container-header">
Your code
</div>
</header>
<div className="code">
{ subjectCodeEditor.DOM }
</div>
<footer>
<button className="submit-button">Submit</button>
</footer>
</div>
)
}
function CodePanel(sources) {
const {DOM} = sources
const {buttonClicks$, initialCodeValue$} = intent(sources)
const params$ = Observable.just({
theme: 'ace/theme/monokai',
mode: 'ace/mode/javascript'
})
const subjectCodeEditor = AceEditor({DOM, initialValue$: initialCodeValue$, params$})
const vtree$ = view(subjectCodeEditor)
return {
DOM: vtree$,
buttonClicks$: buttonClicks$,
code$: subjectCodeEditor.value$
}
}
function CodePanelWrapper(sources) {
return isolate(CodePanel)(sources)
}
export default CodePanelWrapper
| import {div, header, footer, button, p, hJSX} from '@cycle/dom'
import isolate from '@cycle/isolate'
import AceEditor from 'cyclejs-ace-editor'
let {Observable} = require('rx')
function intent({DOM}) {
const buttonClicks$ = DOM.select('.submit-button').events('click')
return {
buttonClicks$
}
}
function view(subjectCodeEditor) {
return Observable
.just(
<div id="code">
<header>
<div className="container-header">
Your code
</div>
</header>
<div className="code">
{ subjectCodeEditor.DOM }
</div>
<footer>
<button className="submit-button">Submit</button>
</footer>
</div>
)
}
function CodePanel(sources) {
const codeTemplate = 'function sum() {\n\n}\n\nmodule.exports = sum'
const {DOM} = sources
const initialValue$ = Observable.just(codeTemplate)
const {buttonClicks$} = intent(sources)
const params$ = Observable.just({
theme: 'ace/theme/monokai',
mode: 'ace/mode/javascript'
})
const subjectCodeEditor = AceEditor({DOM, initialValue$, params$})
const vtree$ = view(subjectCodeEditor)
return {
DOM: vtree$,
buttonClicks$: buttonClicks$,
code$: subjectCodeEditor.value$
}
}
function CodePanelWrapper(sources) {
return isolate(CodePanel)(sources)
}
export default CodePanelWrapper
|
Tweak old integration test docstring | from spec import skip, Spec, ok_
from fabric.connection import Connection
class Main(Spec):
def connection_open_generates_real_connection(self):
c = Connection('localhost')
c.open()
ok_(c.client.get_transport().active)
def simple_command_on_host(self):
"""
Run command on host "localhost"
"""
skip()
Connection('localhost').run('echo foo')
# => Result
def simple_command_on_multiple_hosts(self):
"""
Run command on localhost...twice!
"""
skip()
Batch(['localhost', 'localhost']).run('echo foo')
# => [Result, Result
def sudo_command(self):
"""
Run command via sudo on host "localhost"
"""
skip()
Connection('localhost').sudo('echo foo')
def mixed_sudo_and_normal_commands(self):
"""
Run command via sudo, and not via sudo, on "localhost"
"""
skip()
cxn = Connection('localhost')
cxn.run('whoami')
cxn.sudo('whoami')
# Alternately...
cxn.run('whoami', runner=Basic)
cxn.run('whoami', runner=Sudo)
def switch_command_between_local_and_remote(self):
"""
Run command truly locally, and over SSH via "localhost"
"""
# TODO: Only really makes sense at the task level though...
skip()
# Basic/raw
run('hostname') # Or Context().run('hostname')
Connection('localhost').run('hostname')
| from spec import skip, Spec, ok_
from fabric.connection import Connection
class Main(Spec):
def connection_open_generates_real_connection(self):
c = Connection('localhost')
c.open()
ok_(c.client.get_transport().active)
def simple_command_on_host(self):
"""
Run command on host "localhost"
"""
skip()
Connection('localhost').run('echo foo')
# => Result
def simple_command_on_multiple_hosts(self):
"""
Run command on localhost...twice!
"""
skip()
Batch(['localhost', 'localhost']).run('echo foo')
# => [Result, Result
def sudo_command(self):
"""
Run command via sudo on host "localhost"
"""
skip()
Connection('localhost').sudo('echo foo')
def mixed_sudo_and_normal_commands(self):
"""
Run command via sudo, and not via sudo, on "localhost"
"""
skip()
cxn = Connection('localhost')
cxn.run('whoami')
cxn.sudo('whoami')
# Alternately...
cxn.run('whoami', runner=Basic)
cxn.run('whoami', runner=Sudo)
def switch_command_between_local_and_remote(self):
"""
Run command truly locally, and over SSH via "localhost"
Only really makes sense at the task level though...
"""
skip()
# Basic/raw
run('hostname') # Or Context().run('hostname')
Connection('localhost').run('hostname')
|
Update product relative link to link to the correct parent page | <?php
class CataloguePageProductExtension extends DataExtension
{
public function updateRelativeLink($base, $action)
{
$page = null;
// Try to find the current product's page
if ($this->owner->CataloguePages()->exists()) {
$page = $this->owner->CataloguePages()->first();
} elseif ($category = $this->owner->Categories()->first()) {
if($category->CataloguePages()->exists()) {
$page = $category->CataloguePages()->first();
}
}
// If no page has been found, revert to a default
if (!$page) {
$page = CataloguePage::get()->first();
}
$link = Controller::join_links(
$page->RelativeLink("product"),
$this->owner->URLSegment,
$action
);
return $link;
}
public function updateAncestors($ancestors, $include_parent)
{
// Check if there is a catalogue page with this product
$page = CataloguePage::get()
->filter("Products.ID", $this->owner->ID)
->first();
if(!$page) {
// Else check we have a product in a category that matches
$categories = $this->owner->Categories();
$page = null;
// Find the first category page we have mapped
foreach($categories as $category) {
if(!$page && $category->CataloguePages()->exists()) {
$page = $category->CataloguePages()->first();
}
}
}
if($page) {
// Clear all ancestors
foreach($ancestors as $ancestor) {
$ancestors->remove($ancestor);
}
if($include_parent) {
$ancestors->push($page);
}
while($page = $page->getParent()) {
$ancestors->push($page);
}
}
}
}
| <?php
class CataloguePageProductExtension extends DataExtension
{
public function updateRelativeLink($base, $action)
{
$page = CataloguePage::get()->first();
$link = Controller::join_links(
$page->RelativeLink("product"),
$this->owner->URLSegment,
$action
);
return $link;
}
public function updateAncestors($ancestors, $include_parent)
{
// Check if there is a catalogue page with this product
$page = CataloguePage::get()
->filter("Products.ID", $this->owner->ID)
->first();
if(!$page) {
// Else check we have a product in a category that matches
$categories = $this->owner->Categories();
$page = null;
// Find the first category page we have mapped
foreach($categories as $category) {
if(!$page && $category->CataloguePages()->exists()) {
$page = $category->CataloguePages()->first();
}
}
}
if($page) {
// Clear all ancestors
foreach($ancestors as $ancestor) {
$ancestors->remove($ancestor);
}
if($include_parent) {
$ancestors->push($page);
}
while($page = $page->getParent()) {
$ancestors->push($page);
}
}
}
}
|
ENH: Update tools script for file renaming | #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import inspect
from string import Template
datasets = dict(inspect.getmembers(sm.datasets, inspect.ismodule))
datasets.pop('utils')
datasets.pop('nile') #TODO: fix docstring in nile
doc_template = Template(u"""$TITLE
$title_
Description
-----------
$DESCRIPTION
Notes
-----
$NOTES
Source
------
$SOURCE
Copyright
---------
$COPYRIGHT
""")
for dataset in datasets:
write_pth = join('../docs/source/datasets/generated',
dataset+'.rst')
data_mod = datasets[dataset]
with open(os.path.realpath(write_pth), 'w') as rst_file:
title = getattr(data_mod,'TITLE')
descr = getattr(data_mod, 'DESCRLONG')
copyr = getattr(data_mod, 'COPYRIGHT')
notes = getattr(data_mod, 'NOTE')
source = getattr(data_mod, 'SOURCE')
write_file = doc_template.substitute(TITLE=title,
title_='='*len(title),
DESCRIPTION=descr, NOTES=notes,
SOURCE=source, COPYRIGHT=copyr)
rst_file.write(write_file)
| #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import inspect
from string import Template
datasets = dict(inspect.getmembers(sm.datasets, inspect.ismodule))
datasets.pop('datautils')
datasets.pop('nile') #TODO: fix docstring in nile
doc_template = Template(u"""$TITLE
$title_
Description
-----------
$DESCRIPTION
Notes
-----
$NOTES
Source
------
$SOURCE
Copyright
---------
$COPYRIGHT
""")
for dataset in datasets:
write_pth = join('../docs/source/datasets/generated',
dataset+'.rst')
data_mod = datasets[dataset]
with open(os.path.realpath(write_pth), 'w') as rst_file:
title = getattr(data_mod,'TITLE')
descr = getattr(data_mod, 'DESCRLONG')
copyr = getattr(data_mod, 'COPYRIGHT')
notes = getattr(data_mod, 'NOTE')
source = getattr(data_mod, 'SOURCE')
write_file = doc_template.substitute(TITLE=title,
title_='='*len(title),
DESCRIPTION=descr, NOTES=notes,
SOURCE=source, COPYRIGHT=copyr)
rst_file.write(write_file)
|
Prepend the base URL to all endpoints | package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**
* Base API path
*/
public static final String API_BASE_PATH = BASE_URL + "api";
/**
* The endpoint for accessing user information
*/
public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
/**
* The endpoint for logging in
*/
public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
/**
* The endpoint for logging out
*/
public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
/**
* The endpoint for accessing server information
*/
public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
/**
* The endpoint for accessing channel information
*/
public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
/**
* The endpoint for accepting invites
*/
public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
/**
* The format string for avatar URLs
*/
public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";
}
| package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**
* Base API path
*/
public static final String API_BASE_PATH = "api";
/**
* The endpoint for accessing user information
*/
public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
/**
* The endpoint for logging in
*/
public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
/**
* The endpoint for logging out
*/
public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
/**
* The endpoint for accessing server information
*/
public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
/**
* The endpoint for accessing channel information
*/
public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
/**
* The endpoint for accepting invites
*/
public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
/**
* The format string for avatar URLs
*/
public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";
}
|
Update sample of google chrome developer tools | console.warn('devtools.js');
chrome.devtools.panels.create(
'sample',
'',
'./panel.html',
(panel) => {
let _panelWindow;
// a-0. connect to background
const backgroundPageConnection = chrome.runtime.connect({
name: 'devtools-page'
});
// a-4. pass through message from panel to background
backgroundPageConnection.onMessage.addListener((message) => {
console.warn('from background.js to devtools.js', message);
if (_panelWindow) {
_panelWindow.notifyBackgroundMessage(message);
}
});
// a-2. pass through message from panel
const onShown = (panelWindow) => {
panel.onShown.removeListener(onShown);
_panelWindow = panelWindow;
_panelWindow.respond = (message) => {
backgroundPageConnection.postMessage({
message: message,
tabId: chrome.devtools.inspectedWindow.tabId
});
};
};
panel.onShown.addListener(onShown);
// chrome.runtime.sendMessage({
// tabId: chrome.devtools.inspectedWindow.tabId
// });
}
); | console.warn('devtools.js');
chrome.devtools.panels.create(
'sample',
'',
'./panel.html',
(panel) => {
let _panelWindow;
// a-0. connect to background
const backgroundPageConnection = chrome.runtime.connect({
name: 'devtools-page'
});
// a-4. pass through message from panel
backgroundPageConnection.onMessage.addListener((message) => {
console.warn('from background.js to devtools.js', message);
if (_panelWindow) {
_panelWindow.notifyBackgroundMessage(message);
}
});
// a-2. pass through message from panel
const onShown = (panelWindow) => {
panel.onShown.removeListener(onShown);
_panelWindow = panelWindow;
_panelWindow.respond = (message) => {
backgroundPageConnection.postMessage({
message: message,
tabId: chrome.devtools.inspectedWindow.tabId
});
};
};
panel.onShown.addListener(onShown);
// chrome.runtime.sendMessage({
// tabId: chrome.devtools.inspectedWindow.tabId
// });
}
); |
Use directly magento classes to do store emulation. | <?php
class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
private $scope;
private $categoryId;
private $Category;
private $Formatter;
public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
{
$this->Category = Mage::getModel('catalog/category');
$this->Formatter = new SPM_ShopyMind_DataMapper_Category();
$this->categoryId = $categoryId;
$this->scope = $scope;
}
public function process($formatData = true)
{
$storeIds = $this->scope->storeIds();
/** @var $appEmulation Mage_Core_Model_App_Emulation */
$appEmulation = Mage::getSingleton('core/app_emulation');
$emulatedEnvironment = $appEmulation->startEnvironmentEmulation($storeIds[0]);
$collection = $this->Category->getCollection();
$this->scope->restrictCategoryCollection($collection);
$collection->addAttributeToFilter('entity_id', array('eq' => $this->categoryId))
->addAttributeToSelect('*');
$category = $collection->getFirstItem();
if (is_null($this->categoryId) || !$category->getId()) {
return array();
}
$locale = $this->scope->getConfig('general/locale/code');
$category->setData('locale', (string) $locale);
if ($formatData) {
$data = $this->Formatter->format($category);
} else {
$data = $category;
}
$appEmulation->stopEnvironmentEmulation($emulatedEnvironment);
return $data;
}
}
| <?php
class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
private $scope;
private $categoryId;
private $Category;
private $Formatter;
public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
{
$this->Category = Mage::getModel('catalog/category');
$this->Formatter = new SPM_ShopyMind_DataMapper_Category();
$this->categoryId = $categoryId;
$this->scope = $scope;
}
public function process($formatData = true)
{
$storeIds = $this->scope->storeIds();
ShopymindClient_Callback::startStoreEmulationByStoreId($storeIds[0]);
$collection = $this->Category->getCollection();
$this->scope->restrictCategoryCollection($collection);
$collection->addAttributeToFilter('entity_id', array('eq' => $this->categoryId))
->addAttributeToSelect('*');
$category = $collection->getFirstItem();
if (is_null($this->categoryId) || !$category->getId()) {
return array();
}
$locale = $this->scope->getConfig('general/locale/code');
$category->setData('locale', (string) $locale);
if ($formatData) {
$data = $this->Formatter->format($category);
} else {
$data = $category;
}
ShopymindClient_Callback::stopStoreEmulation();
return $data;
}
}
|
Switch accidentally changed call and dial sounds | 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('dial', 'res/sounds/dial.wav', 1, 1);
$cordovaNativeAudio.preloadComplex('call', 'res/sounds/incoming.mp3', 1, 1);
}
});
return {
playSound: function (sound) {
if ($window.cordova) {
console.log('playing sound: ' + sound);
$cordovaNativeAudio.play(sound);
}
},
loopSound: function (sound) {
if ($window.cordova) {
console.log('looping sound: ' + sound);
$cordovaNativeAudio.loop(sound);
}
},
stopSound: function (sound) {
if ($window.cordova) {
console.log('stopping sound: ' + sound);
$cordovaNativeAudio.stop(sound);
}
},
stopAllSounds: function () {
if ($window.cordova) {
this.stopSound('call');
this.stopSound('dial');
}
}
};
});
| 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('call', 'res/sounds/dial.wav', 1, 1);
$cordovaNativeAudio.preloadComplex('dial', 'res/sounds/incoming.mp3', 1, 1);
}
});
return {
playSound: function (sound) {
if ($window.cordova) {
console.log('playing sound: ' + sound);
$cordovaNativeAudio.play(sound);
}
},
loopSound: function (sound) {
if ($window.cordova) {
console.log('looping sound: ' + sound);
$cordovaNativeAudio.loop(sound);
}
},
stopSound: function (sound) {
if ($window.cordova) {
console.log('stopping sound: ' + sound);
$cordovaNativeAudio.stop(sound);
}
},
stopAllSounds: function () {
if ($window.cordova) {
this.stopSound('call');
this.stopSound('dial');
}
}
};
});
|
Clean hint logic from copy/paste | (function(win, doc, $, ko){
var options = {
hiddenClass: 'hidden'
};
ko.bindingHandlers.hint = {
init:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssClass;
if(hintOptions && hintOptions.hiddenClass){
cssClass = hintOptions.hiddenClass;
}else{
cssClass = options.hiddenClass;
insertCustomCss();
}
applyHint(observable, element, cssClass);
},
update:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssClass;
if(hintOptions && hintOptions.hiddenClass){
cssClass = hintOptions.hiddenClass;
}else{
cssClass = options.hiddenClass;
}
applyHint(observable, element, cssClass);
}
};
function applyHint(observable, element, cssClass){
if (observable()) {
$(element).removeClass(cssClass);
} else {
$(element).addClass(cssClass);
}
}
function insertCustomCss(){
var css = [
'<style>',
'.hidden{display: none !important;}',
'</style>'
];
doc.write(css.join(''));
}
})(window,document, jQuery, ko);
| (function(win, doc, $, ko){
var options = {
hiddenClass: 'hidden'
};
ko.bindingHandlers.hint = {
init:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssClass;
if(hintOptions && hintOptions.hiddenClass){
cssClass = hintOptions.hiddenClass;
}else{
cssClass = options.hiddenClass;
insertCustomCss();
}
if (observable()) {
$(element).removeClass(cssClass);
} else {
$(element).addClass(cssClass);
}
},
update:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssClass;
if(hintOptions && hintOptions.hiddenClass){
cssClass = hintOptions.hiddenClass;
}else{
cssClass = options.hiddenClass;
}
if (observable()) {
$(element).removeClass(cssClass);
} else {
$(element).addClass(cssClass);
}
}
};
function insertCustomCss(){
var css = [
'<style>',
'.hidden{display: none !important;}',
'</style>'
];
doc.write(css.join(''));
}
})(window,document, jQuery, ko);
|
Raise our own ImportError if all fails. Looks better than to complain about
django when that happens | """
Get the best JSON encoder/decoder available on this system.
"""
__version__ = "0.1"
__author__ = "Rune Halvorsen <[email protected]>"
__homepage__ = "http://bitbucket.org/runeh/anyjson/"
__docformat__ = "restructuredtext"
"""
.. function:: serialize(obj)
Serialize the object to JSON.
.. function:: deserialize(obj)
Deserialize JSON-encoded object to a Python object.
"""
# Try to import a module that provides json parsing and emitting, starting
# with the fastest alternative and falling back to the slower ones.
try:
# cjson is the fastest
import cjson
serialize = cjson.encode
deserialize = cjson.decode
except ImportError:
try:
# Then try to find simplejson. Later versions has C speedups which
# makes it pretty fast.
import simplejson
serialize = simplejson.dumps
deserialize = simplejson.loads
except ImportError:
try:
# Then try to find the python 2.6 stdlib json module.
import json
serialize = json.dumps
deserialize = json.loads
except ImportError:
try:
# If all of the above fails, try to fallback to the simplejson
# embedded in Django.
from django.utils import simplejson
serialize = simplejson.dumps
deserialize = simplejson.loads
except:
raise ImportError("No json module found")
| """
Get the best JSON encoder/decoder available on this system.
"""
__version__ = "0.1"
__author__ = "Rune Halvorsen <[email protected]>"
__homepage__ = "http://bitbucket.org/runeh/anyjson/"
__docformat__ = "restructuredtext"
"""
.. function:: serialize(obj)
Serialize the object to JSON.
.. function:: deserialize(obj)
Deserialize JSON-encoded object to a Python object.
"""
# Try to import a module that provides json parsing and emitting, starting
# with the fastest alternative and falling back to the slower ones.
try:
# cjson is the fastest
import cjson
serialize = cjson.encode
deserialize = cjson.decode
except ImportError:
try:
# Then try to find simplejson. Later versions has C speedups which
# makes it pretty fast.
import simplejson
serialize = simplejson.dumps
deserialize = simplejson.loads
except ImportError:
try:
# Then try to find the python 2.6 stdlib json module.
import json
serialize = json.dumps
deserialize = json.loads
except ImportError:
# If all of the above fails, try to fallback to the simplejson
# embedded in Django.
from django.utils import simplejson
serialize = simplejson.dumps
deserialize = simplejson.loads
|
Remove relevance settings, but leave the extended example. | /*
Language: Flix
Category: functional
Author: Magnus Madsen <[email protected]>
*/
function (hljs) {
var CHAR = {
className: 'string',
begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
};
var STRING = {
className: 'string',
variants: [
{
begin: '"', end: '"'
}
]
};
var NAME = {
className: 'title',
begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/
};
var METHOD = {
className: 'function',
beginKeywords: 'def',
end: /[:={\[(\n;]/,
excludeEnd: true,
contains: [NAME]
};
return {
keywords: {
literal: 'true false',
keyword: 'case class def else enum if impl import in lat rel index let match namespace switch type yield with'
},
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
CHAR,
STRING,
METHOD,
hljs.C_NUMBER_MODE
]
};
}
| /*
Language: Flix
Category: functional
Author: Magnus Madsen <[email protected]>
*/
function (hljs) {
var CHAR = {
className: 'string',
begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/,
relevance: 0
};
var STRING = {
className: 'string',
variants: [
{
begin: '"', end: '"'
}
],
relevance: 0
};
var NAME = {
className: 'title',
begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,
relevance: 0
};
var METHOD = {
className: 'function',
beginKeywords: 'def',
end: /[:={\[(\n;]/,
excludeEnd: true,
contains: [NAME],
relevance: 0
};
return {
keywords: {
literal: 'true false',
keyword: 'case|10 class def|0 else|0 enum|0 if|0 impl import|0 in|0 lat|10 rel|10 index|10 let|0 match|0 namespace|10 switch|0 type|0 yield|0 with|0'
},
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
CHAR,
STRING,
METHOD,
hljs.C_NUMBER_MODE
]
};
}
|
Correct paths to Codeception etc. | <?php
/**
* Define Robo commands for building and testing Drupal User Registry Codeception module.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* @type string
* Location of directory containing source code.
*/
const SRC_DIR = "src";
/**
* @type string
* Location of directory containing documentation files.
*/
const DOCS_DIR = "docs";
/**
* @type string
* Location of directory containing Codeception tests.
*/
const TESTS_DIR = "tests";
/**
* Generate PhpDocumentator files.
*/
public function docsGenerate()
{
$this->taskExec(sprintf("phpdoc run -d %s -t %s", self::SRC_DIR, self::DOCS_DIR))
->run();
}
/**
* Clean PhpDocumentor directory.
*/
public function docsClean()
{
$this->taskCleanDir(self::DOCS_DIR)->run();
}
/**
* Run (functional) tests.
*/
public function testsRun()
{
// Still have to build the *Tester classes if we've just checked out.
$this->taskExec("cd tests && vendor/bin/codecept build && cd -")->run();
$this->taskCodecept(self::TESTS_DIR . DIRECTORY_SEPARATOR . "vendor/bin/codecept")
->option("config", self::TESTS_DIR . DIRECTORY_SEPARATOR . "codeception.yml")
->suite("functional")
->run();
}
}
| <?php
/**
* Define Robo commands for building and testing Drupal User Registry Codeception module.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* @type string
* Location of directory containing source code.
*/
const SRC_DIR = "src";
/**
* @type string
* Location of directory containing documentation files.
*/
const DOCS_DIR = "docs";
/**
* @type string
* Location of directory containing Codeception tests.
*/
const TESTS_DIR = "tests";
/**
* Generate PhpDocumentator files.
*/
public function docsGenerate()
{
$this->taskExec(sprintf("phpdoc run -d %s -t %s", self::SRC_DIR, self::DOCS_DIR))
->run();
}
/**
* Clean PhpDocumentor directory.
*/
public function docsClean()
{
$this->taskCleanDir(self::DOCS_DIR)->run();
}
/**
* Run (functional) tests.
*/
public function testsRun()
{
// Still have to build the *Tester classes if we've just checked out.
$this->taskExec("cd tests && vendor/bin/codecept build && cd -")->run();
$this->taskCodecept("tests/vendor/bin/codecept")
->option("config", self::TESTS_DIR . "/tests/codeception.yml")
->suite("functional")
->run();
}
}
|
Allow Django Evolution to install along with Django >= 1.7.
As we're working toward some degree of compatibility with newer versions
of Django, we need to ease up on the version restriction. Now's a good
time to do so. Django Evolution no longer has an upper bounds on the
version range. | #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/runtests.py')
test.run_tests = run_tests
PACKAGE_NAME = 'django_evolution'
download_url = (
'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' %
(VERSION[0], VERSION[1]))
# Build the package
setup(
name=PACKAGE_NAME,
version=get_package_version(),
description='A database schema evolution tool for the Django web framework.',
url='http://code.google.com/p/django-evolution/',
author='Ben Khoo',
author_email='[email protected]',
maintainer='Christian Hammond',
maintainer_email='[email protected]',
download_url=download_url,
packages=find_packages(exclude=['tests']),
install_requires=[
'Django>=1.4.10',
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/runtests.py')
test.run_tests = run_tests
PACKAGE_NAME = 'django_evolution'
download_url = (
'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' %
(VERSION[0], VERSION[1]))
# Build the package
setup(
name=PACKAGE_NAME,
version=get_package_version(),
description='A database schema evolution tool for the Django web framework.',
url='http://code.google.com/p/django-evolution/',
author='Ben Khoo',
author_email='[email protected]',
maintainer='Christian Hammond',
maintainer_email='[email protected]',
download_url=download_url,
packages=find_packages(exclude=['tests']),
install_requires=[
'Django>=1.4.10,<1.7.0',
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Support older apache httpclient libs | package com.akamai.edgegrid.signer.apachehttpclient;
import com.akamai.edgegrid.signer.ClientCredential;
import com.akamai.edgegrid.signer.ClientCredentialProvider;
import com.akamai.edgegrid.signer.exceptions.NoMatchingCredentialException;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
public class ApacheHttpClientEdgeGridRoutePlanner extends DefaultRoutePlanner {
private final ApacheHttpClientEdgeGridRequestSigner binding;
public ApacheHttpClientEdgeGridRoutePlanner(ClientCredential clientCredential) {
super(DefaultSchemePortResolver.INSTANCE);
this.binding = new ApacheHttpClientEdgeGridRequestSigner(clientCredential);
}
public ApacheHttpClientEdgeGridRoutePlanner(ClientCredentialProvider clientCredentialProvider) {
super(DefaultSchemePortResolver.INSTANCE);
this.binding = new ApacheHttpClientEdgeGridRequestSigner(clientCredentialProvider);
}
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
try {
ClientCredential clientCredential = binding.getClientCredentialProvider().getClientCredential(binding.map(request));
HttpHost target = new HttpHost(clientCredential.getHost(), -1, "https");
return super.determineRoute(target, request, context);
} catch (NoMatchingCredentialException e) {
throw new RuntimeException(e);
}
}
}
| package com.akamai.edgegrid.signer.apachehttpclient;
import com.akamai.edgegrid.signer.ClientCredential;
import com.akamai.edgegrid.signer.ClientCredentialProvider;
import com.akamai.edgegrid.signer.exceptions.NoMatchingCredentialException;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
public class ApacheHttpClientEdgeGridRoutePlanner extends DefaultRoutePlanner {
private final ApacheHttpClientEdgeGridRequestSigner binding;
public ApacheHttpClientEdgeGridRoutePlanner(ClientCredential clientCredential) {
super(DefaultSchemePortResolver.INSTANCE);
this.binding = new ApacheHttpClientEdgeGridRequestSigner(clientCredential);
}
public ApacheHttpClientEdgeGridRoutePlanner(ClientCredentialProvider clientCredentialProvider) {
super(DefaultSchemePortResolver.INSTANCE);
this.binding = new ApacheHttpClientEdgeGridRequestSigner(clientCredentialProvider);
}
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
try {
ClientCredential clientCredential = binding.getClientCredentialProvider().getClientCredential(binding.map(request));
HttpHost target = HttpHost.create("https://" + clientCredential.getHost());
return super.determineRoute(target, request, context);
} catch (NoMatchingCredentialException e) {
throw new RuntimeException(e);
}
}
}
|
Bump elastalert version to 0.1.0 | # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.1.0',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='[email protected]',
setup_requires='setuptools',
license='Copyright 2014 Yelp',
entry_points={
'console_scripts': ['elastalert-create-index=elastalert.create_index:main',
'elastalert-test-rule=elastalert.test_rule:main',
'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main',
'elastalert=elastalert.elastalert:main']},
packages=find_packages(),
package_data={'elastalert': ['schema.yaml']},
install_requires=[
'argparse',
'elasticsearch',
'jira==0.32', # jira.exceptions is missing from later versions
'jsonschema',
'mock',
'python-dateutil',
'PyStaticConfiguration',
'pyyaml',
'simplejson',
'boto',
'botocore',
'blist',
'croniter',
'configparser',
'aws-requests-auth'
]
)
| # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.0.99',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='[email protected]',
setup_requires='setuptools',
license='Copyright 2014 Yelp',
entry_points={
'console_scripts': ['elastalert-create-index=elastalert.create_index:main',
'elastalert-test-rule=elastalert.test_rule:main',
'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main',
'elastalert=elastalert.elastalert:main']},
packages=find_packages(),
package_data={'elastalert': ['schema.yaml']},
install_requires=[
'argparse',
'elasticsearch',
'jira==0.32', # jira.exceptions is missing from later versions
'jsonschema',
'mock',
'python-dateutil',
'PyStaticConfiguration',
'pyyaml',
'simplejson',
'boto',
'botocore',
'blist',
'croniter',
'configparser',
'aws-requests-auth'
]
)
|
Fix declaration of namespace and uses | <?php
namespace SlaxWeb\Bootstrap;
use SlaxWeb\Hooks\Hooks;
use SlaxWeb\Registry\Container as Registry;
class Swf
{
/**
* Composer Autoloader
*
* @var object
*/
protected $_loader = null;
/**
* Router
*
* @var \SlaxWeb\Router\Router
*/
protected $_router = null;
public function __construct(\Composer\Autoload\ClassLoader $loader, \SlaxWeb\Router\Router $router)
{
$this->_loader = $loader;
$this->_router = $router;
Hooks::call("bootstrap.after.construct");
}
public function configureAutoload()
{
$this->_loader->add("Controller\\", APPPATH);
$this->_loader->add("Model\\", APPPATH);
$this->_loader->add("View\\", APPPATH);
Hooks::call("bootstrap.after.autoload");
}
public function routeRequest()
{
Hooks::call("bootstrap.before.route");
require_once APPPATH . "config/routes.php";
$route = $this->_router->process();
Hooks::call("bootstrap.before.controller");
if (is_object($route["action"]) && $route["action"] instanceof \Closure) {
call_user_func_array($route["action"], $route["params"]);
} else {
$controller = Registry::setAlias("controller", "\\Controller\\{$route["action"][0]}");
$controller->{$route["action"][1]}(...$route["params"]);
}
Hooks::call("bootstrap.after.route");
}
}
| <?php
namespace \SlaxWeb\Bootstrap;
use \SlaxWeb\Hooks\Hooks;
use \SlaxWeb\Registry\Container as Registry;
class Swf
{
/**
* Composer Autoloader
*
* @var object
*/
protected $_loader = null;
/**
* Router
*
* @var \SlaxWeb\Router\Router
*/
protected $_router = null;
public function __construct(\Composer\Autoload\ClassLoader $loader, \SlaxWeb\Router\Router $router)
{
$this->_loader = $loader;
$this->_router = $router;
Hooks::call("bootstrap.after.construct");
}
public function configureAutoload()
{
$this->_loader->add("Controller\\", APPPATH);
$this->_loader->add("Model\\", APPPATH);
$this->_loader->add("View\\", APPPATH);
Hooks::call("bootstrap.after.autoload");
}
public function routeRequest()
{
Hooks::call("bootstrap.before.route");
require_once APPPATH . "config/routes.php";
$route = $this->_router->process();
Hooks::call("bootstrap.before.controller");
if (is_object($route["action"]) && $route["action"] instanceof \Closure) {
call_user_func_array($route["action"], $route["params"]);
} else {
$controller = Registry::setAlias("controller", "\\Controller\\{$route["action"][0]}");
$controller->{$route["action"][1]}(...$route["params"]);
}
Hooks::call("bootstrap.after.route");
}
}
|
Correct sequence name for oracle
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@977 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.domain;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Rhett Sutphin
*/
@Entity
@Table(name = "ae_notifications")
@GenericGenerator(name="id-generator", strategy = "native",
parameters = {
@Parameter(name="sequence", value="seq_ae_notifications_id")
}
)
public class AdverseEventNotification extends AbstractDomainObject {
private StudyParticipantAssignment assignment;
private AdverseEvent adverseEvent;
private boolean dismissed;
////// BEAN PROPERTIES
@ManyToOne
public StudyParticipantAssignment getAssignment() {
return assignment;
}
public void setAssignment(StudyParticipantAssignment assignment) {
this.assignment = assignment;
}
@OneToOne
@JoinColumn(name="adverse_event_id")
@Cascade(CascadeType.ALL)
public AdverseEvent getAdverseEvent() {
return adverseEvent;
}
public void setAdverseEvent(AdverseEvent adverseEvent) {
this.adverseEvent = adverseEvent;
}
public boolean isDismissed() {
return dismissed;
}
public void setDismissed(boolean dismissed) {
this.dismissed = dismissed;
}
}
| package edu.northwestern.bioinformatics.studycalendar.domain;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Rhett Sutphin
*/
@Entity
@Table(name = "ae_notifications")
@GenericGenerator(name="id-generator", strategy = "native",
parameters = {
@Parameter(name="sequence", value="seq_adverse_event_notifications_id")
}
)
public class AdverseEventNotification extends AbstractDomainObject {
private StudyParticipantAssignment assignment;
private AdverseEvent adverseEvent;
private boolean dismissed;
////// BEAN PROPERTIES
@ManyToOne
public StudyParticipantAssignment getAssignment() {
return assignment;
}
public void setAssignment(StudyParticipantAssignment assignment) {
this.assignment = assignment;
}
@OneToOne
@JoinColumn(name="adverse_event_id")
@Cascade(CascadeType.ALL)
public AdverseEvent getAdverseEvent() {
return adverseEvent;
}
public void setAdverseEvent(AdverseEvent adverseEvent) {
this.adverseEvent = adverseEvent;
}
public boolean isDismissed() {
return dismissed;
}
public void setDismissed(boolean dismissed) {
this.dismissed = dismissed;
}
}
|
Add test case for new version of IUCN | <?php
namespace Test\AppBundle\API\Details;
use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismsWithTraitTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('details', 'organismsWithTrait');
//Test for the correct number of elements in the returned array
$results = $service->execute(new ParameterBag(array(
'dbversion' => $default_db,
'trait_type_id' => 1)),
null
);
$this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
$results = $service->execute(
new ParameterBag(array(
'dbversion' => $default_db,
'trait_type_id' => 3, 'limit' => 30000
)),
null
);
$this->assertEquals(23185, count($results));
$results = $service->execute(
new ParameterBag(array(
'dbversion' => $default_db,
'trait_type_id' => 1, 'limit' => 10
)),
null
);
$this->assertEquals(10, count($results));
$this->assertTrue(array_key_exists('fennec_id',$results[0]));
$this->assertTrue(array_key_exists('scientific_name',$results[0]));
}
} | <?php
namespace Test\AppBundle\API\Details;
use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismsWithTraitTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('details', 'organismsWithTrait');
//Test for the correct number of elements in the returned array
$results = $service->execute(new ParameterBag(array(
'dbversion' => $default_db,
'trait_type_id' => 1)),
null
);
$this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
$results = $service->execute(
new ParameterBag(array(
'dbversion' => $default_db,
'trait_type_id' => 1, 'limit' => 10
)),
null
);
$this->assertEquals(10, count($results));
$this->assertTrue(array_key_exists('fennec_id',$results[0]));
$this->assertTrue(array_key_exists('scientific_name',$results[0]));
}
} |
Update ALLOWED_HOSTS for move to service domain | from .base import *
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
GOOGLE_ANALYTICS_ID = "UA-53811587-1"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ.get('POSTGRES_PASS', ''),
'HOST': os.environ.get('POSTGRES_HOST', ''),
'PORT': os.environ.get('POSTGRES_PORT', ''),
'OPTIONS': {
'sslmode': 'require',
},
}
}
BROKER_TRANSPORT_OPTIONS = {'region': 'eu-west-1',
'queue_name_prefix': 'production-',
'polling_interval': 1,
'visibility_timeout': 3600}
INSTALLED_APPS += ('raven.contrib.django.raven_compat', )
ALLOWED_HOSTS = ["www.makeaplea.justice.gov.uk", "www.makeaplea.service.gov.uk"]
# Enable CachedStaticFilesStorage for cache-busting assets
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
STORE_USER_DATA = True
ENCRYPTED_COOKIE_KEYS = [
os.environ["ENCRYPTED_COOKIE_KEY"]
]
| from .base import *
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
GOOGLE_ANALYTICS_ID = "UA-53811587-1"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ.get('POSTGRES_PASS', ''),
'HOST': os.environ.get('POSTGRES_HOST', ''),
'PORT': os.environ.get('POSTGRES_PORT', ''),
'OPTIONS': {
'sslmode': 'require',
},
}
}
BROKER_TRANSPORT_OPTIONS = {'region': 'eu-west-1',
'queue_name_prefix': 'production-',
'polling_interval': 1,
'visibility_timeout': 3600}
INSTALLED_APPS += ('raven.contrib.django.raven_compat', )
ALLOWED_HOSTS = ["www.makeaplea.justice.gov.uk", "www.service.justice.gov.uk" ]
# Enable CachedStaticFilesStorage for cache-busting assets
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
STORE_USER_DATA = True
ENCRYPTED_COOKIE_KEYS = [
os.environ["ENCRYPTED_COOKIE_KEY"]
]
|
Fix serverUrl invokable call in the mailer plugin | <?php
namespace RbComment\Mvc\Controller\Plugin;
use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class Mailer extends AbstractPlugin
{
private $serverUrlHelper;
private $mailerService;
private $configService;
public function __construct(
$serverUrlHelper,
$mailerService,
array $configService
) {
$this->serverUrlHelper = $serverUrlHelper;
$this->mailerService = $mailerService;
$this->configService = $configService;
}
public function __invoke($comment)
{
$mailerConfig = $this->configService['rb_comment']['email'];
$htmlContent = $comment->content;
$htmlContent .= '<br><br>';
$htmlContent .= '<a href="' . $this->serverUrlHelper->__invoke() . $comment->uri . '#rbcomment-' . $comment->id . '">' .
$mailerConfig['context_link_text'] .
'</a>';
$html = new MimePart($htmlContent);
$html->type = "text/html";
$body = new MimeMessage();
$body->setParts([$html]);
$message = new Message();
$message->addFrom($mailerConfig['from'])
->setSubject($mailerConfig['subject'])
->setBody($body);
foreach ($mailerConfig['to'] as $mConfig) {
$message->addTo($mConfig);
}
$this->mailerService->send($message);
}
}
| <?php
namespace RbComment\Mvc\Controller\Plugin;
use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class Mailer extends AbstractPlugin
{
private $serverUrlHelper;
private $mailerService;
private $configService;
public function __construct(
$serverUrlHelper,
$mailerService,
array $configService
) {
$this->serverUrlHelper = $serverUrlHelper;
$this->mailerService = $mailerService;
$this->configService = $configService;
}
public function __invoke($comment)
{
$mailerConfig = $this->configService['rb_comment']['email'];
$htmlContent = $comment->content;
$htmlContent .= '<br><br>';
$htmlContent .= '<a href="' . $this->serverUrlHelper() . $comment->uri . '#rbcomment-' . $comment->id . '">' .
$mailerConfig['context_link_text'] .
'</a>';
$html = new MimePart($htmlContent);
$html->type = "text/html";
$body = new MimeMessage();
$body->setParts([$html]);
$message = new Message();
$message->addFrom($mailerConfig['from'])
->setSubject($mailerConfig['subject'])
->setBody($body);
foreach ($mailerConfig['to'] as $mConfig) {
$message->addTo($mConfig);
}
$this->mailerService->send($message);
}
}
|
Fix default captcha reload algo
System helper on method "buildSingleTag" escaping all quotes that make
imposible use inline javascript in onClick method | <?php
namespace Ffcms\Core\Helper\HTML\Form;
use Ffcms\Core\App;
use Ffcms\Core\Helper\HTML\System\NativeGenerator;
class CaptchaField extends NativeGenerator implements iField
{
private $properties;
private $name;
/**
* CaptchaField constructor. Pass attributes inside model.
* @param array $properties
* @param string $name
* @param string|null $value
*/
public function __construct($properties, $name, $value = null)
{
$this->properties = $properties;
$this->name = $name;
}
/**
* Build captcha response
* {@inheritDoc}
* @see \Ffcms\Core\Helper\HTML\Form\iField::make()
*/
public function make()
{
// if captcha is 'full-type' based just return rendered output
if (App::$Captcha->isFull()) {
return App::$Captcha->get();
}
// get image link
$image = App::$Captcha->get();
$response = '<img id="src-secure-image" src="' . $image . '" alt="captcha" onClick="this.src=\''.$image.'&rnd=\'+Math.random()" />';
// render response tag with image
$this->properties['type'] = 'text';
$response .= self::buildSingleTag('input', $this->properties);
return $response;
}
} | <?php
namespace Ffcms\Core\Helper\HTML\Form;
use Ffcms\Core\App;
use Ffcms\Core\Helper\HTML\System\NativeGenerator;
class CaptchaField extends NativeGenerator implements iField
{
private $properties;
private $name;
/**
* CaptchaField constructor. Pass attributes inside model.
* @param array $properties
* @param string $name
* @param string|null $value
*/
public function __construct($properties, $name, $value = null)
{
$this->properties = $properties;
$this->name = $name;
}
/**
* Build captcha response
* {@inheritDoc}
* @see \Ffcms\Core\Helper\HTML\Form\iField::make()
*/
public function make()
{
// if captcha is 'full-type' based just return rendered output
if (App::$Captcha->isFull()) {
return App::$Captcha->get();
}
// get image link
$image = App::$Captcha->get();
// build image tag
$response = self::buildSingleTag('img', [
'id' => 'src-secure-image',
'src' => $image,
'alt' => 'secure captcha image',
'onClick' => 'this.src=\'' . $image . '&rnd=\'+Math.random()'
]);
// render response tag with image
$this->properties['type'] = 'text';
$response .= self::buildSingleTag('input', $this->properties);
return $response;
}
} |
Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method | """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False
settings.SITE_ID = 1
settings.EDX_API_KEY = "test"
settings.ALTERNATE_QUEUE_ENVS = ['cms']
settings.USE_S3_FOR_CUSTOMER_THEMES = False
if settings.ENABLE_COMPREHENSIVE_THEMING:
assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, (
'Tahoe supports a single theme, please double check that '
'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.'
)
# Add the LMS-generated customer CSS files to the list
# LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css`
customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes')
if path.isdir(customer_themes_dir):
settings.STATICFILES_DIRS.insert(0, ('customer_themes', customer_themes_dir))
# This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths
# from the redirect mechanics.
settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
| """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False
settings.SITE_ID = 1
settings.EDX_API_KEY = "test"
settings.ALTERNATE_QUEUE_ENVS = ['cms']
settings.USE_S3_FOR_CUSTOMER_THEMES = False
if settings.ENABLE_COMPREHENSIVE_THEMING:
assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, (
'Tahoe supports a single theme, please double check that '
'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.'
)
# Add the LMS-generated customer CSS files to the list
# LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css`
customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes')
if path.isdir(customer_themes_dir):
settings.STATICFILES_DIRS.insert(0, customer_themes_dir)
# This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths
# from the redirect mechanics.
settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
|
Put exception eating back in | package org.opencds.cqf.config;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Library;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* Created by Christopher on 1/12/2017.
*/
public class STU3LibrarySourceProvider implements LibrarySourceProvider {
private LibraryResourceProvider provider;
private FhirLibrarySourceProvider innerProvider;
public STU3LibrarySourceProvider(LibraryResourceProvider provider) {
this.provider = provider;
this.innerProvider = new FhirLibrarySourceProvider();
}
@Override
public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
try {
Library lib = provider.getDao().read(new IdType(versionedIdentifier.getId()));
for (Attachment content : lib.getContent()) {
if (content.getContentType().equals("text/cql")) {
return new ByteArrayInputStream(content.getData());
}
}
}
catch(Exception e){}
return this.innerProvider.getLibrarySource(versionedIdentifier);
}
} | package org.opencds.cqf.config;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Library;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* Created by Christopher on 1/12/2017.
*/
public class STU3LibrarySourceProvider implements LibrarySourceProvider {
private LibraryResourceProvider provider;
private FhirLibrarySourceProvider innerProvider;
public STU3LibrarySourceProvider(LibraryResourceProvider provider) {
this.provider = provider;
this.innerProvider = new FhirLibrarySourceProvider();
}
@Override
public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
Library lib = provider.getDao().read(new IdType(versionedIdentifier.getId()));
if (lib != null) {
for (Attachment content : lib.getContent()) {
if (content.getContentType().equals("text/cql")) {
return new ByteArrayInputStream(content.getData());
}
}
}
return this.innerProvider.getLibrarySource(versionedIdentifier);
}
} |
Fix font-awesome LESS source not being found in some cases | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Asset;
use Less_Exception_Parser;
use Less_Parser;
class LessCompiler extends RevisionCompiler
{
/**
* @var string
*/
protected $cachePath;
/**
* @param string $path
* @param string $filename
* @param bool $watch
* @param string $cachePath
*/
public function __construct($path, $filename, $watch, $cachePath)
{
parent::__construct($path, $filename, $watch);
$this->cachePath = $cachePath;
}
/**
* {@inheritdoc}
*/
public function compile()
{
ini_set('xdebug.max_nesting_level', 200);
$parser = new Less_Parser([
'compress' => true,
'cache_dir' => $this->cachePath,
'import_dirs' => [
base_path().'vendor/fortawesome/font-awesome/less' => '',
],
]);
try {
foreach ($this->files as $file) {
$parser->parseFile($file);
}
foreach ($this->strings as $callback) {
$parser->parse($callback());
}
return $parser->getCss();
} catch (Less_Exception_Parser $e) {
// TODO: log an error somewhere?
}
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Asset;
use Less_Exception_Parser;
use Less_Parser;
class LessCompiler extends RevisionCompiler
{
/**
* @var string
*/
protected $cachePath;
/**
* @param string $path
* @param string $filename
* @param bool $watch
* @param string $cachePath
*/
public function __construct($path, $filename, $watch, $cachePath)
{
parent::__construct($path, $filename, $watch);
$this->cachePath = $cachePath;
}
/**
* {@inheritdoc}
*/
public function compile()
{
ini_set('xdebug.max_nesting_level', 200);
$parser = new Less_Parser([
'compress' => true,
'cache_dir' => $this->cachePath,
'import_dirs' => [
'vendor/fortawesome/font-awesome/less' => '',
],
]);
try {
foreach ($this->files as $file) {
$parser->parseFile($file);
}
foreach ($this->strings as $callback) {
$parser->parse($callback());
}
return $parser->getCss();
} catch (Less_Exception_Parser $e) {
// TODO: log an error somewhere?
}
}
}
|
[FIX] Define UTC as tz in get_working_days_of_date method | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_dt=None,
leaves=None, compute_leaves=False,
resource_id=None, default_interval=None,
context=None):
context = context or {}
context['tz'] = 'UTC'
if start_dt is None:
start_dt = datetime.now().replace(hour=0, minute=0, second=0)
if end_dt is None:
end_dt = datetime.now().replace(hour=23, minute=59, second=59)
days = 0
current = start_dt
while current <= end_dt:
if id is None:
days += 1
else:
end_day = current.replace(hour=23, minute=59, second=59)
end = end_dt if end_day > end_dt else end_day
working_intervals = self.get_working_intervals_of_day(
cr, uid, id, start_dt=current, end_dt=end, leaves=leaves,
compute_leaves=compute_leaves, resource_id=resource_id,
default_interval=default_interval, context=context)
if working_intervals:
days += 1
next = current + timedelta(days=1)
current = next
return days
| # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_dt=None,
leaves=None, compute_leaves=False,
resource_id=None, default_interval=None,
context=None):
if start_dt is None:
start_dt = datetime.now().replace(hour=0, minute=0, second=0)
if end_dt is None:
end_dt = datetime.now().replace(hour=23, minute=59, second=59)
days = 0
current = start_dt
while current <= end_dt:
if id is None:
days += 1
else:
end_day = current.replace(hour=23, minute=59, second=59)
end = end_dt if end_day > end_dt else end_day
working_intervals = self.get_working_intervals_of_day(
cr, uid, id, start_dt=current, end_dt=end, leaves=leaves,
compute_leaves=compute_leaves, resource_id=resource_id,
default_interval=default_interval, context=context)
if working_intervals:
days += 1
next = current + timedelta(days=1)
current = next
return days
|
Refresh the widget data on browser restart. | (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === null) {
storage.put(key, defaults[key]);
}
}
}
console.info('current storage:');
for(var i = 0; i < localStorage.length; i++) {
console.info(localStorage.key(i)+'='+localStorage.getItem(localStorage.key(i)));
}
// keep track of some notifications
storage.put('notifications', {});
panels.MainPanel(widgets);
// widgets initialization
for(var widget in widgets) {
widgets[widget].init();
}
// continue last session if credentials are available
if(storage.get('user') && storage.get('username') && storage.get('password')) {
for(var widget in widgets) {
// use 'load' instead of 'restore' to refresh the data on browser restart
widgets[widget].load();
}
// look for phone numbers in tabs from now on
page.init();
}
});
window.logout = function() {
console.info('logout');
chrome.runtime.sendMessage('logout');
panels.resetStorage();
panels.resetWidgets();
page.reset();
storage.remove('user');
storage.remove('username');
storage.remove('password');
};
})();
| (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === null) {
storage.put(key, defaults[key]);
}
}
}
console.info('current storage:');
for(var i = 0; i < localStorage.length; i++) {
console.info(localStorage.key(i)+'='+localStorage.getItem(localStorage.key(i)));
}
// keep track of some notifications
storage.put('notifications', {});
panels.MainPanel(widgets);
// widgets initialization
for(var widget in widgets) {
widgets[widget].init();
}
// continue last session if credentials are available
if(storage.get('user') && storage.get('username') && storage.get('password')) {
for(var widget in widgets) {
widgets[widget].restore();
}
// look for phone numbers in tabs from now on
page.init();
}
});
window.logout = function() {
console.info('logout');
chrome.runtime.sendMessage('logout');
panels.resetStorage();
panels.resetWidgets();
page.reset();
storage.remove('user');
storage.remove('username');
storage.remove('password');
};
})();
|
Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
Fix line ending printing on Python 3
To reflect the changes in
https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py
[email protected]
Bug: none
Change-Id: I25ba29042f537bfef57fba93115be2c194649864
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2914883
Commit-Queue: Tim van der Lippe <[email protected]>
Commit-Queue: Jack Franklin <[email protected]>
Auto-Submit: Tim van der Lippe <[email protected]>
Reviewed-by: Jack Franklin <[email protected]> | #!/usr/bin/env vpython
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', 'node'),
'Windows': ('win', 'node.exe'),
}[platform.system()])
def RunNode(cmd_parts, output=subprocess.PIPE):
cmd = [GetBinaryPath()] + cmd_parts
process = subprocess.Popen(cmd,
cwd=os.getcwd(),
stdout=output,
stderr=output,
universal_newlines=True)
stdout, stderr = process.communicate()
if process.returncode != 0:
print('%s failed:\n%s\n%s' % (cmd, stdout, stderr))
exit(process.returncode)
return stdout
if __name__ == '__main__':
args = sys.argv[1:]
# Accept --output as the first argument, and then remove
# it from the args entirely if present.
if len(args) > 0 and args[0] == '--output':
output = None
args = sys.argv[2:]
else:
output = subprocess.PIPE
RunNode(args, output)
| #!/usr/bin/env vpython
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', 'node'),
'Windows': ('win', 'node.exe'),
}[platform.system()])
def RunNode(cmd_parts, output=subprocess.PIPE):
cmd = [GetBinaryPath()] + cmd_parts
process = subprocess.Popen(cmd,
cwd=os.getcwd(),
stdout=output,
stderr=output)
stdout, stderr = process.communicate()
if process.returncode != 0:
print('%s failed:\n%s\n%s' % (cmd, stdout, stderr))
exit(process.returncode)
return stdout
if __name__ == '__main__':
args = sys.argv[1:]
# Accept --output as the first argument, and then remove
# it from the args entirely if present.
if len(args) > 0 and args[0] == '--output':
output = None
args = sys.argv[2:]
else:
output = subprocess.PIPE
RunNode(args, output)
|
Fix an issue with being able to update statuses | <?php
namespace Github\Api\Repository;
use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;
/**
* @link http://developer.github.com/v3/repos/statuses/
* @author Joseph Bielawski <[email protected]>
*/
class Statuses extends AbstractApi
{
/**
* @link http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-sha
*
* @param string $username
* @param string $repository
* @param string $sha
*
* @return array
*/
public function show($username, $repository, $sha)
{
return $this->get('/repos/'.urlencode($username).'/'.urlencode($repository).'/statuses/'.urlencode($sha));
}
/**
* @link http://developer.github.com/v3/repos/statuses/#create-a-status
*
* @param string $username
* @param string $repository
* @param string $sha
* @param array $params
*
* @return array
*
* @throws MissingArgumentException
*/
public function create($username, $repository, $sha, array $params = array())
{
if (!isset($params['state'])) {
throw new MissingArgumentException('state');
}
return $this->post('repos/'.urlencode($username).'/'.urlencode($repository).'/statuses/'.urlencode($sha), $params);
}
}
| <?php
namespace Github\Api\Repository;
use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;
/**
* @link http://developer.github.com/v3/repos/statuses/
* @author Joseph Bielawski <[email protected]>
*/
class Statuses extends AbstractApi
{
/**
* @link http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-sha
*
* @param string $username
* @param string $repository
* @param string $sha
*
* @return array
*/
public function show($username, $repository, $sha)
{
return $this->get('/repos/'.urlencode($username).'/'.urlencode($repository).'/statuses/'.urlencode($sha));
}
/**
* @link http://developer.github.com/v3/repos/statuses/#create-a-status
*
* @param string $username
* @param string $repository
* @param string $sha
* @param array $params
*
* @return array
*
* @throws MissingArgumentException
*/
public function create($username, $repository, $sha, array $params = array())
{
if (!isset($params['state'])) {
throw new MissingArgumentException('state');
}
return $this->post('repos/'.urlencode($username).'/'.urlencode($repository).'/statuses'.urlencode($sha), $params);
}
}
|
Fix regression error in file path. | 'use strict';
var path = require('path'),
childProcess = require('child_process'),
phantomjs = require('phantomjs'),
binPath = phantomjs.path;
module.exports = function (filepath, options, callback) {
var opt = options || {},
cb = callback || function () {},
runner = './node_modules/qunit-phantomjs-runner/runner.js';
if (opt.verbose) {
runner = './node_modules/qunit-phantomjs-runner/runner-list.js';
}
var absolutePath = path.resolve(filepath),
isAbsolutePath = absolutePath.indexOf(filepath) >= 0,
childArgs = [];
if (opt['phantomjs-options'] && opt['phantomjs-options'].length) {
childArgs.push( opt['phantomjs-options'] );
}
childArgs.push(
path.join(__dirname, runner),
(isAbsolutePath ? 'file:///' + absolutePath.replace(/\\/g, '/') : filepath)
);
if ( opt.timeout ) {
childArgs.push( opt.timeout );
}
var proc = childProcess.execFile(binPath, childArgs, function (err, stdout, stderr) {
console.log('Testing ' + path.relative(__dirname, filepath));
if (stdout) {
stdout = stdout.trim(); // Trim trailing cr-lf
console.log(stdout);
}
if (stderr) {
console.log(stderr);
}
if (err) {
console.log(err);
}
});
proc.on('close', function (code) {
return cb(code);
});
};
| 'use strict';
var path = require('path'),
childProcess = require('child_process'),
phantomjs = require('phantomjs'),
binPath = phantomjs.path;
module.exports = function (filepath, options, callback) {
var opt = options || {},
cb = callback || function () {},
runner = './node_modules/qunit-phantomjs-runner/runner.js';
if (opt.verbose) {
runner = './node_modules/qunit-phantomjs-runner/runner-list.js';
}
var absolutePath = path.resolve(filepath),
isAbsolutePath = absolutePath.indexOf(filepath) >= 0,
childArgs = [];
if (opt['phantomjs-options'] && opt['phantomjs-options'].length) {
childArgs.push( opt['phantomjs-options'] );
}
childArgs.push(
path.join(__dirname, runner),
(isAbsolutePath ? 'file:///' + absolutePath.replace(/\\/g, '/') : file.path)
);
if ( opt.timeout ) {
childArgs.push( opt.timeout );
}
var proc = childProcess.execFile(binPath, childArgs, function (err, stdout, stderr) {
console.log('Testing ' + path.relative(__dirname, filepath));
if (stdout) {
stdout = stdout.trim(); // Trim trailing cr-lf
console.log(stdout);
}
if (stderr) {
console.log(stderr);
}
if (err) {
console.log(err);
}
});
proc.on('close', function (code) {
return cb(code);
});
};
|
Remove treebeard dependency (it's django-treebeard). | from setuptools import setup
version = '0.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'cassandralib',
'django-extensions',
'django-nose',
'django-treebeard',
'lizard-security',
'lizard-ui >= 4.0b5',
'pandas',
],
tests_require = [
]
setup(name='ddsc-core',
version=version,
description="TODO",
long_description=long_description,
# Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Programming Language :: Python',
'Framework :: Django',
],
keywords=[],
author='TODO',
author_email='[email protected]',
url='',
license='GPL',
packages=['ddsc_core'],
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
entry_points={
'console_scripts': [
]},
)
| from setuptools import setup
version = '0.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'cassandralib',
'django-extensions',
'django-nose',
'django-treebeard',
'lizard-security',
'lizard-ui >= 4.0b5',
'pandas',
'treebeard',
],
tests_require = [
]
setup(name='ddsc-core',
version=version,
description="TODO",
long_description=long_description,
# Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Programming Language :: Python',
'Framework :: Django',
],
keywords=[],
author='TODO',
author_email='[email protected]',
url='',
license='GPL',
packages=['ddsc_core'],
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
entry_points={
'console_scripts': [
]},
)
|
Update component state even when not editing | import React, { Component } from 'react'
import { Creatable } from 'react-select'
import R from 'ramda'
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options
}
componentWillReceiveProps = nextProps => {
if (nextProps.input.value) {
// because it could be user custom tag, we need to put in
// into list of options:
const computedOptions = (values, options) => {
const allOptions = values.reduce((acc, value) => {
const transformedValue = {
value,
label: value
}
acc.push(transformedValue)
return acc
}, options)
return R.uniq(allOptions)
}
this.setState({
multiValue: nextProps.input.value,
options: computedOptions(nextProps.input.value, nextProps.options)
})
}
}
handleOnChange = value => {
this.setState((prevState, props) => ({ multiValue: value }))
this.props.input.onChange((value) ? value.split(',') : [])
}
render () {
const { multi, multiValue } = this.state
return (
<Creatable
{...this.props}
className='j-select'
placeholder={this.props.placeholder}
multi={multi}
simpleValue
options={this.state.options}
onChange={this.handleOnChange}
value={multiValue}
/>
)
}
}
export default TagSelect
| import React, { Component } from 'react'
import { Creatable } from 'react-select'
import R from 'ramda'
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options
}
componentWillReceiveProps = nextProps => {
if (nextProps.edit && nextProps.input.value) {
// because it could be user custom tag, we need to put in
// into list of options:
const computedOptions = (values, options) => {
const allOptions = values.reduce((acc, value) => {
const transformedValue = {
value,
label: value
}
acc.push(transformedValue)
return acc
}, options)
return R.uniq(allOptions)
}
this.setState({
multiValue: nextProps.input.value,
options: computedOptions(nextProps.input.value, nextProps.options)
})
}
}
handleOnChange = value => {
this.setState((prevState, props) => ({ multiValue: value }))
this.props.input.onChange((value) ? value.split(',') : [])
}
render () {
const { multi, multiValue } = this.state
return (
<Creatable
{...this.props}
className='j-select'
placeholder={this.props.placeholder}
multi={multi}
simpleValue
options={this.state.options}
onChange={this.handleOnChange}
value={multiValue}
/>
)
}
}
export default TagSelect
|
Revert "adding settings for EJS render method" | 'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
var assign = require('object-assign');
module.exports = function (options, settings) {
options = options || {};
settings = settings || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit(
'error',
new gutil.PluginError('gulp-ejs', 'Streaming not supported')
);
}
options = assign({}, options, file.data);
options.filename = file.path;
try {
file.contents = new Buffer(
ejs.render(file.contents.toString(), options)
);
if (typeof settings.ext !== 'undefined') {
file.path = gutil.replaceExtension(file.path, settings.ext);
}
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-ejs', err.toString()));
}
this.push(file);
cb();
});
};
| 'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
var assign = require('object-assign');
module.exports = function (options, settings) {
options = options || {};
settings = settings || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit(
'error',
new gutil.PluginError('gulp-ejs', 'Streaming not supported')
);
}
options = assign({}, options, file.data);
options.filename = file.path;
try {
file.contents = new Buffer(
ejs.render(file.contents.toString(), options, settings)
);
if (typeof settings.ext !== 'undefined') {
file.path = gutil.replaceExtension(file.path, settings.ext);
}
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-ejs', err.toString()));
}
this.push(file);
cb();
});
};
|
Make it possible to run this test stand-alone. | # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
import __hello__
except ImportError as x:
self.fail("import __hello__ failed:" + str(x))
try:
import __phello__
except ImportError as x:
self.fail("import __phello__ failed:" + str(x))
try:
import __phello__.spam
except ImportError as x:
self.fail("import __phello__.spam failed:" + str(x))
if sys.platform != "mac": # On the Mac this import does succeed.
try:
import __phello__.foo
except ImportError:
pass
else:
self.fail("import __phello__.foo should have failed")
self.assertEquals(stdout.getvalue(),
'Hello world...\nHello world...\nHello world...\n')
def test_main():
run_unittest(FrozenTests)
if __name__ == "__main__":
test_main()
| # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
import __hello__
except ImportError as x:
self.fail("import __hello__ failed:" + str(x))
try:
import __phello__
except ImportError as x:
self.fail("import __phello__ failed:" + str(x))
try:
import __phello__.spam
except ImportError as x:
self.fail("import __phello__.spam failed:" + str(x))
if sys.platform != "mac": # On the Mac this import does succeed.
try:
import __phello__.foo
except ImportError:
pass
else:
self.fail("import __phello__.foo should have failed")
self.assertEquals(stdout.getvalue(),
'Hello world...\nHello world...\nHello world...\n')
def test_main():
run_unittest(FrozenTests)
|
Add in ajax for newadminbox | $.fn.editable.defaults.mode = 'inline';
$(document).ready(function() {
$('#newelectionbox').submit(function(event) {
document.getElementById("submitbtn").disabled = true;
document.getElementById("submitbtn").innerHTML = "Creating...";
var formData = {
'election' : $('input[name=election]').val(),
'_csrf' : $('input[name=_csrf]').val()
};
var formsub = $.ajax({
type : 'POST',
url : '/endpoints/process_new_election.php',
data : formData,
dataType : 'json',
encode : true
});
formsub.done(function(data) {
if (!data.success) {
document.getElementById("submitbtn").disabled = false;
document.getElementById("submitbtn").innerHTML = "Error";
} else {
$('#newelectionbox').modal('hide');
location.reload();
}
});
event.preventDefault();
});
$('#newadminbox').submit(function(event) {
document.getElementById("submitbtn_newadmin").disabled = true;
document.getElementById("submitbtn_newadmin").innerHTML = "Adding...";
var formData = {
'email' : $('input[name=email]').val(),
'_csrf' : $('input[name=_csrf]').val()
};
var formsub = $.ajax({
type : 'POST',
url : '/endpoints/process_new_election_admin.php',
data : formData,
dataType : 'json',
encode : true
});
formsub.done(function(data) {
if (!data.success) {
document.getElementById("submitbtn_newadmin").disabled = false;
document.getElementById("submitbtn_newadmin").innerHTML = "Error";
} else {
$('#newadminbox').modal('hide');
location.reload();
}
});
event.preventDefault();
});
});
| $.fn.editable.defaults.mode = 'inline';
$(document).ready(function() {
$('#newelectionbox').submit(function(event) {
document.getElementById("submitbtn").disabled = true;
document.getElementById("submitbtn").innerHTML = "Creating...";
var formData = {
'election' : $('input[name=election]').val(),
'_csrf' : $('input[name=_csrf]').val()
};
var formsub = $.ajax({
type : 'POST',
url : '/endpoints/process_new_election.php',
data : formData,
dataType : 'json',
encode : true
});
formsub.done(function(data) {
if (!data.success) {
document.getElementById("submitbtn").disabled = false;
document.getElementById("submitbtn").innerHTML = "Error";
} else {
$('#newelectionbox').modal('hide');
location.reload();
}
});
event.preventDefault();
});
}); |
Build base instead of preflight | import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
return postcss([tailwind(), require('autoprefixer')])
.process(css, {
from: `./${filename}.css`,
to: `./dist/${filename}.css`,
map: { inline: false },
})
.then(result => {
fs.writeFileSync(`./dist/${filename}.css`, result.css)
if (result.map) {
fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
}
return result
})
.then(result => {
const minified = new CleanCSS().minify(result.css)
fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
})
.then(resolve)
.catch(error => {
console.log(error)
reject()
})
})
})
}
console.info('Building Tailwind!')
Promise.all([
buildDistFile('base'),
buildDistFile('components'),
buildDistFile('utilities'),
buildDistFile('tailwind'),
]).then(() => {
console.log('Finished Building Tailwind!')
})
| import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
return postcss([tailwind(), require('autoprefixer')])
.process(css, {
from: `./${filename}.css`,
to: `./dist/${filename}.css`,
map: { inline: false },
})
.then(result => {
fs.writeFileSync(`./dist/${filename}.css`, result.css)
if (result.map) {
fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
}
return result
})
.then(result => {
const minified = new CleanCSS().minify(result.css)
fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
})
.then(resolve)
.catch(error => {
console.log(error)
reject()
})
})
})
}
console.info('Building Tailwind!')
Promise.all([
buildDistFile('preflight'),
buildDistFile('components'),
buildDistFile('utilities'),
buildDistFile('tailwind'),
]).then(() => {
console.log('Finished Building Tailwind!')
})
|
Remove esacpe method at driver (use bind instead) | <?php
namespace DB\Driver;
/**
* Interface for all database driver. Any database driver must implement
* this class.
*
* @package DB\Driver
*/
interface IDriver
{
/**
* Connect to selected database host
*
* @param string $host Database host name
* @param string $user Username for database host
* @param string $password Password for database host
*/
public function connect($host, $user, $password);
/**
* Connect to database in the host.
*
* @param string $name Database name
* @param bool $forceCreate If set to true, will create database if
* database is not exists
*/
public function database($name, $forceCreate=false);
/**
* Perform Query based on the driver.
*
* @param string $sql SQL that need to be run
*
* @return \DB\Result Database query result
*/
public function query($sql);
/**
* Perform database query by binding the data to query syntax.
*
* @param string $sql SQL
* @param array $data Data that will be binded to query
*
* @return \DB\Result Database query result
*/
public function bind($sql, $data=[]);
}
?>
| <?php
namespace DB\Driver;
/**
* Interface for all database driver. Any database driver must implement
* this class.
*
* @package DB\Driver
*/
interface IDriver
{
/**
* Connect to selected database host
*
* @param string $host Database host name
* @param string $user Username for database host
* @param string $password Password for database host
*/
public function connect($host, $user, $password);
/**
* Connect to database in the host.
*
* @param string $name Database name
* @param bool $forceCreate If set to true, will create database if
* database is not exists
*/
public function database($name, $forceCreate=false);
/**
* Perform Query based on the driver.
*
* @param string $sql SQL that need to be run
*
* @return \DB\Result Database query result
*/
public function query($sql);
/**
* Perform database query by binding the data to query syntax.
*
* @param string $sql SQL
* @param array $data Data that will be binded to query
*
* @return \DB\Result Database query result
*/
public function bind($sql, $data=[]);
public function escape($string);
}
?>
|
Update to compatible with PHPWebDriver 1.12.0 | <?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');
/**
* SystemWebDriver This class is a duplication of WebDriver class in order to return a custom session object, which extends a few methods based on WebDriverSession class
*
* @uses PHPWebDriver_WebDriver
* @package tests
* @version //autogen//
* @copyright Copyright (c) 2013 All rights reserved.
* @author
* @license PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
*/
class SystemWebDriver extends PHPWebDriver_WebDriver {
function __construct($executor = null) {
if (! is_null($executor)) {
parent::__construct($executor);
} else {
parent::__construct();
}
}
public function session($browser = 'firefox',
$additional_capabilities = array(),
$curl_opts = array(),
$browser_profile = null) {
$capabilities = new PHPWebDriver_WebDriverDesiredCapabilities();
$desired_capabilities = array_merge($capabilities->$browser, $additional_capabilities);
if ($browser == 'firefox' && $browser_profile) {
$desired_capabilities['firefox_profile'] = $browser_profile->encoded();
}
$curl_opts = $curl_opts + array(CURLOPT_FOLLOWLOCATION => true);
$results = $this->curl(
'POST',
'/session',
array('desiredCapabilities' => $desired_capabilities),
$curl_opts);
return new SystemWebDriverSession($results['info']['url'].$results['sessionId']);
}
}
| <?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');
class SystemWebDriver extends PHPWebDriver_WebDriver {
function __construct($executor = null) {
if (! is_null($executor)) {
parent::__construct($executor);
} else {
parent::__construct();
}
}
public function session($browser = 'firefox',
$additional_capabilities = array(),
$curl_opts = array(),
$browser_profile = null) {
$capabilities = new PHPWebDriver_WebDriverDesiredCapabilities();
$desired_capabilities = array_merge($capabilities->$browser, $additional_capabilities);
if ($browser == 'firefox' && $browser_profile) {
$desired_capabilities['firefox_profile'] = $browser_profile->encoded();
}
$curl_opts = $curl_opts + array(CURLOPT_FOLLOWLOCATION => true);
$results = $this->curl(
'POST',
'/session',
array('desiredCapabilities' => $desired_capabilities),
$curl_opts);
return new SystemWebDriverSession($results['info']['url']);
}
} |
Update tests to use refactored path() | <?php
require_once 'minim/plugins/tests/tests.php';
require_once 'minim/minim.php';
class Minim_TestCase extends TestCase
{
function test_minim_get_plugin()
{
$minim = new Minim();
$this->assertTrue($minim !== minim());
$minim->plugin_paths = array(
path(dirname(__FILE__), 'res')
);
$plugin =& $minim->get_plugin('dummy');
$class = get_class($plugin);
$this->assertTrue(($class == 'DummyPlugin'),
"Class mismatch: $class");
}
function test_minim_get_unregistered_plugin()
{
$minim = new Minim();
try
{
$minim->get_plugin('not_registered');
}
catch (Minim_Exception $me)
{
// test passes
return;
}
catch (Exception $e)
{
$this->fail('Caught unexpected exception: '.$e->getMessage());
}
$this->fail('Expected Minim_Exception');
}
function test_minim_get_null_plugin()
{
$minim = new Minim();
try
{
$minim->get_plugin(NULL);
}
catch (Minim_Exception $me)
{
// test passes
return;
}
catch (Exception $e)
{
$this->fail('Caught unexpected exception: '.$e);
}
$this->fail('Expected Minim_Exception');
}
}
| <?php
require_once 'minim/plugins/tests/tests.php';
require_once 'minim/minim.php';
class Minim_TestCase extends TestCase
{
function test_minim_get_plugin()
{
$minim = new Minim();
$this->assertTrue($minim !== minim());
$minim->plugin_paths = array(
build_path(dirname(__FILE__), 'res')
);
$plugin =& $minim->get_plugin('dummy');
$class = get_class($plugin);
$this->assertTrue(($class == 'DummyPlugin'),
"Class mismatch: $class");
}
function test_minim_get_unregistered_plugin()
{
$minim = new Minim();
try
{
$minim->get_plugin('not_registered');
}
catch (Minim_Exception $me)
{
// test passes
return;
}
catch (Exception $e)
{
$this->fail('Caught unexpected exception: '.$e->getMessage());
}
$this->fail('Expected Minim_Exception');
}
function test_minim_get_null_plugin()
{
$minim = new Minim();
try
{
$minim->get_plugin(NULL);
}
catch (Minim_Exception $me)
{
// test passes
return;
}
catch (Exception $e)
{
$this->fail('Caught unexpected exception: '.$e);
}
$this->fail('Expected Minim_Exception');
}
}
|
Include codegen package in distribution. | # -*- coding: utf-8 -*-
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.codegen', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
| # -*- coding: utf-8 -*-
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='[email protected]',
packages=['grako', 'grako.test'],
scripts=['scripts/grako'],
url='http://bitbucket.org/apalala/grako',
license='BSD License',
description='A generator of PEG/Packrat parsers from EBNF grammars.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Interpreters',
'Topic :: Text Processing :: General'
],
ext_modules=cythonize(
"grako/**/*.py",
exclude=[
'grako/__main__.py',
'grako/test/__main__.py',
'grako/test/*.py'
]
) if CYTHON else [],
)
|
Use method store instead of storePublicly | <?php
namespace Canvas\Http\Controllers;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
class MediaController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @return mixed
*/
public function store()
{
$payload = request()->file();
// We only expect single file uploads at this time
$file = reset($payload);
if ($file instanceof UploadedFile) {
$path = $file->store($this->getBaseStoragePath(), [
'disk' => config('canvas.storage_disk'),
]);
return Storage::disk(config('canvas.storage_disk'))->url($path);
}
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\JsonResponse
*/
public function destroy()
{
$file = pathinfo(request()->getContent());
$storagePath = $this->getBaseStoragePath();
$path = "{$storagePath}/{$file['basename']}";
$fileDeleted = Storage::disk(config('canvas.storage_disk'))->delete($path);
if ($fileDeleted) {
return response()->json([], 204);
}
}
/**
* Return the storage path url.
*
* @return string
*/
private function getBaseStoragePath(): string
{
return sprintf('%s/%s', config('canvas.storage_path'), 'images');
}
}
| <?php
namespace Canvas\Http\Controllers;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
class MediaController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @return mixed
*/
public function store()
{
$payload = request()->file();
// We only expect single file uploads at this time
$file = reset($payload);
if ($file instanceof UploadedFile) {
$path = $file->storePublicly($this->getBaseStoragePath(), [
'disk' => config('canvas.storage_disk'),
]);
return Storage::disk(config('canvas.storage_disk'))->url($path);
}
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\JsonResponse
*/
public function destroy()
{
$file = pathinfo(request()->getContent());
$storagePath = $this->getBaseStoragePath();
$path = "{$storagePath}/{$file['basename']}";
$fileDeleted = Storage::disk(config('canvas.storage_disk'))->delete($path);
if ($fileDeleted) {
return response()->json([], 204);
}
}
/**
* Return the storage path url.
*
* @return string
*/
private function getBaseStoragePath(): string
{
return sprintf('%s/%s', config('canvas.storage_path'), 'images');
}
}
|
Create "Register configurations" method and move config codes | <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Indicates if loading of the provider is deferred
*
* @var bool
*/
protected $defer = false;
/**
* Register the application services
*
* @return void
*/
public function register()
{
//
}
/**
* Perform post-registration booting of services
*
* @return void
*/
public function boot()
{
// Register configurations
$this->registerConfigurations();
// If running in console
if ($this->app->runningInConsole())
{
return;
}
// If CharacterSolver is disabled
if (!$this->app['config']->get('charactersolver.enabled'))
{
return;
}
// Add a new middleware to end of the stack if it does not already exist
$this->registerMiddleware(Middleware\CharacterSolver::class);
}
/**
* Register the CharacterSolver middleware
*
* @param string $middleware
*/
protected function registerMiddleware($middleware)
{
$kernel = $this->app['Illuminate\Contracts\Http\Kernel'];
$kernel->pushMiddleware($middleware);
}
/**
* Register configurations
*
* @return void
*/
protected function registerConfigurations()
{
// Default package configuration
$this->mergeConfigFrom(
__DIR__ . '/../config/charactersolver.php', 'charactersolver'
);
// Publish the config file
$this->publishes([
__DIR__ . '/../config/charactersolver.php' => config_path('charactersolver.php')
], 'config');
}
}
| <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Indicates if loading of the provider is deferred
*
* @var bool
*/
protected $defer = false;
/**
* Register the application services
*
* @return void
*/
public function register()
{
// Default package configuration
$this->mergeConfigFrom(
__DIR__ . '/../config/charactersolver.php', 'charactersolver'
);
}
/**
* Perform post-registration booting of services
*
* @return void
*/
public function boot()
{
// Publish the config file
$this->publishConfig();
// If running in console
if ($this->app->runningInConsole())
{
return;
}
// If CharacterSolver is disabled
if (!$this->app['config']->get('charactersolver.enabled'))
{
return;
}
// Add a new middleware to end of the stack if it does not already exist
$this->registerMiddleware(Middleware\CharacterSolver::class);
}
/**
* Register the CharacterSolver middleware
*
* @param string $middleware
*/
protected function registerMiddleware($middleware)
{
$kernel = $this->app['Illuminate\Contracts\Http\Kernel'];
$kernel->pushMiddleware($middleware);
}
/**
* Publish the config file
*/
protected function publishConfig()
{
$this->publishes([
__DIR__ . '/../config/charactersolver.php' => config_path('charactersolver.php')
], 'config');
}
}
|
Modify indicator list query.
Format indicator queries.
Corrected missing { for getIndicatorToUpdate | import gql from "graphql-tag";
class IndicatorRepository {
static getListPage(pageNumber, pageSize) {
return gql`
{
allIndicators{
nodes {
id
name
indicatorTypeByIndicatorTypeId {
name
}
indicatorGroupByIndicatorGroupId {
name
}
executionOrder
flagActive
updatedDate
}
}
}
`
}
static getFormDropdownData() {
return gql`
{
allIndicatorTypes {
nodes {
id
name
}
}
allIndicatorGroups {
nodes {
id
name
}
}
}
`
}
static insert() {
return gql`
mutation addNewIndicator($indicator: IndicatorInput!) {
createIndicator(input: { indicator: $indicator }) {
indicator {
id
name
description
}
}
}
`
}
static getIndicatorToUpdate(id) {
return gql`
{
indicatorById(id:` + id + `) {
id
name
description
executionOrder
flagActive
createdDate
updatedDate
indicatorTypeId
}
}
`
}
static update() {
return gql`
mutation updateIndicator($id: Int!, $indicatorPatch: IndicatorPatch!) {
updateIndicatorById(input: {id: $id, indicatorPatch: $indicatorPatch}) {
indicator {
id
}
}
}
`
}
}
export default IndicatorRepository; | import gql from "graphql-tag";
class IndicatorRepository {
static getListPage(pageNumber, pageSize) {
return gql`{
allIndicators{
nodes {
id
name
description
executionOrder
flagActive
createdDate
updatedDate
indicatorTypeId
}
}
}`
}
static getFormDropdownData() {
return gql`
{
allIndicatorTypes {
nodes {
id
name
}
}
allIndicatorGroups {
nodes {
id
name
}
}
}`
}
static insert() {
return gql`
mutation addNewIndicator($indicator: IndicatorInput!) {
createIndicator(input: { indicator: $indicator }) {
indicator {
id
name
description
}
}
}`
}
static getIndicatorToUpdate(id) {
return gql`
indicatorById(id:` + id + `) {
id
name
description
executionOrder
flagActive
createdDate
updatedDate
indicatorTypeId
}
}`
}
static update() {
return gql`
mutation updateIndicator($id: Int!, $indicatorPatch: IndicatorPatch!) {
updateIndicatorById(input: {id: $id, indicatorPatch: $indicatorPatch}) {
indicator {
id
}
}
}`
}
}
export default IndicatorRepository; |
Update last seen date when connecting through socket.io | 'use strict';
/*
* Socket.io related things go !
*/
import { log, LOG_TYPES } from './log';
import { decodeJWT } from './JWT';
import models from '../models';
const User = models.User;
const EVENT_TYPES = {
DISCONNECT : 'disconnect',
CONNECTION : 'connection',
TOKEN_VALID : 'token_valid',
TOKEN_INVALID : 'token_invalid',
CONTACT_ONLINE : 'contact:online',
CONTACT_OFFLINE : 'contact:offline'
};
let io;
let connections = [];
function createSocketIO(server, app) {
io = require('socket.io')(server);
io.on(EVENT_TYPES.CONNECTION, (socket) => {
socket.on(EVENT_TYPES.DISCONNECT, () => {
log(`Socket disconnected with id ${socket.id}`, LOG_TYPES.WARN);
let i = connections.indexOf(socket);
connections.splice(i, 1);
});
decodeJWT(socket.handshake.query.token)
.then( results => {
log(`Socket connected with id ${socket.id}`);
socket.emit('token_valid', {});
let lastSeen = Date.now();
results.lastSeen = lastSeen;
socket.user = results;
User.update({ lastSeen: lastSeen }, { where: { id: results.id } });
connections.push(socket);
})
.catch(error => {
log(`Token from ${socket.id} is invalid`, LOG_TYPES.ALERT)
socket.emit('token_invalid', {});
socket.disconnect(true);
})
});
}
export { io, connections, createSocketIO, EVENT_TYPES }
| 'use strict';
/*
* Socket.io related things go !
*/
import { log, LOG_TYPES } from './log';
import { decodeJWT } from './JWT';
const EVENT_TYPES = {
DISCONNECT : 'disconnect',
CONNECTION : 'connection',
TOKEN_VALID : 'token_valid',
TOKEN_INVALID : 'token_invalid',
CONTACT_ONLINE : 'contact:online',
CONTACT_OFFLINE : 'contact:offline'
};
let io;
let connections = [];
function createSocketIO(server, app) {
io = require('socket.io')(server);
io.on(EVENT_TYPES.CONNECTION, (socket) => {
socket.on(EVENT_TYPES.DISCONNECT, () => {
log(`Socket disconnected with id ${socket.id}`, LOG_TYPES.WARN);
let i = connections.indexOf(socket);
connections.splice(i, 1);
});
decodeJWT(socket.handshake.query.token)
.then( results => {
log(`Socket connected with id ${socket.id}`);
socket.emit('token_valid', {});
socket.user = results;
connections.push(socket);
})
.catch(error => {
log(`Token from ${socket.id} is invalid`, LOG_TYPES.ALERT)
socket.emit('token_invalid', {});
socket.disconnect(true);
})
});
}
export { io, connections, createSocketIO, EVENT_TYPES }
|
Abort with appropriate status codes in the decorator | from functools import wraps
from flask import session, redirect, url_for, request, abort
from alexandria import mongo
def not_even_one(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if mongo.Books.find_one() is None:
return redirect(url_for('upload'))
return f(*args, **kwargs)
return decorated_function
def authenticated(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print request.method
if request.method == 'GET':
token = request.args.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
abort(403)
elif request.method == 'POST':
token = request.form.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
abort(403)
else:
abort(405)
return f(*args, **kwargs)
return decorated_function
def administrator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
user = mongo.Users.find_one({'username': session.get('username')})
if user['role'] != 0:
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
| from functools import wraps
from flask import session, redirect, url_for, request, abort
from alexandria import mongo
def not_even_one(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if mongo.Books.find_one() is None:
return redirect(url_for('upload'))
return f(*args, **kwargs)
return decorated_function
def authenticated(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print request.method
if request.method == 'GET':
token = request.args.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
#abort(403)
pass
elif request.method == 'POST':
token = request.form.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
#abort(403)
pass
else:
#abort(405)
pass
return f(*args, **kwargs)
return decorated_function
def administrator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
user = mongo.Users.find_one({'username': session.get('username')})
if user['role'] != 0:
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
|
Fix bug in isOnTarget BandBangController | package com.team254.frc2015.subsystems.controllers;
import com.team254.lib.util.Controller;
public class BangBangFinishLineController extends Controller {
private double m_position;
private double m_goal;
private double m_tolerance;
private double m_direction = 0.0;
public BangBangFinishLineController(double tolerance) {
m_tolerance = tolerance;
}
public void setGoal(double goal) {
m_goal = goal;
}
public double getGoal() {
return m_goal;
}
@Override
public void reset() {
m_direction = 0.0;
}
@Override
public boolean isOnTarget() {
if (m_direction == 0.0) {
return false;
}
return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
: m_position < (m_goal + m_tolerance));
}
public double update(double position) {
if (m_direction == 0.0) {
m_direction = (position > m_goal ? -1.0 : 1.0);
}
m_position = position;
if (m_direction > 0) {
if (position < (m_goal - m_tolerance)) {
return 1.0;
} else {
return 0.0;
}
} else {
if (position > (m_goal + m_tolerance)) {
return -1.0;
} else {
return 0.0;
}
}
}
}
| package com.team254.frc2015.subsystems.controllers;
import com.team254.lib.util.Controller;
public class BangBangFinishLineController extends Controller {
private double m_position;
private double m_goal;
private double m_tolerance;
private double m_direction = 0.0;
public BangBangFinishLineController(double tolerance) {
m_tolerance = tolerance;
}
public void setGoal(double goal) {
m_goal = goal;
}
public double getGoal() {
return m_goal;
}
@Override
public void reset() {
m_direction = 0.0;
}
@Override
public boolean isOnTarget() {
return (m_direction > 0 ? m_position > (m_goal - m_tolerance)
: m_position < (m_goal + m_tolerance));
}
public double update(double position) {
if (m_direction == 0.0) {
m_direction = (position > m_goal ? -1.0 : 1.0);
}
m_position = position;
if (m_direction > 0) {
if (position < (m_goal - m_tolerance)) {
return 1.0;
} else {
return 0.0;
}
} else {
if (position > (m_goal + m_tolerance)) {
return -1.0;
} else {
return 0.0;
}
}
}
}
|
Fix the description of DecompilationPhase.__init__(). | #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <[email protected]> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Phase of a decompilation."""
class DecompilationPhase:
"""Phase of a decompilation."""
def __init__(self, name, part, description, completion):
"""Initializes the phase."""
self._name = name
self._part = part
self._description = description
self._completion = completion
@property
def name(self):
"""Name of the phase (`str`)."""
return self._name
@property
def part(self):
"""Part to which the phase belongs (`str`).
May be ``None`` if the phase does not belong to any part.
"""
return self._part
@property
def description(self):
"""Description of the phase (`str`)."""
return self._description
@property
def completion(self):
"""Completion (in percentages, ``0-100``)."""
return self._completion
def __eq__(self, other):
return (self.__class__ == other.__class__ and
self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self == other
def __repr__(self):
return '{}(name={!r}, part={!r}, description={!r}, completion={})'.format(
__name__ + '.' + self.__class__.__name__,
self.name,
self.part,
self.description,
self.completion
)
| #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <[email protected]> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Phase of a decompilation."""
class DecompilationPhase:
"""Phase of a decompilation."""
def __init__(self, name, part, description, completion):
"""Initializes a phase."""
self._name = name
self._part = part
self._description = description
self._completion = completion
@property
def name(self):
"""Name of the phase (`str`)."""
return self._name
@property
def part(self):
"""Part to which the phase belongs (`str`).
May be ``None`` if the phase does not belong to any part.
"""
return self._part
@property
def description(self):
"""Description of the phase (`str`)."""
return self._description
@property
def completion(self):
"""Completion (in percentages, ``0-100``)."""
return self._completion
def __eq__(self, other):
return (self.__class__ == other.__class__ and
self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self == other
def __repr__(self):
return '{}(name={!r}, part={!r}, description={!r}, completion={})'.format(
__name__ + '.' + self.__class__.__name__,
self.name,
self.part,
self.description,
self.completion
)
|
Increase timeout of clean_duplicate_nodes job | import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
timeout=3600,
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
| import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
|
Use related_name etc to avoid code
Signed-off-by: Chris Lamb <[email protected]> | from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from takeyourmeds.reminder.models import Reminder
class ReminderTimeField(serializers.RelatedField):
def to_representation(self, model):
return model.cronstring
class ReminderSerializer(serializers.ModelSerializer):
times = ReminderTimeField(many=True, read_only=True)
def create(self, data):
req = self.context['request']
data['user_id'] = req.user.pk
obj = super(ReminderSerializer, self).create(data)
for x in req.data.get('times', []):
obj.times.create(cronstring=x)
return obj
class Meta:
model = Reminder
fields = (
'times',
'message',
'audiourl',
'telnumber',
)
class ReminderViewSet(viewsets.ModelViewSet):
queryset = Reminder.objects.all()
serializer_class = ReminderSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
return Reminder.objects.filter(user=self.request.user)
@api_view(('POST',))
def trigger_now(request):
# FIXME: Move parameter to urlconf
pk = request.data.get('id')
reminder = Reminder.objects.get(pk=pk)
reminder.dispatch_task()
return Response({'message': "Triggered"})
| from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from takeyourmeds.reminder.models import Reminder, ReminderTime
class ReminderTimeField(serializers.RelatedField):
def to_representation(self, model):
return model.cronstring
class ReminderSerializer(serializers.ModelSerializer):
times = ReminderTimeField(many=True, read_only=True)
def create(self, data):
req = self.context['request']
data['user_id'] = req.user.pk
obj = super(ReminderSerializer, self).create(data)
for time in req.data.get('times', []):
ReminderTime.objects.create(
reminder=obj,
cronstring=time,
)
return obj
class Meta:
model = Reminder
fields = (
'times',
'message',
'audiourl',
'telnumber',
)
class ReminderViewSet(viewsets.ModelViewSet):
queryset = Reminder.objects.all()
serializer_class = ReminderSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
return Reminder.objects.filter(user=self.request.user)
@api_view(('POST',))
def trigger_now(request):
# FIXME: Move parameter to urlconf
pk = request.data.get('id')
reminder = Reminder.objects.get(pk=pk)
reminder.dispatch_task()
return Response({'message': "Triggered"})
|
Fix syntax error which causes redeclaration of a variable. | 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
{ environment: 'development' },
{ environment: 'integration' },
{ environment: 'production' },
{ environment: 'test' }
];
testCases.forEach(function (testCase) {
it('should successfully load the specified configuration: ' + testCase.environment, function () {
expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined;
});
});
});
describe('not existing configuration', function () {
it('should throw an error if the specified configuration does not exist', function () {
var environment = 'any not existing',
expectedErrorMessage = 'Config file for system environment not existing:' + environment,
getConfig = config.getConfig;
expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage);
});
});
});
});
| 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
{ environment: 'development' },
{ environment: 'integration' },
{ environment: 'production' },
{ environment: 'test' }
];
testCases.forEach(function (testCase) {
it('should successfully load the specified configuration: ' + testCase.environment, function () {
expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined;
});
});
});
describe('not existing configuration', function () {
it('should throw an error if the specified configuration does not exist', function () {
var environment = 'any not existing',
expectedErrorMessage = 'Config file for system environment not existing:', environment,
getConfig = config.getConfig;
expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage);
});
});
});
});
|
Add path in test to src | import unittest
import sys
sys.path.append('../src')
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
['piece'], ['of'], ['text']])
def test_bigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 2)
self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'],
['a', 'random'], ['random', 'piece'],
['piece', 'of'], ['of', 'text']])
def test_fourgrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 4)
self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'],
['is', 'a', 'random', 'piece'],
['a', 'random', 'piece', 'of'],
['random', 'piece', 'of', 'text']])
if __name__ == '__main__':
unittest.main()
| import unittest
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
['piece'], ['of'], ['text']])
def test_bigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 2)
self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'],
['a', 'random'], ['random', 'piece'],
['piece', 'of'], ['of', 'text']])
def test_fourgrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 4)
self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'],
['is', 'a', 'random', 'piece'],
['a', 'random', 'piece', 'of'],
['random', 'piece', 'of', 'text']])
if __name__ == '__main__':
unittest.main()
|
Fix values sent to CloudWatch for requests and allocations. Check that CloudWatch is available and change timer to 50 seconds. | var async = require('async');
var context;
var publishTimer;
function publishToDashboard() {
async.waterfall([
function(callback) {
context.consuler.getKeyValue(context.keys.request, function(result) {
callback(null, result);
});
},
function(requests, callback) {
context.consuler.getKeyValue(context.keys.allocation, function(result) {
callback(null, requests, result);
});
},
function(requests, allocations, callback) {
var timestamp = new Date();
context.AwsHandler.publishMultiple([
{
MetricName: context.strings.requestCount,
Dimensions: [],
Timestamp: timestamp,
Unit: "Count",
Value: requests.length - 1
},
{
MetricName: context.strings.allocationCount,
Dimensions: [],
Timestamp: timestamp,
Unit: "Count",
Value: allocations.length - 1
}
]);
}
], function (err, results) {});
}
module.exports = function (c) {
if (context.config.aws && context.config.aws.cloudwatch) {
context = c;
publishTimer = setInterval(publishToDashboard, 50000);
}
}
| var async = require('async');
var context;
var publishTimer;
function publishToDashboard() {
async.waterfall([
function(callback) {
context.consuler.getKeyValue(context.keys.request, function(result) {
callback(null, result);
});
},
function(requests, callback) {
context.consuler.getKeyValue(context.keys.allocation, function(result) {
callback(null, requests, result);
});
},
function(requests, allocations, callback) {
var timestamp = new Date();
context.AwsHandler.publishMultiple([
{
MetricName: context.strings.requestCount,
Dimensions: [],
Timestamp: timestamp,
Unit: "Count",
Value: requests
},
{
MetricName: context.strings.allocationCount,
Dimensions: [],
Timestamp: timestamp,
Unit: "Count",
Value: allocations
}
]);
}
], function (err, results) {});
}
module.exports = function (c) {
context = c;
publishTimer = setInterval(publishToDashboard, 60000);
}
|
Make sure we're checking ints to ints. | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.loads(message)
for attacker in kill['attackers']:
if int(attacker['corporationID']) in self.bot.kill_corps:
break
else:
if int(kill['victim']['corporationID']) not in self.bot.kill_corps:
return
print message
body, html = self.bot.call_command('kill', [], None, no_url=False, raw=kill)
text = 'New Kill: {}'.format(body)
for room in self.bot.rooms:
self.bot.send_message(room, text, mtype='groupchat')
def connect(self, url):
url = urlparse.urlparse(url)
self.conn = stomp.Connection([(url.hostname, url.port)])
self.conn.set_listener('', self)
self.conn.start()
self.conn.connect('guest', 'guest')
self.conn.subscribe(destination='/topic/kills', ack='auto', id=1) | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.loads(message)
for attacker in kill['attackers']:
if int(attacker['corporationID']) in self.bot.kill_corps:
break
else:
if kill['victim']['corporationID'] not in self.bot.kill_corps:
return
print message
body, html = self.bot.call_command('kill', [], None, no_url=False, raw=kill)
text = 'New Kill: {}'.format(body)
for room in self.bot.rooms:
self.bot.send_message(room, text, mtype='groupchat')
def connect(self, url):
url = urlparse.urlparse(url)
self.conn = stomp.Connection([(url.hostname, url.port)])
self.conn.set_listener('', self)
self.conn.start()
self.conn.connect('guest', 'guest')
self.conn.subscribe(destination='/topic/kills', ack='auto', id=1) |
Add a test for the multi-location Rsync::fromPath. | <?php
use AspectMock\Test as test;
use Robo\Robo;
class RsyncTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $guy;
// tests
public function testRsync()
{
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/')
->toHost('localhost')
->toUser('dev')
->toPath('/var/www/html/app/')
->recursive()
->excludeVcs()
->checksum()
->wholeFile()
->verbose()
->progress()
->humanReadable()
->stats()
->getCommand()
)->equals(
'rsync --recursive --exclude .git --exclude .svn --exclude .hg --checksum --whole-file --verbose --progress --human-readable --stats src/ \'dev@localhost:/var/www/html/app/\''
);
// From the folder 'foo bar' (with space) in 'src' directory
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/foo bar/baz')
->toHost('localhost')
->toUser('dev')
->toPath('/var/path/with/a space')
->getCommand()
)->equals(
'rsync \'src/foo bar/baz\' \'dev@localhost:/var/path/with/a space\''
);
// Copy two folders, 'src/foo' and 'src/bar'
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath(['src/foo', 'src/bar'])
->toHost('localhost')
->toUser('dev')
->toPath('/var/path/with/a space')
->getCommand()
)->equals(
'rsync src/foo src/bar \'dev@localhost:/var/path/with/a space\''
);
}
}
| <?php
use AspectMock\Test as test;
use Robo\Robo;
class RsyncTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $guy;
// tests
public function testRsync()
{
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/')
->toHost('localhost')
->toUser('dev')
->toPath('/var/www/html/app/')
->recursive()
->excludeVcs()
->checksum()
->wholeFile()
->verbose()
->progress()
->humanReadable()
->stats()
->getCommand()
)->equals(
'rsync --recursive --exclude .git --exclude .svn --exclude .hg --checksum --whole-file --verbose --progress --human-readable --stats src/ \'dev@localhost:/var/www/html/app/\''
);
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/foo bar/baz')
->toHost('localhost')
->toUser('dev')
->toPath('/var/path/with/a space')
->getCommand()
)->equals(
'rsync \'src/foo bar/baz\' \'dev@localhost:/var/path/with/a space\''
);
}
}
|
Support seminars in addition to lectures and labs | from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
| from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
|
Fix "AppRegistryNotReady: Models aren't loaded yet" | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
import django
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'django.db.backends.postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'django.db.backends.sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASES=dict(default=dict(ENGINE=db_engine, NAME=db_name)),
INSTALLED_APPS = [
'django.contrib.contenttypes',
'genericm2m',
'genericm2m.genericm2m_tests',
],
MIDDLEWARE_CLASSES = (),
)
from django.test.utils import get_runner
django.setup()
def runtests(*test_args):
if not test_args:
if sys.version_info[0] > 2:
test_args = ['genericm2m.genericm2m_tests']
else:
test_args = ["genericm2m_tests"]
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import sys
from os.path import dirname, abspath
import django
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'django.db.backends.postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'django.db.backends.sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASES=dict(default=dict(ENGINE=db_engine, NAME=db_name)),
INSTALLED_APPS = [
'django.contrib.contenttypes',
'genericm2m',
'genericm2m.genericm2m_tests',
],
)
from django.test.utils import get_runner
def runtests(*test_args):
if not test_args:
if sys.version_info[0] > 2:
test_args = ['genericm2m.genericm2m_tests']
else:
test_args = ["genericm2m_tests"]
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Add unique identifier in front of the label | 'use strict';
// convert an experiment, an array of spectra, to a chart
var types=require('./types.js');
module.exports=function (experiments, channels, index) {
var channels = channels || 'RGBWZE'
if (! Array.isArray(experiments)) experiments=[experiments];
var chart = {
type: "chart",
value: {
title: "Open Spectrophotometer results",
"axis": [
{
"label": "nM"
},
{
"label": "Y axis"
}
],
"data": []
}
}
var counter=0;
for (var i = 0; i < experiments.length; i++) {
if ((index === undefined) || (index === i)) {
var experiment=experiments[i];
for (var key in experiment) {
if (channels.indexOf(key)>-1) {
var data=experiment[key];
chart.value.data.push({
"x":data.x,
"y":data.y,
"label":(++counter)+". "+types[key].label+": "+data.name,
xAxis: 0,
yAxis: 1,
lineWidth: 2,
color: 'red'
});
}
}
}
}
return chart;
}
| 'use strict';
// convert an experiment, an array of spectra, to a chart
var types=require('./types.js');
module.exports=function (experiments, channels, index) {
var channels = channels || 'RGBWZE'
if (! Array.isArray(experiments)) experiments=[experiments];
var chart = {
type: "chart",
value: {
title: "Open Spectrophotometer results",
"axis": [
{
"label": "nM"
},
{
"label": "Y axis"
}
],
"data": []
}
}
for (var i = 0; i < experiments.length; i++) {
if ((index === undefined) || (index === i)) {
var experiment=experiments[i];
for (var key in experiment) {
if (channels.indexOf(key)>-1) {
var data=experiment[key];
chart.value.data.push({
"x":data.x,
"y":data.y,
"label":types[key].label+": "+data.name,
xAxis: 0,
yAxis: 1,
lineWidth: 2,
color: 'red'
});
}
}
}
}
return chart;
}
|
Add registration of world + protection cmds
Signed-off-by: Ollie <[email protected]> | package com.volumetricpixels.vitals.main;
import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;
import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.commands.ProtectionCommands;
import com.volumetricpixels.vitals.main.commands.WorldCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;
public class Vitals extends CommonPlugin {
private VitalsConfiguration config;
@Override
public void onDisable() {
getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
}
@Override
public void onEnable() {
config = new VitalsConfiguration(getDataFolder());
// Register commands.
AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);
getEngine().getRootCommand().addSubCommands(this, ProtectionCommands.class, commandRegistration);
getEngine().getRootCommand().addSubCommands(this, WorldCommands.class, commandRegistration);
getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
}
public VitalsConfiguration getConfig() {
return config;
}
} | package com.volumetricpixels.vitals.main;
import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;
import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;
public class Vitals extends CommonPlugin {
private VitalsConfiguration config;
@Override
public void onDisable() {
getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
}
@Override
public void onEnable() {
config = new VitalsConfiguration(getDataFolder());
// Register commands.
AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);
getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
}
public VitalsConfiguration getConfig() {
return config;
}
} |
Fix URLs in footer for children pages | import React, {Component, PropTypes} from "react"
import SVGIcon from "../SVGIcon"
import requireRaw from "../requireRaw"
export default class Footer extends Component {
static contextTypes = {
file: PropTypes.object.isRequired,
}
static defaultProps = {
playground: true,
}
static propTypes = {
playground: PropTypes.bool,
}
render() {
return (
<footer className="cssnext-Footer">
<p>
<SVGIcon
svg={requireRaw("./src/assets/cssnext.svg")}
className="cssnext-Header-logo-img"
style={{
height: "1rem",
verticalAlign: "middle",
}}
/>
{" is brought to you by "}
<a href="https://twitter.com/MoOx">@MoOx</a>
{" & "}
<a href="https://github.com/cssnext/cssnext/graphs/contributors">
some other contributors
</a>.
</p>
<small>
<a href="/it-s-cssnext-not-CSSNext">
{"Note: it's cssnext, not CSSNext"}
</a>
<span style={{
opacity: ".4",
marginLeft: "1rem",
}}>
<a href="/credits">
Credits
</a>
{" | "}
<a href={
"https://github.com/cssnext/cssnext/edit/master/" +
"docs/content/" + this.context.file.filename
}>
Edit this page
</a>
</span>
</small>
</footer>
)
}
}
| import React, {Component, PropTypes} from "react"
import SVGIcon from "../SVGIcon"
import requireRaw from "../requireRaw"
export default class Footer extends Component {
static contextTypes = {
file: PropTypes.object.isRequired,
}
static defaultProps = {
plagryound: true,
}
static propTypes = {
plagyround: PropTypes.bool,
}
render() {
return (
<footer className="cssnext-Footer">
<p>
<SVGIcon
svg={requireRaw("./src/assets/cssnext.svg")}
className="cssnext-Header-logo-img"
style={{
height: "1rem",
verticalAlign: "middle",
}}
/>
{" is brought to you by "}
<a href="https://twitter.com/MoOx">@MoOx</a>
{" & "}
<a href="https://github.com/cssnext/cssnext/graphs/contributors">
some other contributors
</a>.
</p>
<small>
<a href="it-s-cssnext-not-CSSNext">
{"Note: it's cssnext, not CSSNext"}
</a>
<span style={{
opacity: ".4",
marginLeft: "1rem",
}}>
<a href="credits">
Credits
</a>
{" | "}
<a href={
"https://github.com/cssnext/cssnext/edit/master/" +
"docs/content/" + this.context.file.filename
}>
Edit this page
</a>
</span>
</small>
</footer>
)
}
}
|
Fix units on wallet info screen | 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
| 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset.asset, walletService.walletUnit)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
|
Change the behaviour of the markdown text processor so it follows better whitespace boundary rules | <?php
namespace App\Helpers\BBCode\Processors;
class MarkdownTextProcessor extends Processor {
function Process($result, $text, $scope) {
/*
* Like everything else here, this isn't exactly markdown, but it's close.
* _underline_
* /italics/
* *bold*
* ~strikethrough~
* `code`
* Very simple rules: no nesting, no newlines, must start/end on a word boundary
*/
$pre = '%(?<=^|[\p{P}\s])';
$mid = '([^<>\r\n]*?)';
$post = '(?=[\p{P}\s]|$)%imu';
// Bold
$text = preg_replace("{$pre}\*{$mid}\*{$post}", '<strong>$1</strong>', $text);
// Italics
$text = preg_replace("{$pre}/{$mid}/{$post}", '<em>$1</em>', $text);
// Underline
$text = preg_replace("{$pre}_{$mid}_{$post}", '<span class="underline">$1</span>', $text);
// Strikethrough
$text = preg_replace("{$pre}-{$mid}-{$post}", '<span class="strikethrough">$1</span>', $text);
// Code
$text = preg_replace("{$pre}`{$mid}`{$post}", '<code>$1</code>', $text);
return $text;
}
}
| <?php
namespace App\Helpers\BBCode\Processors;
class MarkdownTextProcessor extends Processor {
function Process($result, $text, $scope) {
/*
* Like everything else here, this isn't exactly markdown, but it's close.
* _underline_
* /italics/
* *bold*
* ~strikethrough~
* `code`
* Very simple rules: no nesting, no newlines, must start/end on a word boundary
*/
// Bold
$text = preg_replace('/\*([.,;\'"]*?\b[^<>\r\n]*?\b[.,;\'"]*?)\*/si', '<strong>$1</strong>', $text);
// Italics
$text = preg_replace('%/([.,;\'"]*?\b[^<>\r\n]*?\b[.,;\'"]*?)/%si', '<em>$1</em>', $text);
// Underline
$text = preg_replace('/\b_([^<>\r\n]*?)_\b/si', '<span class="underline">$1</span>', $text);
// Strikethrough
$text = preg_replace('/~([.,;\'"]*?\b[^<>\r\n]*?\b[.,;\'"]*?)~/si', '<span class="strikethrough">$1</span>', $text);
// Code
$text = preg_replace('/`([.,;\'"]*?\b[^<>]*?\b[.,;\'"]*?)`/si', '<code>$1</code>', $text);
return $text;
}
}
|
Fix an issue that caused unnecessary code to end up in the transpiled file. | var clone= require('clone');
var paths = require('./build/paths');
var webpackConfig = clone(require('./webpack.config.js'));
// Add istanbul-instrumenter to webpack configuration
webpackConfig.module.loaders.push(
{
test: /\.js$/,
exclude: /(node_modules|test)/,
loader: 'babel-istanbul-loader'
}
);
webpackConfig.output.filename += '.test';
webpackConfig.plugins = [];
webpackConfig.externals = [];
// The main configuration
module.exports = function(config) {
config.set({
frameworks: [
'jasmine-jquery',
'jasmine-ajax',
'jasmine'
],
files: [
'test/*.spec.js',
],
preprocessors: {
'test/*.spec.js': [
'webpack'
],
},
coverageReporter: {
reporters: [
{ type: 'cobertura', dir: paths.coverageDir, subdir: '.', file: 'coverage.xml' },
{ type: 'html', dir: paths.coverageDir, subdir: 'html' },
{ type: 'text' }
]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
reporters: ['spec', 'coverage'],
browsers: ['Chrome', 'Firefox'],
});
}
| var paths = require('./build/paths');
var webpackConfig = require('./webpack.config.js');
// Add istanbul-instrumenter to webpack configuration
webpackConfig.module.loaders.push(
{
test: /\.js$/,
exclude: /(node_modules|test)/,
loader: 'babel-istanbul-loader'
}
);
// The main configuration
var configuration = function(config) {
config.set({
frameworks: [
'jasmine-jquery',
'jasmine-ajax',
'jasmine'
],
files: [
'test/*.spec.js',
],
preprocessors: {
'test/*.spec.js': [
'webpack'
],
},
coverageReporter: {
reporters: [
{ type: 'cobertura', dir: paths.coverageDir, subdir: '.', file: 'coverage.xml' },
{ type: 'html', dir: paths.coverageDir, subdir: 'html' },
{ type: 'text' }
]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
reporters: ['spec', 'coverage'],
browsers: ['Chrome', 'Firefox'],
});
}
module.exports = configuration;
|
Rename a variable in TrackingTreeNodeDecocator | package hu.webarticum.treeprinter.decorator;
import hu.webarticum.treeprinter.TreeNode;
public class TrackingTreeNodeDecorator extends AbstractTreeNodeDecorator {
public final TrackingTreeNodeDecorator parent;
public final int index;
public TrackingTreeNodeDecorator(TreeNode baseNode) {
this(baseNode, null, 0);
}
public TrackingTreeNodeDecorator(TreeNode baseNode, TrackingTreeNodeDecorator parent, int index) {
super(baseNode);
this.parent = parent;
this.index = index;
}
@Override
public String content() {
return decoratedNode.content();
}
@Override
protected TreeNode decorateChild(TreeNode childNode, int index) {
return new TrackingTreeNodeDecorator(childNode, this, index);
}
@Override
public boolean isDecorable() {
return false;
}
@Override
public int hashCode() {
int parentHashCode = parent != null ? parent.hashCode(): 0;
return (parentHashCode * 37) + index;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof TrackingTreeNodeDecorator)) {
return false;
}
TrackingTreeNodeDecorator otherTrackingTreeNodeDecorator = (TrackingTreeNodeDecorator) other;
TrackingTreeNodeDecorator otherParent = otherTrackingTreeNodeDecorator.parent;
if (this == otherTrackingTreeNodeDecorator) {
return true;
} else if (parent == null) {
if (otherParent != null) {
return false;
}
} else if (otherParent == null || !parent.equals(otherParent)) {
return false;
}
return index == otherTrackingTreeNodeDecorator.index;
}
}
| package hu.webarticum.treeprinter.decorator;
import hu.webarticum.treeprinter.TreeNode;
public class TrackingTreeNodeDecorator extends AbstractTreeNodeDecorator {
public final TrackingTreeNodeDecorator parent;
public final int index;
public TrackingTreeNodeDecorator(TreeNode baseNode) {
this(baseNode, null, 0);
}
public TrackingTreeNodeDecorator(TreeNode baseNode, TrackingTreeNodeDecorator parent, int index) {
super(baseNode);
this.parent = parent;
this.index = index;
}
@Override
public String content() {
return decoratedNode.content();
}
@Override
protected TreeNode decorateChild(TreeNode childNode, int index) {
return new TrackingTreeNodeDecorator(childNode, this, index);
}
@Override
public boolean isDecorable() {
return false;
}
@Override
public int hashCode() {
int parentHashCode = parent != null ? parent.hashCode(): 0;
return (parentHashCode * 37) + index;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof TrackingTreeNodeDecorator)) {
return false;
}
TrackingTreeNodeDecorator otherReferenceTreeNode = (TrackingTreeNodeDecorator) other;
TrackingTreeNodeDecorator otherParent = otherReferenceTreeNode.parent;
if (this == otherReferenceTreeNode) {
return true;
} else if (parent == null) {
if (otherParent != null) {
return false;
}
} else if (otherParent == null || !parent.equals(otherParent)) {
return false;
}
return index == otherReferenceTreeNode.index;
}
}
|
Add some comments in dockerfile | 'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/easydownload-dev'
},
itemCron: '*/5 * * * * *',
thingCron: '*/10 * * * * *',
esCron: '*/20 * * * * *',
elasticSearch: {
host: 'misscatandzuozuo.info:19200',
index: 'mongoindex',
type: 'thing',
loglevel: 'warning',
scanLimit : 30,
"ikAugAnalyzer": {
"analysis": {
"analyzer": {
"ik_aug": {
"type": "custom"
, "tokenizer" : "ik"
, "use_smart" : true
}
}
}
},
mapping: {
"thing": {
"_all": {
"indexAnalyzer": "ik_aug",
"searchAnalyzer": "ik_aug",
"term_vector": "no",
"store": "false"
},
"properties": {
"title": {
"type": "string",
"store": "no",
"term_vector": "with_positions_offsets",
"indexAnalyzer": "ik_aug",
"searchAnalyzer": "ik_aug",
"include_in_all": "true",
"boost": 8
}
}
}
}
},
seedDB: true
};
| 'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/easydownload-dev'
},
itemCron: '*/5 * * * * *',
thingCron: '*/10 * * * * *',
esCron: '*/20 * * * * *',
elasticSearch: {
host: 'localhost:9200',
index: 'mongoindex',
type: 'thing',
loglevel: 'warning',
scanLimit : 30,
"ikAugAnalyzer": {
"analysis": {
"analyzer": {
"ik_aug": {
"type": "custom"
, "tokenizer" : "ik"
, "use_smart" : true
}
}
}
},
mapping: {
"thing": {
"_all": {
"indexAnalyzer": "ik_aug",
"searchAnalyzer": "ik_aug",
"term_vector": "no",
"store": "false"
},
"properties": {
"title": {
"type": "string",
"store": "no",
"term_vector": "with_positions_offsets",
"indexAnalyzer": "ik_aug",
"searchAnalyzer": "ik_aug",
"include_in_all": "true",
"boost": 8
}
}
}
}
},
seedDB: true
};
|
Integrate improvement by JProffitt71 to properly support Jade view extend/include | define(['./module', '_'], function (views, _) {
'use strict';
var templates = {};
var jade = require('jade'),
fs = require('fs'),
path = require('path');
fs.readdir(path.resolve('./views'), function(err, files) {
console.log("Found %d files", files.length);
_.each(files, function(f) {
templates[f.substring(0, f.length - 5)] = {
tmplfile:fs.readFileSync(path.resolve('./views', f)),
tmplpath: path.resolve('./views', f),
compiled:false
};
});
});
views.provider('view', function() {
this.renderView = function(name, context, options) {
return function(params, path) {
var tmpl = templates[name];
if(!tmpl.compiled) {
console.log("View %s isn't compiled, compiling it now", name);
tmpl.tmpl = jade.compile(tmpl.tmplfile, {'filename': tmpl.tmplpath});
tmpl.compiled = true;
}
return tmpl.tmpl(_.extend(context || {}, {
params:params,
path:path
}));
};
};
function ViewRenderer() {
}
this.$get = function() {
return new ViewRenderer();
};
});
});
| define(['./module', '_'], function (views, _) {
'use strict';
var templates = {};
var jade = require('jade'),
fs = require('fs'),
path = require('path');
fs.readdir(path.resolve('./views'), function(err, files) {
console.log("Found %d files", files.length);
_.each(files, function(f) {
templates[f.substring(0, f.length - 5)] = {
tmplfile:fs.readFileSync(path.resolve('./views', f)),
compiled:false
};
});
});
views.provider('view', function() {
this.renderView = function(name, context, options) {
return function(params, path) {
var tmpl = templates[name];
if(!tmpl.compiled) {
console.log("View %s isn't compiled, compiling it now", name);
tmpl.tmpl = jade.compile(tmpl.tmplfile);
tmpl.compiled = true;
}
return tmpl.tmpl(_.extend(context || {}, {
params:params,
path:path
}));
};
};
function ViewRenderer() {
}
this.$get = function() {
return new ViewRenderer();
};
});
});
|
Use addProvider method instead of constructor | <?php
namespace DisposableEmailChecker\Tests;
use DisposableEmailChecker\Checker;
use DisposableEmailChecker\Provider\ChainProvider;
use DisposableEmailChecker\Provider\InMemoryProvider;
class CheckerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider validResults
*/
public function testCheckWithDefaultProvider($email, $expected)
{
$checker = new Checker();
$this->assertEquals($expected, $checker->check($email));
}
/**
* @dataProvider validResults
*/
public function testCheckWithChainProvider($email, $expected)
{
$provider = new ChainProvider();
$provider->addProvider(new InMemoryProvider());
$checker = new Checker($provider);
$this->assertEquals($expected, $checker->check($email));
}
public function testCheckWithInMemoryProviderAndCustomDomain()
{
$provider = new InMemoryProvider();
$provider->addDomain('mycompany.com');
$checker = new Checker($provider);
$this->assertTrue($checker->check('[email protected]'));
}
public function validResults()
{
return array(
array('[email protected]', true),
array('[email protected]', false),
array('[email protected]', true),
array('[email protected]', false),
array('[email protected]', false),
);
}
/**
* @expectedException \DisposableEmailChecker\Exception\InvalidEmailException
*/
public function testCheckWithInvalidEmail()
{
$checker = new Checker();
$checker->check('invalid email');
}
}
| <?php
namespace DisposableEmailChecker\Tests;
use DisposableEmailChecker\Checker;
use DisposableEmailChecker\Provider\ChainProvider;
use DisposableEmailChecker\Provider\InMemoryProvider;
class CheckerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider validResults
*/
public function testCheckWithDefaultProvider($email, $expected)
{
$checker = new Checker();
$this->assertEquals($expected, $checker->check($email));
}
/**
* @dataProvider validResults
*/
public function testCheckWithChainProvider($email, $expected)
{
$provider = new ChainProvider(array(
new InMemoryProvider()
));
$checker = new Checker($provider);
$this->assertEquals($expected, $checker->check($email));
}
public function testCheckWithInMemoryProviderAndCustomDomain()
{
$provider = new InMemoryProvider();
$provider->addDomain('mycompany.com');
$checker = new Checker($provider);
$this->assertTrue($checker->check('[email protected]'));
}
public function validResults()
{
return array(
array('[email protected]', true),
array('[email protected]', false),
array('[email protected]', true),
array('[email protected]', false),
array('[email protected]', false),
);
}
/**
* @expectedException \DisposableEmailChecker\Exception\InvalidEmailException
*/
public function testCheckWithInvalidEmail()
{
$checker = new Checker();
$checker->check('invalid email');
}
}
|
Fix old media from not being removed | <?php namespace Torann\MediaSort\Disks;
use File;
use Config;
use Storage;
use Exception;
abstract class AbstractDisk {
/**
* The current media object being processed.
*
* @var \Torann\MediaSort\Manager
*/
public $media;
/**
* Storage configurations.
*
* @var array
*/
public $config;
/**
* Constructor method
*
* @param \Torann\MediaSort\Manager $media
*/
function __construct($media)
{
$this->media = $media;
$this->config = Config::get('filesystems.disks.' . $this->media->disk);
}
/**
* Remove an attached file.
*
* @param array $files
*/
public function remove($files)
{
foreach ($files as $file)
{
try {
Storage::delete($file);
}
// Ignore not found exceptions
catch (Exception $e) {}
}
}
/**
* Move an uploaded file to it's intended target.
*
* @param string $source
* @param string $target
* @return void
*/
public function move($source, $target)
{
// Save file
Storage::put(
$target,
File::get($source),
$this->media->visibility
);
}
} | <?php namespace Torann\MediaSort\Disks;
use File;
use Config;
use Storage;
use Exception;
abstract class AbstractDisk {
/**
* The current media object being processed.
*
* @var \Torann\MediaSort\Manager
*/
public $media;
/**
* Storage configurations.
*
* @var array
*/
public $config;
/**
* Constructor method
*
* @param \Torann\MediaSort\Manager $media
*/
function __construct($media)
{
$this->media = $media;
$this->config = Config::get('filesystems.disks.' . $this->media->disk);
}
/**
* Remove an attached file.
*
* @param array $files
*/
public function remove($files)
{
foreach ($files as $file)
{
try {
Storage::deleteDirectory($file);
}
// Ignore not found exceptions
catch (Exception $e) {}
}
}
/**
* Move an uploaded file to it's intended target.
*
* @param string $source
* @param string $target
* @return void
*/
public function move($source, $target)
{
// Save file
Storage::put(
$target,
File::get($source),
$this->media->visibility
);
}
} |
Clear the status only when the timeout is valid | 'use strict';
import { StatsCollector } from './lib/stats';
export default function(RED) {
class DeviceStatsNode {
constructor(n) {
RED.nodes.createNode(this, n);
this.name = n.name;
this.mem = n.mem;
this.nw = n.nw;
this.load = n.load;
this.hostname = n.hostname;
this.useString = n.useString;
this.collector = new StatsCollector(this);
this.status({});
this.on('input', msg => {
clearTimeout(this.timeout);
delete this.timeout;
this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' });
let opts = msg ? msg.payload : null;
this.collector.collect(opts).then(stats => {
if (this.useString || opts && opts.useString) {
stats = JSON.stringify(stats);
}
this.send({ payload: stats });
this.timeout = setTimeout(() => {
if (this.timeout) {
this.status({});
}
}, 750);
}).catch(err => {
RED.log.warn(RED._('device-stats.errors.unknown', { error: err }));
this.status({});
});
});
}
}
RED.nodes.registerType('DeviceStats', DeviceStatsNode);
}
| 'use strict';
import { StatsCollector } from './lib/stats';
export default function(RED) {
class DeviceStatsNode {
constructor(n) {
RED.nodes.createNode(this, n);
this.name = n.name;
this.mem = n.mem;
this.nw = n.nw;
this.load = n.load;
this.hostname = n.hostname;
this.useString = n.useString;
this.collector = new StatsCollector(this);
this.status({});
this.on('input', msg => {
clearTimeout(this.timeout);
this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' });
let opts = msg ? msg.payload : null;
this.collector.collect(opts).then(stats => {
if (this.useString || opts && opts.useString) {
stats = JSON.stringify(stats);
}
this.send({ payload: stats });
this.timeout = setTimeout(() => {
this.status({});
}, 750);
}).catch(err => {
RED.log.warn(RED._('device-stats.errors.unknown', { error: err }));
this.status({});
});
});
}
}
RED.nodes.registerType('DeviceStats', DeviceStatsNode);
}
|
Convert rows to list in EVL CEG parser
It needs to access cells directly | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
rows = list(rows)
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
| from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"agent_automated_dupes", "calls_answered_by_advisor"
]
def ceg_rows(rows):
for column in itertools.count(3):
date = ceg_date(rows, column)
if not isinstance(date, datetime):
return
if date >= d_tz(2012, 4, 1):
yield [
date, "month", rows[5][column], rows[6][column],
rows[9][column], rows[11][column], rows[12][column],
rows[13][column], rows[15][column], rows[17][column]
]
def ceg_date(rows, column):
try:
return rows[3][column]
except IndexError:
return None
yield ceg_keys(rows)
for row in ceg_rows(rows):
yield row
|
Allow web command to be used with a non-existent environment | <?php
namespace Platformsh\Cli\Command;
use Platformsh\Cli\Service\Url;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class WebCommand extends CommandBase
{
protected function configure()
{
$this
->setName('web')
->setDescription('Open the Web UI');
Url::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Attempt to select the appropriate project and environment.
try {
$this->validateInput($input);
$environmentId = $this->getSelectedEnvironment()->id;
} catch (\Exception $e) {
// If a project has been specified but is not found, then error out.
if ($input->getOption('project') && !$this->hasSelectedProject()) {
throw $e;
}
// If an environment ID has been specified but not found, then use
// the specified ID anyway. This allows building a URL when an
// environment doesn't yet exist.
$environmentId = $input->getOption('environment');
}
if ($this->hasSelectedProject()) {
$url = $this->getSelectedProject()->getLink('#ui');
if (!empty($environmentId)) {
$url .= '/environments/' . rawurlencode($environmentId);
}
} else {
$url = $this->config()->get('service.accounts_url');
}
/** @var \Platformsh\Cli\Service\Url $urlService */
$urlService = $this->getService('url');
$urlService->openUrl($url);
}
}
| <?php
namespace Platformsh\Cli\Command;
use Platformsh\Cli\Service\Url;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class WebCommand extends CommandBase
{
protected function configure()
{
$this
->setName('web')
->setDescription('Open the Web UI');
Url::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Attempt to select the appropriate project and environment.
try {
$this->validateInput($input);
} catch (\Exception $e) {
// Ignore errors.
}
$url = $this->config()->get('service.accounts_url');
if ($this->hasSelectedProject()) {
$url = $this->getSelectedProject()->getLink('#ui');
if ($this->hasSelectedEnvironment()) {
$url .= '/environments/' . rawurlencode($this->getSelectedEnvironment()->id);
}
}
/** @var \Platformsh\Cli\Service\Url $urlService */
$urlService = $this->getService('url');
$urlService->openUrl($url);
}
}
|
Store created assert and reuse.
This makes it clearer when asserts need to be created and is more efficient. | define('parsley/factory/constraint', [
'parsley/utils'
], function (ParsleyUtils) {
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
var assert = {};
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
if ('function' === typeof window.ParsleyValidator.validators[name])
assert = window.ParsleyValidator.validators[name](requirements);
if ('Assert' !== assert.__parentClass__)
throw new Error('Valid validator expected');
var getPriority = function () {
if ('undefined' !== typeof parsleyField.options[name + 'Priority'])
return parsleyField.options[name + 'Priority'];
return ParsleyUtils.get(assert, 'priority') || 2;
};
priority = priority || getPriority();
// If validator have a requirementsTransformer, execute it
if ('function' === typeof assert.requirementsTransformer) {
requirements = assert.requirementsTransformer();
// rebuild assert with new requirements
assert = window.ParsleyValidator.validators[name](requirements);
}
return $.extend(assert, {
name: name,
requirements: requirements,
priority: priority,
groups: [priority],
isDomConstraint: isDomConstraint || ParsleyUtils.attr(parsleyField.$element, parsleyField.options.namespace, name)
});
};
return ConstraintFactory;
});
| define('parsley/factory/constraint', [
'parsley/utils'
], function (ParsleyUtils) {
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
if ('function' !== typeof window.ParsleyValidator.validators[name] ||
'Assert' !== window.ParsleyValidator.validators[name](requirements).__parentClass__)
throw new Error('Valid validator expected');
var getPriority = function () {
if ('undefined' !== typeof parsleyField.options[name + 'Priority'])
return parsleyField.options[name + 'Priority'];
return ParsleyUtils.get(window.ParsleyValidator.validators[name](requirements), 'priority') || 2;
};
priority = priority || getPriority();
// If validator have a requirementsTransformer, execute it
if ('function' === typeof window.ParsleyValidator.validators[name](requirements).requirementsTransformer)
requirements = window.ParsleyValidator.validators[name](requirements).requirementsTransformer();
return $.extend(window.ParsleyValidator.validators[name](requirements), {
name: name,
requirements: requirements,
priority: priority,
groups: [priority],
isDomConstraint: isDomConstraint || ParsleyUtils.attr(parsleyField.$element, parsleyField.options.namespace, name)
});
};
return ConstraintFactory;
});
|
Use function name with bind | define([
'jquery',
'underscore',
'backbone',
'app',
'text!templates/auth/signUpTemplate.html'
], function($, _, Backbone, app, signUpTemplate){
var SignUpView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
_.bindAll(this, 'onSignupAttempt', 'render');
// Listen for session logged_in state changes and re-render
app.session.on("change:logged_in", this.render);
},
events: {
'click #sign-up-btn' : 'onLoginAttempt'
},
onSignupAttempt: function(event) {
if(evt) evt.preventDefault();
if(this.$("#login-form").parsley('validate')) {
app.session.login({
username: this.$("#login-username-input").val(),
password: this.$("#login-password-input").val()
}, {
success: function(mod, res){
if(DEBUG) console.log("SUCCESS", mod, res);
},
error: function(err){
if(DEBUG) console.log("ERROR", err);
app.showAlert('Bummer dude!', err.error, 'alert-danger');
}
});
} else {
// Invalid clientside validations thru parsley
if(DEBUG) console.log("Did not pass clientside validation");
}
},
render: function() {
$('.menu a').removeClass('active');
this.$el.html(signUpTemplate);
}
});
return SignUpView;
});
| define([
'jquery',
'underscore',
'backbone',
'app',
'text!templates/auth/signUpTemplate.html'
], function($, _, Backbone, app, signUpTemplate){
var SignUpView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
_.bindAll(this);
// Listen for session logged_in state changes and re-render
app.session.on("change:logged_in", this.render);
},
events: {
'click #sign-up-btn' : 'onLoginAttempt'
},
onSignupAttempt: function(event) {
if(evt) evt.preventDefault();
if(this.$("#login-form").parsley('validate')) {
app.session.login({
username: this.$("#login-username-input").val(),
password: this.$("#login-password-input").val()
}, {
success: function(mod, res){
if(DEBUG) console.log("SUCCESS", mod, res);
},
error: function(err){
if(DEBUG) console.log("ERROR", err);
app.showAlert('Bummer dude!', err.error, 'alert-danger');
}
});
} else {
// Invalid clientside validations thru parsley
if(DEBUG) console.log("Did not pass clientside validation");
}
},
render: function() {
$('.menu a').removeClass('active');
this.$el.html(signUpTemplate);
}
});
return SignUpView;
});
|
Fix bug in serving partial css files | var task = function(gulp, config) {
'use strict';
gulp.task('browserSync', function() {
var path = require('path');
var fs = require('fs');
var browserSync = require('browser-sync').create();
var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');
browserSync.init({
server: {
// Serve both project root and dist to enable sourcemaps
baseDir: [process.cwd(), config.dist.root],
middleware: function (req, res, next) {
var location;
// Enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
// Rewrite html5 urls
var matches = html5Regex.exec(req.url);
//console.log('req', req.url);
var file = path.join(config.dist.root, req.url.split('?')[0]);
//console.log('file', file);
if (req.method === 'GET' && matches && !fs.existsSync(file)) {
console.log('no file -> hashbang!', file);
location = '/'+config.name+'/#!'+matches[1];
res.writeHead(302, {'Location': location});
res.end();
} else {
console.log('serve file', file);
next();
}
},
directory: config.dirListings || false
},
// Watch for updates in dist
files: [config.dist.root+'/**/*'],
// Disable input mirroring between connected browsers
ghostMode: false,
open: false
});
});
};
module.exports = task;
| var task = function(gulp, config) {
'use strict';
gulp.task('browserSync', function() {
var path = require('path');
var fs = require('fs');
var browserSync = require('browser-sync').create();
var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');
browserSync.init({
server: {
// Serve both project root and dist to enable sourcemaps
baseDir: [process.cwd(), config.dist.root],
middleware: function (req, res, next) {
var location;
// Enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
// Rewrite html5 urls
var matches = html5Regex.exec(req.url);
//console.log('req', req.url);
var file = path.join(config.dist.root, req.url);
//console.log('file', file);
if (req.method === 'GET' && matches && !fs.existsSync(file)) {
//console.log('no file -> hashbang!');
location = '/'+config.name+'/#!'+matches[1];
res.writeHead(302, {'Location': location});
res.end();
} else {
//console.log('serve file');
next();
}
},
directory: config.dirListings || false
},
// Watch for updates in dist
files: [config.dist.root+'/**/*'],
// Disable input mirroring between connected browsers
ghostMode: false,
open: false
});
});
};
module.exports = task;
|
Trim NID and make it uppercase & combine dummy email inline | <?php
namespace App\Services;
use App\Student;
use App\User;
use Carbon\Carbon;
class UserService
{
/**
* 尋找使用者,若找不到,則建立使用者並綁定
*
* @param Student $student
* @return User
*/
public function findOrCreateAndBind(Student $student)
{
$user = $student->user;
if (!$user) {
$user = $this->findOrCreateByNid($student->nid);
$user->student()->save($student);
}
return $user;
}
/**
* @param string $nid
* @return User
*/
public function findOrCreateByNid($nid)
{
$nid = trim(strtoupper($nid));
/** @var User $user */
$user = User::query()->firstOrCreate([
'nid' => $nid,
], [
'name' => $nid,
'email' => $nid . '@fcu.edu.tw',
'password' => '',
'confirm_at' => Carbon::now(),
'register_at' => Carbon::now(),
'register_ip' => request()->getClientIp(),
]);
return $user;
}
}
| <?php
namespace App\Services;
use App\Student;
use App\User;
use Carbon\Carbon;
class UserService
{
/**
* 尋找使用者,若找不到,則建立使用者並綁定
*
* @param Student $student
* @return User
*/
public function findOrCreateAndBind(Student $student)
{
$user = $student->user;
if (!$user) {
$user = $this->findOrCreateByNid($student->nid);
$user->student()->save($student);
}
return $user;
}
/**
* @param string $nid
* @return User
*/
public function findOrCreateByNid($nid)
{
$email = $nid . '@fcu.edu.tw';
/** @var User $user */
$user = User::query()->firstOrCreate([
'nid' => $nid,
], [
'name' => $nid,
'email' => $email,
'password' => '',
'confirm_at' => Carbon::now(),
'register_at' => Carbon::now(),
'register_ip' => request()->getClientIp(),
]);
return $user;
}
}
|
Fix custom widget to raise correct exception type. | """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise ConvertError("Invalid date")
elif not parts[1] and parts[2]:
raise ConvertError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise ConvertError("Invalid date")
return '-'.join(parts)
| """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise validation.FieldValidationError("Invalid date")
elif not parts[1] and parts[2]:
raise validation.FieldValidationError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise validation.FieldValidationError("Invalid date")
return '-'.join(parts)
|
Fix use of 'json' instead of 'j'
This bug was created when switching from simplejson to json module,
due to python 2.5->2.7 migration. Any variables named 'json' needed
to be renamed, and this is an instance that was missed. | import os
import models
import config
import time
from hashlib import md5
import json
import serverinfo
from google.appengine.ext import webapp
"""
{
"info": {
"name": "<name>",
"start_utc": <long>
},
"command": {
"command": "<command name>",
"<arg0 name>": "<arg0 value>",
"<arg1 name>": "<arg1 value>"
// etc
}
}
"""
class SendCommand(webapp.RequestHandler):
def post(self):
hash = self.request.body[:32]
j = self.request.body[32:]
m = md5(j + config.SENDCOMMAND_SECRET)
if m.hexdigest() == hash:
c = json.loads(j)
serverinfo.ServerInfo.send_command(c['info'],
json.dumps(c['command']))
if config.is_debug():
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('ok')
else:
if config.is_debug():
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('not ok')
| import os
import models
import config
import time
from hashlib import md5
import json
import serverinfo
from google.appengine.ext import webapp
"""
{
"info": {
"name": "<name>",
"start_utc": <long>
},
"command": {
"command": "<command name>",
"<arg0 name>": "<arg0 value>",
"<arg1 name>": "<arg1 value>"
// etc
}
}
"""
class SendCommand(webapp.RequestHandler):
def post(self):
hash = self.request.body[:32]
j = self.request.body[32:]
m = md5(json + config.SENDCOMMAND_SECRET)
if m.hexdigest() == hash:
c = json.loads(j)
serverinfo.ServerInfo.send_command(c['info'],
json.dumps(c['command']))
if config.is_debug():
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('ok')
else:
if config.is_debug():
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('not ok')
|
Add classifier type to the base class | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classification_type, classifier, key, default=None):
"""
Gets the value held by the classifier, key composite key.
If it doesn't exist, return default.
"""
raise NotImplementedError()
def get_key_list(self, classification_type, classifier, keys, default=None):
"""
Given a list of key, classifier pairs get all values.
If key, classifier doesn't exist, return default.
Subclasses can override this to make more efficient queries for bulk
requests.
"""
return [self.get_key(classification_type, classifier, key, default)
for classifier, key in izip(repeat(classifier), keys)]
def set_key_list(self, classification_type, classifier, key_value_pairs):
"""
Given a list of pairs of key, value and a classifier set them all.
Subclasses can override this to make more efficient queries for bulk
requests.
"""
return [self.set_key(classification_type, classifier, key, value)
for classifier, key, value
in izip(repeat(classifier), key_value_pairs)]
def set_key(self, classification_type, classifier, key, value):
"""
Set the value held by the classifier, key composite key.
"""
raise NotImplementedError()
| class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classifier, key, default=None):
"""
Gets the value held by the classifier, key composite key.
If it doesn't exist, return default.
"""
raise NotImplementedError()
def get_key_list(self, classifier, keys, default=None):
"""
Given a list of key, classifier pairs get all values.
If key, classifier doesn't exist, return default.
Subclasses can override this to make more efficient queries for bulk
requests.
"""
return [self.get_key(classifier, key, default)
for key in keys]
def set_key_list(self, classifier, key_value_pairs):
"""
Given a list of pairs of key, value and a classifier set them all.
Subclasses can override this to make more efficient queries for bulk
requests.
"""
return [self.set_key(classifier, key, value)
for key, value in key_value_pairs]
def set_key(self, classifier, key, value):
"""
Set the value held by the classifier, key composite key.
"""
raise NotImplementedError()
|
Add id to navigation bar and removed unnecessary spacer | Ext.define('SenchaFront.view.Main', {
extend: 'Ext.NavigationView',
xtype: 'main',
requires: [
'Ext.plugin.ListSwipeAction',
'Ext.dataview.List'
],
config: {
ui: 'sencha',
fullscreen: true,
id: 'navigationView',
items: [
{
title: 'Profiles',
xtype: 'list',
ui: 'sencha',
store: 'profiles',
itemTpl: '{name}',
scrollable: true,
id: 'profileList',
plugins: [
{
type: 'listswipeaction',
deleteButton: true,
ui: 'sencha',
syncDelete: true
}
]
}
],
navigationBar: {
ui: 'sencha',
id: 'navigationBar',
items: [
{
xtype: 'button',
id: 'addProfileButton',
iconCls: 'add'
}
]
}
}
});
| Ext.define('SenchaFront.view.Main', {
extend: 'Ext.NavigationView',
xtype: 'main',
requires: [
'Ext.plugin.ListSwipeAction',
'Ext.dataview.List'
],
config: {
ui: 'sencha',
fullscreen: true,
id: 'navigationView',
items: [
{
title: 'Profiles',
xtype: 'list',
ui: 'sencha',
store: 'profiles',
itemTpl: '{name}',
scrollable: true,
id: 'profileList',
plugins: [
{
type: 'listswipeaction',
deleteButton: true,
ui: 'sencha',
syncDelete: true
}
]
}
],
navigationBar: {
ui: 'sencha',
items: [
{
xtype: 'spacer'
},
{
xtype: 'button',
id: 'addProfileButton',
iconCls: 'add'
}
]
}
}
});
|
Use 'params' instead of 'parameters' | // ==UserScript==
// @name Slickdeals Don't Track Me!
// @version 1.1
// @description Replaces outgoing Slickdeals tracking links with direct links.
// @match http://slickdeals.net/f/*
// @namespace https://github.com/gg/slickdeals-dont-track-me
// @author Gregg Gajic <https://github.com/gg>
// @license MIT
// ==/UserScript==
(function() {
var getQueryStringParams = function (url) {
// See: http://stackoverflow.com/a/3855394
return (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})((url.split('?')[1] || '').split('&'));
};
var contentBody = document.getElementById('maincontent') || document.getElementById('posts');
var aElements = contentBody.getElementsByTagName('a');
for (var i = 0, a; a = aElements[i]; i++) {
var queryParams = getQueryStringParams(a.href);
var directUrl = queryParams['u2'];
if (directUrl) {
a.href = directUrl;
a.onclick = '';
};
}
})();
| // ==UserScript==
// @name Slickdeals Don't Track Me!
// @version 1.1
// @description Replaces outgoing Slickdeals tracking links with direct links.
// @match http://slickdeals.net/f/*
// @namespace https://github.com/gg/slickdeals-dont-track-me
// @author Gregg Gajic <https://github.com/gg>
// @license MIT
// ==/UserScript==
(function() {
var getQueryStringParameters = function (url) {
// See: http://stackoverflow.com/a/3855394
return (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})((url.split('?')[1] || '').split('&'));
};
var contentBody = document.getElementById('maincontent') || document.getElementById('posts');
var aElements = contentBody.getElementsByTagName('a');
for (var i = 0, a; a = aElements[i]; i++) {
var queryParamters = getQueryStringParameters(a.href);
var directUrl = queryParamters['u2'];
if (directUrl) {
a.href = directUrl;
a.onclick = '';
};
}
})();
|
Update skip condition for tests | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
|
Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
| import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
|
Use a function to chain sendCommands method | var Q = require('q'),
mpd = require('mpd'),
EventEmitter = require('events').EventEmitter,
winston = require('winston');
exports.create = function (port, logger) {
var client;
var logger = logger || winston;
var ready = Q.defer();
function connect(mpdClient) {
client = mpdClient || mpd.connect({
port: port, host: 'localhost'
});
client.on('ready', function() {
logger.info('ready on port '+port);
ready.resolve();
});
client.on('error', function(err) {
var errMsg = 'Cannot connect to port '+port+': '+err;
instance.emit('error', err);
ready.reject(err);
});
client.on('system', function(name) {
instance.emit('system', name);
});
instance.on('error', function(err) {
logger.warn(err);
});
return ready.promise;
}
function formatCommand(command) {
if(command.length == 1) {
command[1] = [];
}
return mpd.cmd(command[0], command[1]);
}
function sendCommands(commands) {
var commandList = commands.map(formatCommand),
promise = instance.ready().then(function() {
Q.ninvoke(client, 'sendCommands', commandList)
});
return promise;
}
var instance = new EventEmitter();
instance.formatCommand = formatCommand;
instance.sendCommands = sendCommands;
instance.connect = connect;
instance.ready = function() { return ready.promise} ;
return instance;
};
| var Q = require('q'),
mpd = require('mpd'),
EventEmitter = require('events').EventEmitter,
winston = require('winston');
exports.create = function (port, logger) {
var client;
var logger = logger || winston;
var ready = Q.defer();
function connect(mpdClient) {
client = mpdClient || mpd.connect({
port: port, host: 'localhost'
});
client.on('ready', function() {
logger.info('ready on port '+port);
ready.resolve();
});
client.on('error', function(err) {
var errMsg = 'Cannot connect to port '+port+': '+err;
instance.emit('error', err);
ready.reject(err);
});
client.on('system', function(name) {
instance.emit('system', name);
});
instance.on('error', function(err) {
logger.warn(err);
});
return ready.promise;
}
function formatCommand(command) {
if(command.length == 1) {
command[1] = [];
}
return mpd.cmd(command[0], command[1]);
}
function sendCommands(commands) {
var commandList = commands.map(formatCommand),
promise = instance.ready().then(
Q.ninvoke(client, 'sendCommands', commandList)
);
return promise;
}
var instance = new EventEmitter();
instance.formatCommand = formatCommand;
instance.sendCommands = sendCommands;
instance.connect = connect;
instance.ready = function() { return ready.promise} ;
return instance;
};
|
Make sure all properties are set during insert and errors are logged properly | import sqlite3 from 'sqlite3';
import { createLogObject } from './csv.js';
const SQL_PROPERTIES = [
'event_id', 'date', 'id', 'name', 'type', 'value', 'battery', 'dark', 'daylight'
]
const SQL = `
INSERT INTO log (${SQL_PROPERTIES.join(", ")})
VALUES (${SQL_PROPERTIES.map(v => `\$${v}`).join(", ")})
`;
export default class SQLiteLogger {
constructor(dbURL) {
this.db = new sqlite3.Database(dbURL);
//date,id,name,type,value,battery,dark,daylight
this.db.run(`CREATE TABLE IF NOT EXISTS log (
event_id TEXT PRIMARY KEY,
date TEXT NOT NULL,
id NUMERIC NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
value TEXT NOT NULL,
battery NUMERIC,
dark TEXT,
daylight TEXT
)`);
}
log = s => {
const msg = createLogObject(s);
if (msg.type) {
const dbInsert = SQL_PROPERTIES.reduce((pv, cv) => {
pv[`\$${cv}`] = '';
return pv;
}, {});
for (const property in msg) {
if (msg[property] != null) {
dbInsert[`$${property}`] = msg[property];
}
}
this.db.run(SQL, dbInsert, (err) => {
if (err) {
console.log("Error while executing", dbInsert)
return console.error(err)
}
});
}
};
} | import sqlite3 from 'sqlite3';
import { createLogObject } from './csv.js';
const SQL = `
INSERT INTO log (event_id, date, id, name, type, value, battery, dark, daylight)
VALUES ($event_id, $date, $id, $name, $type, $value, $battery, $dark, $daylight)
`;
export default class SQLiteLogger {
constructor(dbURL) {
this.db = new sqlite3.Database(dbURL);
//date,id,name,type,value,battery,dark,daylight
this.db.run(`CREATE TABLE IF NOT EXISTS log (
event_id TEXT PRIMARY KEY,
date TEXT NOT NULL,
id NUMERIC NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
value TEXT NOT NULL,
battery NUMERIC,
dark TEXT,
daylight TEXT
)`);
}
log = s => {
const msg = createLogObject(s);
if (msg.type) {
const dbInsert = {};
for (const property in msg) {
dbInsert[`$${property}`] = msg[property];
}
try {
this.db.run(SQL, dbInsert);
} catch (err) {
console.exception("Could not insert log line", dbInsert)
}
}
};
} |
Add Moksha Hub version requirement
New features of statscache require a moksha installation with corresponding
support, or else it won't run at all. | """ Setup file for statscache """
from setuptools import setup
def get_description():
with open('README.rst', 'r') as f:
return ''.join(f.readlines()[2:])
requires = [
'fedmsg',
'moksha.hub>=1.4.6',
'fedmsg_meta_fedora_infrastructure',
'sqlalchemy',
]
tests_require = [
'nose',
'freezegun'
]
setup(
name='statscache',
version='0.0.1',
description='Daemon to build and keep fedmsg statistics',
long_description=get_description(),
author='Ralph Bean',
author_email='[email protected]',
url="https://github.com/fedora-infra/statscache/",
download_url="https://pypi.python.org/pypi/statscache/",
license='LGPLv2+',
install_requires=requires,
tests_require=tests_require,
test_suite='nose.collector',
packages=['statscache'],
include_package_data=True,
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Programming Language :: Python',
],
entry_points={
'moksha.consumer': [
"statscache_consumer = statscache.consumer:StatsConsumer",
],
'moksha.producer': [
"statscache_producers = statscache.producer:producers",
],
},
)
| """ Setup file for statscache """
from setuptools import setup
def get_description():
with open('README.rst', 'r') as f:
return ''.join(f.readlines()[2:])
requires = [
'fedmsg',
'fedmsg_meta_fedora_infrastructure',
'sqlalchemy',
]
tests_require = [
'nose',
'freezegun'
]
setup(
name='statscache',
version='0.0.1',
description='Daemon to build and keep fedmsg statistics',
long_description=get_description(),
author='Ralph Bean',
author_email='[email protected]',
url="https://github.com/fedora-infra/statscache/",
download_url="https://pypi.python.org/pypi/statscache/",
license='LGPLv2+',
install_requires=requires,
tests_require=tests_require,
test_suite='nose.collector',
packages=['statscache'],
include_package_data=True,
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Programming Language :: Python',
],
entry_points={
'moksha.consumer': [
"statscache_consumer = statscache.consumer:StatsConsumer",
],
'moksha.producer': [
"statscache_producers = statscache.producer:producers",
],
},
)
|
Fix empty void when user has no tags for tags' index view | @extends('layout')
@section('body')
<div class="wrapper spacing-top-large spacing-bottom-large">
<div class="box">
<div class="section">
<div class="row">
<div class="column align-middle">
<span class="color-dark">@lang('general.tags')</span>
</div>
<div class="column align-middle text-align-right">
<a href="/tags/create">@lang('actions.create')</a>
</div>
</div>
</div>
@if (count($tags) > 0)
<ul class="section">
@foreach ($tags as $tag)
<li class="row">
<div class="column">{{ $tag->name }}</div>
<div class="column">
<form class="action" method="POST" action="/tags/{{ $tag->id }}">
{{ method_field('delete') }}
{{ csrf_field() }}
<button>@lang('actions.delete')</button>
</form>
</div>
</li>
@endforeach
</ul>
@else
<div class="section">You don't have any tags</div>
@endif
</div>
</div>
@endsection
| @extends('layout')
@section('body')
<div class="wrapper spacing-top-large spacing-bottom-large">
<div class="box">
<div class="section">
<div class="row">
<div class="column align-middle">
<span class="color-dark">@lang('general.tags')</span>
</div>
<div class="column align-middle text-align-right">
<a href="/tags/create">@lang('actions.create')</a>
</div>
</div>
</div>
<ul class="section">
@foreach ($tags as $tag)
<li class="row">
<div class="column">{{ $tag->name }}</div>
<div class="column">
<form class="action" method="POST" action="/tags/{{ $tag->id }}">
{{ method_field('delete') }}
{{ csrf_field() }}
<button>@lang('actions.delete')</button>
</form>
</div>
</li>
@endforeach
</ul>
</div>
</div>
@endsection
|
Clean up module loading printing | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.modules['Functions.'+name]
for f in glob ('Functions/%s.pyc' % name):
os.remove(f)
reload(src)
components = name.split('.')
for comp in components[:1]:
src = getattr(src, comp)
ModuleName = str(src).split("from")[0].strip("(").rstrip(" ")
if loadType != 'rel':
print ModuleName + " loaded."
func = src.Instantiate()
GlobalVars.functions.update({name:func})
return loadType
def UnloadFunction(name):
success = True
if name in GlobalVars.functions.keys():
del GlobalVars.functions[name]
else:
success = False
return success
def AutoLoadFunctions():
root = os.path.join('.', 'Functions')
for item in os.listdir(root):
if not os.path.isfile(os.path.join(root, item)):
continue
if not item.endswith('.py'):
continue
try:
if item[:-3] not in GlobalVars.nonDefaultModules:
LoadFunction(item[:-3])
except Exception, x:
print x.args
| import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.modules['Functions.'+name]
for f in glob ('Functions/%s.pyc' % name):
os.remove(f)
reload(src)
components = name.split('.')
for comp in components[:1]:
src = getattr(src, comp)
print str(src)
func = src.Instantiate()
GlobalVars.functions.update({name:func})
return loadType
def UnloadFunction(name):
success = True
if name in GlobalVars.functions.keys():
del GlobalVars.functions[name]
else:
success = False
return success
def AutoLoadFunctions():
root = os.path.join('.', 'Functions')
for item in os.listdir(root):
if not os.path.isfile(os.path.join(root, item)):
continue
if not item.endswith('.py'):
continue
try:
if item[:-3] not in GlobalVars.nonDefaultModules:
LoadFunction(item[:-3])
except Exception, x:
print x.args
|
Add method to remove logged messages | <?php
namespace PicoFeed;
use DateTime;
use DateTimeZone;
/**
* Logging class
*
* @author Frederic Guillot
* @package picofeed
*/
class Logging
{
/**
* List of messages
*
* @static
* @access private
* @var array
*/
private static $messages = array();
/**
* Default timezone
*
* @static
* @access private
* @var array
*/
private static $timezone = 'UTC';
/**
* Add a new message
*
* @static
* @access public
* @param string $message Message
*/
public static function setMessage($message)
{
$date = new DateTime('now', new DateTimeZone(self::$timezone));
self::$messages[] = '['.$date->format('Y-m-d H:i:s').'] '.$message;
}
/**
* Get all logged messages
*
* @static
* @access public
* @return array
*/
public static function getMessages()
{
return self::$messages;
}
/**
* Remove all logged messages
*
* @static
* @access public
*/
public static function deleteMessages()
{
self::$messages = array();
}
/**
* Set a different timezone
*
* @static
* @see http://php.net/manual/en/timezones.php
* @access public
* @param string $timezone Timezone
*/
public static function setTimeZone($timezone)
{
self::$timezone = $timezone ?: self::$timezone;
}
}
| <?php
namespace PicoFeed;
use DateTime;
use DateTimeZone;
/**
* Logging class
*
* @author Frederic Guillot
* @package picofeed
*/
class Logging
{
/**
* List of messages
*
* @static
* @access private
* @var array
*/
private static $messages = array();
/**
* Default timezone
*
* @static
* @access private
* @var array
*/
private static $timezone = 'UTC';
/**
* Add a new message
*
* @static
* @access public
* @param string $message Message
*/
public static function setMessage($message)
{
$date = new DateTime('now', new DateTimeZone(self::$timezone));
self::$messages[] = '['.$date->format('Y-m-d H:i:s').'] '.$message;
}
/**
* Get all logged messages
*
* @static
* @access public
* @return array
*/
public static function getMessages()
{
return self::$messages;
}
/**
* Set a different timezone
*
* @static
* @see http://php.net/manual/en/timezones.php
* @access public
* @param string $timezone Timezone
*/
public static function setTimeZone($timezone)
{
self::$timezone = $timezone ?: self::$timezone;
}
}
|
Update init command to not hang. | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Init extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mangapie:init';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Initializes mangapie';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment('Generating app key...');
// avoid generating a key if it already exists
if (!config('app.key')) {
Artisan::call('key:generate');
} else {
$this->comment('App key already exists. Skipping.');
}
$this->comment('Publishing vendor files...');
if (\File::exists('config/image.php') == false) {
Artisan::call('vendor:publish', ['--provider' => 'Intervention\\Image\\ImageServiceProviderLaravel5']);
} else {
$this->comment('Config file for Intervention\\Image already exists. Skipping.');
}
$this->comment('Migrating...');
Artisan::call('migrate', ['--force' => true]);
$this->comment('Seeding database...');
Artisan::call('db:seed', ['--force' => true]);
$this->comment('Finished initializing mangapie.');
}
}
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Init extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mangapie:init';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Initializes mangapie';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment('Generating app key...');
// avoid generating a key if it already exists
if (!config('app.key')) {
Artisan::call('key:generate');
} else {
$this->comment('App key already exists. Skipping.');
}
$this->comment('Publishing vendor files...');
Artisan::call('vendor:publish');
$this->comment('Migrating...');
Artisan::call('migrate', ['--force' => true]);
$this->comment('Seeding database...');
Artisan::call('db:seed', ['--force' => true]);
$this->comment('Finished initializing mangapie.');
}
}
|
Set logging level to INFO | import logging
from time import time, sleep
from .net_utils import *
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def target_scaner(interface, min_interval=30):
old_peers = {}
while True:
begin_time = time()
peers = {}
for ip, mac in arp_scaner():
peers[ip] = mac
if ip in old_peers: # Still online
del old_peers[ip] # Remove it from old_peers
# Now targets in old_peers
logger.info("%d target(s) found", len(old_peers))
for target in old_peers.items():
yield target
old_peers = peers
# Wait for next scanning, if needed
interval = time() - begin_time
if interval < min_interval:
sleep(min_interval - interval)
def try_target(target, interface, max_attempts=5, sleep_time=5):
ip, mac = target
logger.info("Trying target: %s, %s", ip, mac)
if not spoof_mac(mac, interface): # Failed to spoof mac
return False
for i in range(max_attempts):
sleep(sleep_time)
if get_ip() == ip:
break
else: # Failed to get this IP
return False
infos = check_online()
if infos: # Succeeded
return infos
else: # An offline IP
return False
| import logging
from time import time, sleep
from .net_utils import *
logger = logging.getLogger(__name__)
def target_scaner(interface, min_interval=30):
old_peers = {}
while True:
begin_time = time()
peers = {}
for ip, mac in arp_scaner():
peers[ip] = mac
if ip in old_peers: # Still online
del old_peers[ip] # Remove it from old_peers
# Now targets in old_peers
logger.info("%d target(s) found", len(old_peers))
for target in old_peers.items():
yield target
old_peers = peers
# Wait for next scanning, if needed
interval = time() - begin_time
if interval < min_interval:
sleep(min_interval - interval)
def try_target(target, interface, max_attempts=5, sleep_time=5):
ip, mac = target
logger.info("Trying target: %s, %s", ip, mac)
if not spoof_mac(mac, interface): # Failed to spoof mac
return False
for i in range(max_attempts):
sleep(sleep_time)
if get_ip() == ip:
break
else: # Failed to get this IP
return False
infos = check_online()
if infos: # Succeeded
return infos
else: # An offline IP
return False
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.