text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Define version in one place
try: from setuptools import setup except ImportError: from distutils.core import setup from code_formatter import __version__ CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Libraries :: Python Modules'] setup( name='code-formatter', author='Tomasz Rybarczyk', author_email='paluho@gmail.com', classifiers=CLASSIFIERS, description='', dependency_links=[], install_requires=[], url='https://github.com/paluh/code-formatter', packages=['code_formatter', 'code_formatter.extras'], scripts=[], test_suite='code_formatter.tests.test_suite', zip_safe=False, version = __version__, )
try: from setuptools import setup except ImportError: from distutils.core import setup CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Libraries :: Python Modules'] setup( name='code-formatter', author='Tomasz Rybarczyk', author_email='paluho@gmail.com', classifiers=CLASSIFIERS, description='', dependency_links=[], install_requires=[], url='https://github.com/paluh/code-formatter', packages=['code_formatter', 'code_formatter.extras'], scripts=[], test_suite='code_formatter.tests.test_suite', zip_safe=False, version = '0.1.0c1', )
Create Tests Dynamically When Needed
// TODO docs, see data/breakpoint.js define(function(require, exports, module) { var Data = require("./data"); function File(options) { this.data = options || {}; if (!this.data.items) this.data.items = []; if (!this.data.status) this.data.status = "pending"; this.type = "file"; this.keepChildren = true; } File.prototype = new Data( ["path", "type", "coverage", "passed", "fullOutput", "output", "ownPassed"], ["items"] ); File.prototype.__defineGetter__("passed", function(){ return typeof this.data.ownPassed == "number" ? this.data.ownPassed : this.data.passed; }); File.prototype.equals = function(file) { return this.data.label == file.label; }; File.prototype.addTest = function(def, parent) { var test = Data.fromJSON([def])[0]; (parent || this).data.items.push(test); return test; }; module.exports = File; });
// TODO docs, see data/breakpoint.js define(function(require, exports, module) { var Data = require("./data"); function File(options) { this.data = options || {}; if (!this.data.items) this.data.items = []; if (!this.data.status) this.data.status = "pending"; this.type = "file"; this.keepChildren = true; } File.prototype = new Data( ["path", "type", "coverage", "passed", "fullOutput", "output", "ownPassed"], ["items"] ); File.prototype.__defineGetter__("passed", function(){ return typeof this.data.ownPassed == "number" ? this.data.ownPassed : this.data.passed; }); File.prototype.equals = function(file) { return this.data.label == file.label; }; File.prototype.addTest = function(def) { var test = Data.fromJSON([def])[0]; this.data.items.push(test); return test; }; module.exports = File; });
Convert binhex regression test to PyUnit. We could use a better test for this.
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Based on an original test by Roger E. Masse. """ import binhex import os import tempfile import test_support import unittest class BinHexTestCase(unittest.TestCase): def setUp(self): self.fname1 = tempfile.mktemp() self.fname2 = tempfile.mktemp() def tearDown(self): try: os.unlink(self.fname1) except OSError: pass try: os.unlink(self.fname2) except OSError: pass DATA = 'Jack is my hero' def test_binhex(self): f = open(self.fname1, 'w') f.write(self.DATA) f.close() binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) f = open(self.fname1, 'r') finish = f.readline() f.close() self.assertEqual(self.DATA, finish) test_support.run_unittest(BinHexTestCase)
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.write(start) f.close() binhex.binhex(fname1, fname2) if verbose: print 'binhex' binhex.hexbin(fname2, fname1) if verbose: print 'hexbin' f = open(fname1, 'r') finish = f.readline() f.close() # on Windows an open file cannot be unlinked if start != finish: print 'Error: binhex != hexbin' elif verbose: print 'binhex == hexbin' try: import os os.unlink(fname1) os.unlink(fname2) except: pass test()
Make it abstract and redefine createUnit() as abstract
package com.redhat.ceylon.eclipse.core.typechecker; import java.util.List; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; public abstract class IdePhasedUnit extends PhasedUnit { private TypeChecker typeChecker; public IdePhasedUnit(VirtualFile unitFile, VirtualFile srcDir, CompilationUnit cu, Package p, ModuleManager moduleManager, TypeChecker typeChecker, List<CommonToken> tokenStream) { super(unitFile, srcDir, cu, p, moduleManager, typeChecker.getContext(), tokenStream); this.typeChecker = typeChecker; } public IdePhasedUnit(PhasedUnit other) { super(other); if (other instanceof IdePhasedUnit) { typeChecker = ((IdePhasedUnit) other).typeChecker; } } public TypeChecker getTypeChecker() { return typeChecker; } public abstract Unit createUnit(); }
package com.redhat.ceylon.eclipse.core.typechecker; import java.util.List; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; public class IdePhasedUnit extends PhasedUnit { private TypeChecker typeChecker; public IdePhasedUnit(VirtualFile unitFile, VirtualFile srcDir, CompilationUnit cu, Package p, ModuleManager moduleManager, TypeChecker typeChecker, List<CommonToken> tokenStream) { super(unitFile, srcDir, cu, p, moduleManager, typeChecker.getContext(), tokenStream); this.typeChecker = typeChecker; } public IdePhasedUnit(PhasedUnit other) { super(other); if (other instanceof IdePhasedUnit) { typeChecker = ((IdePhasedUnit) other).typeChecker; } } public TypeChecker getTypeChecker() { return typeChecker; } }
Return constructed URL for each result.
from django.shortcuts import render from ord_hackday.search.models import Portal import requests import json def search(request): c = {} if 'query' in request.GET: query = request.GET['query'] if len(query) > 0: portals = Portal.objects.all() c['portals'] = portals c['results'] = [] for portal in portals: url = portal.url + '/api/3/action/package_search?q=' + query r = requests.get(url) json_result = json.loads(r.text) if json_result['success']: for r in json_result['result']['results']: r['result_url'] = portal.url + '/dataset/' + r['name'] c['results'].append(r) return render(request, 'search.html', c)
from django.shortcuts import render from ord_hackday.search.models import Portal import requests import json def search(request): c = {} if 'query' in request.GET: query = request.GET['query'] if len(query) > 0: portals = Portal.objects.all() c['portals'] = portals c['results'] = [] for portal in portals: url = portal.url + '/api/3/action/package_search?q=' + query r = requests.get(url) json_result = json.loads(r.text) if json_result['success']: for r in json_result['result']['results']: c['results'].append(r) return render(request, 'search.html', c)
Make sure that hidden files are taken into account (e.g. .nojekyll)
<?php namespace Couscous\Module\Template\Step; use Couscous\Model\LazyFile; use Couscous\Model\Project; use Couscous\Step; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * Load asset files from the template directory. * * Assets are any file that is not a Twig template. * * @author Matthieu Napoli <matthieu@mnapoli.fr> */ class LoadAssets implements Step { /** * @var Filesystem */ private $filesystem; public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } public function __invoke(Project $project) { if (! $project->metadata['template.directory']) { return; } $files = new Finder(); $files->files() ->in($project->metadata['template.directory']) ->ignoreDotFiles(false) ->notName('*.twig'); $project->watchlist->watchFiles($files); foreach ($files as $file) { /** @var SplFileInfo $file */ $project->addFile(new LazyFile($file->getPathname(), $file->getRelativePathname())); } } }
<?php namespace Couscous\Module\Template\Step; use Couscous\Model\LazyFile; use Couscous\Model\Project; use Couscous\Step; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * Load asset files from the template directory. * * Assets are any file that is not a Twig template. * * @author Matthieu Napoli <matthieu@mnapoli.fr> */ class LoadAssets implements Step { /** * @var Filesystem */ private $filesystem; public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } public function __invoke(Project $project) { if (! $project->metadata['template.directory']) { return; } $files = new Finder(); $files->files() ->in($project->metadata['template.directory']) ->notName('*.twig'); $project->watchlist->watchFiles($files); foreach ($files as $file) { /** @var SplFileInfo $file */ $project->addFile(new LazyFile($file->getPathname(), $file->getRelativePathname())); } } }
Remove extraneous test for already handled edge case
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
Fix unit test that uses PHP7+ functionality
<?php namespace Tests\Result; use Stratedge\Wye\Result; use Stratedge\Wye\Wye; class SetNumRowsTest extends \Tests\TestCase { public function testReturnsSelf() { $result = Wye::makeResult(); $this->assertSame($result, $result->setNumRows(123)); } public function testSetsPropertyValue() { $result = new Mock(new Wye); $result->setNumRows(56342); $this->assertSame(56342, $result->num_rows); } public function testSetsPropertyValueAsInteger() { $result = new Mock(new Wye); $result->setNumRows('hello'); $this->assertSame(0, $result->num_rows); } } class Mock extends Result { public $num_rows; }
<?php namespace Tests\Result; use Stratedge\Wye\Result; use Stratedge\Wye\Wye; class SetNumRowsTest extends \Tests\TestCase { public function testReturnsSelf() { $result = Wye::makeResult(); $this->assertSame($result, $result->setNumRows(123)); } public function testSetsPropertyValue() { $result = new class (new Wye) extends Result { public $num_rows; }; $result->setNumRows(56342); $this->assertSame(56342, $result->num_rows); } public function testSetsPropertyValueAsInteger() { $result = new class (new Wye) extends Result { public $num_rows; }; $result->setNumRows('hello'); $this->assertSame(0, $result->num_rows); } }
Support naive filtering in python API Change-Id: I10caecf68c73e7c722a9ab93a718b80c588d4d0e
# Copyright 2014 - Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mistralclient.api import base class Task(base.Resource): resource_name = 'Task' class TaskManager(base.ResourceManager): resource_class = Task def update(self, id, state): self._ensure_not_empty(id=id, state=state) data = { 'state': state } return self._update('/tasks/%s' % id, data) def list(self, execution_id=None): url = '/tasks' if execution_id: url = '/executions/%s/tasks' % execution_id return self._list(url, response_key='tasks') def get(self, id): self._ensure_not_empty(id=id) return self._get('/tasks/%s' % id)
# Copyright 2014 - Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mistralclient.api import base class Task(base.Resource): resource_name = 'Task' class TaskManager(base.ResourceManager): resource_class = Task def update(self, id, state): self._ensure_not_empty(id=id, state=state) data = { 'state': state } return self._update('/tasks/%s' % id, data) def list(self): return self._list('/tasks', response_key='tasks') def get(self, id): self._ensure_not_empty(id=id) return self._get('/tasks/%s' % id)
Add rel on fork link
import React from 'react' import { makeStyles } from '@material-ui/core/styles' import Fab from '@material-ui/core/Fab' import Badge from '@material-ui/core/Badge' const useStyles = makeStyles(() => ({ fork: { position: 'absolute', right: 30, top: 30 } })) const Fork = ({ stars }) => { const classes = useStyles() return ( <div className={classes.fork}> <Badge badgeContent={stars || 0} max={999} color="primary"> <Fab target="_blank" variant="extended" rel="noreferrer noopener" href="https://github.com/ooade/NextSimpleStarter" > Fork me </Fab> </Badge> </div> ) } export default Fork
import React from 'react' import { makeStyles } from '@material-ui/core/styles' import Fab from '@material-ui/core/Fab' import Badge from '@material-ui/core/Badge' const useStyles = makeStyles(() => ({ fork: { position: 'absolute', right: 30, top: 30 } })) const Fork = ({ stars }) => { const classes = useStyles() return ( <div className={classes.fork}> <Badge badgeContent={stars || 0} max={999} color="primary"> <Fab variant="extended" href="https://github.com/ooade/NextSimpleStarter" target="_blank" > Fork me </Fab> </Badge> </div> ) } export default Fork
Hide zoom buttons fixed (Only on android >3.0)
package cl.uchile.ing.adi.quicklooklib.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import cl.uchile.ing.adi.quicklooklib.R; /** * Created by dudu on 04-01-2016. */ public class WebFragment extends QuicklookFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_web, container, false); WebView web = (WebView) v.findViewById(R.id.web_fragment); web.loadUrl("file://"+this.item.getPath()); web.getSettings().setBuiltInZoomControls(true); web.getSettings().setDisplayZoomControls(false); return v; } }
package cl.uchile.ing.adi.quicklooklib.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import cl.uchile.ing.adi.quicklooklib.R; /** * Created by dudu on 04-01-2016. */ public class WebFragment extends QuicklookFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_web, container, false); WebView web = (WebView) v.findViewById(R.id.web_fragment); web.loadUrl("file://"+this.item.getPath()); return v; } }
Fix bug with multiple quizes in a row
let Quiz; let currentQuizWord = {}; let currentArray; async function startQuiz(folderKey) { currentArray = 0; await fetch(`/study?folderKey=${folderKey}`) .then(res => res.json()) .then(result => { Quiz = result; return Quiz.length; }).catch("Could not find any cards"); } function nextQuizWord() { let nextWord = {}; if (Quiz[currentArray].length != 0) { nextWord = Quiz[currentArray].shift(); } else { currentArray++; if (currentArray >= Quiz.length) { return "!@end"; } else { nextWord = Quiz[currentArray].shift(); } } currentQuizWord = nextWord; return nextWord; } function updateWordQueues(correct, cardKey) { if (correct == "false" && currentArray < Quiz.length - 1) { Quiz[currentArray + 1].push(currentQuizWord); } // Updates the card's familarity score fetch('/study', { method: 'POST', body: `cardKey=${cardKey}&answeredCorrectly=${correct}`, headers: { 'Content-type': 'application/x-www-form-urlencoded' } }); } function getRound() { return currentArray; } export { startQuiz, updateWordQueues, nextQuizWord, getRound };
let Quiz; let currentQuizWord = {}; let currentArray = 0; let test = 0; async function startQuiz(folderKey) { await fetch(`/study?folderKey=${folderKey}`) .then(res => res.json()) .then(result => { Quiz = result; console.log(Quiz[0].length); return Quiz.length; }).catch("Could not find any cards"); } function nextQuizWord() { let nextWord = {}; if (Quiz[currentArray].length != 0) { nextWord = Quiz[currentArray].shift(); } else { currentArray++; if (currentArray >= Quiz.length) { return "!@end"; } else { nextWord = Quiz[currentArray].shift(); } } currentQuizWord = nextWord; return nextWord; } function updateWordQueues(correct, cardKey) { if (correct == "false" && currentArray < Quiz.length - 1) { Quiz[currentArray + 1].push(currentQuizWord); } // Updates the card's familarity score fetch('/study', { method: 'POST', body: `cardKey=${cardKey}&answeredCorrectly=${correct}`, headers: { 'Content-type': 'application/x-www-form-urlencoded' } }); } function getRound() { return currentArray; } export { startQuiz, updateWordQueues, nextQuizWord, getRound };
Fix name clash over "utils" in ardinfo plugin script.
#!/usr/bin/python import os import sys sys.path.append("/usr/local/munki") from munkilib import FoundationPlist sys.path.append("/usr/local/sal") import utils def main(): ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist" if os.path.exists(ard_path): ard_prefs = FoundationPlist.readPlist(ard_path) else: ard_prefs = {} sal_result_key = "ARD_Info_{}" prefs_key_prefix = "Text{}" data = { sal_result_key.format(i): ard_prefs.get(prefs_key_prefix.format(i), "") for i in range(1, 5)} utils.add_plugin_results('ARD_Info', data) if __name__ == "__main__": main()
#!/usr/bin/python import os import sys sys.path.append("/usr/local/munki/munkilib") import FoundationPlist sys.path.append("/usr/local/sal") import utils def main(): ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist" if os.path.exists(ard_path): ard_prefs = FoundationPlist.readPlist(ard_path) else: ard_prefs = {} sal_result_key = "ARD_Info_{}" prefs_key_prefix = "Text{}" data = { sal_result_key.format(i): ard_prefs.get(prefs_key_prefix.format(i), "") for i in range(1, 5)} utils.add_plugin_results('ARD_Info', data) if __name__ == "__main__": main()
Fix naming issues with tasks
from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "rssmailer@praus.net", recipients)
from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.mail.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.mail.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "rssmailer@praus.net", recipients)
Remove unused config module import
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') const config = require('config') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
Adjust camera to persisted settings
import React from 'react' import { render } from 'react-dom' import { compose, applyMiddleware, createStore } from 'redux'; import { Provider } from 'react-redux'; import logger from 'redux-logger'; import persistState, {mergePersistedState} from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage'; import filter from 'redux-localstorage-filter'; const hot = (state, action) => { return require('./reducers').default(state, action); }; const reducer = compose( mergePersistedState((initialState, persistedState) => { let state = { ...initialState, ...persistedState }; state.camera = require('./reducers/camera').resetCamera(null, state.settings); return state; }) )(hot); const storage = compose( filter(['settings','macros']) )(adapter(window.localStorage)); const middleware = compose( applyMiddleware( logger({ collapsed: true })), persistState(storage, 'LaserWeb') ); const store = createStore(reducer, middleware); export function GlobalStore() { return store; } function Hot(props) { const LaserWeb = require('./components/laserweb').default; return <LaserWeb />; } function renderHot() { render(( <Provider store={store}> <Hot /> </Provider> ), document.getElementById('laserweb')); } renderHot(); if (module.hot) { module.hot.accept('./reducers', renderHot); module.hot.accept('./components/laserweb', renderHot); }
import React from 'react' import { render } from 'react-dom' import { compose, applyMiddleware, createStore } from 'redux'; import { Provider } from 'react-redux'; import logger from 'redux-logger'; import persistState, {mergePersistedState} from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage'; import filter from 'redux-localstorage-filter'; const hot = (state, action) => { return require('./reducers').default(state, action); }; const reducer = compose( mergePersistedState() )(hot); const storage = compose( filter(['settings','macros']) )(adapter(window.localStorage)); const middleware = compose( applyMiddleware( logger({ collapsed: true })), persistState(storage, 'LaserWeb') ); const store = createStore(reducer, middleware); export function GlobalStore() { return store; } function Hot(props) { const LaserWeb = require('./components/laserweb').default; return <LaserWeb />; } function renderHot() { render(( <Provider store={store}> <Hot /> </Provider> ), document.getElementById('laserweb')); } renderHot(); if (module.hot) { module.hot.accept('./reducers', renderHot); module.hot.accept('./components/laserweb', renderHot); }
Fix backward compatibility for RN < 0.47
package com.react.rnspinkit; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by suzuri04x2 on 2016/5/10. */ public class RNSpinkitPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> list = new ArrayList<>(); list.add(new RNSpinkit(reactContext)); return list; } }
package com.react.rnspinkit; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by suzuri04x2 on 2016/5/10. */ public class RNSpinkitPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> list = new ArrayList<>(); list.add(new RNSpinkit(reactContext)); return list; } }
Set default state back to null
const knex = require('knex'); const cfg = require('../config'); const db = knex(cfg.db); module.exports = { async createUser(telegramId) { return db('user') .insert({ telegram_id: telegramId }); }, async linkUser(telegramId, username) { return db('user') .where({ telegram_id: telegramId }) .update({ piikki_username: username }); }, async unlinkUser(telegramId) { return db('user') .where({ telegram_id: telegramId }) .update({ piikki_username: null, json_state: null }); }, async getUser(telegramId) { return db('user') .first() .where({ telegram_id: telegramId }); }, async getUserState(telegramId) { const user = await db('user') .first('json_state') .where({ telegram_id: telegramId }); return user ? JSON.parse(user.json_state) : null; }, async setUserState(telegramId, state) { return db('user') .where({ telegram_id: telegramId }) .update({ json_state: (state ? JSON.stringify(state) : null) }); }, };
const knex = require('knex'); const cfg = require('../config'); const db = knex(cfg.db); module.exports = { async createUser(telegramId) { return db('user') .insert({ telegram_id: telegramId }); }, async linkUser(telegramId, username) { return db('user') .where({ telegram_id: telegramId }) .update({ piikki_username: username }); }, async unlinkUser(telegramId) { return db('user') .where({ telegram_id: telegramId }) .update({ piikki_username: null, json_state: null }); }, async getUser(telegramId) { return db('user') .first() .where({ telegram_id: telegramId }); }, async getUserState(telegramId) { const user = await db('user') .first('json_state') .where({ telegram_id: telegramId }); return user ? JSON.parse(user.json_state) : null; }, async setUserState(telegramId, state) { return db('user') .where({ telegram_id: telegramId }) .update({ json_state: (state ? JSON.stringify(state) : JSON.stringify({})) }); }, };
Fix indenation to project's default
<?php /** * Will hold data from the Kaltura Player components to be passed on to the live analytics system * @package api * @subpackage objects */ class KalturaLiveStatsEvent extends KalturaObject { /** * @var int */ public $partnerId; /** * @var string */ public $entryId; /** * an integer representing the type of event being sent from the player * @var KalturaLiveStatsEventType */ public $eventType; /** * a unique string generated by the client that will represent the client-side session: the primary component will pass it on to other components that sprout from it * @var string */ public $sessionId; /** * incremental sequence of the event * @var int */ public $eventIndex; /** * buffer time in seconds from the last 10 seconds * @var int */ public $bufferTime; /** * bitrate used in the last 10 seconds * @var int */ public $bitrate; /** * the referrer of the client * @var string */ public $referrer; /** * @var bool */ public $isLive; /** * delivery type used for this stream * @var KalturaPlaybackProtocol */ public $deliveryType; }
<?php /** * Will hold data from the Kaltura Player components to be passed on to the live analytics system * @package api * @subpackage objects */ class KalturaLiveStatsEvent extends KalturaObject { /** * @var int */ public $partnerId; /** * @var string */ public $entryId; /** * an integer representing the type of event being sent from the player * @var KalturaLiveStatsEventType */ public $eventType; /** * a unique string generated by the client that will represent the client-side session: the primary component will pass it on to other components that sprout from it * @var string */ public $sessionId; /** * incremental sequence of the event * @var int */ public $eventIndex; /** * buffer time in seconds from the last 10 seconds * @var int */ public $bufferTime; /** * bitrate used in the last 10 seconds * @var int */ public $bitrate; /** * the referrer of the client * @var string */ public $referrer; /** * @var bool */ public $isLive; /** * delivery type used for this stream * @var KalturaPlaybackProtocol */ public $deliveryType; }
Allow for a zero-length atom at the end
define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) { 'use strict'; function open(item) { function onAtom(item, byteSource) { return byteSource.slice(0, 8).getBytes().then(function(headerBytes) { var length = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4).getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var atomItem = itemOM.createItem(name); if (length > 8) { atomItem.byteSource = byteSource.slice(8, length); } item.addItem(atomItem); if (byteSource.byteLength >= (length + 8)) { return onAtom(item, byteSource.slice(length)); } }); } return onAtom(item, item.byteSource); } return open; });
define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) { 'use strict'; function open(item) { function onAtom(item, byteSource) { return byteSource.slice(0, 8).getBytes().then(function(headerBytes) { var length = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4).getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var atomItem = itemOM.createItem(name); if (length > 8) { atomItem.byteSource = byteSource.slice(8, length); } item.addItem(atomItem); if (byteSource.byteLength > (length + 8)) { return onAtom(item, byteSource.slice(length)); } }); } return onAtom(item, item.byteSource); } return open; });
fix: Make sure an object is being destructured at getPage
import React from "react"; import ReactDOMServer from "react-dom/server"; import { Route, StaticRouter } from "react-router"; import config from "config"; // Aliased through webpack import paths from "../paths"; import BodyContent from "../BodyContent"; // TODO: what if a route isn't found? module.exports = function renderPage(location, cb) { const allPages = paths.getAllPages(config); const page = paths.getPageForPath(location, allPages); (config.renderPage || renderDefault)( { location, content: BodyContent(page, allPages), }, (err, { html, context } = {}) => { if (err) { return cb(err); } return cb(null, { html, page, context }); } ); }; function renderDefault({ location, content }, cb) { cb(null, { html: ReactDOMServer.renderToStaticMarkup( <StaticRouter location={location} context={{}}> <Route component={content} /> </StaticRouter> ), }); }
import React from "react"; import ReactDOMServer from "react-dom/server"; import { Route, StaticRouter } from "react-router"; import config from "config"; // Aliased through webpack import paths from "../paths"; import BodyContent from "../BodyContent"; // TODO: what if a route isn't found? module.exports = function renderPage(location, cb) { const allPages = paths.getAllPages(config); const page = paths.getPageForPath(location, allPages); (config.renderPage || renderDefault)( { location, content: BodyContent(page, allPages), }, (err, { html, context }) => { if (err) { return cb(err); } return cb(null, { html, page, context }); } ); }; function renderDefault({ location, content }, cb) { cb(null, { html: ReactDOMServer.renderToStaticMarkup( <StaticRouter location={location} context={{}}> <Route component={content} /> </StaticRouter> ), }); }
Fix SSL security provider integration tests They were running with none provider instead.
import os from pymco.test import ctxt from . import base FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures') class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', 'plugin.ssl_server_private': os.path.join(FIXTURES_PATH, 'server-private.pem'), 'securityprovider': 'ssl', 'plugin.ssl_client_cert_dir': FIXTURES_PATH, } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
from . import base class SSLTestCase(base.IntegrationTestCase): '''RabbitMQ integration test case.''' CTXT = { 'plugin.activemq.pool.1.port': 61614, 'plugin.activemq.pool.1.password': 'marionette', 'plugin.ssl_server_public': 'tests/fixtures/server-public.pem', 'plugin.ssl_client_private': 'tests/fixtures/client-private.pem', 'plugin.ssl_client_public': 'tests/fixtures/client-public.pem', } class TestWithSSLMCo20x(base.MCollective20x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo22x(base.MCollective22x, SSLTestCase): '''MCollective integration test case.''' class TestWithSSLMCo23x(base.MCollective23x, SSLTestCase): '''MCollective integration test case.'''
Use SNI correctly for cert check
'use strict'; const tls = require('tls'); const Promise = require('bluebird'); const moment = require('moment'); const SITES = ['porybox.com', 'hq.porygon.co', 'modapps.porygon.co']; module.exports = { period: 60 * 60 * 24, concurrent: true, task () { return Promise.reduce(SITES, (messages, host) => { return getSecureSocket(host).then(socket => { if (!socket.authorized) { return messages.concat(`Warning: The site ${host} has an invalid SSL certificate. SSL error: ${socket.authorizationError}`); } const expirationTime = moment.utc(socket.getPeerCertificate().valid_to, 'MMM D HH:mm:ss YYYY'); if (expirationTime < moment().add({days: 14})) { return messages.concat(`Warning: The SSL certificate for ${host} expires ${expirationTime.fromNow()}`); } return messages; }); }, []); } }; function getSecureSocket(host) { return new Promise(resolve => { const socket = tls.connect({host, servername: host, port: 443, rejectUnauthorized: false}, () => resolve(socket)); }); }
'use strict'; const tls = require('tls'); const Promise = require('bluebird'); const moment = require('moment'); const SITES = ['porybox.com', 'hq.porygon.co', 'modapps.porygon.co']; module.exports = { period: 60 * 60 * 24, concurrent: true, task () { return Promise.reduce(SITES, (messages, host) => { return getSecureSocket(host).then(socket => { if (!socket.authorized) { return messages.concat(`Warning: The site ${host} has an invalid SSL certificate. SSL error: ${socket.authorizationError}`); } const expirationTime = moment.utc(socket.getPeerCertificate().valid_to, 'MMM D HH:mm:ss YYYY'); if (expirationTime < moment().add({days: 14})) { return messages.concat(`Warning: The SSL certificate for ${host} expires ${expirationTime.fromNow()}`); } return messages; }); }, []); } }; function getSecureSocket(host) { return new Promise(resolve => { const socket = tls.connect({host, port: 443, rejectUnauthorized: false}, () => resolve(socket)); }); }
Fix issue with Windows file paths
<?php /* * This file is part of phpnsc. * * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace rg\tools\phpnsc; class NamespaceString { private $namespaceVendor; private $root; private $fullFilePath; public function __construct($namespaceVendor, $root, $fullFilePath) { $this->namespaceVendor = $namespaceVendor; $this->root = $root; $this->fullFilePath = $fullFilePath; } public function getNamespace() { $namespace = ''; $relativePath = str_replace($this->root, '', $this->fullFilePath); $relativePathParts = explode(DIRECTORY_SEPARATOR, $relativePath); for ($i = 1; $i < count($relativePathParts) - 1; ++$i) { $namespace .= '\\'.$relativePathParts[$i]; } if ($this->namespaceVendor) { return $this->namespaceVendor.$namespace; } return trim($namespace, '\\'); } public function __toString() { return $this->getNamespace(); } }
<?php /* * This file is part of phpnsc. * * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace rg\tools\phpnsc; class NamespaceString { private $namespaceVendor; private $root; private $fullFilePath; public function __construct($namespaceVendor, $root, $fullFilePath) { $this->namespaceVendor = $namespaceVendor; $this->root = $root; $this->fullFilePath = $fullFilePath; } public function getNamespace() { $namespace = ''; $relativePath = str_replace($this->root, '', $this->fullFilePath); $relativePathParts = explode('/', $relativePath); for ($i = 1; $i < count($relativePathParts) - 1; ++$i) { $namespace .= '\\'.$relativePathParts[$i]; } if ($this->namespaceVendor) { return $this->namespaceVendor.$namespace; } return trim($namespace, '\\'); } public function __toString() { return $this->getNamespace(); } }
Make testrunner work with Django 1.7).
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command INSTALLED_APPS = ( # Required contrib apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', # Our app and it's test app. 'dbsettings', ) SETTINGS = { 'INSTALLED_APPS': INSTALLED_APPS, 'SITE_ID': 1, 'ROOT_URLCONF': 'dbsettings.tests.test_urls', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, } if not settings.configured: settings.configure(**SETTINGS) if django.VERSION >= (1, 7): django.setup() call_command('test', 'dbsettings')
#!/usr/bin/env python from django.conf import settings from django.core.management import call_command INSTALLED_APPS = ( # Required contrib apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', # Our app and it's test app. 'dbsettings', ) SETTINGS = { 'INSTALLED_APPS': INSTALLED_APPS, 'SITE_ID': 1, 'ROOT_URLCONF': 'dbsettings.tests.test_urls', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, } if not settings.configured: settings.configure(**SETTINGS) call_command('test', 'dbsettings')
Implement a proper Fisher-Yates shuffle.
const Card = require('./card.js'); class Deck { constructor() { this.cards = []; for (let suit of Card.Suits()) { for (let rank of Card.Ranks()) { let card = new Card(rank, suit); this.cards.push(card); } } } // Public: Performs a proper Fisher-Yates shuffle. // // Returns nothing; the shuffle is in-place. shuffle() { let temp, idx; let cardsRemaining = this.cards.length; // While there remain elements to shuffle… while (cardsRemaining) { // Pick a remaining element… idx = Math.floor(Math.random() * cardsRemaining--); // And swap it with the current element. temp = this.cards[cardsRemaining]; this.cards[cardsRemaining] = this.cards[idx]; this.cards[idx] = temp; } } drawCard() { return this.cards.shift(); } toString() { return this.cards.join(); } } module.exports = Deck;
const Card = require('./card.js'); class Deck { constructor() { this.cards = []; for (let suit of Card.Suits()) { for (let rank of Card.Ranks()) { let card = new Card(rank, suit); this.cards.push(card); } } } shuffle() { let numberOfCards = this.cards.length; for (let index = 0; index < numberOfCards; index++) { let newIndex = Deck.getRandomInt(0, numberOfCards); let cardToSwap = this.cards[newIndex]; this.cards[newIndex] = this.cards[index]; this.cards[index] = cardToSwap; } } drawCard() { return this.cards.shift(); } toString() { return this.cards.join(); } static getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } } module.exports = Deck;
Use login screen instead of login modal
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'form', classNameBindings: [ 'isValid:valid:invalid' ], cancel: 'cancel', isValid: Ember.computed.alias('formModel.isValid'), notify: 'notify', save: 'save', showButtons: true, actions: { cancel: function () { this.sendAction('cancel'); }, submit: function () { this.set('formModel.showInputErrors', true); if (!this.get('isValid')) { // console.log('[ValidatedFormComponent] Not submitting invalid formModel.'); return false; } var self = this; var deferred = Ember.RSVP.defer(); this.set('errors', false); this.sendAction('save', deferred); deferred.promise.catch(function (result) { // console.log('[ValidatedFormComponent]', result); if (result.unauthorized) self.sendAction('transitionTo', 'login.screen'); self.set('errors', result.errors || [ 'Oops! There was a problem.' ]); }); }, notify: function (opts) { this.sendAction('notify', opts); } } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'form', classNameBindings: [ 'isValid:valid:invalid' ], cancel: 'cancel', isValid: Ember.computed.alias('formModel.isValid'), notify: 'notify', save: 'save', showButtons: true, actions: { cancel: function () { this.sendAction('cancel'); }, submit: function () { this.set('formModel.showInputErrors', true); if (!this.get('isValid')) { // console.log('[ValidatedFormComponent] Not submitting invalid formModel.'); return false; } var self = this; var deferred = Ember.RSVP.defer(); this.set('errors', false); this.sendAction('save', deferred); deferred.promise.catch(function (result) { // console.log('[ValidatedFormComponent]', result); if (result.unauthorized) self.sendAction('openModal', 'login'); self.set('errors', result.errors || [ 'Oops! There was a problem.' ]); }); }, notify: function (opts) { this.sendAction('notify', opts); } } });
Add Sublime Text 3 support
from __future__ import print_function import sublime, sublime_plugin import subprocess import threading DEBUG = False # Base rsync command template: rsync -arv <local> <remote> base_cmd = "rsync -arv {0} {1}" class SyncOnSaveCommand(sublime_plugin.EventListener): def on_post_save(self, view): """ Sync directory containing the current directory after saving. """ synced_dirs = sublime.load_settings("SyncOnSave.sublime-settings").get("synced_dirs") file_name = view.file_name() for synced_dir in synced_dirs.keys(): if file_name.startswith(synced_dir): # Current file is in a synced directory. remote = synced_dirs[synced_dir]["remote"] cmd = base_cmd.format(synced_dir, remote) if DEBUG: print(cmd) # Execute rsync in a new thread, to avoid noticeable network lag on save. thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True}) thread.daemon = True thread.start()
import sublime, sublime_plugin import subprocess import threading DEBUG = False # Base rsync command template: rsync -arv <local> <remote> base_cmd = "rsync -arv {0} {1}" class SyncOnSaveCommand(sublime_plugin.EventListener): def on_post_save(self, view): """ Sync directory containing the current directory after saving. """ synced_dirs = sublime.load_settings("SyncOnSave.sublime-settings").get("synced_dirs") file_name = view.file_name() for synced_dir in synced_dirs.keys(): if file_name.startswith(synced_dir): # Current file is in a synced directory. remote = synced_dirs[synced_dir]["remote"] cmd = base_cmd.format(synced_dir, remote) if DEBUG: print cmd # Execute rsync in a new thread, to avoid noticeable network lag on save. thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True}) thread.daemon = True thread.start()
Update URL and fix typo in description.
from distutils.core import setup # Keeping all Python code for package in lib directory NAME = 'cplate' VERSION = '0.1' AUTHOR = 'Alexander W Blocker' AUTHOR_EMAIL = 'ablocker@gmail.com' URL = 'https://www.github.com/awblocker/cplate' DESCRIPTION = 'Probabilistic deconvolution for chromatin-structure estimation.' REQUIRES = ['numpy(>=1.6)','scipy(>=0.9)', 'yaml', 'mpi4py'] PACKAGE_DIR = {'': 'lib'} PACKAGES = ['cplate'] SCRIPTS = ('deconvolve_em', 'deconvolve_mcmc', 'detect_em', 'summarise_mcmc', 'summarise_clusters_mcmc', 'summarise_params_mcmc') SCRIPTS = ['scripts/cplate_' + script for script in SCRIPTS] setup(name=NAME, url=URL, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, packages=PACKAGES, package_dir=PACKAGE_DIR, scripts=SCRIPTS, requires=REQUIRES )
from distutils.core import setup # Keeping all Python code for package in lib directory NAME = 'cplate' VERSION = '0.1' AUTHOR = 'Alexander W Blocker' AUTHOR_EMAIL = 'ablocker@gmail.com' URL = 'http://www.awblocker.com' DESCRIPTION = 'Probablistic deconvolution for chromatin-structure estimation.' REQUIRES = ['numpy(>=1.6)','scipy(>=0.9)', 'yaml', 'mpi4py'] PACKAGE_DIR = {'': 'lib'} PACKAGES = ['cplate'] SCRIPTS = ('deconvolve_em', 'deconvolve_mcmc', 'detect_em', 'summarise_mcmc', 'summarise_clusters_mcmc', 'summarise_params_mcmc') SCRIPTS = ['scripts/cplate_' + script for script in SCRIPTS] setup(name=NAME, url=URL, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, packages=PACKAGES, package_dir=PACKAGE_DIR, scripts=SCRIPTS, requires=REQUIRES )
Install the nanomsg.h file, we need it.
from setuptools import setup import generate generate.run() setup( name='nnpy', version='0.1', url='https://github.com/djc/jasinja', license='MIT', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='cffi-based Python bindings for nanomsg', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['nnpy'], package_data={'nnpy': ['*.h']}, install_requires=['cffi'], )
from setuptools import setup import generate generate.run() setup( name='nnpy', version='0.1', url='https://github.com/djc/jasinja', license='MIT', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='cffi-based Python bindings for nanomsg', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['nnpy'], install_requires=['cffi'], )
Fix @OneOf to approve null values
package com.forter.contracts.validation; import com.google.common.base.Preconditions; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; /** * Checks against one of the specified values. * Returns isValid true if the value is null. Use @NotNull to explicitly reject null values. */ public class OneOfValidator implements ConstraintValidator<OneOf, Object>{ private List<String> values; @Override public void initialize(OneOf constraintAnnotation) { values = Arrays.asList(constraintAnnotation.value()); Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation"); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { return value == null || values.contains(String.valueOf(value)); } }
package com.forter.contracts.validation; import com.google.common.base.Preconditions; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; /** * Checks against one of the specified values */ public class OneOfValidator implements ConstraintValidator<OneOf, Object>{ private List<String> values; @Override public void initialize(OneOf constraintAnnotation) { values = Arrays.asList(constraintAnnotation.value()); Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation"); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { return value != null && values.contains(String.valueOf(value)); } }
Improve image size replacement regex (part 2)
// Define search and replace terms for image src link let search = /\/s[0-9]+/g; let replace = '/s512'; function getProfileImageContainer() { // Get profile image containers return $('#channel-header-container'); } function getProfileImage(container) { // Get profile image tag return container.find('img'); } function wrapEnlargeLink() { // Get profile image link let imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag nested within container let imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src URL let src = imageTag.attr('src'); // Replace image pixel value in URL for a larger 512px image src = src.replace(search, replace); // Wrap image tag with a link that points to the larger image $( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" ); } // One-time injection wrapEnlargeLink();
// Define search and replace terms for image src link let search = /\/s[0-9]+/g; let replace = 's512'; function getProfileImageContainer() { // Get profile image containers return $('#channel-header-container'); } function getProfileImage(container) { // Get profile image tag return container.find('img'); } function wrapEnlargeLink() { // Get profile image link let imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag nested within container let imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src URL let src = imageTag.attr('src'); // Replace image pixel value in URL for a larger 512px image src = src.replace(search, replace); // Wrap image tag with a link that points to the larger image $( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" ); } // One-time injection wrapEnlargeLink();
Use 2.4 email iterator syntax so the fixture tests pass python2.4 called its email iterators: email.Iterators. python2.5 uses email.iterators, but to allow cross-version code, Iterators works. Signed-off-by: Jonny Lamb <54cd04502facfcf96b325c60af9b1611ee761860@jonnylamb.com>
# -*- coding: utf-8 -*- import email from DebianChangesBot.utils import quoted_printable def parse_mail(fileobj): headers, body = {}, [] msg = email.message_from_file(fileobj) for k, v in msg.items(): headers[k] = quoted_printable(v).replace('\n', '').strip() for line in email.Iterators.body_line_iterator(msg): line = unicode(line, 'utf-8', 'replace').replace('\n', '') body.append(line) # Merge lines joined with "=\n" i = len(body) - 1 while i > 0: i -= 1 prev = body[i] if len(prev) == 74 and prev.endswith('='): body[i] = body[i][:-1] + body[i + 1] del body[i + 1] # Remove =20 from end of lines i = 0 while i < len(body): if body[i].endswith('=20'): body[i] = body[i][:-3] + ' ' i += 1 return headers, body
# -*- coding: utf-8 -*- import email from DebianChangesBot.utils import quoted_printable def parse_mail(fileobj): headers, body = {}, [] msg = email.message_from_file(fileobj) for k, v in msg.items(): headers[k] = quoted_printable(v).replace('\n', '').strip() for line in email.iterators.body_line_iterator(msg): line = unicode(line, 'utf-8', 'replace').replace('\n', '') body.append(line) # Merge lines joined with "=\n" i = len(body) - 1 while i > 0: i -= 1 prev = body[i] if len(prev) == 74 and prev.endswith('='): body[i] = body[i][:-1] + body[i + 1] del body[i + 1] # Remove =20 from end of lines i = 0 while i < len(body): if body[i].endswith('=20'): body[i] = body[i][:-3] + ' ' i += 1 return headers, body
Destroy any old bind, makes this function repeat-callable
function hook_menu(){ $.contextMenu('destroy','.feeder_entry'); $.contextMenu({ selector: '.feeder_entry', callback: function(key, options) { if(key == 'gallery'){ var id = $(this).attr('specie_id'); var folder = ''; $.each(collection_data.species,function(){ if(this.id == id){ folder = this.name.replace(/ /g,'_').replace(/\./g,'').toLowerCase(); console.log(this); window.open("http://soundspawn.com/browser.php?p="+folder); } }); console.log(this); } }, items: { "gallery": {name: "Gallery", icon: "quit"}, } }); }
function hook_menu(){ $.contextMenu({ selector: '.feeder_entry', callback: function(key, options) { if(key == 'gallery'){ var id = $(this).attr('specie_id'); var folder = ''; $.each(collection_data.species,function(){ if(this.id == id){ folder = this.name.replace(/ /g,'_').replace(/\./g,'').toLowerCase(); console.log(this); window.open("http://soundspawn.com/browser.php?p="+folder); } }); console.log(this); } }, items: { "gallery": {name: "Gallery", icon: "quit"}, } }); }
Check for safe_mode before passing 5th parameter to mail()
<?php /* Invokes the mail() function in Swift Mailer. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //@require 'Swift/Transport/MailInvoker.php'; /** * This is the implementation class for {@link Swift_Transport_MailInvoker}. * * @package Swift * @subpackage Transport * @author Chris Corbyn */ class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker { /** * Send mail via the mail() function. * * This method takes the same arguments as PHP mail(). * * @param string $to * @param string $subject * @param string $body * @param string $headers * @param string $extraParams * * @return boolean */ public function mail($to, $subject, $body, $headers = null, $extraParams = null) { if (!ini_get('safe_mode')) { return mail($to, $subject, $body, $headers, $extraParams); } else { return mail($to, $subject, $body, $headers); } } }
<?php /* Invokes the mail() function in Swift Mailer. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //@require 'Swift/Transport/MailInvoker.php'; /** * This is the implementation class for {@link Swift_Transport_MailInvoker}. * * @package Swift * @subpackage Transport * @author Chris Corbyn */ class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker { /** * Send mail via the mail() function. * * This method takes the same arguments as PHP mail(). * * @param string $to * @param string $subject * @param string $body * @param string $headers * @param string $extraParams * * @return boolean */ public function mail($to, $subject, $body, $headers = null, $extraParams = null) { return mail($to, $subject, $body, $headers, $extraParams); } }
Add additional condition to transaction time PDF test
package com.github.rnowling.bps.datagenerator.generators.transaction; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestTransactionTimePDF { @Test public void testProbability() throws Exception { TransactionTimePDF pdf = new TransactionTimePDF(); assertEquals(pdf.probability(0.5, 0.75), 0.0, 0.000001); assertEquals(pdf.probability(0.5, 0.5), 1.0, 0.000001); assertEquals(pdf.probability(0.75, 0.5), 1.0, 0.000001); } @Test public void testFixConditional() throws Exception { TransactionTimePDF pdf = new TransactionTimePDF(); assertEquals(pdf.fixConditional(0.75).probability(0.5), 0.0, 0.000001); assertEquals(pdf.fixConditional(0.5).probability(0.5), 1.0, 0.000001); assertEquals(pdf.fixConditional(0.5).probability(0.75), 1.0, 0.000001); } }
package com.github.rnowling.bps.datagenerator.generators.transaction; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestTransactionTimePDF { @Test public void testProbability() throws Exception { TransactionTimePDF pdf = new TransactionTimePDF(); assertEquals(pdf.probability(0.5, 0.75), 0.0, 0.000001); assertEquals(pdf.probability(0.75, 0.5), 1.0, 0.000001); } @Test public void testFixConditional() throws Exception { TransactionTimePDF pdf = new TransactionTimePDF(); assertEquals(pdf.fixConditional(0.75).probability(0.5), 0.0, 0.000001); assertEquals(pdf.fixConditional(0.5).probability(0.75), 1.0, 0.000001); } }
Select ovh-eu entrypoint for test integration
# Test for one implementation of the interface from unittest import TestCase from lexicon.providers.ovh import Provider from lexicon.common.options_handler import env_auth_options from integration_tests import IntegrationTests # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from integration_tests.IntegrationTests class OvhProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'ovh' domain = 'elogium.net' def _filter_headers(self): return ['X-Ovh-Application', 'X-Ovh-Consumer', 'X-Ovh-Signature'] # Override _test_options to call env_auth_options and then import auth config from env variables def _test_options(self): cmd_options = env_auth_options(self.provider_name) cmd_options['auth_entrypoint'] = 'ovh-eu' cmd_options['domain'] = self.domain return cmd_options
# Test for one implementation of the interface from unittest import TestCase from lexicon.providers.ovh import Provider from lexicon.common.options_handler import env_auth_options from integration_tests import IntegrationTests # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from integration_tests.IntegrationTests class OvhProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'ovh' domain = 'elogium.net' def _filter_headers(self): return ['X-Ovh-Application', 'X-Ovh-Consumer', 'X-Ovh-Signature'] # Override _test_options to call env_auth_options and then import auth config from env variables def _test_options(self): cmd_options = env_auth_options(self.provider_name) cmd_options['domain'] = self.domain return cmd_options
Integrate AlertsCtrl with CreateCtrl controller
/** * Create Controller */ angular .module('RDash') .controller('CreateCtrl', ['$scope', '$http', CreateCtrl]); function CreateCtrl($scope, $http) { $scope.sendPost = function() { var payload = { meta: { project: $scope.project, module: $scope.module, name: $scope.name }, unikernel: $scope.unikernel, config: $scope.config, backend: $scope.backend }; $http.post("http://localhost:5000/api/unikernel/create", payload).success(function(data, status) { $scope.addAlert('success', '[code ' + data.code + '] [ID ' + data._id + '] ' + data.message); }).error(function(data, status) { $scope.addAlert('danger', '[code ' + data.code + '] ' + data.message); }); }; }
/** * Create Controller */ angular .module('RDash') .controller('CreateCtrl', ['$scope', '$http', CreateCtrl]); function CreateCtrl($scope, $http) { $scope.sendPost = function() { var payload = { meta: { project: $scope.project, module: $scope.module, name: $scope.name }, unikernel: $scope.unikernel, config: $scope.config, backend: $scope.backend }; $http.post("http://localhost:5000/api/unikernel/create", payload).success(function(data, status) { alert(JSON.stringify(data)); }).error(function(data, status) { alert(JSON.stringify(data)); }); }; }
Add comment to undefined sender
var logger = require('log4js').getLogger('vaildMessage'); var nconf = require('nconf'); nconf.file('bots', __dirname + '/../config/bots.json') .file('receviers', __dirname + '/../config/receivers.json') .file('senders', __dirname + '/../config/senders.json'); function vaildMessage(receiver,message,botname,sender,password){ //If miss message, return error code 369 if(message === undefined){ return {error:369}; } //If receiver not found, return error code 333 if(nconf.get(receiver) === undefined){ return {error:333}; } //If sender not found, return error code 380 if(nconf.get(sender) === undefined){ return {error:380}; } //If bot not found, return error code 360 if(nconf.get(botname) === undefined){ return {error:360}; } //If password missmatch, return error code 361 if(password !== nconf.get(sender).password1 && password !== nconf.get(sender).password2){ return {error:361}; } //If there are not any error, return null error return {error:null}; } module.exports = { 'vaildMessage':vaildMessage };
var logger = require('log4js').getLogger('vaildMessage'); var nconf = require('nconf'); nconf.file('bots', __dirname + '/../config/bots.json') .file('receviers', __dirname + '/../config/receivers.json') .file('senders', __dirname + '/../config/senders.json'); function vaildMessage(receiver,message,botname,sender,password){ //If miss message, return error code 369 if(message === undefined){ return {error:369}; } //If receiver not found, return error code 333 if(nconf.get(receiver) === undefined){ return {error:333}; } if(nconf.get(sender) === undefined){ return {error:380}; } //If bot not found, return error code 360 if(nconf.get(botname) === undefined){ return {error:360}; } //If password missmatch, return error code 361 if(password !== nconf.get(sender).password1 && password !== nconf.get(sender).password2){ return {error:361}; } } module.exports = { 'vaildMessage':vaildMessage };
Fix the version string generation when not a final or RC release.
# The version of Review Board. # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (1, 1, 0, 'alpha', 1, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (VERSION[3], VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5]
# The version of Review Board. # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (1, 1, 0, 'alpha', 1, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (release_tag, VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5]
Allow multiple paths for CLI Resolves #60
#!/usr/bin/env node 'use strict'; var program = require('commander'), meta = require('../package.json'), lint = require('../index'); var configPath, ignores, configOptions = {}; var detectPattern = function (pattern) { var detects, formatted; detects = lint.lintFiles(pattern, configOptions, configPath); formatted = lint.format(detects); if (program.verbose) { lint.outputResults(formatted); } if (program.exit) { lint.failOnError(detects); } }; program .version(meta.version) .usage('[options] <pattern>') .option('-c, --config [path]', 'path to custom config file') .option('-i, --ignore [pattern]', 'pattern to ignore. For multiple ignores, separate each pattern by `, `') .option('-q, --no-exit', 'do not exit on errors') .option('-v, --verbose', 'verbose output') .parse(process.argv); if (program.config && program.config !== true) { configPath = program.config; } if (program.ignore && program.ignore !== true) { ignores = program.ignore.split(', '); configOptions = { 'files': { 'ignore': ignores } }; } if (program.args.length === 0) { detectPattern(null); } else { program.args.forEach(function (path) { detectPattern(path); }); }
#!/usr/bin/env node 'use strict'; var program = require('commander'), meta = require('../package.json'), lint = require('../index'); var detects, formatted, configPath, ignores, configOptions = {}; program .version(meta.version) .usage('[options] <pattern>') .option('-c, --config [path]', 'path to custom config file') .option('-i, --ignore [pattern]', 'pattern to ignore. For multiple ignores, separate each pattern by `, `') .option('-q, --no-exit', 'do not exit on errors') .option('-v, --verbose', 'verbose output') .parse(process.argv); if (program.config && program.config !== true) { configPath = program.config; } if (program.ignore && program.ignore !== true) { ignores = program.ignore.split(', '); configOptions = { 'files': { 'ignore': ignores } }; } detects = lint.lintFiles(program.args[0], configOptions, configPath); formatted = lint.format(detects); if (program.verbose) { lint.outputResults(formatted); } if (program.exit) { lint.failOnError(detects); }
Disable root-token head changes when not editing
"use strict"; angular.module('arethusa.core').directive('rootToken', [ 'state', 'depTree', function(state, depTree) { return { restrict: 'A', scope: {}, link: function(scope, element, attrs) { function apply(fn) { scope.$apply(fn()); } var changeHeads = depTree.mode === 'editor'; element.bind('click', function() { apply(function() { if (changeHeads) { state.handleChangeHead('0000', 'click'); state.deselectAll(); } }); }); element.bind('mouseenter', function () { apply(function() { element.addClass('hovered'); }); }); element.bind('mouseleave', function () { apply(function() { element.removeClass('hovered'); }); }); } }; } ]);
"use strict"; angular.module('arethusa.core').directive('rootToken', [ 'state', function(state) { return { restrict: 'A', scope: {}, link: function(scope, element, attrs) { function apply(fn) { scope.$apply(fn()); } element.bind('click', function() { apply(function() { state.handleChangeHead('0000', 'click'); state.deselectAll(); }); }); element.bind('mouseenter', function () { apply(function() { element.addClass('hovered'); }); }); element.bind('mouseleave', function () { apply(function() { element.removeClass('hovered'); }); }); } }; } ]);
Add resource for listing teams
(function(){ var app = angular.module('ng-attendance', ['ngResource', 'ui.router']); app.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('dev_list', { url: "/", templateUrl: '/static/html/dev_list.html', controller: 'DevListController', controllerAs: 'dev_list' }) .state('dev_detail', { url: '/:id', templateUrl: '/static/html/dev_detail.html', controller: 'DevDetailController', controllerAs: 'dev_detail' }); }); app.factory("Developer", function($resource) { return $resource("/devs/:id"); }); app.factory("Team", function($resource) { return $resource("/teams"); }); app.controller('DevListController', function(Developer){ controller = this; Developer.query(function(data) { controller.devs = data; }); }); app.controller('DevDetailController', function($stateParams, Developer){ console.log($stateParams); this.dev = Developer.get({id: $stateParams.id}); }); })();
(function(){ var app = angular.module('ng-attendance', ['ngResource', 'ui.router']); app.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('dev_list', { url: "/", templateUrl: '/static/html/dev_list.html', controller: 'DevListController', controllerAs: 'dev_list' }) .state('dev_detail', { url: '/:id', templateUrl: '/static/html/dev_detail.html', controller: 'DevDetailController', controllerAs: 'dev_detail' }); }); app.factory("Developer", function($resource) { return $resource("/devs/:id"); }); app.controller('DevListController', function(Developer){ controller = this; console.log("dev list"); Developer.query(function(data) { controller.devs = data; }); }); app.controller('DevDetailController', function($stateParams, Developer){ console.log($stateParams); this.dev = Developer.get({id: $stateParams.id}); }); })();
Set port by environment variable
import recommender import os from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('template.html') @app.route('/graph') def my_link(): # here we want to get the value of user (i.e. ?user=some-value) seed = request.args.get('seed') nsfw = bool(request.args.get('nsfw')) breadth = int(request.args.get('breadth')) depth = int(request.args.get('depth')) rec = recommender.Recommender(breadth, depth, nsfw) rec.load_dataset() # Graph parameters rec.output_path = 'static' (result, msg) = rec.generate_graph(seed, True) if result == 'Sucess': filename = msg html = "<img src='" + filename + "'></img>" else: html = msg return html if __name__ == '__main__': port = int(os.environ.get('PORT',5000)) app.run(host='0.0.0.0', port=port)
import recommender from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('template.html') @app.route('/graph') def my_link(): # here we want to get the value of user (i.e. ?user=some-value) seed = request.args.get('seed') nsfw = bool(request.args.get('nsfw')) breadth = int(request.args.get('breadth')) depth = int(request.args.get('depth')) rec = recommender.Recommender(breadth, depth, nsfw) rec.load_dataset() # Graph parameters rec.output_path = 'static' (result, msg) = rec.generate_graph(seed, True) if result == 'Sucess': filename = msg html = "<img src='" + filename + "'></img>" else: html = msg return html if __name__ == '__main__': app.run(debug=True)
Use codereview.chromium.org instead of chromiumcodereview.appspot.com in extensions doc script. BUG=273810 R=kalman@chromium.org, kalman Review URL: https://codereview.chromium.org/24980005 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@225762 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2012 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. GITHUB_URL = 'https://api.github.com/repos/GoogleChrome/chrome-app-samples' NEW_GITHUB_URL = 'https://api.github.com/repos' GITHUB_BASE = 'https://github.com/GoogleChrome/chrome-app-samples/tree/master' RAW_GITHUB_BASE = ('https://github.com/GoogleChrome/chrome-app-samples/raw/' 'master') OMAHA_PROXY_URL = 'http://omahaproxy.appspot.com/json' OMAHA_DEV_HISTORY = ('http://omahaproxy.appspot.com/history?channel=dev' '&os=win&json=1') SVN_URL = 'http://src.chromium.org/chrome' VIEWVC_URL = 'http://src.chromium.org/viewvc/chrome' EXTENSIONS_SAMPLES = ('http://src.chromium.org/viewvc/chrome/trunk/src/chrome/' 'common/extensions/docs/examples') CODEREVIEW_SERVER = 'https://codereview.chromium.org'
# Copyright (c) 2012 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. GITHUB_URL = 'https://api.github.com/repos/GoogleChrome/chrome-app-samples' NEW_GITHUB_URL = 'https://api.github.com/repos' GITHUB_BASE = 'https://github.com/GoogleChrome/chrome-app-samples/tree/master' RAW_GITHUB_BASE = ('https://github.com/GoogleChrome/chrome-app-samples/raw/' 'master') OMAHA_PROXY_URL = 'http://omahaproxy.appspot.com/json' OMAHA_DEV_HISTORY = ('http://omahaproxy.appspot.com/history?channel=dev' '&os=win&json=1') SVN_URL = 'http://src.chromium.org/chrome' VIEWVC_URL = 'http://src.chromium.org/viewvc/chrome' EXTENSIONS_SAMPLES = ('http://src.chromium.org/viewvc/chrome/trunk/src/chrome/' 'common/extensions/docs/examples') CODEREVIEW_SERVER = 'https://chromiumcodereview.appspot.com'
Add license statement to test file.
// Copyright (c) 2014 David R. Jenni. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "testing" ) type offsetTest struct { data []byte offset int byteOffset int } var offsetTests = []offsetTest{ offsetTest{[]byte("abcdef"), 0, 0}, offsetTest{[]byte("abcdef"), 1, 1}, offsetTest{[]byte("abcdef"), 5, 5}, offsetTest{[]byte("日本語def"), 0, 0}, offsetTest{[]byte("日本語def"), 1, 3}, offsetTest{[]byte("日本語def"), 5, 11}, } func TestByteOffset(t *testing.T) { for _, test := range offsetTests { off, err := byteOffset(bytes.NewReader(test.data), test.offset) if err != nil { t.Errorf("got error %v", err) } if off != test.byteOffset { t.Errorf("expected byte offset %d, got %d", test.byteOffset, off) } } }
package main import ( "bytes" "testing" ) type offsetTest struct { data []byte offset int byteOffset int } var offsetTests = []offsetTest{ offsetTest{[]byte("abcdef"), 0, 0}, offsetTest{[]byte("abcdef"), 1, 1}, offsetTest{[]byte("abcdef"), 5, 5}, offsetTest{[]byte("日本語def"), 0, 0}, offsetTest{[]byte("日本語def"), 1, 3}, offsetTest{[]byte("日本語def"), 5, 11}, } func TestByteOffset(t *testing.T) { for _, test := range offsetTests { off, err := byteOffset(bytes.NewReader(test.data), test.offset) if err != nil { t.Errorf("got error %v", err) } if off != test.byteOffset { t.Errorf("expected byte offset %d, got %d", test.byteOffset, off) } } }
Remove the leading '.' in the entryModule path
'use strict'; const webpackConfig = require('./webpack.config.js'); const loaders = require('./webpack/loaders'); const AotPlugin = require('@ngtools/webpack').AotPlugin; const ENV = process.env.npm_lifecycle_event; const JiT = ENV === 'build:jit'; webpackConfig.module.rules = [ loaders.tslint, loaders.ts, loaders.html, loaders.globalCss, loaders.localCss, loaders.svg, loaders.eot, loaders.woff, loaders.woff2, loaders.ttf, ]; webpackConfig.plugins = webpackConfig.plugins.concat([ new AotPlugin({ tsConfigPath: './tsconfig-aot.json', entryModule: 'src/app/app.module#AppModule', }), ]); if (!JiT) { console.log('AoT: True'); } module.exports = webpackConfig;
'use strict'; const webpackConfig = require('./webpack.config.js'); const loaders = require('./webpack/loaders'); const AotPlugin = require('@ngtools/webpack').AotPlugin; const ENV = process.env.npm_lifecycle_event; const JiT = ENV === 'build:jit'; webpackConfig.module.rules = [ loaders.tslint, loaders.ts, loaders.html, loaders.globalCss, loaders.localCss, loaders.svg, loaders.eot, loaders.woff, loaders.woff2, loaders.ttf, ]; webpackConfig.plugins = webpackConfig.plugins.concat([ new AotPlugin({ tsConfigPath: './tsconfig-aot.json', entryModule: './src/app/app.module#AppModule', }), ]); if (!JiT) { console.log('AoT: True'); } module.exports = webpackConfig;
Add 'shared_targets' only when it doesn't exist Add existence check before actually create it. Change-Id: I96946f736d7263f80f7ad24f8cbbc9a09eb3cc63
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, Table def upgrade(migrate_engine): """Add shared_targets column to Volumes.""" meta = MetaData() meta.bind = migrate_engine volumes = Table('volumes', meta, autoload=True) # NOTE(jdg): We use a default of True because it's harmless for a device # that does NOT use shared_targets to be treated as if it does if not hasattr(volumes.c, 'shared_targets'): volumes.create_column(Column('shared_targets', Boolean, default=True))
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, Table def upgrade(migrate_engine): """Add shared_targets column to Volumes.""" meta = MetaData() meta.bind = migrate_engine volumes = Table('volumes', meta, autoload=True) # NOTE(jdg): We use a default of True because it's harmless for a device # that does NOT use shared_targets to be treated as if it does shared_targets = Column('shared_targets', Boolean, default=True) volumes.create_column(shared_targets)
Allow ajax in sandboxed iframes? yay!
;(function() { now.ready(function() { now.setUrl = function(url) { console.log('Loading url in iframe'); $('#container').html( $('<iframe>', {sandbox: 'allow-same-origin', src: url}) ); }; now.setImage = function(url) { console.log('Loading image'); $('#container').html( $('<div class="imgbg"/>').css({ 'background-image': 'url(' + url + ')' }) ); }; now.reset = function() { console.log('reset'); $('#container').html(''); }; }); function resize() { $('#container').css({ width: window.innerWidth, height: window.innerHeight }); } $(function() { $(window).on('resize', resize); resize(); $(document).keyup(function(e) { if (e.keyCode == 27) { // Esc now.reset(); } }); }); })();
;(function() { now.ready(function() { now.setUrl = function(url) { console.log('Loading url in iframe'); $('#container').html( $('<iframe>', {sandbox: true, src: url}) ); }; now.setImage = function(url) { console.log('Loading image'); $('#container').html( $('<div class="imgbg"/>').css({ 'background-image': 'url(' + url + ')' }) ); }; now.reset = function() { console.log('reset'); $('#container').html(''); }; }); function resize() { $('#container').css({ width: window.innerWidth, height: window.innerHeight }); } $(function() { $(window).on('resize', resize); resize(); $(document).keyup(function(e) { if (e.keyCode == 27) { // Esc now.reset(); } }); }); })();
CHANGE mnc route to POST message
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import http from odoo.http import request class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['POST'], csrf=False) def sms_notification(self, **parameters): sms = request.env['sms.notification'].sudo().create({ 'instance': parameters.get('instance'), 'sender': parameters.get('sender'), 'operator': parameters.get('operator'), 'service': parameters.get('service'), 'language': parameters.get('language'), 'date': parameters.get('receptionDate'), 'uuid': parameters.get('requestUid'), 'text': parameters.get('text'), }) return sms.run_service()
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import http from odoo.http import request class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'], csrf=False) def sms_notification(self, **parameters): sms = request.env['sms.notification'].sudo().create({ 'instance': parameters.get('instance'), 'sender': parameters.get('sender'), 'operator': parameters.get('operator'), 'service': parameters.get('service'), 'language': parameters.get('language'), 'date': parameters.get('receptionDate'), 'uuid': parameters.get('requestUid'), 'text': parameters.get('text'), }) return sms.run_service()
Use sys.stdin if not other streams found for all()
"""Module to handle streams of text""" import os import sys import contextlib from itertools import chain from six import StringIO from pysyte import iteration from pysyte.platforms import get_clipboard_data def clipboard_stream(name=None): stream = StringIO(get_clipboard_data()) stream.name = name or '<clipboard>' return stream @contextlib.contextmanager def clipin(): yield clipboard_stream() def arg_paths(): return [a for a in sys.argv[1:] if os.path.isfile(a)] def arg_files(): """yield streams to all arg.isfile()""" for path in arg_paths(): yield open(path) def all(): some = False for path in arg_paths(): yield open(path) some = True if not some: yield sys.stdin def first(): return iteration.first(all()) def last(): return iteration.last(all()) def any(): try: stream = iteration.first(arg_files()) if stream: return arg_files() except ValueError: return iter([clipboard_stream(), sys.stdin]) def first_file(): try: return iteration.first(arg_files()) except ValueError: return None def full_lines(stream): for line in stream.readlines(): stripped = line.rstrip() if stripped: yield stripped
"""Module to handle streams of text""" import os import sys import contextlib from itertools import chain from six import StringIO from pysyte import iteration from pysyte.platforms import get_clipboard_data def clipboard_stream(name=None): stream = StringIO(get_clipboard_data()) stream.name = name or '<clipboard>' return stream @contextlib.contextmanager def clipin(): yield clipboard_stream() def arg_paths(): return [a for a in sys.argv[1:] if os.path.isfile(a)] def arg_files(): """yield streams to all arg.isfile()""" for path in arg_paths(): yield open(path) def all(): more = iter([clipboard_stream(), sys.stdin]) return chain(arg_files(), more) def first(): return iteration.first(all()) def last(): return iteration.last(all()) def any(): try: stream = iteration.first(arg_files()) if stream: return arg_files() except ValueError: return iter([clipboard_stream(), sys.stdin]) def first_file(): try: return iteration.first(arg_files()) except ValueError: return None def full_lines(stream): for line in stream.readlines(): stripped = line.rstrip() if stripped: yield stripped
Put module name into a variable
'use strict'; var angular = require('angular'); var bluebird = require('bluebird'); var MODULE_NAME = 'mwl.bluebird'; angular .module(MODULE_NAME, []) .constant('Bluebird', bluebird) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { return Bluebird.props(promises); } else { return originalAll.call(Bluebird, promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); module.exports = MODULE_NAME;
'use strict'; var angular = require('angular'); var bluebird = require('bluebird'); angular .module('mwl.bluebird', []) .constant('Bluebird', bluebird) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { return Bluebird.props(promises); } else { return originalAll.call(Bluebird, promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); module.exports = 'mwl.bluebird';
TST: Check mean and STD of returned ECG signal
from __future__ import division, print_function, absolute_import import pytest from numpy.testing import assert_equal, assert_allclose, assert_almost_equal from scipy._lib._numpy_compat import suppress_warnings from scipy.misc import pade, logsumexp, face, ascent, electrocardiogram from scipy.special import logsumexp as sc_logsumexp def test_logsumexp(): # make sure logsumexp can be imported from either scipy.misc or # scipy.special with suppress_warnings() as sup: sup.filter(DeprecationWarning, "`logsumexp` is deprecated") assert_allclose(logsumexp([0, 1]), sc_logsumexp([0, 1]), atol=1e-16) def test_pade(): # make sure scipy.misc.pade exists with suppress_warnings() as sup: sup.filter(DeprecationWarning, "`pade` is deprecated") pade([1, 2], 1) def test_face(): assert_equal(face().shape, (768, 1024, 3)) def test_ascent(): assert_equal(ascent().shape, (512, 512)) def test_electrocardiogram(): # Test shape, dtype and stats of signal ecg = electrocardiogram() assert ecg.dtype == float assert_equal(ecg.shape, (108000,)) assert_almost_equal(ecg.mean(), -0.16510875) assert_almost_equal(ecg.std(), 0.5992473991177294)
from __future__ import division, print_function, absolute_import import pytest from numpy.testing import assert_equal, assert_allclose from scipy._lib._numpy_compat import suppress_warnings from scipy.misc import pade, logsumexp, face, ascent, electrocardiogram from scipy.special import logsumexp as sc_logsumexp def test_logsumexp(): # make sure logsumexp can be imported from either scipy.misc or # scipy.special with suppress_warnings() as sup: sup.filter(DeprecationWarning, "`logsumexp` is deprecated") assert_allclose(logsumexp([0, 1]), sc_logsumexp([0, 1]), atol=1e-16) def test_pade(): # make sure scipy.misc.pade exists with suppress_warnings() as sup: sup.filter(DeprecationWarning, "`pade` is deprecated") pade([1, 2], 1) def test_face(): assert_equal(face().shape, (768, 1024, 3)) def test_ascent(): assert_equal(ascent().shape, (512, 512)) def test_electrocardiogram(): # Test shape and dtype of signal ecg = electrocardiogram() assert_equal(ecg.shape, (108000,)) assert ecg.dtype == float
[iso-core] Use sequelize.import now that eval is enabled
const fs = require('fs'); const path = require('path'); function loadModels(Sequelize, sequelize, modelsPath, {schema} = {}) { const db = {}; const modelsDirectory = path.join(__dirname, modelsPath) for (const filename of fs.readdirSync(modelsDirectory)) { if (filename.endsWith('.js')) { let model = sequelize.import(path.join(modelsDirectory, filename)); if (schema) { model = model.schema(schema); } db[model.name[0].toUpperCase() + model.name.substr(1)] = model; } } Object.keys(db).forEach((modelName) => { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); return db; } module.exports = loadModels
const fs = require('fs'); const path = require('path'); function loadModels(Sequelize, sequelize, modelsPath, {schema} = {}) { const db = {}; const modelsDirectory = path.join(__dirname, modelsPath) for (const filename of fs.readdirSync(modelsDirectory)) { if (filename.endsWith('.js')) { let model = require(path.join(modelsDirectory, filename))(sequelize, Sequelize) // eslint-disable-line if (schema) { model = model.schema(schema); } db[model.name[0].toUpperCase() + model.name.substr(1)] = model; } } Object.keys(db).forEach((modelName) => { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); return db; } module.exports = loadModels
Add on server start up remove messages
if (Meteor.isClient) { Template.messages.rendered = function () { scrollPosition(); }; Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $(".messageBox").prop({ scrollTop: $(".messageBox").prop("scrollHeight") }); }; $(document).ready(function(){ scrollPosition(); }); var sendMessage = function() { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; scrollPosition(); } }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { sendMessage(); } }, 'click #sendMessage': function(event) { sendMessage(); } }; if (Meteor.isServer) { Meteor.startup(function () { Messages.remove({}); }); } }
if (Meteor.isClient) { Template.messages.rendered = function () { scrollPosition(); }; Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $(".messageBox").prop({ scrollTop: $(".messageBox").prop("scrollHeight") }); }; $(document).ready(function(){ scrollPosition(); }); var sendMessage = function() { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; scrollPosition(); } }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { sendMessage(); } }, 'click #sendMessage': function(event) { sendMessage(); } }; if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } }
Drop references from popped classes. git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@704 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
package com.thoughtworks.xstream.core.util; public final class ClassStack { private Class[] stack; private int pointer; public ClassStack(int initialCapacity) { stack = new Class[initialCapacity]; } public void push(Class value) { if (pointer + 1 >= stack.length) { resizeStack(stack.length * 2); } stack[pointer++] = value; } public void popSilently() { stack[--pointer] = null; } public Class pop() { final Class result = stack[--pointer]; stack[pointer] = null; return result; } public Class peek() { return pointer == 0 ? null : stack[pointer - 1]; } public int size() { return pointer; } public Class get(int i) { return stack[i]; } private void resizeStack(int newCapacity) { Class[] newStack = new Class[newCapacity]; System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity)); stack = newStack; } }
package com.thoughtworks.xstream.core.util; public final class ClassStack { private Class[] stack; private int pointer; public ClassStack(int initialCapacity) { stack = new Class[initialCapacity]; } public void push(Class value) { if (pointer + 1 >= stack.length) { resizeStack(stack.length * 2); } stack[pointer++] = value; } public void popSilently() { pointer--; } public Class pop() { return stack[--pointer]; } public Class peek() { return pointer == 0 ? null : stack[pointer - 1]; } public int size() { return pointer; } public Class get(int i) { return stack[i]; } private void resizeStack(int newCapacity) { Class[] newStack = new Class[newCapacity]; System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity)); stack = newStack; } }
Fix PHP notice from the wrong type hint
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Installer\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { $operation_message = $event->getOperation()->__toString(); WP_CLI::log( ' - ' . $operation_message ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) ); } } } }
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Script\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { $operation_message = $event->getOperation()->__toString(); WP_CLI::log( ' - ' . $operation_message ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) ); } } } }
Refactor to more functional style
import createDebug from 'debug'; import { onLoad } from './util'; const debug = createDebug('ms:api'); const partitionArray = (array, size) => array.map((e, i) => (i % size === 0) ? array.slice(i, i + size) : null).filter(e => e); onLoad(() => { $('#create_filter').on('click', () => { const bits = Array.from($('input[type=checkbox]')).reduce((arr, el) => { const $el = $(el); arr[$el.data('index')] = Number($el.is(':checked')); return arr; }, []); const bytes = partitionArray(bits, 8); debug(bits.join('')); debug(bytes.map(x => x.join('')).join(' ')); debug(bytes.map(x => parseInt(x.join(''), 2)).join(' ')); let unsafeFilter = ''; for (let i = 0; i < bytes.length; i++) { const nextByte = bytes[i].join(''); const charCode = parseInt(nextByte.toString(), 2); unsafeFilter += String.fromCharCode(charCode); debug(nextByte, charCode, unsafeFilter); } const filter = btoa(unsafeFilter); debug(filter); window.prompt('Your filter:', filter); }); });
import createDebug from 'debug'; import { onLoad } from './util'; const debug = createDebug('ms:api'); const partitionArray = (array, size) => array.map((e, i) => (i % size === 0) ? array.slice(i, i + size) : null).filter(e => e); onLoad(() => { $('#create_filter').on('click', () => { const checkboxes = $('input[type=checkbox]'); const bits = new Array(checkboxes.length); $.each(checkboxes, (index, item) => { const $item = $(item); const arrayIndex = $item.data('index'); if ($item.is(':checked')) { bits[arrayIndex] = 1; debug($item, arrayIndex); } else { bits[arrayIndex] = 0; } }); const bytes = partitionArray(bits, 8); debug(bits.join('')); debug(bytes.map(x => x.join('')).join(' ')); debug(bytes.map(x => parseInt(x.join(''), 2)).join(' ')); let unsafeFilter = ''; for (let i = 0; i < bytes.length; i++) { const nextByte = bytes[i].join(''); const charCode = parseInt(nextByte.toString(), 2); unsafeFilter += String.fromCharCode(charCode); debug(nextByte, charCode, unsafeFilter); } const filter = btoa(unsafeFilter); debug(filter); window.prompt('Your filter:', filter); }); });
Add 'me' to profile IdentifierError
from ..error import IdentifierError from ..objects.profile import Profile from .base import Base class Profiles(Base): RESOURCE_ID_PREFIX = 'pfl_' def get_resource_object(self, result): return Profile(result, self.client) def get(self, profile_id, **params): if not profile_id or \ (not profile_id.startswith(self.RESOURCE_ID_PREFIX) and not profile_id == 'me'): raise IdentifierError( "Invalid profile ID: '{id}'. A profile ID should start with '{prefix}' " "or it should be 'me'.".format( id=profile_id, prefix=self.RESOURCE_ID_PREFIX) ) return super(Profiles, self).get(profile_id, **params)
from ..error import IdentifierError from ..objects.profile import Profile from .base import Base class Profiles(Base): RESOURCE_ID_PREFIX = 'pfl_' def get_resource_object(self, result): return Profile(result, self.client) def get(self, profile_id, **params): if not profile_id or \ (not profile_id.startswith(self.RESOURCE_ID_PREFIX) and not profile_id == 'me'): raise IdentifierError( "Invalid profile ID: '{id}'. A profile ID should start with '{prefix}'.".format( id=profile_id, prefix=self.RESOURCE_ID_PREFIX) ) return super(Profiles, self).get(profile_id, **params)
Add html title to guide list refs #393
/* globals MarkdownFilePaths: false */ // MarkdownFilePaths are created in run.js and passed through webpack import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Landing from './pages/home/index'; import Guide from './pages/guide/index'; import GuideList from './pages/guideList/index'; import NotFound from './pages/error/index'; import ComingSoon from './pages/comingSoon'; // does not work when passing './content' as an variable const req = require.context('./content', true, /^\.\/.*\.md/); const routesForMarkdownFiles = MarkdownFilePaths.map(path => { const { title, html } = req(`./${path}`); const url = `${path.slice(0, -'.md'.length)}/`; console.log(`[Route generator] file ${path} -> url ${url}`); return <Route key={path} path={url} title={title} docHtml={html} />; }); const routes = ( <Route path="/"> <IndexRoute title="Skygear Documentation" component={Landing} /> <Route path="guides/" title="Guides" component={GuideList} /> <Route path="guide" component={Guide}> {routesForMarkdownFiles} </Route> <Route path="coming-soon/" title="Coming Soon" component={ComingSoon} /> <Route path="*" title="404: Not Found" component={NotFound} /> </Route> ); // Be sure to export the React component so that it can be statically rendered export default routes;
/* globals MarkdownFilePaths: false */ // MarkdownFilePaths are created in run.js and passed through webpack import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Landing from './pages/home/index'; import Guide from './pages/guide/index'; import GuideList from './pages/guideList/index'; import NotFound from './pages/error/index'; import ComingSoon from './pages/comingSoon'; // does not work when passing './content' as an variable const req = require.context('./content', true, /^\.\/.*\.md/); const routesForMarkdownFiles = MarkdownFilePaths.map(path => { const { title, html } = req(`./${path}`); const url = `${path.slice(0, -'.md'.length)}/`; console.log(`[Route generator] file ${path} -> url ${url}`); return <Route key={path} path={url} title={title} docHtml={html} />; }); const routes = ( <Route path="/"> <IndexRoute title="Skygear Documentation" component={Landing} /> <Route path="guides/" component={GuideList} /> <Route path="guide" component={Guide}> {routesForMarkdownFiles} </Route> <Route path="coming-soon/" title="Coming Soon" component={ComingSoon} /> <Route path="*" title="404: Not Found" component={NotFound} /> </Route> ); // Be sure to export the React component so that it can be statically rendered export default routes;
Check path of current page before starting the slider.
// Placeholder manifest file. // the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js' var index = 1; $(document).ready(function() { if (window.location.pathname == "/") { startSlider(); } }); function startSlider() { images = $("#showcase_inner_container > img"); count = images.size(); loop = setInterval( function() { document.getElementById("showcase_inner_container").className = "showcase_img"; $("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)"); if (index == count) { index = 0; document.getElementById("showcase_inner_container").className = "showcase_img_reset"; $("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)"); } index += 1; }, 5000); }
// Placeholder manifest file. // the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js' var index = 1; $(document).ready(function() { startSlider(); }); function startSlider() { images = $("#showcase_inner_container > img"); count = images.size(); loop = setInterval( function() { document.getElementById("showcase_inner_container").className = "showcase_img"; $("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)"); if (index == count) { index = 0; document.getElementById("showcase_inner_container").className = "showcase_img_reset"; $("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)"); } index += 1; }, 5000); }
Make sure the ReadOnly map is made available
package org.realityforge.replicant.client.transport; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class RequestManager { private final Map<String, RequestEntry> _requests = new HashMap<>(); private final Map<String, RequestEntry> _roRequests = Collections.unmodifiableMap( _requests ); private int _requestID; @Nonnull public final RequestEntry newRequestRegistration( @Nullable final String cacheKey, final boolean bulkLoad ) { final RequestEntry entry = new RequestEntry( newRequestID(), cacheKey, bulkLoad ); _requests.put( entry.getRequestID(), entry ); return entry; } @Nullable public final RequestEntry getRequest( @Nonnull final String requestID ) { return _requests.get( requestID ); } public Map<String, RequestEntry> getRequests() { return _roRequests; } public final boolean removeRequest( @Nonnull final String requestID ) { return null != _requests.remove( requestID ); } protected String newRequestID() { return String.valueOf( ++_requestID ); } }
package org.realityforge.replicant.client.transport; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class RequestManager { private final Map<String, RequestEntry> _requests = new HashMap<>(); private final Map<String, RequestEntry> _roRequests = Collections.unmodifiableMap( _requests ); private int _requestID; @Nonnull public final RequestEntry newRequestRegistration( @Nullable final String cacheKey, final boolean bulkLoad ) { final RequestEntry entry = new RequestEntry( newRequestID(), cacheKey, bulkLoad ); _requests.put( entry.getRequestID(), entry ); return entry; } @Nullable public final RequestEntry getRequest( @Nonnull final String requestID ) { return _requests.get( requestID ); } public Map<String, RequestEntry> getRequests() { return _requests; } public final boolean removeRequest( @Nonnull final String requestID ) { return null != _requests.remove( requestID ); } protected String newRequestID() { return String.valueOf( ++_requestID ); } }
Add try block to argv remove statement When running nose-watch withing an environment like django-nose argv doesn't contain any arguments to remove.
import sys from nose.plugins import Plugin from subprocess import Popen class WatchPlugin(Plugin): """ Plugin that use watchdog for continuous tests run. """ name = 'watch' is_watching = False sys = sys def call(self, args): Popen(args).wait() def finalize(self, result): argv = list(self.sys.argv) try: argv.remove('--with-watch') except ValueError: pass watchcmd = 'clear && ' + ' '.join(argv) call_args = ['watchmedo', 'shell-command', '-c', watchcmd, '-R', '-p', '*.py', '.'] try: self.call(call_args) except KeyboardInterrupt: self.sys.stdout.write('\nStopped\n')
import sys from nose.plugins import Plugin from subprocess import Popen class WatchPlugin(Plugin): """ Plugin that use watchdog for continuous tests run. """ name = 'watch' is_watching = False sys = sys def call(self, args): Popen(args).wait() def finalize(self, result): argv = list(self.sys.argv) argv.remove('--with-watch') watchcmd = 'clear && ' + ' '.join(argv) call_args = ['watchmedo', 'shell-command', '-c', watchcmd, '-R', '-p', '*.py', '.'] try: self.call(call_args) except KeyboardInterrupt: self.sys.stdout.write('\nStopped\n')
Make sure JVM doesn't shutdown from command line
package org.obolibrary.robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import py4j.GatewayServer; /** * Starts a gateway server for Py4J to execute ROBOT operations via Python. This class can be used * to start the JVM directly from python using Py4J's `launch_gateway`. * * @author <a href="mailto:rbca.jackson@gmail.com">Becky Jackson</a> */ public class PythonOperation { /** Logger. */ private static final Logger logger = LoggerFactory.getLogger(PythonOperation.class); /** * Run a Gateway Server. * * @param args strings to use as arguments */ public void main(String[] args) { GatewayServer gs = null; try { gs = run(null); } finally { if (gs != null) { gs.shutdown(); } } } /** * Run a Gateway Server. * * @param port port to run JVM on, or null */ public static GatewayServer run(Integer port) { GatewayServer gs; if (port != null) { gs = new GatewayServer(null, port); } else { gs = new GatewayServer(null); } gs.start(); port = gs.getPort(); logger.debug(String.format("JVM started on port %d", port)); return gs; } }
package org.obolibrary.robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import py4j.GatewayServer; /** * Starts a gateway server for Py4J to execute ROBOT operations via Python. This class can be used * to start the JVM directly from python using Py4J's `launch_gateway`. * * @author <a href="mailto:rbca.jackson@gmail.com">Becky Jackson</a> */ public class PythonOperation { /** Logger. */ private static final Logger logger = LoggerFactory.getLogger(PythonOperation.class); /** * Run a Gateway Server. * * @param args strings to use as arguments */ public void main(String[] args) { run(null); } /** * Run a Gateway Server. * * @param port port to run JVM on, or null */ public static void run(Integer port) { GatewayServer gs; if (port != null) { gs = new GatewayServer(null, port); } else { gs = new GatewayServer(null); } try { gs.start(); port = gs.getPort(); logger.debug(String.format("JVM started on port %d", port)); } finally { gs.shutdown(); } } }
Make @AutoValue.Builder builder an interface
package com.veyndan.paper.reddit.post; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.auto.value.AutoValue; @AutoValue public abstract class Flair { public enum Type { LINK, UNDEFINED } @NonNull public abstract Type type(); @Nullable public abstract String text(); @Nullable public abstract Drawable icon(); public abstract int backgroundColor(); public static Builder builder(@ColorInt final int backgroundColor) { return new AutoValue_Flair.Builder() .backgroundColor(backgroundColor) .type(Type.UNDEFINED); } @AutoValue.Builder public interface Builder { Builder type(Type type); Builder text(String text); Builder icon(Drawable icon); Builder backgroundColor(@ColorInt int backgroundColor); Flair build(); } }
package com.veyndan.paper.reddit.post; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.auto.value.AutoValue; @AutoValue public abstract class Flair { public enum Type { LINK, UNDEFINED } @NonNull public abstract Type type(); @Nullable public abstract String text(); @Nullable public abstract Drawable icon(); public abstract int backgroundColor(); public static Builder builder(@ColorInt final int backgroundColor) { return new AutoValue_Flair.Builder() .backgroundColor(backgroundColor) .type(Type.UNDEFINED); } @AutoValue.Builder public abstract static class Builder { public abstract Builder type(Type type); public abstract Builder text(String text); public abstract Builder icon(Drawable icon); public abstract Builder backgroundColor(@ColorInt int backgroundColor); public abstract Flair build(); } }
[security][symfony] Fix fatal error on old symfony versions. PHP Fatal error: Undefined class constant 'ABSOLUTE_URL' in ....
<?php namespace Payum\Core\Bridge\Symfony\Security; use Payum\Core\Registry\StorageRegistryInterface; use Payum\Core\Security\AbstractGenericTokenFactory; use Payum\Core\Storage\StorageInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class TokenFactory extends AbstractGenericTokenFactory { /** * @var \Symfony\Component\Routing\RouterInterface */ protected $urlGenerator; /** * @param UrlGeneratorInterface $urlGenerator * @param StorageInterface $tokenStorage * @param StorageRegistryInterface $storageRegistry * @param string $capturePath * @param string $notifyPath */ public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath) { $this->urlGenerator = $urlGenerator; parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath); } /** * @param string $path * @param array $parameters * * @return string */ protected function generateUrl($path, array $parameters = array()) { return $this->urlGenerator->generate($path, $parameters, true); } }
<?php namespace Payum\Core\Bridge\Symfony\Security; use Payum\Core\Registry\StorageRegistryInterface; use Payum\Core\Security\AbstractGenericTokenFactory; use Payum\Core\Security\TokenInterface; use Payum\Core\Storage\StorageInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class TokenFactory extends AbstractGenericTokenFactory { /** * @var \Symfony\Component\Routing\RouterInterface */ protected $urlGenerator; /** * @param UrlGeneratorInterface $urlGenerator * @param StorageInterface $tokenStorage * @param StorageRegistryInterface $storageRegistry * @param string $capturePath * @param string $notifyPath */ public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath) { $this->urlGenerator = $urlGenerator; parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath); } /** * @param string $path * @param array $parameters * * @return string */ protected function generateUrl($path, array $parameters = array()) { return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } }
Use process.env.PWD to resolve server hook path
#!/usr/bin/env node // Modules var connect = require('connect'), fs = require('fs'), http = require('http'), path = require('path'), serveStatic = require('serve-static'), serveIndex = require('serve-index'); // Variables var app = connect(), hookFile = path.join(process.env.PWD, 'web-server-hook.js'); function main(port, rootPath, indexFile) { var hook = { config: function() {}, postConfig: function() {} }; rootPath = path.resolve(rootPath); if (fs.existsSync(hookFile)) { hook = require(hookFile); } if (undefined !== hook.config) { hook.config(app, port, rootPath); } app.use(serveStatic(rootPath, {'index': [indexFile]})); app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'})); if (undefined !== hook.postConfig) { hook.postConfig(app, port, rootPath); } if (undefined != hook.createServer) { hook.createServer(app, port, rootPath); } else { http.createServer(app).listen(port, function() { console.log('Static server started at http://localhost:%d/', port); }); } } module.exports = main;
#!/usr/bin/env node // Modules var connect = require('connect'), fs = require('fs'), http = require('http'), path = require('path'), serveStatic = require('serve-static'), serveIndex = require('serve-index'); // Variables var app = connect(), hookFile = 'web-server-hook.js'; function main(port, rootPath, indexFile) { var hook = { config: function() {}, postConfig: function() {} }; rootPath = path.resolve(rootPath); if (fs.existsSync(path.resolve(hookFile))) { hook = require('./' + hookFile); } if (undefined !== hook.config) { hook.config(app, port, rootPath); } app.use(serveStatic(rootPath, {'index': [indexFile]})); app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'})); if (undefined !== hook.postConfig) { hook.postConfig(app, port, rootPath); } if (undefined != hook.createServer) { hook.createServer(app, port, rootPath); } else { http.createServer(app).listen(port, function() { console.log('Static server started at http://localhost:%d/', port); }); } } module.exports = main;
Use ast.If not ast.IfExp for if tag
import ast from .library import Library register = Library() @register.tag(name='block') def block(parser, token): token = token.strip() parser.build_method(token, endnodes=['endblock']) return ast.Expr(value=ast.YieldFrom( value=ast.Call( func=ast.Attribute( value=ast.Name(id='self', ctx=ast.Load()), attr=token, ctx=ast.Load() ), args=[ ast.Name(id='context', ctx=ast.Load()), ], keywords=[], starargs=None, kwargs=None ) )) @register.tag(name='if') def do_if(parser, token): code = ast.parse(token, mode='eval') nodelist = list(parser.parse_node(['endif'])) return ast.If(test=code.body, body=nodelist) @register.tag(name='else') def do_else(parser, token=None): return ast.Expr(value=ast.Yield(value=ast.Str(s='')))
import ast from .library import Library register = Library() @register.tag(name='block') def block(parser, token): token = token.strip() parser.build_method(token, endnodes=['endblock']) return ast.YieldFrom( value=ast.Call( func=ast.Attribute( value=ast.Name(id='self', ctx=ast.Load()), attr=token, ctx=ast.Load() ), args=[ ast.Name(id='context', ctx=ast.Load()), ], keywords=[], starargs=None, kwargs=None ) ) @register.tag(name='if') def do_if(parser, token): code = ast.parse(token, mode='eval') nodelist = list(parser.parse_node(['endif'])) return ast.IfExp(test=code.body, body=nodelist) @register.tag(name='else') def do_else(parser, token=None): return ast.Yield(value=ast.Str(s=''))
Include lib/* in the build command
module.exports = function( grunt ) { 'use strict'; // Project configuration. grunt.initConfig( { pkg: grunt.file.readJSON( 'package.json' ), copy: { main: { src: [ 'includes/**', 'lib/**', 'languages/**', 'composer.json', 'CHANGELOG.md', 'LICENSE.txt', 'readme.txt', 'sticky-tax.php' ], dest: 'dist/' }, }, makepot: { target: { options: { domainPath: '/languages', mainFile: 'sticky-tax.php', potFilename: 'sticky-tax.pot', potHeaders: { poedit: true, 'x-poedit-keywordslist': true }, type: 'wp-plugin', updateTimestamp: false } } }, } ); grunt.loadNpmTasks( 'grunt-contrib-copy' ); grunt.loadNpmTasks( 'grunt-wp-i18n' ); grunt.registerTask( 'build', [ 'i18n', 'copy' ] ); grunt.registerTask( 'i18n', [ 'makepot' ] ); grunt.util.linefeed = '\n'; };
module.exports = function( grunt ) { 'use strict'; // Project configuration. grunt.initConfig( { pkg: grunt.file.readJSON( 'package.json' ), copy: { main: { src: [ 'includes/**', 'languages/**', 'composer.json', 'CHANGELOG.md', 'LICENSE.txt', 'readme.txt', 'sticky-tax.php' ], dest: 'dist/' }, }, makepot: { target: { options: { domainPath: '/languages', mainFile: 'sticky-tax.php', potFilename: 'sticky-tax.pot', potHeaders: { poedit: true, 'x-poedit-keywordslist': true }, type: 'wp-plugin', updateTimestamp: false } } }, } ); grunt.loadNpmTasks( 'grunt-contrib-copy' ); grunt.loadNpmTasks( 'grunt-wp-i18n' ); grunt.registerTask( 'build', [ 'i18n', 'copy' ] ); grunt.registerTask( 'i18n', [ 'makepot' ] ); grunt.util.linefeed = '\n'; };
Add user_id index to conversions table - To speed up search when finding new/renew conversions
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddUserIdToConversionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('conversions', function (Blueprint $table) { $table->string('user_id')->after('article_id')->nullable(); $table->index(['user_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('conversions', function (Blueprint $table) { $table->dropColumn('user_id'); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddUserIdToConversionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('conversions', function (Blueprint $table) { $table->string('user_id')->after('article_id')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('conversions', function (Blueprint $table) { $table->dropColumn('user_id'); }); } }
Add docstring to Post class
""" pyblogit.posts ~~~~~~~~~~~~~~ This module contains the data model to represent blog posts and methods to manipulate it. """ class post(object): """The post data model""" def __init__(self, post_id, title, url, author, content, images, labels, status): self._post_id = post_id self._title = title self._url = url self._author = author self._content = content self._images = images self._labels = labels @property def post_id(self): return self._post_id @property def title(self): return self._title @property def url(self): return self._url @property def author(self): return self._author @property def content(self): return self._content @property def images(self): return self._images @property def labels(self): return self._labels
""" pyblogit.posts ~~~~~~~~~~~~~~ This module contains the data model to represent blog posts and methods to manipulate it. """ class post(object): def __init__(self, post_id, title, url, author, content, images, labels, status): self._post_id = post_id self._title = title self._url = url self._author = author self._content = content self._images = images self._labels = labels @property def post_id(self): return self._post_id @property def title(self): return self._title @property def url(self): return self._url @property def author(self): return self._author @property def content(self): return self._content @property def images(self): return self._images @property def labels(self): return self._labels
Add Ember 1.13 to the test matrix
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-1.13', dependencies: { 'ember': '1.13.8' }, resolutions: { 'ember': '1.13.8' } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
Add a noop pipe to ensure end is called
import gulp from 'gulp'; import es from 'event-stream'; import nugetRestore from 'gulp-nuget-restore'; export default { /** * Task name * @type {String} */ name: 'sitecore:nuget-restore', /** * Task description * @type {String} */ description: 'Restore all nuget packages for solution.', /** * Task default configuration * @type {Object} */ config: { deps: [], }, /** * Task help options * @type {Object} */ help: { 'solution, -s': 'Solution file path', }, /** * Task function * @param {object} config * @param {Function} end * @param {Function} error */ fn(config, end, error) { if (!config.solution) { error('A solution file path was not set.'); return; } gulp.src(config.solution) .pipe(nugetRestore()) .pipe(es.through(() => {})) .on('end', end); }, };
import gulp from 'gulp'; import nugetRestore from 'gulp-nuget-restore'; export default { /** * Task name * @type {String} */ name: 'sitecore:nuget-restore', /** * Task description * @type {String} */ description: 'Restore all nuget packages for solution.', /** * Task default configuration * @type {Object} */ config: { deps: [], }, /** * Task help options * @type {Object} */ help: { 'solution, -s': 'Solution file path', }, /** * Task function * @param {object} config * @param {Function} end * @param {Function} error */ fn(config, end, error) { if (!config.solution) { error('A solution file path was not set.'); return; } gulp.src(config.solution) .pipe(nugetRestore()) .on('end', end); }, };
Configure webpack dev server for pushState
var path = require('path') module.exports = { devtool: '#eval-source-map', entry: { app: ['./src/index.js'] }, output: { path: path.resolve(__dirname, 'public/assets'), publicPath: 'assets/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] }, { test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] }, devServer: { historyApiFallback: true } }
var path = require('path') module.exports = { devtool: '#eval-source-map', entry: { app: ['./src/index.js'] }, output: { path: path.resolve(__dirname, 'public/assets'), publicPath: 'assets/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] }, { test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] } }
Use atcHandler.PipelineConfig instead of GetConfig [#105155444] Signed-off-by: Evan Short <5b1db704470d35a058f1f4a9e1a5a172a6ea69d3@pivotal.io>
package atcclient import "github.com/concourse/atc" //go:generate counterfeiter . Handler type Handler interface { // AbortBuild() // BuildEvents() // CreateBuild() // CreatePipe() // DeletePipeline() // DownloadCLI() // HijackContainer() // ListContainer() // ListJobInputs() // ReadPipe() // SaveConfig() // WritePipe() AllBuilds() ([]atc.Build, error) Build(buildID string) (atc.Build, error) Job(pipelineName, jobName string) (atc.Job, error) JobBuild(pipelineName, jobName, buildName string) (atc.Build, error) PipelineConfig(pipelineName string) (atc.Config, error) } type AtcHandler struct { client Client } func NewAtcHandler(c Client) AtcHandler { return AtcHandler{client: c} }
package atcclient import "github.com/concourse/atc" //go:generate counterfeiter . Handler type Handler interface { // AbortBuild() // BuildEvents() // CreateBuild() // CreatePipe() // DeletePipeline() // DownloadCLI() // GetConfig() // HijackContainer() // ListContainer() // ListJobInputs() // ReadPipe() // SaveConfig() // WritePipe() AllBuilds() ([]atc.Build, error) Build(buildID string) (atc.Build, error) Job(pipelineName, jobName string) (atc.Job, error) JobBuild(pipelineName, jobName, buildName string) (atc.Build, error) } type AtcHandler struct { client Client } func NewAtcHandler(c Client) AtcHandler { return AtcHandler{client: c} }
Fix minor formatting things, remove debug message
package org.usfirst.frc4915.debuggersystem; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.LogRecord; public class CustomFormatter extends Formatter { @Override public String format(LogRecord record) { String output = ""; output += record.getLoggerName(); output += ": "; output += record.getMessage(); output += "\n"; return output; } @Override public String formatMessage(LogRecord record) { String output = ""; output += record.getLoggerName(); output += ": "; output += record.getMessage(); output += "\n"; return output; } @Override public String getTail(Handler h) { return ""; } @Override public String getHead(Handler h) { return ""; } }
package org.usfirst.frc4915.debuggersystem; import java.util.logging.*; public class CustomFormatter extends Formatter { public CustomFormatter() { super(); } @Override public String format(LogRecord record) { String output = ""; output += record.getLoggerName(); output += ": "; output += record.getMessage(); //System.out.println("Custom format was called"); output += "\n"; return output; } @Override public String formatMessage(LogRecord record) { String output = ""; output += record.getLoggerName(); output += ": "; output += record.getMessage(); System.out.println("Custom formatMessage was called"); output += "\n"; return output; } @Override public String getTail(Handler h) { return ""; } @Override public String getHead(Handler h) { return ""; } }
Update registration of Twig view It now maches the way the Twig-View readme suggests.
<?php // DIC configuration $container = $app->getContainer(); // ----------------------------------------------------------------------------- // Service providers // ----------------------------------------------------------------------------- // Twig $container['view'] = function ($c) { $view = new \Slim\Views\Twig($c['settings']['view']['template_path'], $c['settings']['view']['twig']); // Add extensions $view->addExtension(new Slim\Views\TwigExtension($c['router'], $c['request']->getUri())); $view->addExtension(new Twig_Extension_Debug()); return $view; }; // Flash messages $container['flash'] = function ($c) { return new \Slim\Flash\Messages; }; // ----------------------------------------------------------------------------- // Service factories // ----------------------------------------------------------------------------- // monolog $container['logger'] = function ($c) { $settings = $c['settings']['logger']; $logger = new \Monolog\Logger($settings['name']); $logger->pushProcessor(new \Monolog\Processor\UidProcessor()); $logger->pushHandler(new \Monolog\Handler\StreamHandler($settings['path'], \Monolog\Logger::DEBUG)); return $logger; }; // ----------------------------------------------------------------------------- // Action factories // ----------------------------------------------------------------------------- $container['App\Action\HomeAction'] = function ($c) { return new App\Action\HomeAction($c['view'], $c['logger']); };
<?php // DIC configuration $container = $app->getContainer(); // ----------------------------------------------------------------------------- // Service providers // ----------------------------------------------------------------------------- // Twig $view = new \Slim\Views\Twig( $app->settings['view']['template_path'], $app->settings['view']['twig'] ); $view->addExtension(new Twig_Extension_Debug()); $view->addExtension(new \Slim\Views\TwigExtension($app->router, $app->request->getUri())); $container['view'] = $view; // Flash messages $container['flash'] = function ($c) { return new \Slim\Flash\Messages; }; // ----------------------------------------------------------------------------- // Service factories // ----------------------------------------------------------------------------- // monolog $container['logger'] = function ($c) { $settings = $c['settings']['logger']; $logger = new \Monolog\Logger($settings['name']); $logger->pushProcessor(new \Monolog\Processor\UidProcessor()); $logger->pushHandler(new \Monolog\Handler\StreamHandler($settings['path'], \Monolog\Logger::DEBUG)); return $logger; }; // ----------------------------------------------------------------------------- // Action factories // ----------------------------------------------------------------------------- $container['App\Action\HomeAction'] = function ($c) { return new App\Action\HomeAction($c['view'], $c['logger']); };
Add comments on variable settings
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() # Values come from `EMAIL_SUBJECT_RE`. CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() # Values come from `EMAIL_SUBJECT_RE`. TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
import os import re from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer CSV_FOLDER = os.getcwd() CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv' # Restrict emails by sender. EMAIL_FROM = 'sender@example.com' # Restrict emails by subject. EMAIL_SUBJECT_RE = re.compile(''.join([ r'(?P<year>\d{4})', r'(?P<month>\d{2})', r'(?P<day>\d{2})', r'(?P<hour>\d{2})', r'(?P<minute>\d{2})', r'\.csv', ])) LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() TABLE_NAME_FORMAT = 'data_{year}{month}' def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
Fix usage of `url_title` in CategoryAdmin.
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
Fix pem type for parsing private RSA keys
package sign import ( "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" ) func parsePrivateKey(data []byte) (*rsa.PrivateKey, error) { pemData, err := pemParse(data, "RSA PRIVATE KEY") if err != nil { return nil, err } return x509.ParsePKCS1PrivateKey(pemData) } func parsePublicKey(data []byte) (*rsa.PublicKey, error) { pemData, err := pemParse(data, "PUBLIC KEY") if err != nil { return nil, err } keyInterface, err := x509.ParsePKIXPublicKey(pemData) if err != nil { return nil, err } pubKey, ok := keyInterface.(*rsa.PublicKey) if !ok { return nil, fmt.Errorf("Could not cast parsed key to *rsa.PublickKey") } return pubKey, nil } func pemParse(data []byte, pemType string) ([]byte, error) { block, _ := pem.Decode(data) if block == nil { return nil, fmt.Errorf("No PEM block found") } if pemType != "" && block.Type != pemType { return nil, fmt.Errorf("Public key's type is '%s', expected '%s'", block.Type, pemType) } return block.Bytes, nil }
package sign import ( "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" ) func parsePrivateKey(data []byte) (*rsa.PrivateKey, error) { pemData, err := pemParse(data, "PRIVATE KEY") if err != nil { return nil, err } return x509.ParsePKCS1PrivateKey(pemData) } func parsePublicKey(data []byte) (*rsa.PublicKey, error) { pemData, err := pemParse(data, "PUBLIC KEY") if err != nil { return nil, err } keyInterface, err := x509.ParsePKIXPublicKey(pemData) if err != nil { return nil, err } pubKey, ok := keyInterface.(*rsa.PublicKey) if !ok { return nil, fmt.Errorf("Could not cast parsed key to *rsa.PublickKey") } return pubKey, nil } func pemParse(data []byte, pemType string) ([]byte, error) { block, _ := pem.Decode(data) if block == nil { return nil, fmt.Errorf("No PEM block found") } if pemType != "" && block.Type != pemType { return nil, fmt.Errorf("Public key's type is '%s', expected '%s'", block.Type, pemType) } return block.Bytes, nil }
Save result as array of school name only
var Xray = require('x-ray'), fs = require('fs') var x = Xray() var baseURLPrefix = "http://www.thaischool.in.th/sitemap.php?school_area=&province_id=", baseURLSuffix = "&schooltype_id=&txtsearch=", provinces = require('./provinces.json') function appendObject(obj){ var resultFile = fs.readFileSync('./result/result.json') var result = JSON.parse(resultFile) result.push(obj) var resultJSON = JSON.stringify(result) fs.writeFileSync('./result/result.json', resultJSON) } function appendArray(arr){ var resultFile = fs.readFileSync('./result/schools.json') var result = JSON.parse(resultFile) Array.prototype.push.apply(result, obj); var resultJSON = JSON.stringify(result) fs.writeFileSync('./result/schools.json', resultJSON) } provinces.map(function(province){ x(baseURLPrefix + province['id'] + baseURLSuffix, 'form', ['td > a']) .paginate('a[title="Next"]@href')(function(err, arr) { appendObject({ province: province['name'], schools: arr }) appendArray(arr) }) })
var Xray = require('x-ray'), fs = require('fs') var x = Xray() var baseURLPrefix = "http://www.thaischool.in.th/sitemap.php?school_area=&province_id=", baseURLSuffix = "&schooltype_id=&txtsearch=", provinces = require('./provinces.json') function appendObject(obj){ var resultFile = fs.readFileSync('./result/result.json') var result = JSON.parse(resultFile) result.push(obj) var resultJSON = JSON.stringify(result) fs.writeFileSync('./result/result.json', resultJSON) } provinces.map(function(province){ x(baseURLPrefix + province['id'] + baseURLSuffix, 'form', ['td > a']) .paginate('a[title="Next"]@href')(function(err, arr) { appendObject({ province: province['name'], schools: arr }) }) })
Make default action on confirmToProceed very clear It's not clear by default whether this will default to Yes or No. This fixes that.
<?php namespace Illuminate\Console; use Closure; trait ConfirmableTrait { /** * Confirm before proceeding with the action * * @param string $warning * @param \Closure $callback * @return bool */ public function confirmToProceed($warning = 'Application In Production!', Closure $callback = null) { $shouldConfirm = $callback ?: $this->getDefaultConfirmCallback(); if (call_user_func($shouldConfirm)) { if ($this->option('force')) return true; $this->comment(str_repeat('*', strlen($warning) + 12)); $this->comment('* '.$warning.' *'); $this->comment(str_repeat('*', strlen($warning) + 12)); $this->output->writeln(''); $confirmed = $this->confirm('Do you really wish to run this command? [Y/n]'); if ( ! $confirmed) { $this->comment('Command Cancelled!'); return false; } } return true; } /** * Get the default confirmation callback. * * @return \Closure */ protected function getDefaultConfirmCallback() { return function() { return $this->getLaravel()->environment() == 'production'; }; } }
<?php namespace Illuminate\Console; use Closure; trait ConfirmableTrait { /** * Confirm before proceeding with the action * * @param string $warning * @param \Closure $callback * @return bool */ public function confirmToProceed($warning = 'Application In Production!', Closure $callback = null) { $shouldConfirm = $callback ?: $this->getDefaultConfirmCallback(); if (call_user_func($shouldConfirm)) { if ($this->option('force')) return true; $this->comment(str_repeat('*', strlen($warning) + 12)); $this->comment('* '.$warning.' *'); $this->comment(str_repeat('*', strlen($warning) + 12)); $this->output->writeln(''); $confirmed = $this->confirm('Do you really wish to run this command?'); if ( ! $confirmed) { $this->comment('Command Cancelled!'); return false; } } return true; } /** * Get the default confirmation callback. * * @return \Closure */ protected function getDefaultConfirmCallback() { return function() { return $this->getLaravel()->environment() == 'production'; }; } }
Return a 404 if the package was not found
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', methods=['GET', 'HEAD']) def packages(package_type, letter, name, version): """Get the contents of a package.""" filepath = os.path.join(current_app.config['BASEDIR'], name.lower(), version.lower()) if os.path.isfile(filepath): with open(filepath, 'rb') as egg: mimetype = magic.from_file(filepath, mime=True) contents = egg.read() return make_response(contents, 200, {'Content-Type': mimetype}) return make_response('Package not found', 404)
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', methods=['GET', 'HEAD']) def packages(package_type, letter, name, version): """Get the contents of a package.""" filepath = os.path.join(current_app.config['BASEDIR'], name.lower(), version.lower()) if os.path.isfile(filepath): with open(filepath, 'rb') as egg: mimetype = magic.from_file(filepath, mime=True) contents = egg.read() return make_response(contents, 200, {'Content-Type': mimetype})
Add and fix scheduled command to cleanup MailBody content
<?php namespace App\Console; use App\Draw; use App\MailBody; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { $schedule->call(function () { Draw::where('expiration', '<=', DB::raw('CURRENT_TIMESTAMP'))->delete(); MailBody::where('created_at', '<=', DB::raw('DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 DAY)'))->delete(); })->daily(); } }
<?php namespace App\Console; use Draw; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { $schedule->call(function () { Draw::where('expiration', '<=', date('Y-m-d'))->delete(); })->daily(); } }
Add Django version trove classifiers.
import os from setuptools import setup, find_packages NAME = 'djangae' PACKAGES = find_packages() DESCRIPTION = 'Django integration with Google App Engine' URL = "https://github.com/potatolondon/djangae" LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() AUTHOR = 'Potato London Ltd.' EXTRAS = { "test": ["webtest"], } setup( name=NAME, version='0.9.1', packages=PACKAGES, # metadata for upload to PyPI author=AUTHOR, description=DESCRIPTION, long_description=LONG_DESCRIPTION, keywords=["django", "Google App Engine", "GAE"], url=URL, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Framework :: Django :: 1.7', 'Framework :: Django :: 1.8', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], include_package_data=True, # dependencies extras_require=EXTRAS, tests_require=EXTRAS['test'], )
import os from setuptools import setup, find_packages NAME = 'djangae' PACKAGES = find_packages() DESCRIPTION = 'Django integration with Google App Engine' URL = "https://github.com/potatolondon/djangae" LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() AUTHOR = 'Potato London Ltd.' EXTRAS = { "test": ["webtest"], } setup( name=NAME, version='0.9.1', packages=PACKAGES, # metadata for upload to PyPI author=AUTHOR, description=DESCRIPTION, long_description=LONG_DESCRIPTION, keywords=["django", "Google App Engine", "GAE"], url=URL, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], include_package_data=True, # dependencies extras_require=EXTRAS, tests_require=EXTRAS['test'], )
Add comments and remove second test
describe('Member', function() { it('should create a new member', function() { // Navigate to list page. browser.get('#/member-list'); // Click on the create button. element(by.linkText('Create new')).click(); // Enter a name. element(by.model('item.name')).sendKeys('New member'); // Save. $('.btn-primary').click(); // Expect an id to be generated. expect(element(by.model('item._id')).getAttribute('value')).toBeDefined(); // Expect a message to be shown. expect(element(by.binding('message')).getText()).toBe('Member created'); // With a promise. element(by.binding('message')).getText().then(function(text) { console.log('The message is: ' + text); }); }); });
describe('Member', function() { it('should create a new member', function() { browser.get('#/member-list'); $('.btn-primary').click(); element(by.model('item.name')).sendKeys('New member'); $('.btn-primary').click(); var idElement = element(by.model('item._id')); expect(idElement.getAttribute('value')).toBeDefined(); idElement.getAttribute('value').then(function(value) { console.log('value', value); }); expect(element(by.binding('message')).getText()).toBe('Member created'); }); it('should update existing member', function() { browser.get('#/member-list'); var list = element.all(by.repeater('item in list')); list.get(0).findElement(by.css('a')).click(); // Get the name. element(by.model('item.name')).getAttribute('value').then(function(name) { return name + '_Updated'; }).then(function(updatedName) { var field = element(by.model('item.name')); field.clear(); field.sendKeys(updatedName); }); $('.btn-primary').click(); expect(element(by.binding('message')).getText()).toBe('Member updated'); }); });
Revert "Add AuthorFactory and BookFactory." This reverts commit 8cde42f87a82206cf63b3a5e4b0ec6c38d66d3a7.
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) )
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint from .models import Author from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) ) class AuthorFactory(DjangoModelFactory): class Meta: model = Author django_get_or_create = ('name',) name = 'Noam Chomsky' class BookFactory(DjangoModelFactory): class Meta: model = Book django_get_or_create = ('title',) title = 'Colorless Green Ideas Sleep Furiously'
Add ResolveEvent function that use POST instead of DELETE
package sensu import ( "encoding/json" "fmt" ) // GetEvents Return all the current events func (s *Sensu) GetEvents() ([]interface{}, error) { return s.GetList("events", 0, 0) } // GetEventsForClient Returns the current events for given client func (s *Sensu) GetEventsForClient(client string) ([]interface{}, error) { //return s.Get("events", client) // TODO is this the correct way? need validation?? return s.GetList(fmt.Sprintf("events/%s", client), 0, 0) } // GetEventsCheckForClient Returns the event for a check for a client func (s *Sensu) GetEventsCheckForClient(client string, check string) ([]interface{}, error) { //return s.Get("events", client) // TODO is this the correct way? need validation?? return s.GetList(fmt.Sprintf("events/%s/%s", client, check), 0, 0) } // ResolveEvent delete an event func (s *Sensu) ResolveEvent(payload interface{}) (map[string]interface{}, error) { // return s.Post(fmt.Sprintf("stashes/create"), payload) payloadstr, err := json.Marshal(payload) if err != nil { return nil, fmt.Errorf("Stash parsing error: %q returned: %v", err, err) } return s.PostPayload("resolve", string(payloadstr[:])) }
package sensu import "fmt" // GetEvents Return all the current events func (s *Sensu) GetEvents() ([]interface{}, error) { return s.GetList("events", 0, 0) } // GetEventsForClient Returns the current events for given client func (s *Sensu) GetEventsForClient(client string) ([]interface{}, error) { //return s.Get("events", client) // TODO is this the correct way? need validation?? return s.GetList(fmt.Sprintf("events/%s", client), 0, 0) } // GetEventsCheckForClient Returns the event for a check for a client func (s *Sensu) GetEventsCheckForClient(client string, check string) ([]interface{}, error) { //return s.Get("events", client) // TODO is this the correct way? need validation?? return s.GetList(fmt.Sprintf("events/%s/%s", client, check), 0, 0) } // ResolveEvent Resolves an event (delayed action) func (s *Sensu) ResolveEvent(client string, check string) (map[string]interface{}, error) { return s.Delete(fmt.Sprintf("events/%s/%s", client, check)) }
[FIX] Change the name of module in the manifest
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Field Required in Partners", "summary": "Customers and Suppliers Field Required", "version": "9.0.1.0.0", "category": "", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro Preciado>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", ], "data": [ "views/base_partner_view.xml", ], "demo": [ ], "qweb": [ ] }
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Field(s) Required Res Partner", "summary": "Customers and Suppliers Field Required", "version": "9.0.1.0.0", "category": "", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro Preciado>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", ], "data": [ "views/base_partner_view.xml", ], "demo": [ ], "qweb": [ ] }
Increment GopherJS version to 1.16.1.
// +build go1.16 package compiler import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) // Version is the GopherJS compiler version string. const Version = "1.16.1+go1.16.3" // GoVersion is the current Go 1.x version that GopherJS is compatible with. const GoVersion = 16 // CheckGoVersion checks the version of the Go distribution // at goroot, and reports an error if it's not compatible // with this version of the GopherJS compiler. func CheckGoVersion(goroot string) error { if nvc, err := strconv.ParseBool(os.Getenv("GOPHERJS_SKIP_VERSION_CHECK")); err == nil && nvc { return nil } v, err := ioutil.ReadFile(filepath.Join(goroot, "VERSION")) if err != nil { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but failed to read its VERSION file: %v", Version, err) } if !bytes.HasPrefix(v, []byte("go1.16")) { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but found version %s", Version, v) } return nil }
// +build go1.16 package compiler import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) // Version is the GopherJS compiler version string. const Version = "1.16.0+go1.16.3" // GoVersion is the current Go 1.x version that GopherJS is compatible with. const GoVersion = 16 // CheckGoVersion checks the version of the Go distribution // at goroot, and reports an error if it's not compatible // with this version of the GopherJS compiler. func CheckGoVersion(goroot string) error { if nvc, err := strconv.ParseBool(os.Getenv("GOPHERJS_SKIP_VERSION_CHECK")); err == nil && nvc { return nil } v, err := ioutil.ReadFile(filepath.Join(goroot, "VERSION")) if err != nil { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but failed to read its VERSION file: %v", Version, err) } if !bytes.HasPrefix(v, []byte("go1.16")) { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but found version %s", Version, v) } return nil }
Remove get receipt override for given providers
import { Manager as Web3RequestManager } from 'web3-core-requestmanager'; import MiddleWare from '../middleware'; import { ethSendTransaction, ethSign, ethSignTransaction, ethGetTransactionCount } from '../methods'; class GivenProvider { constructor(host, options, store, eventHub) { this.givenProvider = Object.assign({}, host); const requestManager = new Web3RequestManager(host); options = options ? options : null; if (this.givenProvider.sendAsync) { this.givenProvider.send = this.givenProvider.sendAsync; delete this.givenProvider.sendAsync; } this.givenProvider.send_ = this.givenProvider.send; delete this.givenProvider.send; this.givenProvider.send = (payload, callback) => { const req = { payload, store, requestManager, eventHub }; const middleware = new MiddleWare(); middleware.use(ethSendTransaction); middleware.use(ethSignTransaction); middleware.use(ethGetTransactionCount); middleware.use(ethSign); middleware.run(req, callback).then(() => { this.givenProvider.send_(payload, callback); }); }; return this.givenProvider; } } export default GivenProvider;
import { Manager as Web3RequestManager } from 'web3-core-requestmanager'; import MiddleWare from '../middleware'; import { ethSendTransaction, ethSign, ethSignTransaction, ethGetTransactionCount, ethGetTransactionReceipt } from '../methods'; class GivenProvider { constructor(host, options, store, eventHub) { this.givenProvider = Object.assign({}, host); const requestManager = new Web3RequestManager(host); options = options ? options : null; if (this.givenProvider.sendAsync) { this.givenProvider.send = this.givenProvider.sendAsync; delete this.givenProvider.sendAsync; } this.givenProvider.send_ = this.givenProvider.send; delete this.givenProvider.send; this.givenProvider.send = (payload, callback) => { const req = { payload, store, requestManager, eventHub }; const middleware = new MiddleWare(); middleware.use(ethSendTransaction); middleware.use(ethSignTransaction); middleware.use(ethGetTransactionCount); middleware.use(ethGetTransactionReceipt); middleware.use(ethSign); middleware.run(req, callback).then(() => { this.givenProvider.send_(payload, callback); }); }; return this.givenProvider; } } export default GivenProvider;
Load tsconfig.json in gulp file
const gulp = require("gulp"); const fs = require("fs"); const rename = require("gulp-rename"); const sass = require("gulp-sass"); const ts = require("gulp-typescript"); gulp.task("lib_ts", function() { const tsProject = ts.createProject('tsconfig.json'); gulp.src("./src/*.ts") .pipe(tsProject()) .pipe(gulp.dest("./lib")); }); gulp.task("sass", function() { gulp.src("./jqtree.scss") .pipe(sass({errLogToConsole: true})) .pipe(gulp.dest("./")) }); gulp.task("example_sass", function() { gulp.src("./static/example.scss") .pipe(sass({errLogToConsole: true})) .pipe(gulp.dest("./static")); }); gulp.task("default", ["lib_ts", "sass", "example_sass"]);
const gulp = require("gulp"); const fs = require("fs"); const rename = require("gulp-rename"); const sass = require("gulp-sass"); const ts = require("gulp-typescript"); gulp.task("lib_ts", function() { gulp.src("./src/*.ts") .pipe(ts()) .pipe(gulp.dest("./lib")); }); gulp.task("sass", function() { gulp.src("./jqtree.scss") .pipe(sass({errLogToConsole: true})) .pipe(gulp.dest("./")) }); gulp.task("example_sass", function() { gulp.src("./static/example.scss") .pipe(sass({errLogToConsole: true})) .pipe(gulp.dest("./static")); }); gulp.task("default", ["lib_ts", "sass", "example_sass"]);
Add return for async task cmpletition
import gulp from 'gulp'; import plumber from 'gulp-plumber'; import filter from 'gulp-filter'; import changed from 'gulp-changed'; import imagemin from 'gulp-imagemin'; import { plumberConfig, imageminConfig } from '../config'; export const assets = () => { const imageFilter = filter('**/*.{jpg,gif,svg,png}', { restore: true }); return gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) .pipe(plumber(plumberConfig)) .pipe(changed('dest/assets')) // Minify images .pipe(imageFilter) .pipe(changed('dest/assets')) .pipe(imagemin(imageminConfig.images)) .pipe(imageFilter.restore) // Copy other files .pipe(gulp.dest('dest/assets')); }; export const staticFiles = () => gulp.src('**/{*,.*}', { cwd: 'source/static/public' }) .pipe(plumber(plumberConfig)) .pipe(gulp.dest('dest'));
import gulp from 'gulp'; import plumber from 'gulp-plumber'; import filter from 'gulp-filter'; import changed from 'gulp-changed'; import imagemin from 'gulp-imagemin'; import { plumberConfig, imageminConfig } from '../config'; export const assets = () => { const imageFilter = filter('**/*.{jpg,gif,svg,png}', { restore: true }); gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) .pipe(plumber(plumberConfig)) .pipe(changed('dest/assets')) // Minify images .pipe(imageFilter) .pipe(changed('dest/assets')) .pipe(imagemin(imageminConfig.images)) .pipe(imageFilter.restore) // Copy other files .pipe(gulp.dest('dest/assets')); }; export const staticFiles = () => gulp.src('**/{*,.*}', { cwd: 'source/static/public' }) .pipe(plumber(plumberConfig)) .pipe(gulp.dest('dest'));
Fix tests with last changes on api.
# -*- coding: utf-8 -*- from django.db import models from django_orm.postgresql.fields.arrays import ArrayField from django_orm.postgresql.fields.interval import IntervalField from django_orm.postgresql.fields.bytea import ByteaField from django_orm.manager import Manager class IntModel(models.Model): lista = ArrayField(dbtype='int') objects = Manager() class TextModel(models.Model): lista = ArrayField(dbtype='text') objects = Manager() class DoubleModel(models.Model): lista = ArrayField(dbtype='double precision') objects = Manager() class VarcharModel(models.Model): lista = ArrayField(dbtype='varchar(40)') objects = Manager() class IntervalModel(models.Model): iv = IntervalField() objects = Manager() class ByteaModel(models.Model): bb = ByteaField() objects = Manager() from django_orm.postgresql.geometric.fields import PointField, CircleField from django_orm.postgresql.geometric.fields import LsegField, BoxField from django_orm.postgresql.geometric.fields import PathField, PolygonField class GeomModel(models.Model): pt = PointField() pl = PolygonField() ln = LsegField() bx = BoxField() cr = CircleField() ph = PathField() objects = Manager()
# -*- coding: utf-8 -*- from django.db import models from django_orm.postgresql.fields.arrays import ArrayField from django_orm.postgresql.fields.interval import IntervalField from django_orm.postgresql.fields.bytea import ByteaField from django_orm.postgresql.manager import PgManager class IntModel(models.Model): lista = ArrayField(dbtype='int') objects = PgManager() class TextModel(models.Model): lista = ArrayField(dbtype='text') objects = PgManager() class DoubleModel(models.Model): lista = ArrayField(dbtype='double precision') objects = PgManager() class VarcharModel(models.Model): lista = ArrayField(dbtype='varchar(40)') objects = PgManager() class IntervalModel(models.Model): iv = IntervalField() objects = PgManager() class ByteaModel(models.Model): bb = ByteaField() objects = PgManager() from django_orm.postgresql.geometric.fields import PointField, CircleField from django_orm.postgresql.geometric.fields import LsegField, BoxField from django_orm.postgresql.geometric.fields import PathField, PolygonField class GeomModel(models.Model): pt = PointField() pl = PolygonField() ln = LsegField() bx = BoxField() cr = CircleField() ph = PathField() objects = PgManager()
Remove localStorage var that clobbers the global Declaring a var localStorage at the top level clobbers the global localStorage defined by the browser with `undefined`.
var nextTick = process && process.nextTick ? process.nextTick : setImmediate export default { getItem: function (key, cb) { try { var s = localStorage.getItem(key) nextTick(() => { cb(null, s) }) } catch (e) { cb(e) } }, setItem: function (key, string, cb) { try { localStorage.setItem(key, string) nextTick(() => { cb(null) }) } catch (e) { cb(e) } }, removeItem: function (key, cb) { try { localStorage.removeItem(key) nextTick(() => { cb(null) }) } catch (e) { cb(e) } }, getAllKeys: function (cb) { try { var keys = [] for (var i = 0; i < localStorage.length; i++) { keys.push(localStorage.key(i)) } nextTick(() => { cb(null, keys) }) } catch (e) { cb(e) } } }
var nextTick = process && process.nextTick ? process.nextTick : setImmediate var localStorage = localStorage || null export default { getItem: function (key, cb) { try { var s = localStorage.getItem(key) nextTick(() => { cb(null, s) }) } catch (e) { cb(e) } }, setItem: function (key, string, cb) { try { localStorage.setItem(key, string) nextTick(() => { cb(null) }) } catch (e) { cb(e) } }, removeItem: function (key, cb) { try { localStorage.removeItem(key) nextTick(() => { cb(null) }) } catch (e) { cb(e) } }, getAllKeys: function (cb) { try { var keys = [] for (var i = 0; i < localStorage.length; i++) { keys.push(localStorage.key(i)) } nextTick(() => { cb(null, keys) }) } catch (e) { cb(e) } } }
Change saveSimulationProfiles to False in minimal_sensitivity just to test a diff parameter in this job
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # Constraints on generated species generatedSpeciesConstraints( maximumRadicalElectrons = 2, ) # List of species species( label='ethane', reactive=True, structure=SMILES("CC"), ) # Reaction systems simpleReactor( temperature=(1350,'K'), pressure=(1.0,'bar'), initialMoleFractions={ "ethane": 1.0, }, terminationConversion={ 'ethane': 0.9, }, terminationTime=(1e6,'s'), sensitivity=['ethane'], sensitivityThreshold=0.01, ) simulator( atol=1e-16, rtol=1e-8, sens_atol=1e-6, sens_rtol=1e-4, ) model( toleranceKeepInEdge=0.0, toleranceMoveToCore=0.1, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, saveSimulationProfiles=False, generateOutputHTML=False, generatePlots=False, )
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # Constraints on generated species generatedSpeciesConstraints( maximumRadicalElectrons = 2, ) # List of species species( label='ethane', reactive=True, structure=SMILES("CC"), ) # Reaction systems simpleReactor( temperature=(1350,'K'), pressure=(1.0,'bar'), initialMoleFractions={ "ethane": 1.0, }, terminationConversion={ 'ethane': 0.9, }, terminationTime=(1e6,'s'), sensitivity=['ethane'], sensitivityThreshold=0.01, ) simulator( atol=1e-16, rtol=1e-8, sens_atol=1e-6, sens_rtol=1e-4, ) model( toleranceKeepInEdge=0.0, toleranceMoveToCore=0.1, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, saveSimulationProfiles=True, generateOutputHTML=False, generatePlots=False, )
Fix issue where 0 is treated as null
<?php namespace Anomaly\SelectFieldType; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter; /** * Class SelectFieldTypePresenter * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <hello@anomaly.is> * @author Ryan Thompson <ryan@anomaly.is> * @package Anomaly\SelectFieldType */ class SelectFieldTypePresenter extends FieldTypePresenter { /** * The decorated object. * This is for IDE support. * * @var SelectFieldType */ protected $object; /** * Return the selection key. * * @return string|null */ public function key() { return $this->object->getValue(); } /** * Return the selection value. * * @return string|null */ public function value() { $options = $this->object->getOptions(); if (($key = $this->object->getValue()) === null) { return null; } return trans(array_get($options, $key)); } }
<?php namespace Anomaly\SelectFieldType; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter; /** * Class SelectFieldTypePresenter * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <hello@anomaly.is> * @author Ryan Thompson <ryan@anomaly.is> * @package Anomaly\SelectFieldType */ class SelectFieldTypePresenter extends FieldTypePresenter { /** * The decorated object. * This is for IDE support. * * @var SelectFieldType */ protected $object; /** * Return the selection key. * * @return string|null */ public function key() { return $this->object->getValue(); } /** * Return the selection value. * * @return string|null */ public function value() { $options = $this->object->getOptions(); if (!$key = $this->object->getValue()) { return null; } return trans(array_get($options, $key)); } }
Change listening port to env port with default.
var express = require('express'); var bodyParser = require('body-parser'); var http = require('http'); var path = require('path'); var fs = require('fs'); var quotes = require(path.join(__dirname, 'lib', 'quotes')) var app = express(); app.set('port', (process.env.PORT || 5000)); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res) { res.render('index'); }); app.get('/api/listAllOggFiles/', function(req, res) { fs.readdir('public/sounds/', function(err, files){ if (err) { throw err; } var filenames = []; for (var i = 0; i < files.length; i++) { filenames.push(files[i].split('.')[0]); } res.json(filenames); }); }); app.get('/api/getQuotes/', function(req, res){ res.json(quotes); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server up and running. Listening on port ' + app.get('port')); });
var express = require('express'); var bodyParser = require('body-parser'); var http = require('http'); var path = require('path'); var fs = require('fs'); var quotes = require(path.join(__dirname, 'lib', 'quotes')) var app = express(); app.set('port', 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res) { res.render('index'); }); app.get('/api/listAllOggFiles/', function(req, res) { fs.readdir('public/sounds/', function(err, files){ if (err) { throw err; } var filenames = []; for (var i = 0; i < files.length; i++) { filenames.push(files[i].split('.')[0]); } res.json(filenames); }); }); app.get('/api/getQuotes/', function(req, res){ res.json(quotes); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server up and running. Listening on port ' + app.get('port')); });
Fix lint error with annotation
#!/usr/bin/env node import minimist from 'minimist'; import { check, formatter, writeOutput, writeFile } from '../lib/cfpathcheck.js'; const argv = minimist(process.argv.slice(2)); // eslint-disable-line node/prefer-global/process /** * Everything in the file should be customized. */ // Use `-f` or `--file` to specify the source file const file = argv._[0] || argv.f || argv.file || 'TODO.md'; // Use `-r` or `--reporter` to specify the reporter to use const reporter = argv._[1] || argv.r || argv.reporter || 'console'; const outFile = argv.o || argv.outfile; if (!file) { console.error( 'Please provide a source file, either as a first argument or with `-f` or `--file`' ); } /** * Application. */ const violations = check(file, 'json'); const output = formatter(violations, reporter); writeOutput(output); if (outFile) { writeFile( formatter(violations, 'checkstyle'), outFile ); }
#!/usr/bin/env node import minimist from 'minimist'; import { check, formatter, writeOutput, writeFile } from '../lib/cfpathcheck.js'; const argv = minimist(process.argv.slice(2)); /** * Everything in the file should be customized. */ // Use `-f` or `--file` to specify the source file const file = argv._[0] || argv.f || argv.file || 'TODO.md'; // Use `-r` or `--reporter` to specify the reporter to use const reporter = argv._[1] || argv.r || argv.reporter || 'console'; const outFile = argv.o || argv.outfile; if (!file) { console.error( 'Please provide a source file, either as a first argument or with `-f` or `--file`' ); } /** * Application. */ const violations = check(file, 'json'); const output = formatter(violations, reporter); writeOutput(output); if (outFile) { writeFile( formatter(violations, 'checkstyle'), outFile ); }
Make sure we assign the right thing to the styles array.
<?php namespace AbleCore\Modules; class ImageStyleManager { protected $styles = array(); /** * Init * * @return ImageStyleManager A new instance of the ImageStyleManager. */ public static function init() { return new self(); } /** * Define * * @param string $name The machine name of the image style. * @param string $label The human-readable label of the image style. * @param array $effects An array of effects to attach to the style. * * @return ImageStyle The generated image style. */ public function define($name, $label, $effects = array()) { $style = new ImageStyle($name, $label, $effects); $this->styles[] = $style; return $style; } /** * Finish * * @return array The final result, ready to pass to hook_image_default_styles() */ public function fin() { $generated = array(); foreach ($this->styles as $style) { /** @var ImageStyle $style */ $generated[$style->getName()] = $style->getDefinition(); } return $generated; } }
<?php namespace AbleCore\Modules; class ImageStyleManager { protected $styles = array(); /** * Init * * @return ImageStyleManager A new instance of the ImageStyleManager. */ public static function init() { return new self(); } /** * Define * * @param string $name The machine name of the image style. * @param string $label The human-readable label of the image style. * @param array $effects An array of effects to attach to the style. * * @return ImageStyle The generated image style. */ public function define($name, $label, $effects = array()) { $style = new ImageStyle($name, $label, $effects); $this->styles[] = $name; return $style; } /** * Finish * * @return array The final result, ready to pass to hook_image_default_styles() */ public function fin() { $generated = array(); foreach ($this->styles as $style) { /** @var ImageStyle $style */ $generated[$style->getName()] = $style->getDefinition(); } return $generated; } }