text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Check if constants are defined before. | <?php
/**
* Setup global configuration variable.
*/
$config = require 'config.php';
/**
* Register the Composer autoloader.
*/
require WP_CONTENT_DIR.'/../vendor/autoload.php';
/**
* Load Framework Components.
*/
require get_template_directory().'/library/cleanup.php';
require get_template_directory().'/library/editor.php';
require get_template_directory().'/library/login.php';
require get_template_directory().'/library/pages.php';
require get_template_directory().'/library/updates.php';
require get_template_directory().'/library/utils.php';
/**
* Enable Gzip if available.
*/
if (extension_loaded('zlib') && (ini_get('output_handler') !== 'ob_gzhandler'))
{
add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
}
/**
* Speed up page load in WordPress 3.8+.
*/
if (!defined('WP_HTTP_BLOCK_EXTERNAL'))
{
define('WP_HTTP_BLOCK_EXTERNAL', $config['http_block_external']);
}
/**
* Prevent file edit from WordPress administrator dashboard.
*/
if (!defined('DISALLOW_FILE_EDIT'))
{
define('DISALLOW_FILE_EDIT', $config['disallow_file_edit']);
}
/**
* Custom footer text.
*
* @return string
*/
add_filter('admin_footer_text', function() use ($config)
{
return $config['footer_text'];
});
| <?php
/**
* Setup global configuration variable.
*/
$config = require 'config.php';
/**
* Register the Composer autoloader.
*/
require WP_CONTENT_DIR.'/../vendor/autoload.php';
/**
* Load Framework Components.
*/
require get_template_directory().'/library/cleanup.php';
require get_template_directory().'/library/editor.php';
require get_template_directory().'/library/login.php';
require get_template_directory().'/library/pages.php';
require get_template_directory().'/library/updates.php';
require get_template_directory().'/library/utils.php';
/**
* Enable Gzip if available.
*/
if (extension_loaded('zlib') && (ini_get('output_handler') !== 'ob_gzhandler'))
{
add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
}
/**
* Speed up page load in WordPress 3.8+.
*/
define('WP_HTTP_BLOCK_EXTERNAL', $config['http_block_external']);
/**
* Prevent file edit from WordPress administrator dashboard.
*/
define('DISALLOW_FILE_EDIT', $config['disallow_file_edit']);
/**
* Custom footer text.
*
* @return string
*/
add_filter('admin_footer_text', function() use ($config)
{
return $config['footer_text'];
});
|
Change require to link from service | var assert = require('chai').assert;
var HashService = require('../');
var BCryptHash = HashService.BCryptHash;
describe('HashService', function () {
it('Should properly export', function () {
assert.isObject(HashService);
assert.isFunction(HashService.create);
assert.isFunction(HashService.BCryptHash);
});
it('Should properly create bcrypt instance', function () {
assert.instanceOf(HashService.create('bcrypt'), BCryptHash);
});
it('Should properly throw Error if type is unrecognized', function () {
assert.throw(function () {
HashService.create('NOT_EXISTS');
}, Error);
});
it('Should properly hash bcrypt', function () {
var hasher = HashService.create('bcrypt');
var hash = hasher.hashSync('MY_PASSWORD');
assert.ok(hasher.compareSync('MY_PASSWORD', hash));
assert.notOk(hasher.compareSync('WRONG_PASSWORD', hash));
});
});
| var assert = require('chai').assert;
var HashService = require('../');
var BCryptHash = require('../lib/BCryptHash');
describe('HashService', function () {
it('Should properly export', function () {
assert.isObject(HashService);
assert.isFunction(HashService.create);
assert.isFunction(HashService.BCryptHash);
});
it('Should properly create bcrypt instance', function () {
assert.instanceOf(HashService.create('bcrypt'), BCryptHash);
});
it('Should properly throw Error if type is unrecognized', function () {
assert.throw(function () {
HashService.create('NOT_EXISTS');
}, Error);
});
it('Should properly hash bcrypt', function () {
var hasher = HashService.create('bcrypt');
var hash = hasher.hashSync('MY_PASSWORD');
assert.ok(hasher.compareSync('MY_PASSWORD', hash));
assert.notOk(hasher.compareSync('WRONG_PASSWORD', hash));
});
});
|
Change default ESI URL to the new one | package main
import "github.com/spf13/viper"
func init() {
viper.SetDefault("base-url", "http://127.0.0.1:8080")
viper.SetDefault("http_addr", ":8080")
viper.SetDefault("https_addr", "")
viper.SetDefault("https_domain-whitelist", []string{"evepraisal.com"})
viper.SetDefault("letsencrypt_email", "")
viper.SetDefault("db_path", "db/")
viper.SetDefault("backup_path", "db/backups/")
viper.SetDefault("esi_baseurl", "http://esi.evetech.net/latest")
viper.SetDefault("newrelic_app-name", "Evepraisal")
viper.SetDefault("newrelic_license-key", "")
viper.SetDefault("management_addr", "127.0.0.1:8090")
viper.SetDefault("extra-js", "")
viper.SetDefault("ad-block", "")
viper.SetDefault("sso-authorize-url", "https://login.eveonline.com/oauth/authorize")
viper.SetDefault("sso-token-url", "https://login.eveonline.com/oauth/token")
viper.SetDefault("sso-verify-url", "https://login.eveonline.com/oauth/verify")
}
| package main
import "github.com/spf13/viper"
func init() {
viper.SetDefault("base-url", "http://127.0.0.1:8080")
viper.SetDefault("http_addr", ":8080")
viper.SetDefault("https_addr", "")
viper.SetDefault("https_domain-whitelist", []string{"evepraisal.com"})
viper.SetDefault("letsencrypt_email", "")
viper.SetDefault("db_path", "db/")
viper.SetDefault("backup_path", "db/backups/")
viper.SetDefault("esi_baseurl", "https://esi.tech.ccp.is/latest")
viper.SetDefault("newrelic_app-name", "Evepraisal")
viper.SetDefault("newrelic_license-key", "")
viper.SetDefault("management_addr", "127.0.0.1:8090")
viper.SetDefault("extra-js", "")
viper.SetDefault("ad-block", "")
viper.SetDefault("sso-authorize-url", "https://login.eveonline.com/oauth/authorize")
viper.SetDefault("sso-token-url", "https://login.eveonline.com/oauth/token")
viper.SetDefault("sso-verify-url", "https://login.eveonline.com/oauth/verify")
}
|
Add a teardown method for the formulaDAO tests | package beaform.dao;
import org.apache.commons.collections.ListUtils;
import org.junit.Before;
import org.junit.Test;
import beaform.debug.DebugUtils;
import beaform.entities.TransactionSetupException;
import junit.framework.TestCase;
/**
* Test for the formula DA.
*
* @author Steven Post
*
*/
public class FormlaDAOTest extends TestCase {
/**
* {@inheritDoc}
*/
@Override
@Before
public void setUp() {
GraphDbHandlerForJTA.initInstance("test");
DebugUtils.clearDb();
}
/**
* Test for adding a new formula.
* @throws TransactionSetupException
*/
@Test
public void testAddFormula() throws TransactionSetupException {
FormulaDAO.addFormula("Testform", "Description", "100g", ListUtils.EMPTY_LIST, ListUtils.EMPTY_LIST);
assertEquals("This isn't the expected formula", null, null);
}
/**
* {@inheritDoc}
*/
@Override
@After
public void tearDown() {
DebugUtils.clearDb();
}
}
| package beaform.dao;
import org.apache.commons.collections.ListUtils;
import org.junit.Before;
import org.junit.Test;
import beaform.debug.DebugUtils;
import beaform.entities.TransactionSetupException;
import junit.framework.TestCase;
/**
* Test for the formula DA.
*
* @author Steven Post
*
*/
public class FormlaDAOTest extends TestCase {
/**
* {@inheritDoc}
*/
@Override
@Before
public void setUp() {
GraphDbHandlerForJTA.initInstance("test");
DebugUtils.clearDb();
}
/**
* Test for adding a new formula.
* @throws TransactionSetupException
*/
@Test
public void testAddFormula() throws TransactionSetupException {
FormulaDAO.addFormula("Testform", "Description", "100g", ListUtils.EMPTY_LIST, ListUtils.EMPTY_LIST);
assertEquals("This isn't the expected formula", null, null);
}
}
|
Update readline dependency to github so we're up to date | package main
import (
"flag"
"fmt"
"github.com/chzyer/readline"
"github.com/soudy/mathcat"
"os"
"runtime"
)
var precision = flag.Int("precision", 2, "decimal precision used in results")
func getHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func repl() {
p := mathcat.New()
rl, err := readline.NewEx(&readline.Config{
Prompt: "mathcat> ",
HistoryFile: getHomeDir() + "/.mathcat_history",
})
if err != nil {
panic(err)
}
defer rl.Close()
for {
line, err := rl.Readline()
if err != nil {
break
}
res, err := p.Run(line)
if err != nil {
fmt.Println(err)
continue
}
if mathcat.IsWholeNumber(res) {
fmt.Printf("%d\n", int64(res))
} else {
fmt.Printf("%.*f\n", *precision, res)
}
}
}
func main() {
flag.Parse()
repl()
}
| package main
import (
"flag"
"fmt"
"github.com/soudy/mathcat"
"gopkg.in/readline.v1"
"os"
"runtime"
)
var precision = flag.Int("precision", 2, "decimal precision used in results")
func getHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func repl() {
p := mathcat.New()
rl, err := readline.NewEx(&readline.Config{
Prompt: "mathcat> ",
HistoryFile: getHomeDir() + "/.mathcat_history",
})
if err != nil {
panic(err)
}
defer rl.Close()
for {
line, err := rl.Readline()
if err != nil {
break
}
res, err := p.Run(line)
if err != nil {
fmt.Println(err)
continue
}
if mathcat.IsWholeNumber(res) {
fmt.Printf("%d\n", int64(res))
} else {
fmt.Printf("%.*f\n", *precision, res)
}
}
}
func main() {
flag.Parse()
repl()
}
|
Convert pauses longer than 1000 millis into secs | /**
* Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.com)
*
* 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.
*/
package com.excilys.ebi.gatling.recorder.http.event;
public class PauseEvent {
private long durationMillis;
public PauseEvent(long durationMillis) {
this.durationMillis = durationMillis;
}
public long getDuration() {
if (durationMillis < 1000)
return durationMillis;
else
return Math.round((float) durationMillis / 1000);
}
public String getDurationUnit() {
if (durationMillis < 1000)
return "MILLISECONDS";
else
return "SECONDS";
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + getDuration() + " " + getDurationUnit();
}
}
| /**
* Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.com)
*
* 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.
*/
package com.excilys.ebi.gatling.recorder.http.event;
public class PauseEvent {
private long durationMillis;
public PauseEvent(long durationMillis) {
this.durationMillis = durationMillis;
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + durationMillis + " ms";
}
}
|
Split handler into two code paths | package main
import (
"github.com/hoisie/web"
"github.com/russross/blackfriday"
"io/ioutil"
"log"
"os"
)
func handler(ctx *web.Context, path string) {
if path == "" {
ctx.WriteString("foo")
return
} else {
input, err := ioutil.ReadFile(path)
if err != nil {
ctx.NotFound("File Not Found\n" + err.Error())
return
}
ctx.WriteString(string(blackfriday.MarkdownCommon(input)))
return
}
ctx.Abort(500, "Server Error")
}
func main() {
f, err := os.Create("server.log")
if err != nil {
println(err.Error())
return
}
logger := log.New(f, "", log.Ldate|log.Ltime)
web.Get("/(.*)", handler)
web.SetLogger(logger)
web.Run(":8080")
}
| package main
import (
"github.com/hoisie/web"
"github.com/russross/blackfriday"
"io/ioutil"
"log"
"os"
)
func handler(ctx *web.Context, path string) {
input, err := ioutil.ReadFile("testdata/foo.md")
if err != nil {
ctx.NotFound("File Not Found\n" + err.Error())
return
}
ctx.WriteString(string(blackfriday.MarkdownCommon(input)))
}
func main() {
f, err := os.Create("server.log")
if err != nil {
println(err.Error())
return
}
logger := log.New(f, "", log.Ldate|log.Ltime)
web.Get("/(.*)", handler)
web.SetLogger(logger)
web.Run(":8080")
}
|
Fix Cannot read property 'error' of undefined | /**
* Created by Fonov Sergei on 23.12.16.
*/
'use strict'
const req = require('tiny_request')
function sendreq(name, jsonData){
return new Promise((resolve, reject) => {
req.post({ url: this._url+name, jsonData: jsonData, json: true}, function(body, response, err){
if (!err && response.statusCode == 200 && body.ok) {
resolve(body.result)
} else if (body) {
console.log(`Error on method ${name}: ${body.error}`)
reject(body.error)
} else {
reject(err)
}
})
})
}
module.exports = sendreq
| /**
* Created by Fonov Sergei on 23.12.16.
*/
'use strict'
const req = require('tiny_request')
function sendreq(name, jsonData){
return new Promise((resolve, reject) => {
req.post({ url: this._url+name, jsonData: jsonData, json: true}, function(body, response, err){
if (!err && response.statusCode == 200 && body.ok) {
resolve(body.result)
}else {
console.log(`Error on method ${name}: ${body.error}`)
reject(body.error)
}
})
})
}
module.exports = sendreq |
Add locale_group by default to elements
Closes #60 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ElementsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('elements', function ($table) {
$table->engine = 'InnoDB';
$table->string('key');
$table->string('type');
$table->mediumtext('value')->nullable();
$table->string('locale');
$table->string('locale_group')->nullable();
$table->primary(['key', 'locale']);
$table->index(['locale', 'key']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('elements');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ElementsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('elements', function ($table) {
$table->engine = 'InnoDB';
$table->string('key');
$table->string('type');
$table->mediumtext('value')->nullable();
$table->string('locale');
$table->primary(['key', 'locale']);
$table->index(['locale', 'key']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('elements');
}
}
|
Change ExtendedUser to Member in resolver | module.exports = {
type: 'member',
resolve: (content, { bot = false }, msg) => {
const guild = msg.channel.guild
if (!msg.mentions.length) {
content = String(content).toLowerCase()
let members = guild.members.filter(m => {
if (!bot && m.user.bot) return
const name = m.user.username.toLowerCase()
const nick = m.nick ? m.nick.toLowerCase() : name
const discrim = m.user.discriminator
return name === content || nick === content ||
`${name}#${discrim}` === content ||
`${nick}#${discrim}` === content ||
name.includes(content) ||
nick.includes(content)
})
if (members.length) {
return Promise.resolve(members)
} else {
return Promise.reject('member.NOT_FOUND')
}
} else {
return Promise.resolve(msg.mentions.map(m => guild.members.get(m.id)))
}
}
}
| module.exports = {
type: 'member',
resolve: (content, { bot = false }, msg) => {
const guild = msg.channel.guild
if (!msg.mentions.length) {
content = String(content).toLowerCase()
let members = guild.members.filter(m => {
if (!bot && m.user.bot) return
const name = m.user.username.toLowerCase()
const nick = m.nick ? m.nick.toLowerCase() : name
const discrim = m.user.discriminator
return name === content || nick === content ||
`${name}#${discrim}` === content ||
`${nick}#${discrim}` === content ||
name.includes(content) ||
nick.includes(content)
})
if (members.length) {
return Promise.resolve(members)
} else {
return Promise.reject('member.NOT_FOUND')
}
} else {
return Promise.resolve(msg.mentions)
}
}
}
|
Fix bug in time machine logic | package main
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func rootVolPath() string {
volumes, err := filepath.Glob("/Volumes/*")
if err != nil || volumes == nil {
log.Println("Unable to list /Volumes/*")
log.Fatal(err)
}
for _, volume := range volumes {
link_path, err := os.Readlink(volume)
if err == nil && link_path == "/" {
return volume
}
}
log.Fatal("Could not find root volume")
return ""
}
func volPath(target string) string {
var err error
target, err = filepath.Abs(target)
if err != nil {
log.Fatal(err)
}
target = filepath.Clean(target)
target_list := strings.Split(target, string(filepath.Separator))
if len(target_list) >= 2 &&
target_list[0] == "" &&
target_list[1] == "Volumes" {
return target
}
return filepath.Join(rootVolPath(), target)
}
func getTMDir() (dirname string, err error) {
dirname_bytes, err := exec.Command("tmutil", "machinedirectory").CombinedOutput()
if err == nil {
dirname = filepath.Join(strings.TrimSpace(string(dirname_bytes)), "Latest")
}
return
}
| package main
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func rootVolPath() string {
volumes, err := filepath.Glob("/Volumes/*")
if err != nil || volumes == nil {
log.Println("Unable to list /Volumes/*")
log.Fatal(err)
}
for _, volume := range volumes {
link_path, err := os.Readlink(volume)
if err == nil && link_path == "/" {
return volume
}
}
log.Fatal("Could not find root volume")
return ""
}
func volPath(target string) string {
var err error
target, err = filepath.Abs(target)
if err != nil {
log.Fatal(err)
}
target = filepath.Clean(target)
target_list := strings.Split(target, string(filepath.Separator))
if len(target_list) >= 2 &&
target_list[0] == "" &&
target_list[1] == "Volumes" {
return target
}
return filepath.Join(rootVolPath(), target)
}
func getTMDir() (dirname string, err error) {
dirname_bytes, err := exec.Command("tmutil", "machinedirectory").CombinedOutput()
if err != nil {
dirname = filepath.Join(strings.TrimSpace(string(dirname_bytes)), "Latest")
}
return
}
|
Change argument name in Stack() to fix uglify bug. | var ErrorStackParser = require('error-stack-parser');
var UNKNOWN_FUNCTION = '?';
function guessFunctionName(url, line) {
return UNKNOWN_FUNCTION;
}
function gatherContext(url, line) {
return null;
}
function Frame(stackFrame) {
var data = {};
data._stackFrame = stackFrame;
data.url = stackFrame.fileName;
data.line = stackFrame.lineNumber;
data.func = stackFrame.functionName;
data.column = stackFrame.columnNumber;
data.args = stackFrame.args;
data.context = gatherContext(data.url, data.line);
return data;
};
function Stack(exception) {
function getStack() {
var parserStack = [];
try {
parserStack = ErrorStackParser.parse(exception);
} catch(e) {
parserStack = [];
}
var stack = [];
for (var i = 0; i < parserStack.length; i++) {
stack.push(new Frame(parserStack[i]));
}
return stack;
}
return {
stack: getStack(),
message: exception.message,
name: exception.name
};
};
function parse(e) {
return new Stack(e);
}
module.exports = {
guessFunctionName: guessFunctionName,
gatherContext: gatherContext,
parse: parse,
Stack: Stack,
Frame: Frame
};
| var ErrorStackParser = require('error-stack-parser');
var UNKNOWN_FUNCTION = '?';
function guessFunctionName(url, line) {
return UNKNOWN_FUNCTION;
}
function gatherContext(url, line) {
return null;
}
function Frame(stackFrame) {
var data = {};
data._stackFrame = stackFrame;
data.url = stackFrame.fileName;
data.line = stackFrame.lineNumber;
data.func = stackFrame.functionName;
data.column = stackFrame.columnNumber;
data.args = stackFrame.args;
data.context = gatherContext(data.url, data.line);
return data;
};
function Stack(e) {
function getStack() {
var parserStack = [];
try {
parserStack = ErrorStackParser.parse(e);
} catch(e) {
parserStack = [];
}
var stack = [];
for (var i = 0; i < parserStack.length; i++) {
stack.push(new Frame(parserStack[i]));
}
return stack;
}
return {
stack: getStack(),
message: e.message,
name: e.name
};
};
function parse(e) {
return new Stack(e);
}
module.exports = {
guessFunctionName: guessFunctionName,
gatherContext: gatherContext,
parse: parse,
Stack: Stack,
Frame: Frame
};
|
Add TODO to test mail | <?php
namespace Myjob\Http\Controllers;
use Auth;
use Input;
use Myjob\Models\Publisher;
use Session;
use Validator;
use Mail;
class PublishersController extends Controller {
public function getForgottenLink() {
return view("publishers.link");
}
public function postForgottenLink() {
$email = Input::get('email');
if (!Publisher::exists($email)) {
return back()->withErrors(trans('general.texts.forgotten-link-error', ['email' => $email]));
} else {
$secret = Publisher::generate_new_secret($email);
// TODO test when sending mail work again
/*Mail::send('emails.publishers', ['email' => $email, 'secret' => $secret], function ($m) use (&$email) {
$m->to($email)->subject(trans('mails.publishers.link'));
});*/
Session::flash('success', trans('general.texts.forgotten-link-success'));
return redirect()->Action('HomeController@index');
}
}
}
| <?php
namespace Myjob\Http\Controllers;
use Auth;
use Input;
use Myjob\Models\Publisher;
use Session;
use Validator;
use Mail;
class PublishersController extends Controller {
public function getForgottenLink() {
return view("publishers.link");
}
public function postForgottenLink() {
$email = Input::get('email');
if (!Publisher::exists($email)) {
return back()->withErrors(trans('general.texts.forgotten-link-error', ['email' => $email]));
} else {
$secret = Publisher::generate_new_secret($email);
Mail::send('emails.publishers', ['email' => $email, 'secret' => $secret], function ($m) use (&$email) {
$m->to($email)->subject(trans('mails.publishers.link'));
});
Session::flash('success', trans('general.texts.forgotten-link-success'));
return redirect()->Action('HomeController@index');
}
}
}
|
Change import name in deps test | import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import pact
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) as f:
print('name: testproj', file=f)
_cob_on(projdir, 'bootstrap')
assert os.path.exists(python)
assert subprocess.call([python, '-c', 'import pact']) == 1
with yaml.open('a') as f:
print('deps:', file=f)
print(' - pact', file=f)
_cob_on(projdir, 'bootstrap')
assert subprocess.call([python, '-c', 'import pact']) == 0
def _cob_on(cwd, cmd):
x = os.environ.pop('COB_NO_REENTRY')
try:
subprocess.check_call([sys.executable, '-m', 'cob.cli.main', '-vvvvv', str(cmd)], cwd=str(cwd))
finally:
os.environ['COB_NO_REENTRY'] = x
| import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import sentinels
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) as f:
print('name: testproj', file=f)
_cob_on(projdir, 'bootstrap')
assert os.path.exists(python)
assert subprocess.call([python, '-c', 'import sentinels']) == 1
with yaml.open('a') as f:
print('deps:', file=f)
print(' - sentinels', file=f)
_cob_on(projdir, 'bootstrap')
assert subprocess.call([python, '-c', 'import sentinels']) == 0
def _cob_on(cwd, cmd):
x = os.environ.pop('COB_NO_REENTRY')
try:
subprocess.check_call([sys.executable, '-m', 'cob.cli.main', '-vvvvv', str(cmd)], cwd=str(cwd))
finally:
os.environ['COB_NO_REENTRY'] = x
|
Make the listener method private now | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
public class TestScreens {
private static void setup(FMLClientSetupEvent event) {
MainThreadWorker.run(() -> {
ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
});
}
public static void registerMod(IEventBus bus) {
bus.addListener(TestScreens::setup);
}
}
| package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
public class TestScreens {
public static void setup(FMLClientSetupEvent event) {
MainThreadWorker.run(() -> {
ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
});
}
public static void registerMod(IEventBus bus) {
bus.addListener(TestScreens::setup);
}
}
|
Fix vrt scenario script issue. | /**
* Site Kit by Google, Copyright 2022 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import SpinnerButton from './SpinnerButton';
const Template = ( args ) => <SpinnerButton { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Button';
DefaultButton.args = {
children: 'Default Button',
onClick: () => new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ),
};
export default {
title: 'Components/SpinnerButton',
component: SpinnerButton,
};
| /**
* Site Kit by Google, Copyright 2022 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import SpinnerButton from './SpinnerButton';
const Template = ( args ) => <SpinnerButton { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Button';
DefaultButton.args = {
children: 'Default Button',
onClick() {
return new Promise( ( resolve ) => setTimeout( resolve, 5000 ) );
},
};
export default {
title: 'Components/SpinnerButton',
component: SpinnerButton,
};
|
Make this constant-generating script independent of the solidity emulation module. | from decimal import Decimal
from decimal import getcontext
from decimal import ROUND_FLOOR
from decimal import ROUND_CEILING
MIN_PRECISION = 32
MAX_PRECISION = 127
def ln(n):
return Decimal(n).ln()
def log2(n):
return ln(n)/ln(2)
def floor(d):
return int(d.to_integral_exact(rounding=ROUND_FLOOR))
def ceiling(d):
return int(d.to_integral_exact(rounding=ROUND_CEILING))
getcontext().prec = MAX_PRECISION
maxVal = floor(log2(2**(256-MAX_PRECISION)-1)*2**MAX_PRECISION)-1
FLOOR_LN2_EXPONENT = floor(log2((2**256-1)/(maxVal*ln(2))))
FLOOR_LN2_MANTISSA = floor(2**FLOOR_LN2_EXPONENT*ln(2))
CEILING_LN2_MANTISSA = ceiling(2**MIN_PRECISION*ln(2))
print ' uint256 constant CEILING_LN2_MANTISSA = 0x{:x};'.format(CEILING_LN2_MANTISSA)
print ' uint256 constant FLOOR_LN2_MANTISSA = 0x{:x};'.format(FLOOR_LN2_MANTISSA )
print ' uint8 constant FLOOR_LN2_EXPONENT = {:d};' .format(FLOOR_LN2_EXPONENT )
| import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from decimal import Decimal
from decimal import getcontext
from FormulaSolidityPort import fixedLog2
MIN_PRECISION = 32
MAX_PRECISION = 127
getcontext().prec = MAX_PRECISION
ln2 = Decimal(2).ln()
fixedLog2MaxInput = ((1<<(256-MAX_PRECISION))-1)<<MAX_PRECISION
fixedLog2MaxOutput = fixedLog2(fixedLog2MaxInput,MAX_PRECISION)
FLOOR_LN2_EXPONENT = int((((1<<256)-1)/(fixedLog2MaxOutput*ln2)).ln()/ln2)
FLOOR_LN2_MANTISSA = int(2**FLOOR_LN2_EXPONENT*ln2)
CEILING_LN2_MANTISSA = int(ln2*(1<<MIN_PRECISION)+1)
print ' uint256 constant CEILING_LN2_MANTISSA = 0x{:x};'.format(CEILING_LN2_MANTISSA)
print ' uint256 constant FLOOR_LN2_MANTISSA = 0x{:x};'.format(FLOOR_LN2_MANTISSA )
print ' uint8 constant FLOOR_LN2_EXPONENT = {:d};' .format(FLOOR_LN2_EXPONENT )
|
Add waitRegexp as an argument. | var childProcess = require('child_process');
var q = require('q');
/**
* Spawn a child process given a command. Wait for the process to start given
* a regexp that will be matched against stdout.
*
* @param {string} command The command to execute.
* @param {RegExp} waitRegexp An expression used to test when the process has
* started.
* @return {Q.promise} A promise that resolves when the process has stated.
*/
var runCommand = function(command, waitRegexp) {
var deferred = q.defer();
console.log('Running command: [%s]', command);
var commandArray = command.split(/\s/);
// First arg: command, then pass arguments as array.
var child = childProcess.spawn(commandArray[0], commandArray.slice(1));
child.stdout.on('data', function(data) {
var line = data.toString();
process.stdout.write(line);
// Wait until the port is ready to resolve the promise.
if (line.match(waitRegexp)) {
deferred.resolve();
}
});
// The process uses stderr for debugging info. Ignore errors.
child.stderr.on('data', process.stderr.write);
return deferred.promise;
};
module.exports = {
runCommand: runCommand
};
| var childProcess = require('child_process');
var q = require('q');
var runCommand = function(command) {
var deferred = q.defer();
console.log('Running command: [%s]', command);
var commandArray = command.split(/\s/);
// First arg: command, then pass arguments as array.
var child = childProcess.spawn(commandArray[0], commandArray.slice(1));
child.stdout.on('data', function(data) {
var line = data.toString();
process.stdout.write(line);
// Wait until the port is ready to resolve the promise.
if (line.match(/Server listening on/g)) {
deferred.resolve();
}
});
// The process uses stderr for debugging info. Ignore errors.
child.stderr.on('data', process.stderr.write);
return deferred.promise;
};
module.exports = {
runCommand: runCommand
};
|
Fix tests to use pipe as well | import { customTaxonomyFilter } from 'dummy/helpers/custom-taxonomy-filter';
import { module, test } from 'qunit';
module('Unit | Helper | custom taxonomy filter');
test('replace very deep custom taxonomy hierarchy with just final subject name', function(assert) {
let result = customTaxonomyFilter(['bepress|Fruits|Bananas|Green Bananas|Small / Green Bananas|Small Green Bananas with Polka Dots']);
assert.equal(result, 'Small Green Bananas with Polka Dots');
});
test('replace shallow custom taxonomy with just final subject name', function(assert) {
let result = customTaxonomyFilter(['bepress|Fruits']);
assert.equal(result, 'Fruits');
});
test('return original subject if not a custom taxonomy', function(assert) {
let result = customTaxonomyFilter(['Fruits and Bananas']);
assert.equal(result, 'Fruits and Bananas');
});
test('return original subject if separated with slashes', function(assert) {
let result = customTaxonomyFilter(['osf/Fruits/Bananas']);
assert.equal(result, 'osf/Fruits/Bananas');
});
| import { customTaxonomyFilter } from 'dummy/helpers/custom-taxonomy-filter';
import { module, test } from 'qunit';
module('Unit | Helper | custom taxonomy filter');
test('replace very deep custom taxonomy hierarchy with just final subject name', function(assert) {
let result = customTaxonomyFilter(['bepress/Fruits/Bananas/Green Bananas/Small Green Bananas/Small Green Bananas with Polka Dots']);
assert.equal(result, 'Small Green Bananas with Polka Dots');
});
test('replace shallow custom taxonomy with just final subject name', function(assert) {
let result = customTaxonomyFilter(['bepress/Fruits']);
assert.equal(result, 'Fruits');
});
test('return original subject if not a custom taxonomy', function(assert) {
let result = customTaxonomyFilter(['Fruits and Bananas']);
assert.equal(result, 'Fruits and Bananas');
});
test('return original subject if not a recognized custom taxonomy', function(assert) {
let result = customTaxonomyFilter(['osf/Fruits/Bananas']);
assert.equal(result, 'osf/Fruits/Bananas');
});
|
Correct operation. Now to fix panda warnings | import json
import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('statement.csv')
conversions = json.load(open('description_conversion.json'))
output = df[['Date']]
output['Type'] = df.apply(fn, axis=1)
output['Description'] = (df['Counter Party'] + ' ' + df['Reference']).replace(conversions)
output['Paid Out'] = df['Amount (GBP)'].copy()
output['Paid In'] = df['Amount (GBP)'].copy()
output['Paid Out'] = output['Paid Out'] * -1
output['Paid Out'][output['Paid Out'] < 0] = None
output['Paid In'][output['Paid In'] < 0] = None
output['Balance'] = df['Balance (GBP)']
output.to_csv('output.csv', index=False)
| import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('statement.csv')
output = df[['Date']]
output['Type'] = df.apply(fn, axis=1)
output['Description'] = df['Reference']
output['Paid Out'] = df['Amount (GBP)'].copy()
output['Paid In'] = df['Amount (GBP)'].copy()
output['Paid Out'] = output['Paid Out'] * -1
output['Paid Out'][output['Paid Out'] < 0] = None
output['Paid In'][output['Paid In'] < 0] = None
output['Balance'] = df['Balance (GBP)']
print(output)
output.to_csv('output.csv', index=False)
|
Correct history capability for "Diesel Sweeties (web)" | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Diesel Sweeties (web)"
language = "en"
url = "http://www.dieselsweeties.com/"
start_date = "2000-01-01"
rights = "Richard Stevens"
class Crawler(CrawlerBase):
history_capable_days = 155
schedule = "Mo,We,Fr"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.dieselsweeties.com/ds-unifeed.xml")
for entry in feed.for_date(pub_date):
if not hasattr(entry, "summary"):
continue
url = entry.summary.src('img[src*="/strips666/"]')
title = entry.title
text = entry.summary.alt('img[src*="/strips666/"]')
return CrawlerImage(url, title, text)
| from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Diesel Sweeties (web)"
language = "en"
url = "http://www.dieselsweeties.com/"
start_date = "2000-01-01"
rights = "Richard Stevens"
class Crawler(CrawlerBase):
history_capable_date = "2000-01-01"
schedule = "Mo,We,Fr"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.dieselsweeties.com/ds-unifeed.xml")
for entry in feed.for_date(pub_date):
if not hasattr(entry, "summary"):
continue
url = entry.summary.src('img[src*="/strips666/"]')
title = entry.title
text = entry.summary.alt('img[src*="/strips666/"]')
return CrawlerImage(url, title, text)
|
Fix dumb bug in release task | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False):
runner = "python"
if coverage:
runner = "coverage run --source=paramiko"
flags = "--verbose"
ctx.run("{0} test.py {1}".format(runner, flags), pty=True)
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs")
# Move the built docs into where Epydocs used to live
target = 'docs'
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree('sites/docs/_build', target)
# Publish
publish(ctx)
# Remind
print("\n\nDon't forget to update RTD's versions page for new minor releases!")
ns = Collection(test, coverage, release, docs, www)
| from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False):
runner = "python"
if coverage:
runner = "coverage run --source=paramiko"
flags = "--verbose"
ctx.run("{0} test.py {1}".format(runner, flags), pty=True)
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs")
# Move the built docs into where Epydocs used to live
target = 'docs'
rmtree(target, ignore_errors=True)
copytree(docs_build, target)
# Publish
publish(ctx)
# Remind
print("\n\nDon't forget to update RTD's versions page for new minor releases!")
ns = Collection(test, coverage, release, docs, www)
|
Add wsgi_intercept to the dependencies list | #! /usr/bin/env python
from setuptools import setup, find_packages
setup(
name='armet',
version='0.3.0-pre',
description='Clean and modern framework for creating RESTful APIs.',
author='Concordus Applications',
author_email='support@concordusapps.com',
url='http://github.com/armet/python-armet',
package_dir={'armet': 'src/armet'},
packages=find_packages('src'),
install_requires=(
'six', # Python 2 and 3 normalization layer
'python-mimeparse' # For parsing accept and content-type headers
),
extras_require={
'test': (
'nose',
'yanc',
'httplib2',
'flask',
'django',
'wsgi_intercept'
)
}
)
| #! /usr/bin/env python
from setuptools import setup, find_packages
setup(
name='armet',
version='0.3.0-pre',
description='Clean and modern framework for creating RESTful APIs.',
author='Concordus Applications',
author_email='support@concordusapps.com',
url='http://github.com/armet/python-armet',
package_dir={'armet': 'src/armet'},
packages=find_packages('src'),
install_requires=(
'six', # Python 2 and 3 normalization layer
'python-mimeparse' # For parsing accept and content-type headers
),
extras_require={
'test': (
'nose',
'yanc',
'httplib2',
'flask',
'django'
)
}
)
|
Send cookies with AJAX requests | var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1',
ajax: function(url, method, hash) {
hash.xhrFields = {withCredentials: true};
return this._super(url, method, hash);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
}) | var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1'
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
}) |
Fix reference to non-existent field. Inject session state into ctor. | module.exports = (function() {
var def = require('./def');
var util = require('./util');
var guard_undef = util.guard_undef;
var Message = def.type(function(client, raw_msg) {
guard_undef(raw_msg);
this.def_prop('raw', raw_msg);
this.def_prop('channel', client.getChannelGroupOrDMByID(raw_msg.channel));
this.def_prop('user', client.getUserByID(raw_msg.user));
this.def_prop('text', raw_msg.text);
});
Message.def_method(function send_to(name, text) {
return this.respond('@' + name + ': ' + text);
});
Message.def_method(function reply(text) {
return this.send_to(this.user.name, text);
});
Message.def_method(function respond(text) {
this.channel.send(text);
});
return Message;
})();
| module.exports = (function() {
var def = require('./def');
var util = require('./util');
var guard_undef = util.guard_undef;
var Message = def.type(function(raw_msg) {
guard_undef(raw_msg);
this.def_prop('raw', raw_msg);
this.def_prop('channel', slack.getChannelGroupOrDMByID(raw_msg.channel));
this.def_prop('user', slack.getUserByID(raw_msg.user));
this.def_prop('text', raw_msg.text);
});
Message.def_method(function send_to(name, text) {
return this.respond('@' + name + ': ' + text);
});
Message.def_method(function reply(text) {
return this.send_to(this.raw_msg.user.name, text);
});
Message.def_method(function respond(text) {
this.channel.send(text);
});
return Message;
})();
|
Use NetUtil.getNextAvailablePort to get a testing port | /*
* Copyright (c) 2017 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial concept and initial implementation
*/
package coyote.commons.network.http;
//import static org.junit.Assert.*;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import coyote.commons.NetUtil;
/**
*
*/
public class TestHttpd {
private static HTTPD server = null;
private static int port = 54321;
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
port = NetUtil.getNextAvailablePort( port );
server = new TestingServer( port );
try {
server.start( HTTPD.SOCKET_READ_TIMEOUT, true );
} catch ( IOException ioe ) {
System.err.println( "Couldn't start server:\n" + ioe );
server.stop();
server = null;
}
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
server.stop();
}
@Test
public void test() {
assertNotNull( server );
assertTrue( port == server.getPort() );
}
}
| /*
* Copyright (c) 2017 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial concept and initial implementation
*/
package coyote.commons.network.http;
//import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
*/
public class TestHttpd {
private static HTTPD server = null;
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
server = new TestingServer( 62300 );
try {
server.start( HTTPD.SOCKET_READ_TIMEOUT, true );
} catch ( IOException ioe ) {
System.err.println( "Couldn't start server:\n" + ioe );
server.stop();
server = null;
}
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
server.stop();
}
@Test
public void test() {
assertNotNull( server );
}
}
|
Use non-cached sever for mac install script | import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://raw.githubusercontent.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.system().lower():
# Install launch agents
print('Copy paste the following line(s) to execute in your bash terminal:\n')
print('%s %s' % (script, PYTHONPATH))
print('\n')
else:
print('Set these environmental variables to use PVGeo in ParaView:')
print('\n')
print('export PYTHONPATH="%s"' % PYTHONPATH)
print('export PV_PLUGIN_PATH="%s"' % PV_PLUGIN_PATH)
print('\n')
return
if __name__ == '__main__':
arg = sys.argv[1]
if arg.lower() == 'install':
GetInstallationPaths()
else:
raise RuntimeError('Unknown argument: %s' % arg)
| import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://cdn.rawgit.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.system().lower():
# Install launch agents
print('Copy paste the following line(s) to execute in your bash terminal:\n')
print('%s %s' % (script, PYTHONPATH))
print('\n')
else:
print('Set these environmental variables to use PVGeo in ParaView:')
print('\n')
print('export PYTHONPATH="%s"' % PYTHONPATH)
print('export PV_PLUGIN_PATH="%s"' % PV_PLUGIN_PATH)
print('\n')
return
if __name__ == '__main__':
arg = sys.argv[1]
if arg.lower() == 'install':
GetInstallationPaths()
else:
raise RuntimeError('Unknown argument: %s' % arg)
|
Add the different segments that makes up crowdmap endit point as constants for easier maintenance | /*****************************************************************************
** Copyright (c) 2010 - 2012 Ushahidi Inc
** All rights reserved
** Contact: team@ushahidi.com
** Website: http://www.ushahidi.com
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: http://www.gnu.org/licenses/lgpl.html.
**
**
** If you have questions regarding the use of this file, please contact
** Ushahidi developers at team@ushahidi.com.
**
*****************************************************************************/
package com.crowdmap.java.sdk.net;
/**
* Crowdmap constants for http related activities
*/
public interface ICrowdmapConstants {
public String CHARSET_UTF8 = "UTF-8";
public String CONTENT_TYPE_JSON = "application/json";
public String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public String HOST_API = "api.crdmp3.com";
public String API_VERSION = "v1";
public String PROTOCOL_HTTPS = "https";
public String PROTOCOL_HTTP = "http";
public String URL_API = PROTOCOL_HTTP + "://" + HOST_API;
public String SEGMENT_MEDIA = "/media";
public String SEGMENT_MAPS = "/maps";
public String SEGMENT_LOCATIONS = "/locations";
public String SEGMENT_POSTS = "/posts";
public String SEGMENT_PEOPLE = "/people";
public String SEGMENT_EXTERNALS = "/externals";
public String SEGMENT_ABOUT = "/about";
public String SEGMENT_HEARTBEAT = "/heartbeat";
public String SEGMENT_PLACES_SEARCH = "/places/search";
}
| /*****************************************************************************
** Copyright (c) 2010 - 2012 Ushahidi Inc
** All rights reserved
** Contact: team@ushahidi.com
** Website: http://www.ushahidi.com
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: http://www.gnu.org/licenses/lgpl.html.
**
**
** If you have questions regarding the use of this file, please contact
** Ushahidi developers at team@ushahidi.com.
**
*****************************************************************************/
package com.crowdmap.java.sdk.net;
/**
* Crowdmap constants for http related activities
*/
public interface ICrowdmapConstants {
public String CHARSET_UTF8 = "UTF-8";
public String CONTENT_TYPE_JSON = "application/json";
public String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
}
|
Fix up env var name. | package com.nexmo.quickstart.voice;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import java.nio.file.FileSystems;
import static com.nexmo.quickstart.Util.*;
public class OutboundTextToSpeech {
public static void main(String[] args) throws Exception {
configureLogging();
String NEXMO_APPLICATION_ID = envVar("APPLICATION_ID");
String NEXMO_APPLICATION_PRIVATE_KEY = envVar("PRIVATE_KEY");
String NEXMO_NUMBER = envVar("FROM_NUMBER");
String TO_NUMBER = envVar("TO_NUMBER");
AuthMethod auth = new JWTAuthMethod(
NEXMO_APPLICATION_ID,
FileSystems.getDefault().getPath(NEXMO_APPLICATION_PRIVATE_KEY)
);
NexmoClient client = new NexmoClient(auth);
client.getVoiceClient().createCall(new Call(
TO_NUMBER,
NEXMO_NUMBER,
"https://developer.nexmo.com/ncco/tts.json"
));
}
}
| package com.nexmo.quickstart.voice;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import java.nio.file.FileSystems;
import static com.nexmo.quickstart.Util.*;
public class OutboundTextToSpeech {
public static void main(String[] args) throws Exception {
configureLogging();
String NEXMO_APPLICATION_ID = envVar("APPLICATION_ID");
String NEXMO_APPLICATION_PRIVATE_KEY = envVar("NEXMO_APPLICATION_PRIVATE_KEY");
String NEXMO_NUMBER = envVar("FROM_NUMBER");
String TO_NUMBER = envVar("TO_NUMBER");
AuthMethod auth = new JWTAuthMethod(
NEXMO_APPLICATION_ID,
FileSystems.getDefault().getPath(NEXMO_APPLICATION_PRIVATE_KEY)
);
NexmoClient client = new NexmoClient(auth);
client.getVoiceClient().createCall(new Call(
TO_NUMBER,
NEXMO_NUMBER,
"https://developer.nexmo.com/ncco/tts.json"
));
}
}
|
Remove blank line at end of file. | # -*- coding: utf-8 -*-
"""
Property Test: orchard.app
"""
import hypothesis
import hypothesis.strategies as st
import unittest
import orchard
class AppPropertyTest(unittest.TestCase):
def setUp(self):
self.app_context = orchard.app.app_context()
self.app_context.push()
self.client = orchard.app.test_client(use_cookies = True)
def tearDown(self):
self.app_context.pop()
@hypothesis.given(name = st.text(alphabet = ['a', 'b', 'c', 'A', 'B', 'C']))
def test_index(self, name):
response = self.client.get('/{name}'.format(name = name))
data = response.get_data(as_text = True)
self.assertEqual(response.status_code, 200)
self.assertTrue(name in data)
| # -*- coding: utf-8 -*-
"""
Property Test: orchard.app
"""
import hypothesis
import hypothesis.strategies as st
import unittest
import orchard
class AppPropertyTest(unittest.TestCase):
def setUp(self):
self.app_context = orchard.app.app_context()
self.app_context.push()
self.client = orchard.app.test_client(use_cookies = True)
def tearDown(self):
self.app_context.pop()
@hypothesis.given(name = st.text(alphabet = ['a', 'b', 'c', 'A', 'B', 'C']))
def test_index(self, name):
response = self.client.get('/{name}'.format(name = name))
data = response.get_data(as_text = True)
self.assertEqual(response.status_code, 200)
self.assertTrue(name in data)
|
Refactor for changes in retext | 'use strict';
/**
* Dependencies.
*/
var phonetics;
phonetics = require('soundex-code');
/**
* Change handler
*
* @this {WordNode}
*/
function onchange() {
var data,
value;
data = this.data;
value = this.toString();
data.phonetics = value ? phonetics(value, Infinity) : null;
if ('stem' in data) {
data.stemmedPhonetics = value ? phonetics(data.stem, Infinity) : null;
}
}
/**
* Define `soundex`.
*
* @param {Retext} retext
*/
function soundex(retext) {
var WordNode;
WordNode = retext.TextOM.WordNode;
WordNode.on('changetextinside', onchange);
WordNode.on('removeinside', onchange);
WordNode.on('insertinside', onchange);
}
/**
* Expose `soundex`.
*/
module.exports = soundex;
| 'use strict';
/**
* Dependencies.
*/
var phonetics;
phonetics = require('soundex-code');
/**
* Define `soundex`.
*/
function soundex() {}
/**
* Change handler
*
* @this {WordNode}
*/
function onchange() {
var data,
value;
data = this.data;
value = this.toString();
data.phonetics = value ? phonetics(value, Infinity) : null;
if ('stem' in data) {
data.stemmedPhonetics = value ? phonetics(data.stem, Infinity) : null;
}
}
/**
* Define `attach`.
*
* @param {Retext} retext
*/
function attach(retext) {
var WordNode;
WordNode = retext.TextOM.WordNode;
WordNode.on('changetextinside', onchange);
WordNode.on('removeinside', onchange);
WordNode.on('insertinside', onchange);
}
/**
* Expose `attach`.
*/
soundex.attach = attach;
/**
* Expose `soundex`.
*/
module.exports = soundex;
|
Add missing .txt to readme so it can be read in properly. | from setuptools import setup, find_packages
import os
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='geodjango-uscampgrounds',
version='1.0',
description='A set of Django models to store the data files from uscampgrounds.info',
author='Adam Fast',
author_email='adamfast@gmail.com',
url='https://github.com/adamfast/geodjango-uscampgrounds',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
long_description=read('README.txt'),
license = "BSD",
keywords = "django geodjango",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| from setuptools import setup, find_packages
import os
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='geodjango-uscampgrounds',
version='1.0',
description='A set of Django models to store the data files from uscampgrounds.info',
author='Adam Fast',
author_email='adamfast@gmail.com',
url='https://github.com/adamfast/geodjango-uscampgrounds',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
long_description=read('README'),
license = "BSD",
keywords = "django geodjango",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Fix query of group for PostgreSQL | <?php
namespace Lexxpavlov\SettingsBundle\Entity;
use Doctrine\ORM\EntityRepository;
class SettingsRepository extends EntityRepository
{
/**
* @param string $name
* @return Settings[]
*/
public function getGroup($name)
{
return $this->createQueryBuilder('s')
->innerJoin('s.category', 'c')
->where('c.name = :name')
->setParameter('name', $name)
->getQuery()
->getResult();
}
/**
* @param Settings $setting
*/
public function save(Settings $setting)
{
$this->_em->persist($setting);
$this->_em->flush();
}
}
| <?php
namespace Lexxpavlov\SettingsBundle\Entity;
use Doctrine\ORM\EntityRepository;
class SettingsRepository extends EntityRepository
{
/**
* @param string $name
* @return Settings[]
*/
public function getGroup($name)
{
return $this->_em
->createQuery("SELECT s FROM LexxpavlovSettingsBundle:Settings s INNER JOIN LexxpavlovSettingsBundle:Category g WHERE g.id = s.category AND g.name = ?1")
->setParameter(1, $name)
->getResult();
}
/**
* @param Settings $setting
*/
public function save(Settings $setting)
{
$this->_em->persist($setting);
$this->_em->flush();
}
}
|
Fix exclude of sample_project for installation. | import os
from setuptools import setup, find_packages
packages = find_packages(exclude=['sample_project'])
classifiers = """
Topic :: Internet :: WWW/HTTP :: Dynamic Content
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
Development Status :: 4 - Beta
Operating System :: OS Independent
"""
setup(
name='django-pagelets',
version='0.5',
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=packages,
install_requires = [],
include_package_data = True,
exclude_package_data={
'': ['*.sql', '*.pyc'],
'pagelets': ['media/*'],
},
url='http://http://github.com/caktus/django-pagelets',
license='LICENSE.txt',
description='Simple, flexible app for integrating static, unstructured '
'content in a Django site',
classifiers = filter(None, classifiers.split("\n")),
long_description=open('README.rst').read(),
)
| import os
from setuptools import setup, find_packages
packages = find_packages()
packages.remove('sample_project')
classifiers = """
Topic :: Internet :: WWW/HTTP :: Dynamic Content
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
Development Status :: 4 - Beta
"""
setup(
name='django-pagelets',
version='0.5',
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=packages,
install_requires = [],
include_package_data = True,
exclude_package_data={
'': ['*.sql', '*.pyc'],
'pagelets': ['media/*'],
},
url='http://http://github.com/caktus/django-pagelets',
license='LICENSE.txt',
description='Simple, flexible app for integrating static, unstructured '
'content in a Django site',
classifiers = filter(None, classifiers.split("\n")),
long_description=open('README.rst').read(),
)
|
Change list type for a faster script selection | #! /usr/bin/env node
/* eslint import/no-dynamic-require: 0 */
const log = require('winston');
const inquirer = require('inquirer');
const search = require('./lib/search');
const exec = require('./lib/exec');
const packageJSON = require(`${process.cwd()}/package.json`);
const commands = Object.keys(packageJSON.scripts).map(command => ({ command, humanized: command.split(':').join(' ') }));
const searchTerm = process.argv.slice(2).join(' ');
log.remove(log.transports.Console);
log.add(log.transports.Console, { colorize: true });
const prompt = () => {
inquirer.prompt({
message: 'Choose a command to run:',
type: 'rawlist',
name: 'command',
pageSize: 100,
choices: commands.map(c => c.command),
})
.then((answer) => {
exec(answer.command);
});
};
const fuseSearch = () => {
const result = search(commands, searchTerm);
if (result.length > 0) {
const command = result[0].item.command;
exec(command);
} else {
log.error(`There are no results that match "${searchTerm}"`);
process.exit(1);
}
};
if (!searchTerm) {
prompt();
} else {
fuseSearch();
}
| #! /usr/bin/env node
/* eslint import/no-dynamic-require: 0 */
const log = require('winston');
const inquirer = require('inquirer');
const search = require('./lib/search');
const exec = require('./lib/exec');
const packageJSON = require(`${process.cwd()}/package.json`);
const commands = Object.keys(packageJSON.scripts).map(command => ({ command, humanized: command.split(':').join(' ') }));
const searchTerm = process.argv.slice(2).join(' ');
log.remove(log.transports.Console);
log.add(log.transports.Console, { colorize: true });
const prompt = () => {
inquirer.prompt({
message: 'Choose a command to run:',
type: 'list',
name: 'command',
pageSize: 100,
choices: commands.map(c => c.command),
})
.then((answer) => {
exec(answer.command);
});
};
const fuseSearch = () => {
const result = search(commands, searchTerm);
if (result.length > 0) {
const command = result[0].item.command;
exec(command);
} else {
log.error(`There are no results that match "${searchTerm}"`);
process.exit(1);
}
};
if (!searchTerm) {
prompt();
} else {
fuseSearch();
}
|
Use 'lodash/assignIn' to avoid bundling all of lodash. | import assignIn from 'lodash/assignIn';
import {
DISPATCH_TYPE,
STATE_TYPE
} from '../constants';
class Store {
constructor({portName, state = {}}) {
this.port = chrome.runtime.connect({name: portName});
this.listeners = [];
this.state = state;
this.port.onMessage.addListener((message) => {
if (message.type === STATE_TYPE) {
this.replaceState(message.payload);
}
});
this.dispatch = this.dispatch.bind(this);
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
replaceState(state) {
this.state = state;
this.listeners.forEach((l) => l());
}
getState() {
return this.state;
}
dispatch(data) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
type: DISPATCH_TYPE,
payload: data
}, ({error, value}) => {
if (error) {
reject(assignIn((new Error()), error));
} else {
resolve(value.payload);
}
});
});
}
}
export default Store;
| import _ from 'lodash';
import {
DISPATCH_TYPE,
STATE_TYPE
} from '../constants';
class Store {
constructor({portName, state = {}}) {
this.port = chrome.runtime.connect({name: portName});
this.listeners = [];
this.state = state;
this.port.onMessage.addListener((message) => {
if (message.type === STATE_TYPE) {
this.replaceState(message.payload);
}
});
this.dispatch = this.dispatch.bind(this);
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
replaceState(state) {
this.state = state;
this.listeners.forEach((l) => l());
}
getState() {
return this.state;
}
dispatch(data) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
type: DISPATCH_TYPE,
payload: data
}, ({error, value}) => {
if (error) {
reject(_.extend((new Error()), error));
} else {
resolve(value.payload);
}
});
});
}
}
export default Store;
|
Update log to accomidate for web output
If running on a non-CLI system, print out <br> instead of \n | <?php
class Log
{
const LOG_ERROR = 'error';
const LOG_DEBUG = 'debug';
public static function add($level, $tag, $message)
{
$vargs = array_slice(func_get_args(), 3);
if (count($vargs) > 0) {
$params = array_merge(array($message), $vargs);
$message = call_user_func_array('sprintf', $params);
}
$fmt = "%s: [%s][%s] %s\n";
if (substr(PHP_SAPI, 0, 3) != 'cli')
$fmt = nl2br($fmt);
printf($fmt, strtoupper($level), date('Y-m-d H:i:s'), $tag, $message);
}
public static function debug($tag, $message)
{
$args = array_merge(array(self::LOG_DEBUG), func_get_args());
call_user_func_array('Log::add', $args);
}
public static function error($tag, $message)
{
$args = array_merge(array(self::LOG_ERROR), func_get_args());
call_user_func_array('Log::add', $args);
}
}
| <?php
class Log
{
const LOG_ERROR = 'error';
const LOG_DEBUG = 'debug';
public static function add($level, $tag, $message)
{
$vargs = array_slice(func_get_args(), 3);
if (count($vargs) > 0) {
$params = array_merge(array($message), $vargs);
$message = call_user_func_array('sprintf', $params);
}
printf("%s: [%s][%s] %s\n", strtoupper($level), date('Y-m-d H:i:s'), $tag, $message);
}
public static function debug($tag, $message)
{
$args = array_merge(array(self::LOG_DEBUG), func_get_args());
call_user_func_array('Log::add', $args);
}
public static function error($tag, $message)
{
$args = array_merge(array(self::LOG_ERROR), func_get_args());
call_user_func_array('Log::add', $args);
}
}
|
Remove sortObjectKeys to fix comparison function is undefined | import React from 'react'
import { Segment, Message } from 'semantic-ui-react'
import JSONTree from 'react-json-tree'
type Props = {
loading: boolean,
expanded: boolean,
response: any,
error: ?Error,
}
const Response = ({ loading, expanded, response, error }: Props) => {
if (loading) {
return (
<Segment loading className='result' />
)
} else if (error != null) {
return (
<Segment className='result'>
<Message negative>
<Message.Header>{error.message}</Message.Header>
<pre>{error.stack}</pre>
</Message>
</Segment>
)
} else if (response != null) {
return (
<Segment className='result'>
<JSONTree
hideRoot
shouldExpandNode={() => expanded}
data={response}
/>
</Segment>
)
}
return null
}
export default Response
| import React from 'react'
import { Segment, Message } from 'semantic-ui-react'
import JSONTree from 'react-json-tree'
type Props = {
loading: boolean,
expanded: boolean,
response: any,
error: ?Error,
}
const Response = ({ loading, expanded, response, error }: Props) => {
if (loading) {
return (
<Segment loading className='result' />
)
} else if (error != null) {
return (
<Segment className='result'>
<Message negative>
<Message.Header>{error.message}</Message.Header>
<pre>{error.stack}</pre>
</Message>
</Segment>
)
} else if (response != null) {
return (
<Segment className='result'>
<JSONTree
hideRoot
sortObjectKeys
shouldExpandNode={() => expanded}
data={response}
/>
</Segment>
)
}
return null
}
export default Response
|
Remove variables that are defined but never used | // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
// Constants
// ---------
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator) {
baseBrowserDecorator(this)
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
| // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
var exec = require('child_process').exec
// Constants
// ---------
var PROCESS_NAME = 'spartan.exe'
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator, logger) {
baseBrowserDecorator(this)
var log = logger.create('launcher')
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator', 'logger']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
|
Refactor argument processing to list comprehension | from query_builder import FILTER_FIELDS, TEXT_FIELDS
from conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, list):
return [strip_and_lowercase(value) for value in values]
elif isinstance(values, basestring):
return strip_and_lowercase(values)
return values
def convert_request_json_into_index_json(request_json):
filter_fields = [field for field in request_json if field in FILTER_FIELDS]
for field in filter_fields:
request_json["filter_" + field] = \
process_values_for_matching(request_json, field)
if field not in TEXT_FIELDS:
del request_json[field]
return request_json
| import types
from query_builder import FILTER_FIELDS, TEXT_FIELDS
from conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, types.ListType):
fixed = []
for i in values:
fixed.append(strip_and_lowercase(i))
return fixed
elif isinstance(values, basestring):
return strip_and_lowercase(values)
return values
def convert_request_json_into_index_json(request_json):
filter_fields = [field for field in request_json if field in FILTER_FIELDS]
for field in filter_fields:
request_json["filter_" + field] = \
process_values_for_matching(request_json, field)
if field not in TEXT_FIELDS:
del request_json[field]
return request_json
|
Add apparently important SINGLETON field | /*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.slf4j.impl;
import org.slf4j.spi.LoggerFactoryBinder;
import org.slf4j.ILoggerFactory;
public final class StaticLoggerBinder implements LoggerFactoryBinder {
public static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
public ILoggerFactory getLoggerFactory() {
return new Slf4jLoggerFactory();
}
public String getLoggerFactoryClassStr() {
return Slf4jLoggerFactory.class.getName();
}
}
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.slf4j.impl;
import org.slf4j.spi.LoggerFactoryBinder;
import org.slf4j.ILoggerFactory;
public final class StaticLoggerBinder implements LoggerFactoryBinder {
public ILoggerFactory getLoggerFactory() {
return new Slf4jLoggerFactory();
}
public String getLoggerFactoryClassStr() {
return Slf4jLoggerFactory.class.getName();
}
}
|
Fix bug in spec of getBatch.
--
MOS_MIGRATED_REVID=92398218 | // Copyright 2014 Google Inc. All rights reserved.
//
// 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.
package com.google.devtools.build.skyframe;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A graph that exposes its entries and structure, for use by classes that must traverse it.
*/
@ThreadSafe
public interface QueryableGraph {
/**
* Returns the node with the given name, or {@code null} if the node does not exist.
*/
@Nullable
NodeEntry get(SkyKey key);
/**
* Fetches all the given nodes. Returns a map {@code m} such that, for all {@code k} in
* {@code keys}, {@code m.get(k).equals(e)} iff {@code get(k) == e} and {@code e != null}, and
* {@code !m.containsKey(k)} iff {@code get(k) == null}.
*/
Map<SkyKey, NodeEntry> getBatch(Iterable<SkyKey> keys);
}
| // Copyright 2014 Google Inc. All rights reserved.
//
// 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.
package com.google.devtools.build.skyframe;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A graph that exposes its entries and structure, for use by classes that must traverse it.
*/
@ThreadSafe
public interface QueryableGraph {
/**
* Returns the node with the given name, or {@code null} if the node does not exist.
*/
@Nullable
NodeEntry get(SkyKey key);
/**
* Fetches all the given nodes. Returns a map {@code m} such that {@code m.get(k).equals(e)} for
* all {@code k} such that {@code get(k) == e} and {@code e != null}.
*/
Map<SkyKey, NodeEntry> getBatch(Iterable<SkyKey> keys);
}
|
Remove `is.buffer(body)` as it never happens when getting body size
Because buffers are always converted to a stream: https://github.com/sindresorhus/got/blob/master/source/normalize-arguments.js#L111 | 'use strict';
const fs = require('fs');
const util = require('util');
const is = require('@sindresorhus/is');
const isFormData = require('./is-form-data');
module.exports = async options => {
const {body} = options;
if (options.headers['content-length']) {
return Number(options.headers['content-length']);
}
if (!body && !options.stream) {
return 0;
}
if (is.string(body)) {
return Buffer.byteLength(body);
}
if (isFormData(body)) {
return util.promisify(body.getLength.bind(body))();
}
if (body instanceof fs.ReadStream) {
const {size} = await util.promisify(fs.stat)(body.path);
return size;
}
if (is.nodeStream(body) && is.buffer(body._buffer)) {
return body._buffer.length;
}
return null;
};
| 'use strict';
const fs = require('fs');
const util = require('util');
const is = require('@sindresorhus/is');
const isFormData = require('./is-form-data');
module.exports = async options => {
const {body} = options;
if (options.headers['content-length']) {
return Number(options.headers['content-length']);
}
if (!body && !options.stream) {
return 0;
}
if (is.string(body)) {
return Buffer.byteLength(body);
}
if (is.buffer(body)) {
return body.length;
}
if (isFormData(body)) {
return util.promisify(body.getLength.bind(body))();
}
if (body instanceof fs.ReadStream) {
const {size} = await util.promisify(fs.stat)(body.path);
return size;
}
if (is.nodeStream(body) && is.buffer(body._buffer)) {
return body._buffer.length;
}
return null;
};
|
Remove useless deps from latestService. | "use strict";
(function () {
angular
.module("conpa")
.factory("latestService", latestService);
latestService.$inject = ["portfoliosService"];
function latestService(portfoliosService) {
var latestPortfolios = [],
service = {
getLatestPortfolios: getLatestPortfolios,
refresh: refresh
};
return service;
function getLatestPortfolios() {
return latestPortfolios;
}
function refresh() {
portfoliosService.getLastCreatedPortfolios().then(function (ptfs) {
angular.merge(latestPortfolios, ptfs);
});
}
}
}());
| "use strict";
(function () {
angular
.module("conpa")
.factory("latestService", latestService);
latestService.$inject = ["$http", "$q", "portfoliosService"];
function latestService($http, $q, portfoliosService) {
var latestPortfolios = [],
service = {
getLatestPortfolios: getLatestPortfolios,
refresh: refresh
};
return service;
function getLatestPortfolios() {
return latestPortfolios;
}
function refresh() {
portfoliosService.getLastCreatedPortfolios().then(function (ptfs) {
angular.merge(latestPortfolios, ptfs);
});
}
}
}());
|
Check if form is dirty before going back to question list | import React from 'react';
import PropTypes from 'prop-types';
import CreateConnector from './CreateConnector';
import QuestionForm from './Form';
import { formValuesToRequest } from './transforms';
import { questionInitialValues, createHandleSubmit } from './CreateDialog';
import FAButton from '../FAButton';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import Router from 'next/router';
const createBackToListHandler = isDirty => () => {
console.log('isDirty: ');
console.log(isDirty);
if (isDirty) {
console.log('Your form has changed! You can not go back.');
return;
}
Router.push('/admin/questoes');
};
const QuestionCreateForm = () => (
<CreateConnector>
{({ createQuestion }) => (
<QuestionForm
initialValues={questionInitialValues}
onSubmit={createHandleSubmit(createQuestion)}
>
{({ form, isDirty }) => (
<React.Fragment>
<FAButton
onClick={createBackToListHandler(isDirty)}
aria-label="Voltar pra lista de questões"
>
<ArrowBackIcon />
</FAButton>
{form}
</React.Fragment>
)}
</QuestionForm>
)}
</CreateConnector>
);
export default QuestionCreateForm;
| import React from 'react';
import PropTypes from 'prop-types';
import CreateConnector from './CreateConnector';
import QuestionForm from './Form';
import { formValuesToRequest } from './transforms';
import { questionInitialValues, createHandleSubmit } from './CreateDialog';
import NextLink from 'next/link';
import FAButton from '../FAButton';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
const QuestionCreateForm = () => (
<React.Fragment>
<NextLink href={`/admin/questoes`}>
<FAButton aria-label="Voltar pra lista de questões">
<ArrowBackIcon />
</FAButton>
</NextLink>
<CreateConnector>
{({ createQuestion }) => (
<QuestionForm
initialValues={questionInitialValues}
onSubmit={createHandleSubmit(createQuestion)}
/>
)}
</CreateConnector>
</React.Fragment>
);
export default QuestionCreateForm;
|
Add hashmap for fast components lookups | const createTransform = require('./transform')
const assert = require('assert')
let entityId = 0
function Entity (components, tags, renderer) {
assert(!tags || Array.isArray(tags), 'Entity tags must be an array or null')
this.id = entityId++
this.tags = tags || []
this.renderer = renderer
this.components = components ? components.slice(0) : []
this.componentsMap = new Map()
this.components.forEach((component) => {
this.componentsMap.set(component.type, component)
})
this.transform = this.getComponent('Transform')
if (!this.transform) {
this.transform = createTransform({
parent: null
})
this.components.unshift(this.transform)
}
this.components.forEach((component) => component.init(this))
}
Entity.prototype.dispose = function () {
this.components.forEach((component) => {
if (component.dispose) {
component.dispose()
}
})
// detach from the hierarchy
this.transform.set({ parent: null })
}
Entity.prototype.addComponent = function (component) {
this.components.push(component)
this.componentsMap.set(component.type, component)
component.init(this)
}
// Only the last added component of that type will be returned
Entity.prototype.getComponent = function (type) {
return this.componentsMap.get(type)
}
module.exports = function createEntity (components, parent, tags) {
return new Entity(components, parent, tags)
}
| const createTransform = require('./transform')
const assert = require('assert')
let entityId = 0
function Entity (components, tags, renderer) {
assert(!tags || Array.isArray(tags), 'Entity tags must be an array or null')
this.id = entityId++
this.tags = tags || []
this.renderer = renderer
this.components = components ? components.slice(0) : []
this.transform = this.getComponent('Transform')
if (!this.transform) {
this.transform = createTransform({
parent: null
})
this.components.unshift(this.transform)
}
this.components.forEach((component) => component.init(this))
}
Entity.prototype.dispose = function () {
this.components.forEach((component) => {
if (component.dispose) {
component.dispose()
}
})
// detach from the hierarchy
this.transform.set({ parent: null })
}
Entity.prototype.addComponent = function (component) {
this.components.push(component)
component.init(this)
}
Entity.prototype.getComponent = function (type) {
return this.components.find((component) => component.type === type)
}
module.exports = function createEntity (components, parent, tags) {
return new Entity(components, parent, tags)
}
|
Make selectors take in state | // @flow
import React from 'react'
import {MentionHud} from '.'
import {createSelector} from 'reselect'
import {connect, type MapStateToProps} from 'react-redux'
import {getSelectedInbox} from '../../constants/chat'
type ConnectedMentionHudProps = {
onPickUser: (user: string) => void,
onSelectUser: (user: string) => void,
selectUpCounter: number,
selectDownCounter: number,
pickSelectedUserCounter: number,
filter: string,
style?: Object,
}
const fullNameSelector = createSelector(getSelectedInbox, inbox => (inbox ? inbox.get('fullNames') : null))
const participantsSelector = createSelector(
getSelectedInbox,
inbox => (inbox ? inbox.get('participants') : null)
)
const userSelector = createSelector(fullNameSelector, participantsSelector, (fullNames, participants) => {
return participants
? participants.reduce((res, username) => {
const fullName = fullNames ? fullNames.get(username) : ''
res.push({fullName: fullName || '', username})
return res
}, [])
: []
})
const mapStateToProps: MapStateToProps<*, *, *> = (state, {filter}) => {
return {
users: userSelector(state),
filter: filter.toLowerCase(),
}
}
const ConnectedMentionHud: Class<React.Component<ConnectedMentionHudProps, void>> = connect(mapStateToProps)(
MentionHud
)
export default ConnectedMentionHud
| // @flow
import React from 'react'
import {MentionHud} from '.'
import {createSelector} from 'reselect'
import {connect, type MapStateToProps} from 'react-redux'
import {getSelectedInbox} from '../../constants/chat'
type ConnectedMentionHudProps = {
onPickUser: (user: string) => void,
onSelectUser: (user: string) => void,
selectUpCounter: number,
selectDownCounter: number,
pickSelectedUserCounter: number,
filter: string,
style?: Object,
}
const fullNameSelector = inbox => (inbox ? inbox.get('fullNames') : null)
const participantsSelector = inbox => (inbox ? inbox.get('participants') : null)
const userSelector = createSelector(fullNameSelector, participantsSelector, (fullNames, participants) => {
return participants
? participants.reduce((res, username) => {
const fullName = fullNames ? fullNames.get(username) : ''
res.push({fullName: fullName || '', username})
return res
}, [])
: []
})
const mapStateToProps: MapStateToProps<*, *, *> = (state, {filter}) => {
const inbox = getSelectedInbox(state)
return {
users: userSelector(inbox),
filter: filter.toLowerCase(),
}
}
const ConnectedMentionHud: Class<React.Component<ConnectedMentionHudProps, void>> = connect(mapStateToProps)(
MentionHud
)
export default ConnectedMentionHud
|
Update nav bar to link to Phoenix not Ashes | <nav class="navigation">
<a class="navigation__logo" href="http://www.dosomething.org"><span>DoSomething.org</span></a>
<a class="navigation__toggle js-navigation-toggle" href="#"><span>Show Menu</span></a>
<div class="navigation__menu">
<ul class="navigation__primary">
<li>
<a href="{{ config('services.phoenix.url') }}/campaigns">
<strong class="navigation__title">Explore Campaigns</strong>
<span class="navigation__subtitle">Find ways to take action both online and off.</span>
</a>
</li>
<li>
<a href="{{ config('services.phoenix.url') }}/about/who-we-are">
<strong class="navigation__title">What Is DoSomething.org?</strong>
<span class="navigation__subtitle">A global movement for good. </span>
</a>
</li>
</ul>
</div>
</nav>
| <nav class="navigation">
<a class="navigation__logo" href="http://www.dosomething.org"><span>DoSomething.org</span></a>
<a class="navigation__toggle js-navigation-toggle" href="#"><span>Show Menu</span></a>
<div class="navigation__menu">
<ul class="navigation__primary">
<li>
<a href="{{ config('services.drupal.url') }}/campaigns">
<strong class="navigation__title">Explore Campaigns</strong>
<span class="navigation__subtitle">Find ways to take action both online and off.</span>
</a>
</li>
<li>
<a href="{{ config('services.drupal.url') }}/about/who-we-are">
<strong class="navigation__title">What Is DoSomething.org?</strong>
<span class="navigation__subtitle">A global movement for good. </span>
</a>
</li>
</ul>
</div>
</nav>
|
Change the --enable-policy-routing's default value from true to false. | /*
Copyright 2018 Google 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.
*/
package options
import "github.com/spf13/pflag"
type NetdConfig struct {
EnablePolicyRouting bool
EnableMasquerade bool
}
func NewNetdConfig() *NetdConfig {
return &NetdConfig{}
}
func (nc *NetdConfig) AddFlags(fs *pflag.FlagSet) {
fs.BoolVar(&nc.EnablePolicyRouting, "enable-policy-routing", false,
"Enable policy routing.")
fs.BoolVar(&nc.EnableMasquerade, "enable-masquerade", true,
"Enable masquerade.")
}
| /*
Copyright 2018 Google 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.
*/
package options
import "github.com/spf13/pflag"
type NetdConfig struct {
EnablePolicyRouting bool
EnableMasquerade bool
}
func NewNetdConfig() *NetdConfig {
return &NetdConfig{}
}
func (nc *NetdConfig) AddFlags(fs *pflag.FlagSet) {
fs.BoolVar(&nc.EnablePolicyRouting, "enable-policy-routing", true,
"Enable policy routing.")
fs.BoolVar(&nc.EnableMasquerade, "enable-masquerade", true,
"Enable masquerade.")
}
|
Correct Lithuanian short date format. | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = r'Y \m. F j \d.'
TIME_FORMAT = 'H:i:s'
# DATETIME_FORMAT =
# YEAR_MONTH_FORMAT =
# MONTH_DAY_FORMAT =
SHORT_DATE_FORMAT = 'Y-m-d'
# SHORT_DATETIME_FORMAT =
# FIRST_DAY_OF_WEEK =
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
# DATE_INPUT_FORMATS =
# TIME_INPUT_FORMATS =
# DATETIME_INPUT_FORMATS =
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
# NUMBER_GROUPING =
| # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = r'Y \m. F j \d.'
TIME_FORMAT = 'H:i:s'
# DATETIME_FORMAT =
# YEAR_MONTH_FORMAT =
# MONTH_DAY_FORMAT =
SHORT_DATE_FORMAT = 'Y.m.d'
# SHORT_DATETIME_FORMAT =
# FIRST_DAY_OF_WEEK =
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
# DATE_INPUT_FORMATS =
# TIME_INPUT_FORMATS =
# DATETIME_INPUT_FORMATS =
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
# NUMBER_GROUPING =
|
Add class to render for ten day. | import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons';
const TenDay = ({ tenDayForecast }) => {
if(!tenDayForecast) {
return(
<div></div>
)
}
const forecastArray = tenDayForecast.simpleforecast.forecastday;
const icons = new WeatherIcons();
return(
<section>
{forecastArray.map((day, i) => {
return(
<div key={i}>
<h4 className="ten-day">{day.date.weekday_short}</h4>
<h4 className="ten-day">Low {day.low.fahrenheit}</h4>
<h4 className="ten-day">Hi {day.high.fahrenheit}</h4>
<div className={icons[day.icon]}></div>
</div>
);
})}
</section>
)
};
export default TenDay;
| import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons';
const TenDay = ({ tenDayForecast }) => {
if(!tenDayForecast) {
return(
<div></div>
)
}
const forecastArray = tenDayForecast.simpleforecast.forecastday;
const icons = new WeatherIcons();
return(
<article>
{forecastArray.map((day, i) => {
return(
<div key={i}>
<h4 className="ten-day">{day.date.weekday_short}</h4>
<h4 className="ten-day">Low {day.low.fahrenheit}</h4>
<h4 className="ten-day">Hi {day.high.fahrenheit}</h4>
<div className={icons[day.icon]}></div>
</div>
);
})}
</article>
)
};
export default TenDay;
|
Update new tab base URL to auto-forward + display user-friendly title | !(function( global ) {
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
// Pick the right base URL for new tab generation
var newTab_BaseURL = 'data:text/html,<!DOCTYPE html><!--tab_%s--><title>Loading...</title><script>history.forward()</script>';
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
| !(function( global ) {
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
// Pick the right base URL for new tab generation
var newTab_BaseURL = 'data:text/html,<!--tab_%s-->';
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
|
Add test to ensure that style map lines beginning with hash are ignored | from nose.tools import istest, assert_equal
from mammoth import style_reader
from mammoth.options import read_options, _default_style_map
@istest
def default_style_map_is_used_if_style_map_is_not_set():
assert_equal(_default_style_map, read_options({})["style_map"])
@istest
def custom_style_mappings_are_prepended_to_default_style_mappings():
style_map = read_options({
"style_map": "p.SectionTitle => h2"
})["style_map"]
assert_equal(style_reader.read_style("p.SectionTitle => h2"), style_map[0])
assert_equal(_default_style_map, style_map[1:])
@istest
def default_style_mappings_are_ignored_if_include_default_style_map_is_false():
style_map = read_options({
"style_map": "p.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
@istest
def lines_starting_with_hash_in_custom_style_map_are_ignored():
style_map = read_options({
"style_map": "#p.SectionTitle => h3\np.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
| from nose.tools import istest, assert_equal
from mammoth import style_reader
from mammoth.options import read_options, _default_style_map
@istest
def default_style_map_is_used_if_style_map_is_not_set():
assert_equal(_default_style_map, read_options({})["style_map"])
@istest
def custom_style_mappings_are_prepended_to_default_style_mappings():
style_map = read_options({
"style_map": "p.SectionTitle => h2"
})["style_map"]
assert_equal(style_reader.read_style("p.SectionTitle => h2"), style_map[0])
assert_equal(_default_style_map, style_map[1:])
@istest
def default_style_mappings_are_ignored_if_include_default_style_map_is_false():
style_map = read_options({
"style_map": "p.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
|
Fix broken suffix on chapters with a dot. | 'use strict';
var affix = require('./affix');
/**
* Creates an alias for the chapter.
* @param {!{title: ?string}} series
* @param {!{number: number, volume: number}} chapter
* @param {string=} extension
* @return {?string}
*/
module.exports = function (series, chapter, extension) {
var name = invalidate(series.title);
if (!name) return undefined;
var number = '#' + affix(stripSuffix(chapter.number.toFixed(4)), 3);
var prefix = name + '/' + name + ' ';
var suffix = number + '.' + (extension || 'cbz');
if (isNaN(chapter.volume)) return prefix + suffix;
return prefix + 'V' + affix(String(chapter.volume), 2) + ' ' + suffix;
};
/**
* Invalidates the value.
* @param {string} value
* @return {string}
*/
function invalidate(value) {
return value.replace(/["<>\|:\*\?\\\/]/g, '');
}
/**
* Strips a suffix from the zero-padded value.
* @param {string} value
* @return {string}
*/
function stripSuffix(value) {
return value.replace(/0+$/g, '');
}
| 'use strict';
var affix = require('./affix');
/**
* Creates an alias for the chapter.
* @param {!{title: ?string}} series
* @param {!{number: number, volume: number}} chapter
* @param {string=} extension
* @return {?string}
*/
module.exports = function (series, chapter, extension) {
var name = invalidate(series.title);
if (!name) return undefined;
var number = '#' + affix(stripSuffix(chapter.number.toFixed(4)), 3);
var prefix = name + '/' + name + ' ';
var suffix = number + '.' + (extension || 'cbz');
if (isNaN(chapter.volume)) return prefix + suffix;
return prefix + 'V' + affix(String(chapter.volume), 2) + ' ' + suffix;
};
/**
* Invalidates the value.
* @param {string} value
* @return {string}
*/
function invalidate(value) {
return value.replace(/["<>\|:\*\?\\\/]/g, '');
}
/**
* Strips a suffix from the zero-padded value.
* @param {string} value
* @return {string}
*/
function stripSuffix(value) {
return value.replace(/\.0+$/g, '');
}
|
Fix unused variable for $params | <?php namespace Picqer\Financials\Exact\Query;
class Resultset
{
protected $connection;
protected $url;
protected $class;
protected $params;
public function __construct($connection, $url, $class, $params)
{
$this->connection = $connection;
$this->url = $url;
$this->class = $class;
$this->params = $params;
}
public function next()
{
$result = $this->connection->get($this->url, $this->params);
$this->url = $this->connection->nextUrl;
return $this->collectionFromResult($result, $this->class);
}
public function hasMore()
{
return $this->url !== null;
}
protected function collectionFromResult($result)
{
// If we have one result which is not an assoc array, make it the first element of an array for the
// collectionFromResult function so we always return a collection from filter
if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
$result = [ $result ];
}
$class = $this->class;
$collection = [];
foreach ($result as $r) {
$collection[] = new $class($this->connection, $r);
}
return $collection;
}
}
| <?php namespace Picqer\Financials\Exact\Query;
class Resultset
{
protected $connection;
protected $url;
protected $class;
protected $params;
public function __construct($connection, $url, $class, $params)
{
$this->connection = $connection;
$this->url = $url;
$this->class = $class;
$this->params = $params;
}
public function next()
{
$result = $this->connection->get($this->url, $params);
$this->url = $this->connection->nextUrl;
return $this->collectionFromResult($result, $this->class);
}
public function hasMore()
{
return $this->url !== null;
}
protected function collectionFromResult($result)
{
// If we have one result which is not an assoc array, make it the first element of an array for the
// collectionFromResult function so we always return a collection from filter
if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
$result = [ $result ];
}
$class = $this->class;
$collection = [];
foreach ($result as $r) {
$collection[] = new $class($this->connection, $r);
}
return $collection;
}
}
|
Fix support for flake8 v2 | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if not hasattr(flake8, '__version_info__') or flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if flake8 did not find any errors
"""
print('Running flake8')
flake8_style = get_style_guide(config_file=config_file)
paths = []
for root, _, filenames in os.walk('asn1crypto'):
for filename in filenames:
if not filename.endswith('.py'):
continue
paths.append(os.path.join(root, filename))
report = flake8_style.check_files(paths)
success = report.total_errors == 0
if success:
print('OK')
return success
| # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if flake8 did not find any errors
"""
print('Running flake8')
flake8_style = get_style_guide(config_file=config_file)
paths = []
for root, _, filenames in os.walk('asn1crypto'):
for filename in filenames:
if not filename.endswith('.py'):
continue
paths.append(os.path.join(root, filename))
report = flake8_style.check_files(paths)
success = report.total_errors == 0
if success:
print('OK')
return success
|
Update dsub version to 0.3.9.dev0
PiperOrigin-RevId: 313432033 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9.dev0'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.8'
|
Disable the built-in LTTng-Analyses connectors
Too annoying when developping, we'll bring them back later.
Signed-off-by: Alexandre Montplaisir <0b9d8e7da097b5bbfe36e48cca5acfe475f18227@efficios.com> | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.lttng.kernel.core.activator.internal;
import org.lttng.scope.common.core.ScopeCoreActivator;
/**
* Plugin activator
*
* @noreference This class should not be accessed outside of this plugin.
*/
public class Activator extends ScopeCoreActivator {
/**
* Return the singleton instance of this activator.
*
* @return The singleton instance
*/
public static Activator instance() {
return ScopeCoreActivator.getInstance(Activator.class);
}
@Override
protected void startActions() {
// try {
// LttngAnalysesLoader.load();
// } catch (LamiAnalysisFactoryException | IOException e) {
// // Not the end of the world if the analyses are not available
// logWarning("Cannot find LTTng analyses configuration files: " + e.getMessage()); //$NON-NLS-1$
// }
}
@Override
protected void stopActions() {
}
}
| /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.lttng.kernel.core.activator.internal;
import java.io.IOException;
import org.lttng.scope.common.core.ScopeCoreActivator;
import org.lttng.scope.lami.core.module.LamiAnalysisFactoryException;
/**
* Plugin activator
*
* @noreference This class should not be accessed outside of this plugin.
*/
public class Activator extends ScopeCoreActivator {
/**
* Return the singleton instance of this activator.
*
* @return The singleton instance
*/
public static Activator instance() {
return ScopeCoreActivator.getInstance(Activator.class);
}
@Override
protected void startActions() {
try {
LttngAnalysesLoader.load();
} catch (LamiAnalysisFactoryException | IOException e) {
// Not the end of the world if the analyses are not available
logWarning("Cannot find LTTng analyses configuration files: " + e.getMessage()); //$NON-NLS-1$
}
}
@Override
protected void stopActions() {
}
}
|
Add @Alir3z4 as maintainer info | from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "Bringing sanitiy to world of messed-up data",
long_description=open('README.md').read(),
author = "Aaron Swartz",
author_email = "me@aaronsw.com",
maintainer='Alireza Savand',
maintainer_email='alireza.savand@gmail.com',
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
| from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "Bringing sanitiy to world of messed-up data",
long_description=open('README.md').read(),
author = "Aaron Swartz",
author_email = "me@aaronsw.com",
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
|
Return a boolean instead of void
Signed-off-by: Rick Kerkhof <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com> | <?php
/**
* Copyright 2018 The WildPHP Team
*
* You should have received a copy of the MIT license with the project.
* See the LICENSE file for more information.
*/
namespace WildPHP\Core\Connection;
use WildPHP\Messages\Interfaces\OutgoingMessageInterface;
interface QueueInterface
{
/**
* @param OutgoingMessageInterface $command
*
* @return void
*/
public function insertMessage(OutgoingMessageInterface $command);
/**
* @param QueueItem $item
*
* @return bool
*/
public function removeMessage(QueueItem $item);
/**
* @param int $index
*
* @return bool
*/
public function removeMessageByIndex(int $index);
/**
* @param QueueItem $item
*
* @return void
*/
public function scheduleItem(QueueItem $item);
/**
* @return QueueItem[]
*/
public function flush(): array;
} | <?php
/**
* Copyright 2018 The WildPHP Team
*
* You should have received a copy of the MIT license with the project.
* See the LICENSE file for more information.
*/
namespace WildPHP\Core\Connection;
use WildPHP\Messages\Interfaces\OutgoingMessageInterface;
interface QueueInterface
{
/**
* @param OutgoingMessageInterface $command
*
* @return void
*/
public function insertMessage(OutgoingMessageInterface $command);
/**
* @param QueueItem $item
*
* @return bool
*/
public function removeMessage(QueueItem $item);
/**
* @param int $index
*
* @return void
*/
public function removeMessageByIndex(int $index);
/**
* @param QueueItem $item
*
* @return void
*/
public function scheduleItem(QueueItem $item);
/**
* @return QueueItem[]
*/
public function flush(): array;
} |
Make taxonomy template pagination more modular | $term = \Taco\Term\Factory::create(get_queried_object());
$current_page = (get_query_var('paged')) ?: 1;
$per_page = get_option('posts_per_page');
// Or: $per_page = NewsPost::getPostsPerPage();
$term_posts = NewsPost::getByTerm(
$term->taxonomy,
$term->slug,
'slug',
array(
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'offset' => ($current_page - 1) * $per_page
)
);
$total_posts = NewsPost::getCountByTerm(
$term->taxonomy,
$term->slug,
'slug'
);
echo Util::getPagination($current_page, $total_posts, array(
'per_page' => $per_page,
'link_prefix' => '/news/'.$term->slug,
));
| $taxonomy_slug = 'news-type';
$term_slug = \Taco\Term\Factory::create(get_queried_object())->get('slug');
$current_page = (get_query_var('paged')) ?: 1;
$per_page = get_option('posts_per_page');
$per_page = NewsPost::getPostsPerPage();
$news_posts_of_this_type = NewsPost::getByTerm(
$taxonomy_slug,
$term_slug,
'slug',
array(
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'offset' => ($current_page - 1) * $per_page
)
);
$total_posts = NewsPost::getCountByTerm(
$taxonomy_slug,
$term_slug,
'slug'
);
echo Util::getPagination($current_page, $total_posts, array(
'per_page' => $per_page,
'link_prefix' => '/news/'.$term_slug,
));
|
Add tests for planner init | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [50, 80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_init_pieces(self):
self.assertEqual(len(self.planner.pieces_needed), 3)
self.assertEqual(self.planner.pieces_needed[0].length, 75)
def test_init_stock(self):
self.assertEqual(len(self.planner.stock_sizes), 3)
self.assertEqual(self.planner.stock_sizes, [50, 80, 120])
def test_largest_stock(self):
largest = self.planner.largest_stock
self.assertEqual(largest, 120)
def test_finalize(self):
self.planner.cur_stock = cutplanner.Stock(self.planner.largest_stock)
self.planner.cut_piece(cutplanner.Piece(1, 60))
self.planner.finalize_stock()
self.assertEqual(len(self.planner.stock), 1)
self.assertEqual(self.planner.stock[0].length, 80)
if __name__ == '__main__':
unittest.main()
| import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [50, 80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
self.assertEqual(largest, 120)
def test_finalize(self):
self.planner.cur_stock = cutplanner.Stock(self.planner.largest_stock)
self.planner.cut_piece(cutplanner.Piece(1, 60))
self.planner.finalize_stock()
self.assertEqual(len(self.planner.stock), 1)
self.assertEqual(self.planner.stock[0].length, 80)
if __name__ == '__main__':
unittest.main()
|
Add additional columns and indexes | var table = function (table) {
table.increments().primary();
table.string('file_name').notNullable().unique();
table.enum('transfer_state', ['completed', 'partial', 'canceled']).notNullable();
table.integer('transferred_bytes').notNullable();
table.integer('transfer_time').notNullable();
table.integer('response_code').notNullable();
table.string('parsed_user_agent').notNullable();
table.string('raw_user_agent').notNullable();
table.string('country').notNullable();
table.string('ip_address').notNullable();
table.string('parsed_referrer').notNullable();
table.string('raw_referrer').notNullable();
table.string('mime_type').notNullable();
table.timestamps();
// defined by timestamps();
table.index('created_at');
table.index('transfer_state');
};
exports.up = function (knex, Promise) {
return knex.schema.createTable('downloads', table)
.then(function () {
console.log('Downloads table is created!');
});
};
exports.down = function (knex, Promise) {
return knex.schema
.dropTable('downloads', table)
.then(function () {
console.log('Downloads table was dropped!');
});
};
| var table = function (table) {
table.increments().primary();
table.string('file_name').notNullable().unique();
table.boolean('completed').notNullable();
table.integer('transferred_bytes').notNullable();
table.integer('transfer_time').notNullable();
table.string('parsed_user_agent').notNullable();
table.string('raw_user_agent').notNullable();
table.string('country').notNullable();
table.string('ip_address').notNullable();
table.string('parsed_referrer').notNullable();
table.string('raw_referrer').notNullable();
table.string('mime_type').notNullable();
table.timestamps();
// defined by timestamps();
table.index('created_at');
};
exports.up = function (knex, Promise) {
return knex.schema.createTable('downloads', table)
.then(function () {
console.log('Downloads table is created!');
});
};
exports.down = function (knex, Promise) {
return knex.schema
.dropTable('downloads', table)
.then(function () {
console.log('Downloads table was dropped!');
});
};
|
Handle the delay setting change |
var InputForm = React.createClass({
getInitialState: function() {
return {selectedDelay: 3000};
},
handleDelayChange: function(e){
e.preventDefault();
this.setState({selectedDelay: e.currentTarget.valueAsNumber})
},
render() {
return (
<div className="row">
<div className="input-field col s6">
<input placeholder="http://google.com" id="redirect_url" type="text" className="validate" />
</div>
<div className="input-field col s4">
<p className="range-field">
<input type="range" id="delay_time" value={this.state.selectedDelay} min="0" max="10000" step="100" onInput={this.handleDelayChange} />
</p>
</div>
<div className="input-field col s2 center">
<span>{this.state.selectedDelay / 1000}</span> secs
</div>
</div>
)
}
});
module.exports = InputForm;
|
var InputForm = React.createClass({
render() {
return (
<div className="row">
<div className="input-field col s6">
<input placeholder="http://google.com" id="redirect_url" type="text" className="validate" />
</div>
<div className="input-field col s4">
<p className="range-field">
<input type="range" id="delay_time" min="1" max="10000" />
</p>
</div>
<div className="input-field col s2 center">
<span>1</span> Second
</div>
</div>
)
}
});
module.exports = InputForm;
|
Fix account->queue->members JSON property name. | <?php
class Services_Twilio_Rest_Members
extends Services_Twilio_ListResource
{
/**
* Return the member at the front of the queue. Note that any operations
* performed on the Member returned from this function will use the /Front
* Uri, not the Member's CallSid.
*
* @return Services_Twilio_Rest_Member The member at the front of the queue
*/
public function front() {
return new $this->instance_name($this->client, $this->uri . '/Front');
}
/* Participants are identified by CallSid, not like ME123 */
public function getObjectFromJson($params, $idParam = 'sid') {
return parent::getObjectFromJson($params, 'call_sid');
}
public function getResourceName($camelized = false)
{
// The JSON property name is atypical.
return $camelized ? 'Members' : 'queue_members';
}
}
| <?php
class Services_Twilio_Rest_Members
extends Services_Twilio_ListResource
{
/**
* Return the member at the front of the queue. Note that any operations
* performed on the Member returned from this function will use the /Front
* Uri, not the Member's CallSid.
*
* @return Services_Twilio_Rest_Member The member at the front of the queue
*/
public function front() {
return new $this->instance_name($this->client, $this->uri . '/Front');
}
/* Participants are identified by CallSid, not like ME123 */
public function getObjectFromJson($params, $idParam = 'sid') {
return parent::getObjectFromJson($params, 'call_sid');
}
public function getResourceName($camelized = false)
{
// The JSON property name is atypical.
return $camelized ? 'Members' : 'queue_members';
}
}
|
Change return type to static binding | <?php
declare(strict_types = 1);
namespace Sop\JWX\Parameter\Feature;
use Sop\JWX\Parameter\Parameter;
use Sop\JWX\Util\Base64;
use Sop\JWX\Util\BigInt;
/**
* Trait for parameters having Base64urlUInt value.
*
* @see https://tools.ietf.org/html/rfc7518#section-2
*/
trait Base64UIntValue
{
use Base64URLValue;
/**
* Initialize parameter from base10 number.
*
* @param int|string $number
*
* @return self
*/
public static function fromNumber($number): Parameter
{
$data = BigInt::fromBase10($number)->base256();
return static::fromString($data);
}
/**
* Get value as a number.
*
* @return BigInt
*/
public function number(): BigInt
{
return BigInt::fromBase256(Base64::urlDecode($this->value()));
}
}
| <?php
declare(strict_types = 1);
namespace Sop\JWX\Parameter\Feature;
use Sop\JWX\Parameter\Parameter;
use Sop\JWX\Util\Base64;
use Sop\JWX\Util\BigInt;
/**
* Trait for parameters having Base64urlUInt value.
*
* @see https://tools.ietf.org/html/rfc7518#section-2
*/
trait Base64UIntValue
{
use Base64URLValue;
/**
* Initialize parameter from base10 number.
*
* @param int|string $number
*
* @return self
*/
public static function fromNumber($number): Parameter
{
$data = BigInt::fromBase10($number)->base256();
return self::fromString($data);
}
/**
* Get value as a number.
*
* @return BigInt
*/
public function number(): BigInt
{
return BigInt::fromBase256(Base64::urlDecode($this->value()));
}
}
|
Use single quotes instead of double quotes | #!/usr/bin/env python
'''
Script: fy_print_seq_len_in_fasta.py
Function: Print sequence length to STDOUT in fasta file
Note: Python3 is not default installed for most computer,
and the extra-installed module like Biopython could
not be directly used by python3. So, it's not the
righ time to use Python3 now.
Date: 2014/11/11
'''
import sys
if len(sys.argv) < 2:
print('Usage: ' + sys.argv[0] + ' <FASTA>')
sys.exit()
from Bio import SeqIO
seqlen = []
num_of_seq = 0
total_len = 0
for record in SeqIO.parse(sys.argv[1], 'fasta'):
print("%s %i" % (record.id, len(record)))
num_of_seq += 1
total_len += len(record)
seqlen.append(len(record))
seqlen.sort()
min_len = seqlen[0]
max_len = seqlen[-1]
print('Number of sequences: ' + str(num_of_seq))
print('Total length: ' + str(total_len))
print('Max length: ' + str(max_len))
print('Min length: ' + str(min_len))
| #!/usr/bin/env python
'''
Script: fy_print_seq_len_in_fasta.py
Function: Print sequence length to STDOUT in fasta file
Note: Python3 is not default installed for most computer,
and the extra-installed module like Biopython could
not be directly used by python3. So, it's not the
righ time to use Python3 now.
Date: 2014/11/11
'''
import sys
if len(sys.argv) < 2:
print('Usage: ' + sys.argv[0] + ' <FASTA>')
sys.exit()
from Bio import SeqIO
seqlen = []
num_of_seq = 0
total_len = 0
for record in SeqIO.parse(sys.argv[1], 'fasta'):
print("%s %i" % (record.id, len(record)))
num_of_seq += 1
total_len += len(record)
seqlen.append(len(record))
seqlen.sort()
min_len = seqlen[0]
max_len = seqlen[-1]
print("Number of sequences: " + str(num_of_seq))
print("Total length: " + str(total_len))
print("Max length: " + str(max_len))
print("Min length: " + str(min_len))
|
Fix error with 1.8.0_77 in CI, does not happen with 1.8.0_121
Probably a bit ugly, but well for a test it should be acceptable. | package jenkins.util;
import hudson.slaves.DumbSlave;
import java.io.IOException;
import jenkins.security.MasterToSlaveCallable;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class JenkinsJVMRealTest {
@ClassRule
public static JenkinsRule j = new JenkinsRule();
@Test
public void isJenkinsJVM() throws Throwable {
assertThat(new IsJenkinsJVM().call(), is(true));
DumbSlave slave = j.createOnlineSlave();
assertThat(slave.getChannel().call(new IsJenkinsJVM()), is(false));
}
public static class IsJenkinsJVM extends MasterToSlaveCallable<Boolean, IOException> {
@Override
public Boolean call() throws IOException {
return JenkinsJVM.isJenkinsJVM();
}
}
}
| package jenkins.util;
import hudson.slaves.DumbSlave;
import java.io.IOException;
import jenkins.security.MasterToSlaveCallable;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class JenkinsJVMRealTest {
@ClassRule
public static JenkinsRule j = new JenkinsRule();
@Test
public void isJenkinsJVM() throws Exception {
assertThat(new IsJenkinsJVM().call(), is(true));
DumbSlave slave = j.createOnlineSlave();
assertThat(slave.getChannel().call(new IsJenkinsJVM()), is(false));
}
public static class IsJenkinsJVM extends MasterToSlaveCallable<Boolean, IOException> {
@Override
public Boolean call() throws IOException {
return JenkinsJVM.isJenkinsJVM();
}
}
}
|
Revert "Brake tests for demo purposes"
This reverts commit b032050baba4f04d7acaec8f95cbe98c7e68949f. | package main
import "testing"
func TestNopFormatterDoesNothing(t *testing.T) {
src := []byte{68, 68, 68}
fmted, err := NopFormatter().Format(src)
if err != nil {
t.Fatal(err)
}
if !same(fmted, src) {
t.Errorf("want %v, got: %v\n", src, fmted)
}
}
func TestJSONFormatter(t *testing.T) {
src := []byte(`{"json":true}`)
want := []byte(`{
"json": true
}`)
f := &JSONFormatter{
Prefix: "",
Indent: " ",
}
fmted, err := f.Format(src)
if err != nil {
t.Fatal(err)
}
if !same(fmted, want) {
t.Errorf("want %v, got: %v\n", want, fmted)
}
}
func same(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
| package main
import "testing"
func TestNopFormatterDoesNothing(t *testing.T) {
src := []byte{68, 68, 68}
fmted, err := NopFormatter().Format(src)
if err != nil {
t.Fatal(err)
}
if !same(fmted, src) {
t.Errorf("want %v, got: %v\n", src, fmted)
}
}
func TestJSONFormatter(t *testing.T) {
src := []byte(`{"json":false}`)
want := []byte(`{
"json": true
}`)
f := &JSONFormatter{
Prefix: "",
Indent: " ",
}
fmted, err := f.Format(src)
if err != nil {
t.Fatal(err)
}
if !same(fmted, want) {
t.Errorf("want %v, got: %v\n", want, fmted)
}
}
func same(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
|
Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt | import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
| import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
|
Make this test a bit harder. | import json
import unittest
from flask import Flask
from flask.ext.autodoc import Autodoc
class TestAutodocWithFlask(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.autodoc = Autodoc(self.app)
@self.app.route('/')
@self.autodoc.doc()
def index():
"""Returns a hello world message"""
return 'Hello World!'
self.client = self.app.test_client()
def test_html(self):
@self.app.route('/docs')
def html_docs():
return self.autodoc.html()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
def test_json(self):
@self.app.route('/docs')
def json_docs():
return self.autodoc.json()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
data = json.loads(response.data)
self.assertIn('endpoints', data)
| import unittest
from flask import Flask
from flask.ext.autodoc import Autodoc
class TestAutodocWithFlask(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.autodoc = Autodoc(self.app)
@self.app.route('/')
@self.autodoc.doc()
def index():
"""Returns a hello world message"""
return 'Hello World!'
self.client = self.app.test_client()
def test_html(self):
@self.app.route('/docs')
def html_docs():
return self.autodoc.html()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
def test_json(self):
@self.app.route('/docs')
def json_docs():
return self.autodoc.json()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
|
Add full tests for mccattery and cattery | import pytest
from catinabox import cattery, mccattery
@pytest.fixture(params=[
cattery.Cattery,
mccattery.McCattery
])
def cattery_fixture(request):
return request.param()
###########################################################################
# add_cats
###########################################################################
def test__add_cats__succeeds(cattery_fixture):
cattery_fixture.add_cats(["Fluffy", "Snookums"])
assert cattery_fixture.cats == ["Fluffy", "Snookums"]
assert cattery_fixture.num_cats == 2
###########################################################################
# remove_cat
###########################################################################
def test__remove_cat__succeeds(cattery_fixture):
cattery_fixture.add_cats(["Fluffy", "Junior"])
cattery_fixture.remove_cat("Fluffy")
assert cattery_fixture.cats == ["Junior"]
assert cattery_fixture.num_cats == 1
def test__remove_cat__no_cats__fails(cattery_fixture):
with pytest.raises(cattery.CatNotFound):
cattery_fixture.remove_cat("Fluffles")
def test__remove_cat__cat_not_in_cattery__fails(cattery_fixture):
cattery_fixture.add_cats(["Fluffy"])
with pytest.raises(cattery.CatNotFound):
cattery_fixture.remove_cat("Snookums")
| import pytest
from catinabox import cattery
class TestCattery(object):
###########################################################################
# add_cats
###########################################################################
def test__add_cats__succeeds(self):
c = cattery.Cattery()
assert c
###########################################################################
# remove_cat
###########################################################################
def test__remove_cat__succeeds(self):
c = cattery.Cattery()
assert c
def test__remove_cat__no_cats__fails(self):
c = cattery.Cattery()
assert c
def test__remove_cat__cat_not_in_cattery__fails(self):
c = cattery.Cattery()
c.add_cats(["Fluffy"])
with pytest.raises(cattery.CatNotFound):
c.remove_cat("Snookums")
|
Remove superfluous override of 'get_playlist'. | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
| import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
|
Improve readability with local variable | var Class = require('../../utils/Class');
var WebAudioSound = require('./WebAudioSound');
var WebAudioSpriteSound = new Class({
Extends: WebAudioSound,
initialize: function WebAudioSpriteSound(manager, key, config) {
if (config === void 0) { config = {}; }
WebAudioSound.call(this, manager, key, config);
/**
* Local reference to 'spritemap' object form json file generated by audiosprite tool.
*
* @property {object} spritemap
*/
this.spritemap = manager.game.cache.json.get(key).spritemap;
for (var markerName in this.spritemap) {
var marker = this.spritemap[markerName];
this.addMarker({
name: markerName,
start: marker.start,
duration: marker.end - marker.start,
config: config
});
}
}
});
module.exports = WebAudioSpriteSound;
| var Class = require('../../utils/Class');
var WebAudioSound = require('./WebAudioSound');
var WebAudioSpriteSound = new Class({
Extends: WebAudioSound,
initialize: function WebAudioSpriteSound(manager, key, config) {
if (config === void 0) { config = {}; }
WebAudioSound.call(this, manager, key, config);
/**
* Local reference to 'spritemap' object form json file generated by audiosprite tool.
*
* @property {object} spritemap
*/
this.spritemap = manager.game.cache.json.get(key).spritemap;
for (var markerName in this.spritemap) {
this.addMarker({
name: markerName,
start: this.spritemap[markerName].start,
duration: this.spritemap[markerName].end - this.spritemap[markerName].start,
config: config
});
}
}
});
module.exports = WebAudioSpriteSound;
|
[FIX] Include class methods in extend() | !function(exports) {
'use strict';
var RunQueue = exports.RunQueue;
function Component() {
this.next = new RunQueue;
this.end = new RunQueue;
}
Component.extend = function(constructorFn) {
var prop, scope = this;
if(!constructorFn) constructorFn = function() { scope.call(this); };
constructorFn.prototype = new Component;
constructorFn.prototype.constructor = constructorFn;
constructorFn.prototype.proto = constructorFn.prototype;
for(prop in scope) {
if(scope.hasOwnProperty(prop)) constructorFn[prop] = scope[prop];
}
return constructorFn;
}
Component.prototype.init = stub();
Component.prototype.destroy = stub();
Component.prototype.before = stub();
Component.prototype.update = stub();
Component.prototype.after = stub();
Component.prototype.preprocess = stub();
Component.prototype.render = stub();
Component.prototype.postprocess = stub();
function stub() { return function(delta, x, y, z) {}; }
/*
* Export
* ------
*/
exports.Component = Component;
}(seine);
| !function(exports) {
'use strict';
var RunQueue = exports.RunQueue;
function Component() {
this.next = new RunQueue;
this.end = new RunQueue;
}
Component.extend = function(constructorFn) {
var scope = this;
if(!constructorFn) constructorFn = function() { scope.call(this); };
constructorFn.prototype = new Component;
constructorFn.prototype.constructor = constructorFn;
constructorFn.prototype.proto = constructorFn.prototype;
return constructorFn;
}
Component.prototype.init = stub();
Component.prototype.destroy = stub();
Component.prototype.before = stub();
Component.prototype.update = stub();
Component.prototype.after = stub();
Component.prototype.preprocess = stub();
Component.prototype.render = stub();
Component.prototype.postprocess = stub();
function stub() { return function(delta, x, y, z) {}; }
/*
* Export
* ------
*/
exports.Component = Component;
}(seine);
|
Fix crash on start when documents doesn't exists | var fs = require('fs');
var storage = [];
module.exports = {
init: (config, callback) => {
var directories = fs.readdirSync('.');
if (directories.indexOf(config.directory) === -1) {
fs.mkdirSync(config.directory);
config.documents.forEach(name => {
fs.writeFileSync(`${config.directory}/${name}.db`, '');
storage[name] = new Map();
});
return true;
}
config.documents.forEach(name => {
if (!fs.existsSync(`${config.directory}/${name}.db`)) {
fs.writeFileSync(`${config.directory}/${name}.db`, '');
}
var file = fs.readFileSync(`${config.directory}/${name}.db`);
storage[name] = new Map(file);
});
setInterval(() => {
//console.log('----');
//console.log(storage);
storage.forEach((document) => {
console.log('document');
// fs.writeFileSync(`${config.directory}/${}.db`);
});
}, 1000);
return true;
},
get: (document, key) => {
return storage[document].get(key);
},
set: (document, key, value) => {
storage[document].set(key, value);
return true;
}
};
| var fs = require('fs');
var storage = [];
module.exports = {
init: (config, callback) => {
var directories = fs.readdirSync('.');
if (directories.indexOf(config.directory) === -1) {
fs.mkdirSync(config.directory);
config.documents.forEach(name => {
fs.writeFileSync(`${config.directory}/${name}.db`, '{}');
});
return 'done';
}
config.documents.forEach(name => {
var file = fs.readFileSync(`${config.directory}/${name}.db`);
if (file) {
storage[name] = new Map();
file = JSON.parse(file);
Object.keys(file).forEach((key) => {
storage[name].set(key, file[key]);
});
} else {
fs.writeFileSync(`${config.directory}/${name}.db`, '{}');
}
});
return 'test';
},
get: (document, key) => {
return storage[document].get(key);
}
};
|
Add no-save flag to installPackage | const rimraf = require('rimraf')
const tmp = require('tmp');
const childProcess = require('child_process');
const { promisify } = require('util');
const InstallationUtils = {
async getInstallPath() {
return promisify(tmp.dir)();
},
async installPackage(
packageString,
installPath,
) {
const flags = [
'no-package-lock',
'no-shrinkwrap',
'no-optional',
'no-bin-links',
'prefer-offline',
'progress false',
'loglevel error',
'ignore-scripts',
'no-save',
'production',
'json',
];
const command = `npm install ${packageString} --${flags.join(' --')}`;
await promisify(childProcess.exec)(
command,
{cwd: installPath, maxBuffer: 1024 * 500}
);
},
async cleanupPath(installPath) {
const noop = () => {};
rimraf(installPath, noop);
},
}
module.exports = InstallationUtils
| const rimraf = require('rimraf')
const tmp = require('tmp');
const childProcess = require('child_process');
const { promisify } = require('util');
const InstallationUtils = {
async getInstallPath() {
return promisify(tmp.dir)();
},
async installPackage(
packageString,
installPath,
) {
const flags = [
'no-package-lock',
'no-shrinkwrap',
'no-optional',
'no-bin-links',
'prefer-offline',
'progress false',
'loglevel error',
'ignore-scripts',
'save-exact',
'production',
'json',
];
const command = `npm install ${packageString} --${flags.join(' --')}`;
await promisify(childProcess.exec)(
command,
{cwd: installPath, maxBuffer: 1024 * 500}
);
},
async cleanupPath(installPath) {
const noop = () => {};
rimraf(installPath, noop);
},
}
module.exports = InstallationUtils
|
Add check for empty userName and password | const UserDB = require('../db/userdb').Users
exports.form = (req, res, next) => {
res.render('register', {title: 'Welcome to Chat app'})
}
exports.submit = (req, res, next) => {
let data = req.body.user
console.log('data->', data)
console.log('data.name->', data.name, 'data.pass->', data.pass)
if (data.name && data.pass) {
UserDB.find(data, (err, user) => {
if (err) return next(err)
console.log('user->', user)
if (user) {
console.log('user exists')
//res.render('register', {err: 'UserName already taken'})
// res.error('Username already taken')
res.redirect('back')
} else {
UserDB.create(data, (err, user) => {
if (err) return next(err)
res.redirect('/')
})
}
})
} else {
console.log('UserName and Password are mandatory for registration')
res.redirect('back')
}
}
| const UserDB = require('../db/userdb').Users
exports.form = (req, res, next) => {
res.render('register', {title: 'Welcome to Chat app'})
}
exports.submit = (req, res, next) => {
let data = req.body.user
console.log('data->', data)
console.log('data.name->', data.name, 'data.pass->', data.pass)
UserDB.find(data, (err, user) => {
if (err) return next(err)
console.log('user->', user)
if (user) {
console.log('user exists')
//res.render('register', {err: 'UserName already taken'})
// res.error('Username already taken')
res.redirect('back')
} else {
UserDB.create(data, (err, user) => {
if (err) return next(err)
res.redirect('/')
})
}
})
}
|
Add variable lines and columns | import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
| import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
else:
f.write(str(randint(0, 20) - 10))
f.write('\n')
f.close()
|
Add a newline at the end of json files when writing them.
This fixes the really irritating ping-pong of newline/nonewline when editing
json files with an editor, and with `yotta version` commands. | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects so that we preserve the order
# of keys in objects (including, for example, dependencies)
return json.load(f, object_pairs_hook=OrderedDict)
def dump(path, obj):
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f:
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
json.dump(obj, f, indent=2, separators=(',', ': '))
f.write(u'\n')
f.truncate()
def loads(string):
return json.loads(string, object_pairs_hook=OrderedDict)
| # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects so that we preserve the order
# of keys in objects (including, for example, dependencies)
return json.load(f, object_pairs_hook=OrderedDict)
def dump(path, obj):
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f:
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
json.dump(obj, f, indent=2, separators=(',', ': '))
f.truncate()
def loads(string):
return json.loads(string, object_pairs_hook=OrderedDict)
|
Make them fail, so it is a real kata now :). | // 12: destructuring - object
// To do: make all tests pass, leave the assert lines unchanged!
describe('destructuring objects', () => {
it('is simple', () => {
const x = {x: 1};
assert.equal(x, 1);
});
describe('nested', () => {
it('multiple objects', () => {
const magic = {first: 23, second: 42};
const {magic: [second]} = {magic};
assert.equal(second, 42);
});
it('object and array', () => {
const {z:[x]} = {z: [23, 42]};
assert.equal(x, 42);
});
it('array and object', () => {
const [,{lang}] = [null, [{env: 'browser', lang: 'ES6'}]];
assert.equal(lang, 'ES6');
});
});
describe('interesting', () => {
it('missing refs become undefined', () => {
const {z} = {x: 1, z: 2};
assert.equal(z, void 0);
});
it('destructure from builtins (string)', () => {
const {substr} = 1;
assert.equal(substr, String.prototype.substr);
});
});
});
| // 12: destructuring - object
// To do: make all tests pass, leave the assert lines unchanged!
describe('destructuring objects', () => {
it('is simple', () => {
const {x} = {x: 1};
assert.equal(x, 1);
});
describe('nested', () => {
it('multiple objects', () => {
const magic = {first: 23, second: 42};
const {magic: {second}} = {magic};
assert.equal(second, 42);
});
it('object and array', () => {
const {z:[,x]} = {z: [23, 42]};
assert.equal(x, 42);
});
it('array and object', () => {
const [,[{lang}]] = [null, [{env: 'browser', lang: 'ES6'}]];
assert.equal(lang, 'ES6');
});
});
it('missing => undefined', () => {
const {z} = {x: 1};
assert.equal(z, void 0);
});
it('destructure from builtins (string)', () => {
const {substr} = '';
assert.equal(substr, String.prototype.substr);
});
});
|
Use Enny to get the types | var Deffy = require("deffy")
, Typpy = require("typpy")
, Enny = require("enny")
;
var SEPARATOR = "_";
function SubElmId(type, name, parent) {
if (Typpy(type, SubElm)) {
parent = name;
name = type.name;
type = type.type;
}
this.type = type;
this.name = name;
this.parentId = parent;
}
SubElmId.prototype.toString = function () {
return [this.type, this.parentId, this.name].join(SEPARATOR);
};
function SubElm(type, data, parent) {
if (Typpy(data, SubElm)) {
return data;
}
if (typeof type === "string") {
type = Enny.TYPES[type];
}
this.icon = type.icon;
this.name = SubElm.Name(data);
this.label = Deffy(data.label, this.name);
this.type = type.type;
this.id = new SubElmId(this, parent.id)
this.lines = {};
}
SubElm.Name = function (input) {
return input.name || input.event || input.serverMethod || input.method;
};
SubElm.Id = SubElmId;
module.exports = SubElm;
| var Deffy = require("deffy")
, Typpy = require("typpy")
;
var SEPARATOR = "_";
function SubElmId(type, name, parent) {
if (Typpy(type, SubElm)) {
parent = name;
name = type.name;
type = type.type;
}
this.type = type;
this.name = name;
this.parentId = parent;
}
SubElmId.prototype.toString = function () {
return [this.type, this.parentId, this.name].join(SEPARATOR);
};
function SubElm(type, data, parent) {
if (Typpy(data, SubElm)) {
return data;
}
this.name = SubElm.Name(data);
this.label = Deffy(data.label, this.name);
this.type = type;
this.id = new SubElmId(this, parent.id)
this.lines = {};
}
SubElm.Name = function (input) {
return input.name || input.event || input.serverMethod || input.method;
};
SubElm.Id = SubElmId;
module.exports = SubElm;
|
Fix missing initialiation leading to notices. | <?php
/**
* Qafoo PHP Refactoring Browser
*
* LICENSE
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to kontakt@beberlei.de so I can send you a copy immediately.
*/
namespace QafooLabs\Refactoring\Adapters\PHPParser\Visitor;
use PHPParser_Node;
use PHPParser_Node_Stmt_Use;
use PHPParser_Node_Stmt_UseUse;
class UseStatementCollector extends \PHPParser_NodeVisitorAbstract
{
/**
* @var array
*/
private $useDeclarations = array();
public function enterNode(PHPParser_Node $node)
{
if ($node instanceof PHPParser_Node_Stmt_UseUse) {
$this->useDeclarations[] = array(
'name' => implode('\\', $node->name->parts),
'line' => $node->getLine()
);
}
}
public function collectedUseDeclarations()
{
return $this->useDeclarations;
}
}
| <?php
/**
* Qafoo PHP Refactoring Browser
*
* LICENSE
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to kontakt@beberlei.de so I can send you a copy immediately.
*/
namespace QafooLabs\Refactoring\Adapters\PHPParser\Visitor;
use PHPParser_Node;
use PHPParser_Node_Stmt_Use;
use PHPParser_Node_Stmt_UseUse;
class UseStatementCollector extends \PHPParser_NodeVisitorAbstract
{
private $useDeclarations;
public function enterNode(PHPParser_Node $node)
{
if ($node instanceof PHPParser_Node_Stmt_UseUse) {
$this->useDeclarations[] = array(
'name' => implode('\\', $node->name->parts),
'line' => $node->getLine()
);
}
}
public function collectedUseDeclarations()
{
return $this->useDeclarations;
}
}
|
Remove async from mongosoe query | 'use strict';
import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';
function localAuthenticate(User, email, password, done) {
User.findOne({
email: email.toLowerCase()
})
.then(user => {
if (!user) {
return done(null, false, {
message: 'This email is not registered.'
});
}
user.authenticate(password, function(authError, authenticated) {
if (authError) {
return done(authError);
}
if (!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
} else {
return done(null, user);
}
});
})
.catch(err => done(err));
}
export function setup(User, config) {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password' // this is the virtual field on the model
}, function(email, password, done) {
return localAuthenticate(User, email, password, done);
}));
}
| 'use strict';
import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';
function localAuthenticate(User, email, password, done) {
User.findOneAsync({
email: email.toLowerCase()
})
.then(user => {
if (!user) {
return done(null, false, {
message: 'This email is not registered.'
});
}
user.authenticate(password, function(authError, authenticated) {
if (authError) {
return done(authError);
}
if (!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
} else {
return done(null, user);
}
});
})
.catch(err => done(err));
}
export function setup(User, config) {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password' // this is the virtual field on the model
}, function(email, password, done) {
return localAuthenticate(User, email, password, done);
}));
}
|
Fix issue with URL routes | import os
import sys
from werkzeug.urls import url_quote, url_unquote
from werkzeug.routing import PathConverter
def data_filename(fname):
basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if os.path.exists(os.path.join(basedir, 'labmanager_data', fname)):
return os.path.join(basedir, 'labmanager_data', fname)
if os.path.exists(os.path.join(sys.prefix, 'labmanager_data', fname)):
return os.path.join(sys.prefix, 'labmanager_data', fname)
elif os.path.exists(os.path.join(basedir, fname)):
return os.path.abspath(os.path.join(basedir, fname))
else:
return fname
class FullyQuotedUrlConverter(PathConverter):
def to_python(self, value):
return url_unquote(url_unquote(url_unquote(value)))
def to_url(self, value):
return url_quote(url_quote(url_quote(value, self.map.charset, safe=''), self.map.charset, safe=''), self.map.charset, safe='')
| import os
import sys
from werkzeug.urls import url_quote, url_unquote
from werkzeug.routing import PathConverter
def data_filename(fname):
basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if os.path.exists(os.path.join(basedir, 'labmanager_data', fname)):
return os.path.join(basedir, 'labmanager_data', fname)
if os.path.exists(os.path.join(sys.prefix, 'labmanager_data', fname)):
return os.path.join(sys.prefix, 'labmanager_data', fname)
elif os.path.exists(os.path.join(basedir, fname)):
return os.path.abspath(os.path.join(basedir, fname))
else:
return fname
class FullyQuotedUrlConverter(PathConverter):
def to_python(self, value):
return url_unquote(value)
def to_url(self, value):
return url_quote(value, self.map.charset, safe='')
|
Use the new Vue GWT init | package com.axellience.vuegwtdemo.client;
import com.axellience.vuegwt.client.Vue;
import com.axellience.vuegwt.client.VueGWT;
import com.axellience.vuegwt.client.gwtpanel.VueGwtPanel;
import com.axellience.vuegwtdemo.client.components.counter.CounterComponent;
import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>
*/
public class VueGwtDemoApp implements EntryPoint
{
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
VueGWT.initWithVueLib();
// Create a simple GWT panel containing a CounterWithTemplateComponent
RootPanel
.get("simpleCounterComponentContainer")
.add(new VueGwtPanel<>(CounterComponent.class));
Vue.attach("#todoListComponentContainer", TodoListComponent.class);
}
}
| package com.axellience.vuegwtdemo.client;
import com.axellience.vuegwt.client.Vue;
import com.axellience.vuegwt.client.gwtpanel.VueGwtPanel;
import com.axellience.vuegwt.client.resources.VueLib;
import com.axellience.vuegwtdemo.client.components.counter.CounterComponent;
import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>
*/
public class VueGwtDemoApp implements EntryPoint
{
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
VueLib.inject();
// Create a simple GWT panel containing a CounterWithTemplateComponent
RootPanel
.get("simpleCounterComponentContainer")
.add(new VueGwtPanel<>(CounterComponent.class));
Vue.attach("#todoListComponentContainer", TodoListComponent.class);
}
}
|
Set timeout default value to 30sec. | var os = require('os');
var path = require('path');
var paths = require('./paths');
// Guess proxy defined in the env
/*jshint camelcase: false*/
var proxy = process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
var httpsProxy = process.env.HTTPS_PROXY
|| process.env.https_proxy
|| process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
/*jshint camelcase: true*/
var defaults = {
'cwd': process.cwd(),
'directory': 'bower_components',
'registry': 'https://bower.herokuapp.com',
'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git',
'tmp': os.tmpdir ? os.tmpdir() : os.tmpDir(),
'proxy': proxy,
'https-proxy': httpsProxy,
'timeout': 30000,
'ca': { search: [] },
'strict-ssl': true,
'user-agent': 'node/' + process.version + ' ' + process.platform + ' ' + process.arch,
'color': true,
'interactive': false,
'storage': {
packages: path.join(paths.cache, 'packages'),
links: path.join(paths.data, 'links'),
completion: path.join(paths.data, 'completion'),
registry: path.join(paths.cache, 'registry'),
git: path.join(paths.data, 'git')
}
};
module.exports = defaults;
| var os = require('os');
var path = require('path');
var paths = require('./paths');
// Guess proxy defined in the env
/*jshint camelcase: false*/
var proxy = process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
var httpsProxy = process.env.HTTPS_PROXY
|| process.env.https_proxy
|| process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
/*jshint camelcase: true*/
var defaults = {
'cwd': process.cwd(),
'directory': 'bower_components',
'registry': 'https://bower.herokuapp.com',
'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git',
'tmp': os.tmpdir ? os.tmpdir() : os.tmpDir(),
'proxy': proxy,
'https-proxy': httpsProxy,
'timeout': 60000,
'ca': { search: [] },
'strict-ssl': true,
'user-agent': 'node/' + process.version + ' ' + process.platform + ' ' + process.arch,
'color': true,
'interactive': false,
'storage': {
packages: path.join(paths.cache, 'packages'),
links: path.join(paths.data, 'links'),
completion: path.join(paths.data, 'completion'),
registry: path.join(paths.cache, 'registry'),
git: path.join(paths.data, 'git')
}
};
module.exports = defaults;
|
Remove 'TAS' from games blacklist | from bs4 import BeautifulSoup
import requests
import json
import sys
html = requests.get("http://gamesdonequick.com/schedule").text
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('tbody')
first_rows = table.findAll('tr', attrs={'class': None})
games = list()
for row in first_rows:
second_row = row.findNext('tr', attrs={'class': 'second-row'})
duration = 0
if second_row:
duration = second_row.findNext('td').text.strip()
runner_text = row.find('td', attrs={'rowspan': 2})
runner = runner_text.text.strip() if runner_text else ""
start_time_text = row.find('td', attrs={'class': "start-time"})
start_time = start_time_text.text if start_time_text else ""
game = {
'title': row.find('td', attrs={'class': None}).text,
'duration': duration,
'runner': runner,
'start_time': start_time,
}
games.append(game)
blacklist = ['Pre-Show', 'Setup Block', 'Finale']
games = [x for x in games if not any(x['title'].startswith(b) for b in blacklist)]
if len(sys.argv) == 1 or sys.argv[1] == 'verbose':
print json.dumps(games)
else:
with open('../data_file.json', 'w+') as f:
f.write(json.dumps(games))
| from bs4 import BeautifulSoup
import requests
import json
import sys
html = requests.get("http://gamesdonequick.com/schedule").text
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('tbody')
first_rows = table.findAll('tr', attrs={'class': None})
games = list()
for row in first_rows:
second_row = row.findNext('tr', attrs={'class': 'second-row'})
duration = 0
if second_row:
duration = second_row.findNext('td').text.strip()
runner_text = row.find('td', attrs={'rowspan': 2})
runner = runner_text.text.strip() if runner_text else ""
start_time_text = row.find('td', attrs={'class': "start-time"})
start_time = start_time_text.text if start_time_text else ""
game = {
'title': row.find('td', attrs={'class': None}).text,
'duration': duration,
'runner': runner,
'start_time': start_time,
}
games.append(game)
blacklist = ['Pre-Show', 'Setup Block', 'TAS', 'Finale']
games = [x for x in games if not any(x['title'].startswith(b) for b in blacklist)]
if len(sys.argv) == 1 or sys.argv[1] == 'verbose':
print json.dumps(games)
else:
with open('../data_file.json', 'w+') as f:
f.write(json.dumps(games))
|
Update a SeleniumBase tour example | from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('https://xkcd.com/1117/')
self.assert_element('img[alt="My Sky"]')
self.create_shepherd_tour()
self.add_tour_step("Welcome to XKCD!")
self.add_tour_step("This is the XKCD logo.", "#masthead img")
self.add_tour_step("Here's the daily webcomic.", "#comic img")
self.add_tour_step("This is the title.", "#ctitle", alignment="top")
self.add_tour_step("Click here for the next comic.", 'a[rel="next"]')
self.add_tour_step("Click here for the previous one.", 'a[rel="prev"]')
self.add_tour_step("Learn about the author here.", 'a[rel="author"]')
self.add_tour_step("Click here for the license.", 'a[rel="license"]')
self.add_tour_step("Click for a random comic.", 'a[href*="/random/"]')
self.add_tour_step("Thanks for taking this tour!")
self.export_tour(filename="xkcd_tour.js") # This exports the tour
self.play_tour() # This plays the tour
| from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('https://xkcd.com/1117/')
self.assert_element('img[alt="My Sky"]')
self.create_shepherd_tour()
self.add_tour_step("Welcome to XKCD!")
self.add_tour_step("This is the XKCD logo.", "#masthead img")
self.add_tour_step("Here's the daily webcomic.", "#comic img")
self.add_tour_step("This is the title.", "#ctitle", alignment="top")
self.add_tour_step("Click here for the next comic.", 'a[rel="next"]')
self.add_tour_step("Or here for the previous comic.", 'a[rel="prev"]')
self.add_tour_step("Learn about the author here.", 'a[rel="author"]')
self.add_tour_step("Click for the license here.", 'a[rel="license"]')
self.add_tour_step("This selects a random comic.", 'a[href*="random"]')
self.add_tour_step("Thanks for taking this tour!")
# self.export_tour() # Use this to export the tour as [my_tour.js]
self.export_tour(filename="xkcd_tour.js") # You can customize the name
self.play_tour()
|
Fix unit tests after change in optimize API 💀 | import { expect } from 'chai'
import { optimize } from 'webpack'
import preset from './optimize'
describe('optimize webpack preset', function () {
describe('when enabled with the optimize flag', function () {
it('should configure DedupePlugin', function () {
const config = preset.configure({ optimize: true })
const commons = config.plugins.filter((preset) => preset instanceof optimize.DedupePlugin)
expect(commons.length).equal(1)
})
it('should configure UglifyJsPlugin without the warnings', function () {
const config = preset.configure({ optimize: true })
const commons = config.plugins.filter((preset) => preset instanceof optimize.UglifyJsPlugin)
expect(commons.length).equal(1)
const uglifyJsPlugin = commons[0]
expect(uglifyJsPlugin.options.compress.warnings).to.eql(false)
})
})
})
| import { expect } from 'chai'
import { optimize } from 'webpack'
import preset from './optimize'
import buildTargets from '../../build-targets'
describe('optimize webpack preset', function () {
describe('production build target', function () {
it('should configure DedupePlugin', function () {
const config = preset.configure({ buildTarget: buildTargets.PRODUCTION })
const commons = config.plugins.filter((preset) => preset instanceof optimize.DedupePlugin)
expect(commons.length).equal(1)
})
it('should configure UglifyJsPlugin without the warnings', function () {
const config = preset.configure({ buildTarget: buildTargets.PRODUCTION })
const commons = config.plugins.filter((preset) => preset instanceof optimize.UglifyJsPlugin)
expect(commons.length).equal(1)
const uglifyJsPlugin = commons[0]
expect(uglifyJsPlugin.options.compress.warnings).to.eql(false)
})
})
})
|
Update indexes on folders table during migration | package com.fsck.k9.mailstore.migrations;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
class MigrationTo61 {
static void addFolderRemoteId(SQLiteDatabase db) {
if (!columnExists(db, "folders", "remoteId")) {
db.execSQL("ALTER TABLE folders ADD remoteId TEXT");
db.execSQL("UPDATE folders SET remoteId = name");
db.execSQL("DROP INDEX IF EXISTS folder_name");
db.execSQL("CREATE INDEX IF NOT EXISTS folder_remoteId ON folders (remoteId)");
}
}
private static boolean columnExists(SQLiteDatabase db, String table, String columnName) {
Cursor columnCursor = db.rawQuery("PRAGMA table_info(" + table + ")", null);
boolean foundColumn = false;
while (columnCursor.moveToNext()) {
String currentColumnName = columnCursor.getString(1);
if (currentColumnName.equals(columnName)) {
foundColumn = true;
break;
}
}
columnCursor.close();
return foundColumn;
}
}
| package com.fsck.k9.mailstore.migrations;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
class MigrationTo61 {
static void addFolderRemoteId(SQLiteDatabase db) {
if (!columnExists(db, "folders", "remoteId")) {
db.execSQL("ALTER TABLE folders ADD remoteId TEXT");
db.execSQL("UPDATE folders SET remoteId = name");
}
}
private static boolean columnExists(SQLiteDatabase db, String table, String columnName) {
Cursor columnCursor = db.rawQuery("PRAGMA table_info(" + table + ")", null);
boolean foundColumn = false;
while (columnCursor.moveToNext()) {
String currentColumnName = columnCursor.getString(1);
if (currentColumnName.equals(columnName)) {
foundColumn = true;
break;
}
}
columnCursor.close();
return foundColumn;
}
}
|
Add comment that externals RegExp does work | var api = require("./webpack.config.defaults")
.entry("./src/server.js")
.externals(/^@?\w[a-z\-0-9\./]+$/)
.output("build/server")
.target("node")
.when("development", function(api) {
return api
.entry({
server: [
"webpack/hot/poll?1000",
"./src/server.js",
],
})
.sourcemap("source-map")
.plugin("start-server-webpack-plugin")
.plugin("webpack.BannerPlugin", {
banner: `require("source-map-support").install();`,
raw: true,
})
;
})
;
module.exports = api.getConfig();
| var api = require("./webpack.config.defaults")
.entry("./src/server.js")
// @TODO Auto-installed deps aren't in node_modules (yet),
// so let's see if this is a problem or not
.externals(/^@?\w[a-z\-0-9\./]+$/)
// .externals(...require("fs").readdirSync("./node_modules"))
.output("build/server")
.target("node")
.when("development", function(api) {
return api
.entry({
server: [
"webpack/hot/poll?1000",
"./src/server.js",
],
})
.sourcemap("source-map")
.plugin("start-server-webpack-plugin")
.plugin("webpack.BannerPlugin", {
banner: `require("source-map-support").install();`,
raw: true,
})
;
})
;
module.exports = api.getConfig();
|
Add import os in lmod to fix regression | import os # require by lmod output evaluated by exec()
from functools import partial
from os import environ
from subprocess import Popen, PIPE
LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '')
def module(command, *args):
cmd = (environ['LMOD_CMD'], 'python', '--terse', command)
result = Popen(cmd + args, stdout=PIPE, stderr=PIPE)
if command in ('load', 'unload', 'restore', 'save'):
exec(result.stdout.read())
return result.stderr.read().decode()
def avail():
string = module('avail')
modules = []
for entry in string.split():
if not (entry.startswith('/') or entry.endswith('/')):
modules.append(entry)
return modules
def list():
string = module('list').strip()
if string != "No modules loaded":
return string.split()
return []
def savelist(system=LMOD_SYSTEM_NAME):
names = module('savelist').split()
if system:
suffix = '.{}'.format(system)
n = len(suffix)
names = [name[:-n] for name in names if name.endswith(suffix)]
return names
show = partial(module, 'show')
load = partial(module, 'load')
unload = partial(module, 'unload')
restore = partial(module, 'restore')
save = partial(module, 'save')
| from functools import partial
from os import environ
from subprocess import Popen, PIPE
LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '')
def module(command, *args):
cmd = (environ['LMOD_CMD'], 'python', '--terse', command)
result = Popen(cmd + args, stdout=PIPE, stderr=PIPE)
if command in ('load', 'unload', 'restore', 'save'):
exec(result.stdout.read())
return result.stderr.read().decode()
def avail():
string = module('avail')
modules = []
for entry in string.split():
if not (entry.startswith('/') or entry.endswith('/')):
modules.append(entry)
return modules
def list():
string = module('list').strip()
if string != "No modules loaded":
return string.split()
return []
def savelist(system=LMOD_SYSTEM_NAME):
names = module('savelist').split()
if system:
suffix = '.{}'.format(system)
n = len(suffix)
names = [name[:-n] for name in names if name.endswith(suffix)]
return names
show = partial(module, 'show')
load = partial(module, 'load')
unload = partial(module, 'unload')
restore = partial(module, 'restore')
save = partial(module, 'save')
|
Test for attachment in mail test | # -*- coding: utf-8 -*-
from __future__ import with_statement
from django.test import TestCase
from foirequest.tasks import _process_mail
from foirequest.models import FoiRequest
class MailTest(TestCase):
fixtures = ['publicbodies.json', "foirequest.json"]
def test_working(self):
with file("foirequest/tests/test_mail_01.txt") as f:
_process_mail(f.read())
request = FoiRequest.objects.get_by_secret_mail("s.wehrmeyer+axb4afh@fragdenstaat.de")
messages = request.foimessage_set.all()
self.assertEqual(len(messages), 2)
def test_working_with_attachment(self):
with file("foirequest/tests/test_mail_02.txt") as f:
_process_mail(f.read())
request = FoiRequest.objects.get_by_secret_mail("s.wehrmeyer+axb4afh@fragdenstaat.de")
messages = request.foimessage_set.all()
self.assertEqual(len(messages), 2)
self.assertEqual(messages[1].subject, u"Fwd: Informationsfreiheitsgesetz des Bundes, Antragsvordruck für Open Data")
self.assertEqual(len(messages[1].attachments), 1)
self.assertEqual(messages[1].attachments[0].name, u"TI - IFG-Antrag, Vordruck.docx")
| # -*- coding: utf-8 -*-
from __future__ import with_statement
from django.test import TestCase
from foirequest.tasks import _process_mail
from foirequest.models import FoiRequest
class MailTest(TestCase):
fixtures = ['publicbodies.json', "foirequest.json"]
def test_working(self):
with file("foirequest/tests/test_mail_01.txt") as f:
_process_mail(f.read())
request = FoiRequest.objects.get_by_secret_mail("s.wehrmeyer+axb4afh@fragdenstaat.de")
messages = request.foimessage_set.all()
self.assertEqual(len(messages), 2)
def test_working_with_attachment(self):
with file("foirequest/tests/test_mail_02.txt") as f:
_process_mail(f.read())
request = FoiRequest.objects.get_by_secret_mail("s.wehrmeyer+axb4afh@fragdenstaat.de")
messages = request.foimessage_set.all()
self.assertEqual(len(messages), 2)
self.assertEqual(messages[1].subject, u"Fwd: Informationsfreiheitsgesetz des Bundes, Antragsvordruck für Open Data")
self.assertEqual(len(message[1].attachments), 1)
|
Add quick documentation to fallback strategy | /**
* In case of an unsupported browser this will add a body className and register a click handler.
* Upon clicking the button a cookie will be set to stop showing the information on subsequent loads.
*
* @param {boolean} support indicates whether the feature is supported
*/
const bodyClassNameFallback = support => {
const COOKIE_NAME = 'browser-fallback-raised'
const CLASS_NAME = '-browser-not-supported'
const DISMISS_ID = 'dismiss-browser-not-supported'
if (!support) {
const alreadyDetected = document.cookie.indexOf(COOKIE_NAME) !== -1
if (!alreadyDetected) {
document.body.className += ' ' + CLASS_NAME
const $element = document.getElementById(DISMISS_ID)
if ($element !== null) {
$element.onclick = function() {
document.cookie = COOKIE_NAME + '=true'
const reg = new RegExp('(\\s|^)' + CLASS_NAME + '(\\s|$)')
document.body.className = document.body.className.replace(reg, ' ')
}
}
}
}
}
export default bodyClassNameFallback
| const bodyClassNameFallback = support => {
const COOKIE_NAME = 'browser-fallback-raised'
const CLASS_NAME = '-browser-not-supported'
const DISMISS_ID = 'dismiss-browser-not-supported'
if (!support) {
const alreadyDetected = document.cookie.indexOf(COOKIE_NAME) !== -1
if (!alreadyDetected) {
document.body.className += ' ' + CLASS_NAME
const $element = document.getElementById(DISMISS_ID)
if ($element !== null) {
$element.onclick = function() {
document.cookie = COOKIE_NAME + '=true'
const reg = new RegExp('(\\s|^)' + CLASS_NAME + '(\\s|$)')
document.body.className = document.body.className.replace(reg, ' ')
}
}
}
}
}
export default bodyClassNameFallback
|
fix(build): Fix build by reverting changes | module.exports = {
assets: {
files: [{
expand: true,
dot: true,
cwd: '<%= appDir %>',
dest: '<%= distDir %>',
src: [
'images/**/*',
'styles/css/*.css',
'scripts/**/*.{html,css,jpg,jpeg,png,gif,json}',
'template/**/*.html',
'scripts/bower_components/requirejs/require.js'
]
}]
},
js: {
files: [{
expand: true,
dot: true,
cwd: '<%= appDir %>',
dest: '<%= distDir %>',
src: [
'scripts/config.js',
'scripts/bower_components/**/*.js'
]
}]
}
};
| module.exports = {
assets: {
files: [{
expand: true,
dot: true,
dest: '<%= distDir %>',
src: [
'<%= appDir %>/images/**/*',
'<%= appDir %>/styles/css/*.css',
'<%= appDir %>/scripts/**/*.{html,css,jpg,jpeg,png,gif,json}',
'<%= appDir %>/template/**/*.html',
'<%= appDir %>/scripts/bower_components/requirejs/require.js'
]
}]
},
js: {
files: [{
expand: true,
dot: true,
cwd: '<%= appDir %>',
dest: '<%= distDir %>',
src: [
'scripts/config.js',
'scripts/bower_components/**/*.js'
]
}]
}
};
|
Fix index names in migrations
This can be reverted when we upgrade to Laravel 5.7. | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Flarum\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$schema->table('discussions', function (Blueprint $table) use ($schema) {
$table->index(['is_sticky', 'created_at']);
Migration::fixIndexNames($schema, $table);
});
},
'down' => function (Builder $schema) {
$schema->table('discussions', function (Blueprint $table) use ($schema) {
$table->dropIndex(['is_sticky', 'created_at']);
Migration::fixIndexNames($schema, $table);
});
}
];
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$schema->table('discussions', function (Blueprint $table) {
$table->index(['is_sticky', 'created_at']);
});
},
'down' => function (Builder $schema) {
$schema->table('discussions', function (Blueprint $table) {
$table->dropIndex(['is_sticky', 'created_at']);
});
}
];
|
Update test case for updated 'B' codabar character | package codabar
import (
"image/color"
"testing"
)
func Test_Encode(t *testing.T) {
_, err := Encode("FOOBAR")
if err == nil {
t.Error("\"FOOBAR\" should not be encodable")
}
testEncode := func(txt, testResult string) {
code, err := Encode(txt)
if err != nil || code == nil {
t.Fail()
} else {
if code.Bounds().Max.X != len(testResult) {
t.Errorf("%v: length missmatch", txt)
} else {
for i, r := range testResult {
if (code.At(i, 0) == color.Black) != (r == '1') {
t.Errorf("%v: code missmatch on position %d", txt, i)
}
}
}
}
}
testEncode("A40156B", "10110010010101101001010101001101010110010110101001010010101101001001011")
}
| package codabar
import (
"image/color"
"testing"
)
func Test_Encode(t *testing.T) {
_, err := Encode("FOOBAR")
if err == nil {
t.Error("\"FOOBAR\" should not be encodable")
}
testEncode := func(txt, testResult string) {
code, err := Encode(txt)
if err != nil || code == nil {
t.Fail()
} else {
if code.Bounds().Max.X != len(testResult) {
t.Errorf("%v: length missmatch", txt)
} else {
for i, r := range testResult {
if (code.At(i, 0) == color.Black) != (r == '1') {
t.Errorf("%v: code missmatch on position %d", txt, i)
}
}
}
}
}
testEncode("A40156B", "10110010010101101001010101001101010110010110101001010010101101010010011")
}
|
Use intercept instead of callbacks on last commit | module.exports = (function () {
'use strict';
/** Delete cache entries
*
* @function
* @description
* @return void{}
* @arg {Object} query - Optional
* @arg {Function} callback
*/
function del (name, callback) {
var self = this;
var domain = require('domain').create();
domain.on('error', function (error) {
console.log('error error error', {
error: error.name,
message: error.message,
stack: error.stack.split(/\n/)
});
callback(error);
});
domain.run(function () {
var prefix = self.prefix.match(/:$/) ? self.prefix.replace(/:$/, '')
: self.prefix;
/** Tell Redis to delete hash **/
var redisKey = prefix + ':' + name;
self.client.keys(redisKey, domain.intercept(function(rows) {
require('async').each(rows, function(row) {
self.client.del(row, domain.intercept(function () {
self.emit('message', require('util').format('DEL %s', row));
}));
}, callback(null, rows.length));
});
});
}
return del;
})(); | module.exports = (function () {
'use strict';
/** Delete cache entries
*
* @function
* @description
* @return void{}
* @arg {Object} query - Optional
* @arg {Function} callback
*/
function del (name, callback) {
var self = this;
var domain = require('domain').create();
domain.on('error', function (error) {
console.log('error error error', {
error: error.name,
message: error.message,
stack: error.stack.split(/\n/)
});
callback(error);
});
domain.run(function () {
var prefix = self.prefix.match(/:$/) ? self.prefix.replace(/:$/, '')
: self.prefix;
/** Tell Redis to delete hash **/
var redisKey = prefix + ':' + name;
self.client.keys(redisKey, function(err, rows) {
require('async').each(rows, function(row) {
self.client.del(row, domain.intercept(function () {
self.emit('message', require('util').format('DEL %s', row));
}));
}, callback(null, rows.length));
});
});
}
return del;
})(); |
Change to directory config method | from genes.brew import commands as brew
from genes.curl.commands import download
from genes.debian.traits import is_debian
from genes import directory
from genes.directory import DirectoryConfig
from genes.mac.traits import is_osx
from genes.tar.commands import untar
from genes.ubuntu.traits import is_ubuntu
def main():
if is_debian() or is_ubuntu():
download(
"https://download.jetbrains.com/idea/ideaIU-15.0.tar.gz",
"/tmp/ideas.tar.gz"
)
def config_directory()
return DirectoryConfig(
path='/opt/intellij-ideas',
mode='755',
group='root',
user='root',
)
# FIXME: Need to find a way to handle errors here
direcotry.main(config_directory)
untar('/tmp/ideas.tar.gz', '/opt/intellij-ideas')
if is_osx():
brew.update()
brew.cask_install('intellij-idea')
else:
pass
| from genes.brew import commands as brew
from genes.curl.commands import download
from genes.debian.traits import is_debian
from genes.directory import DirectoryBuilder
from genes.mac.traits import is_osx
from genes.tar.commands import untar
from genes.ubuntu.traits import is_ubuntu
def main():
if is_debian() or is_ubuntu():
download(
"https://download.jetbrains.com/idea/ideaIU-15.0.tar.gz",
"/tmp/ideas.tar.gz"
)
DirectoryBuilder('/opt/intellij-ideas').\
set_mode('755').\
set_group('root').\
set_user('root').\
build()
untar('/tmp/ideas.tar.gz', '/opt/intellij-ideas')
if is_osx():
brew.update()
brew.cask_install('intellij-idea')
else:
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.