text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use keys instead of iterkeys to go through all keys on clean_query_set | # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
paginated_objects = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
paginated_objects = paginator.page(paginator.num_pages)
return paginated_objects
def clean_query_string(request):
clean_query_set = request.GET.copy()
clean_query_set = dict(
(k, v) for k, v in request.GET.items() if not k.startswith('o_')
)
try:
del clean_query_set['p']
except:
pass
mstring = []
for key in clean_query_set.keys():
valuelist = request.GET.getlist(key)
mstring.extend(['%s=%s' % (key, val) for val in valuelist])
return '&'.join(mstring)
| # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
paginated_objects = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
paginated_objects = paginator.page(paginator.num_pages)
return paginated_objects
def clean_query_string(request):
clean_query_set = request.GET.copy()
clean_query_set = dict(
(k, v) for k, v in request.GET.items() if not k.startswith('o_')
)
try:
del clean_query_set['p']
except:
pass
mstring = []
for key in clean_query_set.iterkeys():
valuelist = request.GET.getlist(key)
mstring.extend(['%s=%s' % (key, val) for val in valuelist])
return '&'.join(mstring)
|
install: Clean up after read-package-json's _id mess | 'use strict'
var defaultTemplate = {
package: {
dependencies: {},
devDependencies: {},
optionalDependencies: {},
_requiredBy: [],
_phantomChildren: {}
},
loaded: false,
children: [],
requiredBy: [],
missingDeps: {},
missingDevDeps: {},
path: null,
realpath: null
}
function isLink (node) {
return node && node.isLink
}
var create = exports.create = function (node, template) {
if (!template) template = defaultTemplate
Object.keys(template).forEach(function (key) {
if (template[key] != null && typeof template[key] === 'object' && !(template[key] instanceof Array)) {
if (!node[key]) node[key] = {}
return create(node[key], template[key])
}
if (node[key] != null) return
node[key] = template[key]
})
if (isLink(node) || isLink(node.parent)) {
node.isLink = true
}
return node
}
var reset = exports.reset = function (node) {
var child = create(node)
child.package._requiredBy = child.package._requiredBy.filter(function (req) {
return req[0] === '#'
})
child.requiredBy = []
child.package._phantomChildren = {}
// FIXME: cleaning up after read-package-json's mess =(
if (child.package._id === '@') delete child.package._id
child.missingDeps = {}
child.children.forEach(reset)
if (!child.package.version) child.package.version = ''
}
| 'use strict'
var defaultTemplate = {
package: {
dependencies: {},
devDependencies: {},
optionalDependencies: {},
_requiredBy: [],
_phantomChildren: {}
},
loaded: false,
children: [],
requiredBy: [],
missingDeps: {},
missingDevDeps: {},
path: null,
realpath: null
}
function isLink (node) {
return node && node.isLink
}
var create = exports.create = function (node, template) {
if (!template) template = defaultTemplate
Object.keys(template).forEach(function (key) {
if (template[key] != null && typeof template[key] === 'object' && !(template[key] instanceof Array)) {
if (!node[key]) node[key] = {}
return create(node[key], template[key])
}
if (node[key] != null) return
node[key] = template[key]
})
if (isLink(node) || isLink(node.parent)) {
node.isLink = true
}
return node
}
var reset = exports.reset = function (node) {
var child = create(node)
child.package._requiredBy = child.package._requiredBy.filter(function (req) {
return req[0] === '#'
})
child.requiredBy = []
child.package._phantomChildren = {}
child.missingDeps = {}
child.children.forEach(reset)
if (!child.package.version) child.package.version = ''
}
|
Clean up code and add timestamp | const quotes = JSON.parse(require('fs').readFileSync('./data/backup-2016-11-03.json', 'utf8'))
const config = require('./config')
const Twit = require('twit')
const T = new Twit(config.oauth_creds)
function randomQuote () {
return quotes[Math.floor(Math.random() * quotes.length)]
}
function tweetMessage (quote) {
let msg = quote.msg + '\n' + quote.src
T.post('statuses/update', {status: msg}, (err, res) => {
if (err) {
console.error('--->>>')
console.error(msg)
console.error(quote)
console.dir(err)
} else {
console.log('tweet succeed at ', new Date())
console.log(res.text)
}
})
}
tweetMessage(randomQuote())
| const fs = require('fs')
const Twit = require('twit')
const config = require('./config')
const quotes = JSON.parse(fs.readFileSync('./data/backup-2016-11-03.json', 'utf8'))
const T = new Twit(config.oauth_creds)
function randomQuote () {
return quotes[Math.floor(Math.random() * quotes.length)]
}
function tweetMessage (quote) {
let msg = quote.msg + '\n' + quote.src
T.post('statuses/update', {status: msg}, (err, res) => {
if (err) {
console.error('--->>>')
console.error(msg)
console.error(quote)
console.dir(err)
} else {
console.log('tweet succeed.')
console.log(res.text)
}
})
}
tweetMessage(randomQuote())
|
Update javadoc for propgation comparison enum | /*
* Copyright 2013 MovingBlocks
*
* 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 org.terasology.world.propagation;
/**
* An enum that describes how propagation rules have changes when blocks are replaced with others
*/
public enum PropagationComparison {
/**
* Propagation is restricted in some way it wasn't before
*/
MORE_RESTRICTED(true, false),
/**
* Propagation is identical to before
*/
IDENTICAL(false, false),
/**
* Propagation is strictly more permissive than before
*/
MORE_PERMISSIVE(false, true);
private boolean restricting;
private boolean permitting;
PropagationComparison(boolean restricts, boolean permits) {
this.restricting = restricts;
this.permitting = permits;
}
public boolean isRestricting() {
return restricting;
}
public boolean isPermitting() {
return permitting;
}
}
| /*
* Copyright 2013 MovingBlocks
*
* 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 org.terasology.world.propagation;
/**
*/
public enum PropagationComparison {
/**
* Lighting is restricted in some way it wasn't before
*/
MORE_RESTRICTED(true, false),
/**
* Lighting is identical to before
*/
IDENTICAL(false, false),
/**
* Lighting is strictly more permissive than before
*/
MORE_PERMISSIVE(false, true);
private boolean restricting;
private boolean permitting;
PropagationComparison(boolean restricts, boolean permits) {
this.restricting = restricts;
this.permitting = permits;
}
public boolean isRestricting() {
return restricting;
}
public boolean isPermitting() {
return permitting;
}
}
|
Remove unnecessary import of a class in the same package. | package com.topsy.jmxproxy;
import com.topsy.jmxproxy.jmx.ConnectionManager;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMXProxyApplication extends Application<JMXProxyConfiguration> {
private static final Logger LOG = LoggerFactory.getLogger(JMXProxyApplication.class);
public static void main(String[] args) throws Exception {
LOG.info("starting jmxproxy service");
new JMXProxyApplication().run(args);
}
@Override
public String getName() {
return "jmxproxy";
}
@Override
public void initialize(Bootstrap<JMXProxyConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
}
@Override
public void run(JMXProxyConfiguration configuration, Environment environment) {
final ConnectionManager manager = new ConnectionManager(configuration.getApplicationConfiguration());
final JMXProxyResource resource = new JMXProxyResource(manager);
final JMXProxyHealthCheck healthCheck = new JMXProxyHealthCheck(manager);
environment.jersey().setUrlPattern("/jmxproxy/*");
environment.lifecycle().manage(manager);
environment.jersey().register(resource);
environment.healthChecks().register("manager", healthCheck);
}
}
| package com.topsy.jmxproxy;
import com.topsy.jmxproxy.jmx.ConnectionManager;
import com.topsy.jmxproxy.JMXProxyResource;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMXProxyApplication extends Application<JMXProxyConfiguration> {
private static final Logger LOG = LoggerFactory.getLogger(JMXProxyApplication.class);
public static void main(String[] args) throws Exception {
LOG.info("starting jmxproxy service");
new JMXProxyApplication().run(args);
}
@Override
public String getName() {
return "jmxproxy";
}
@Override
public void initialize(Bootstrap<JMXProxyConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
}
@Override
public void run(JMXProxyConfiguration configuration, Environment environment) {
final ConnectionManager manager = new ConnectionManager(configuration.getApplicationConfiguration());
final JMXProxyResource resource = new JMXProxyResource(manager);
final JMXProxyHealthCheck healthCheck = new JMXProxyHealthCheck(manager);
environment.jersey().setUrlPattern("/jmxproxy/*");
environment.lifecycle().manage(manager);
environment.jersey().register(resource);
environment.healthChecks().register("manager", healthCheck);
}
}
|
Remove description missing warning from field sets | import styles from './styles/DefaultFieldset.css'
import React, {PropTypes} from 'react'
export default function Fieldset(props) {
const {fieldset, legend, description} = props
return (
<fieldset className={styles.root} data-nesting-level={props.level}>
<legend className={styles.legend}>{legend || fieldset.legend}</legend>
<div className={styles.inner}>
{
(description || fieldset.description)
&& <p className={styles.description}>
{description || fieldset.description}
</p>
}
<div className={styles.content}>
{props.children}
</div>
</div>
</fieldset>
)
}
Fieldset.defaultProps = {
fieldset: {}
}
Fieldset.propTypes = {
description: PropTypes.string,
legend: PropTypes.string,
fieldset: PropTypes.shape({
description: PropTypes.string,
legend: PropTypes.string
}),
children: PropTypes.node,
level: PropTypes.number
}
| import styles from './styles/DefaultFieldset.css'
import React, {PropTypes} from 'react'
export default function Fieldset(props) {
const {fieldset, legend, description} = props
return (
<fieldset className={styles.root} data-nesting-level={props.level}>
<legend className={styles.legend}>{legend || fieldset.legend}</legend>
<div className={styles.inner}>
<p className={styles.description}>
{description || fieldset.description || 'There is no description!'}
</p>
<div className={styles.content}>
{props.children}
</div>
</div>
</fieldset>
)
}
Fieldset.defaultProps = {
fieldset: {}
}
Fieldset.propTypes = {
description: PropTypes.string,
legend: PropTypes.string,
fieldset: PropTypes.shape({
description: PropTypes.string,
legend: PropTypes.string
}),
children: PropTypes.node,
level: PropTypes.number
}
|
Fix collecstatic command return value
delete_file() method should return a boolean, was missing
a return when calling super() | import hashlib
from django.contrib.staticfiles.management.commands import collectstatic
from cumulus.storage import CloudFilesStorage
class Command(collectstatic.Command):
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if isinstance(self.storage, CloudFilesStorage):
if self.storage.exists(prefixed_path):
try:
etag = self.storage._get_cloud_obj(prefixed_path).etag
digest = "{0}".format(hashlib.md5(source_storage.open(path).read()).hexdigest())
print etag, digest
if etag == digest:
self.log(u"Skipping '{0}' (not modified based on file hash)".format(path))
return False
except:
raise
return super(Command, self).delete_file(path, prefixed_path, source_storage)
| import hashlib
from django.contrib.staticfiles.management.commands import collectstatic
from cumulus.storage import CloudFilesStorage
class Command(collectstatic.Command):
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if isinstance(self.storage, CloudFilesStorage):
if self.storage.exists(prefixed_path):
try:
etag = self.storage._get_cloud_obj(prefixed_path).etag
digest = "{0}".format(hashlib.md5(source_storage.open(path).read()).hexdigest())
print etag, digest
if etag == digest:
self.log(u"Skipping '{0}' (not modified based on file hash)".format(path))
return False
except:
raise
super(Command, self).delete_file(path, prefixed_path, source_storage)
|
Add a param check to be able to boot with an old cache
The parameter is always defined in the bundle. However, in non-debug
mode, the kernel needs to be able to boot with the old cache to clear
the cache, so we need the parameter check.
closes #260 | <?php
namespace Stof\DoctrineExtensionsBundle;
use Stof\DoctrineExtensionsBundle\DependencyInjection\Compiler\SecurityContextPass;
use Stof\DoctrineExtensionsBundle\DependencyInjection\Compiler\ValidateExtensionConfigurationPass;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Gedmo\Uploadable\Mapping\Validator;
class StofDoctrineExtensionsBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new ValidateExtensionConfigurationPass());
$container->addCompilerPass(new SecurityContextPass());
}
public function boot()
{
if ($this->container->hasParameter('stof_doctrine_extensions.uploadable.validate_writable_directory')) {
Validator::$validateWritableDirectory = $this->container->getParameter('stof_doctrine_extensions.uploadable.validate_writable_directory');
}
}
}
| <?php
namespace Stof\DoctrineExtensionsBundle;
use Stof\DoctrineExtensionsBundle\DependencyInjection\Compiler\SecurityContextPass;
use Stof\DoctrineExtensionsBundle\DependencyInjection\Compiler\ValidateExtensionConfigurationPass;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Gedmo\Uploadable\Mapping\Validator;
class StofDoctrineExtensionsBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new ValidateExtensionConfigurationPass());
$container->addCompilerPass(new SecurityContextPass());
}
public function boot()
{
Validator::$validateWritableDirectory = $this->container->getParameter('stof_doctrine_extensions.uploadable.validate_writable_directory');
}
}
|
Replace localhost lookup with static IP to fix test.
Calling InetAddress.getLocalHost() will cause a lookup to occur that may
fail with a java.net.UnknownHostException if the system the test is
running on is not configured correctly.
This is often fixed by echoing "127.0.0.1 $HOSTNAME" to /etc/hosts, but
in this case it seems easier to pick a static IP string to avoid the
lookup entirely and prevent false negatives in the test. | /*
* Copyright (C) 2011 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 com.google.gson;
import java.net.InetAddress;
import junit.framework.TestCase;
/**
* Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
*
* @author Joel Leitch
*/
public class DefaultInetAddressTypeAdapterTest extends TestCase {
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
gson = new Gson();
}
public void testInetAddressSerializationAndDeserialization() throws Exception {
InetAddress address = InetAddress.getByName("8.8.8.8");
String jsonAddress = gson.toJson(address);
assertEquals("\"8.8.8.8\"", jsonAddress);
InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
assertEquals(value, address);
}
}
| /*
* Copyright (C) 2011 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 com.google.gson;
import java.net.InetAddress;
import junit.framework.TestCase;
/**
* Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
*
* @author Joel Leitch
*/
public class DefaultInetAddressTypeAdapterTest extends TestCase {
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
gson = new Gson();
}
public void testInetAddressSerializationAndDeserialization() throws Exception {
InetAddress localhost = InetAddress.getLocalHost();
String localInetAddress = gson.toJson(localhost);
assertEquals("\"" + localhost.getHostAddress() + "\"", localInetAddress);
InetAddress value = gson.fromJson(localInetAddress, InetAddress.class);
assertEquals(localhost, value);
}
}
|
Remove index file created in test | #!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
Fix variable we're looking for. | """General deployment utilities (not Fabric commands)."""
from fabric.api import cd, require, local, env
from buedafab import deploy
def make_archive():
"""Create a compressed archive of the project's repository, complete with
submodules.
TODO We used to used git-archive-all to archive the submodules as well,
since 'git archive' doesn't touch them. We reverted back at some point and
stopped using archives in our deployment strategy, so this may not work with
submodules.
"""
require('release')
require('scratch_path')
with cd(env.scratch_path):
deploy.release.make_pretty_release()
local('git checkout %(release)s' % env)
local('git submodule update --init')
local('git archive --prefix=%(unit)s/ --format tar '
'%(release)s | gzip > %(scratch_path)s/%(archive)s' % env)
def run_extra_deploy_tasks(deployed=False):
"""Run arbitrary functions listed in env.package_installation_scripts.
Each function must accept a single parameter (or just kwargs) that will
indicates if the app was deployed or already existed.
"""
require('release_path')
if not env.extra_deploy_tasks:
return
with cd(env.release_path):
for task in env.extra_deploy_tasks:
task(deployed)
| """General deployment utilities (not Fabric commands)."""
from fabric.api import cd, require, local, env
from buedafab import deploy
def make_archive():
"""Create a compressed archive of the project's repository, complete with
submodules.
TODO We used to used git-archive-all to archive the submodules as well,
since 'git archive' doesn't touch them. We reverted back at some point and
stopped using archives in our deployment strategy, so this may not work with
submodules.
"""
require('release')
require('scratch_path')
with cd(env.scratch_path):
deploy.release.make_pretty_release()
local('git checkout %(release)s' % env)
local('git submodule update --init')
local('git archive --prefix=%(unit)s/ --format tar '
'%(release)s | gzip > %(scratch_path)s/%(archive)s' % env)
def run_extra_deploy_tasks(deployed=False):
"""Run arbitrary functions listed in env.package_installation_scripts.
Each function must accept a single parameter (or just kwargs) that will
indicates if the app was deployed or already existed.
"""
require('release_path')
if not env.package_installation_scripts:
return
with cd(env.release_path):
for task in env.extra_deploy_tasks:
task(deployed)
|
Correct pbm with empty gtu | <?php
/**
* This class has been auto-generated by the Doctrine ORM Framework
*/
class GtuTable extends DarwinTable
{
/* function witch return an array of countries sorted by id
@ListId an array of Id */
public function getCountries($listId)
{
if(empty($listId)) return array();
$q = Doctrine_Query::create()->
from('TagGroups t')->
innerJoin('t.Gtu g')->
orderBy('g.id')->
AndWhere('t.sub_group_name = ?','country')->
WhereIn('g.id',$listId);
$result = $q->execute() ;
$countries = array() ;
foreach($result as $tag)
{
$str = '<ul class="country_tags">';
$tags = explode(";",$tag->getTagValue());
foreach($tags as $value)
if (strlen($value))
$str .= '<li>' . trim($value).'</li>';
$str .= '</ul><div class="clear" />';
$countries[$tag->getGtuRef()] = $str ;
}
return $countries ;
}
}
| <?php
/**
* This class has been auto-generated by the Doctrine ORM Framework
*/
class GtuTable extends DarwinTable
{
/* function witch return an array of countries sorted by id
@ListId an array of Id */
public function getCountries($listId)
{
$q = Doctrine_Query::create()->
from('TagGroups t')->
innerJoin('t.Gtu g')->
orderBy('g.id')->
AndWhere('t.sub_group_name = ?','country')->
WhereIn('g.id',$listId);
$result = $q->execute() ;
$countries = array() ;
foreach($result as $tag)
{
$str = '<ul class="country_tags">';
$tags = explode(";",$tag->getTagValue());
foreach($tags as $value)
if (strlen($value))
$str .= '<li>' . trim($value).'</li>';
$str .= '</ul><div class="clear" />';
$countries[$tag->getGtuRef()] = $str ;
}
return $countries ;
}
}
|
Deal with existing symlinks and add more error checking | #!/usr/bin/python
# FIXME Need to handle the case when symlinks already exists
import os
theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0')
gtkrc_dest = os.path.join(theme_dir, 'gtkrc')
engine_dir = os.path.expanduser('~/.gtk-2.0/engines')
engine_dest = os.path.join(engine_dir, 'libolpc.so')
src_dir = os.path.abspath(os.path.dirname(__file__))
if not os.path.exists(theme_dir):
try:
os.makedirs(theme_dir)
except OSError, exc:
if exc[0] == 17: # File exists
pass
try:
os.unlink(gtkrc_dest)
except OSError, exc:
pass
os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest)
if not os.path.exists(engine_dest):
try:
os.makedirs(engine_dir)
except OSError, exc:
if exc[0] == 17: # File exists
pass
engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so')
try:
os.unlink(engine_dest)
except OSError, exc:
pass
os.symlink(engine_src, engine_dest)
| #!/usr/bin/python
# FIXME Need to handle the case when symlinks already exists
import os
theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0')
engine_dir = os.path.expanduser('~/.gtk-2.0/engines')
src_dir = os.path.abspath(os.path.dirname(__file__))
if not os.path.exists(theme_dir):
try:
os.makedirs(theme_dir)
except OSError, exc:
if exc[0] == 17: # File exists
pass
os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'),
os.path.join(theme_dir, 'gtkrc'))
engine_dest = os.path.join(engine_dir, 'libolpc.so')
if not os.path.exists(engine_dest):
try:
os.makedirs(engine_dir)
except OSError, exc:
if exc[0] == 17: # File exists
pass
engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so')
os.symlink(engine_src, engine_dest)
|
Use pg_lowrite for writing resource to PostgreSQL
Use pg_lowwrite instead of pg_import for writing resource to PostgreSQL database. | <?php
$temp = explode ( '.', $_FILES [ 'fileToUpload' ] [ 'name' ] );
$extension = end ( $temp );
if ( $extension !== 'pdf' )
die ( 'Invalid extension' );
if ( $_FILES [ 'fileToUpload' ] [ 'error' ] > 0 )
{
die ( 'Error code: ' . $_FILES [ 'fileToUpload' ] [ 'error' ] );
}
else
{
require_once ( 'database.php' );
$connection = OpenDatabase();
QueryDatabase ( $connection, 'BEGIN' );
$oid = pg_locreate ( $connection );
$handle = pg_loopen ( $connection, $oid, 'w' );
$fp = fopen ( $_FILES [ 'fileToUpload' ] [ 'tmp_name' ], 'r' );
while ( !feof ( $fp ) )
pg_lowrite ( $handle, fread ( $fp, 4096 ) );
fclose ( $fp );
pg_loclose ( $handle );
QueryDatabase ( $connection, 'COMMIT' );
CloseDatabase ( $connection );
unlink ( $resourcePath );
die ( "OK$oid" );
}
?>
| <?php
$uploadDirectory = 'resourceUploads/';
$temp = explode ( '.', $_FILES [ 'fileToUpload' ] [ 'name' ] );
$extension = end ( $temp );
if ( $extension !== 'pdf' )
die ( 'Invalid extension' );
if ( $_FILES [ 'fileToUpload' ] [ 'error' ] > 0 )
{
die ( 'Error code: ' . $_FILES [ 'fileToUpload' ] [ 'error' ] );
}
else
{
$resourceFilename = $_FILES [ 'fileToUpload' ] [ 'name' ];
$resourcePath = $uploadDirectory . $resourceFilename;
move_uploaded_file ( $_FILES [ 'fileToUpload' ] [ 'tmp_name' ], $resourcePath );
require_once ( 'database.php' );
$connection = OpenDatabase();
QueryDatabase ( $connection, 'BEGIN' );
$oid = pg_lo_import ( $connection, 'C:\\Program Files (x86)\\PostgreSQL\\EnterpriseDB-ApachePHP\\apache\\www\\theta\\' . $resourcePath );
QueryDatabase ( $connection, 'COMMIT' );
CloseDatabase ( $connection );
unlink ( $resourcePath );
die ( "OK$oid" );
}
?>
|
Make authentication adapter available in the request | <?php
/*
* This file is part of the Active Collab Authentication project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\Authentication\Adapter;
use ActiveCollab\Authentication\AuthenticationResult\Transport\Authentication\AuthenticationTransportInterface;
use ActiveCollab\Authentication\AuthenticationResult\Transport\Authorization\AuthorizationTransportInterface;
use ActiveCollab\Authentication\AuthenticationResult\Transport\TransportInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* @package ActiveCollab\Authentication\Adapter
*/
abstract class Adapter implements AdapterInterface
{
/**
* {@inheritdoc}
*/
public function applyTo(ServerRequestInterface $request, ResponseInterface $response, TransportInterface $transport)
{
if ($transport instanceof AuthenticationTransportInterface || $transport instanceof AuthorizationTransportInterface) {
$request = $request
->withAttribute('authentication_adapter', $this)
->withAttribute('authenticated_user', $transport->getAuthenticatedUser())
->withAttribute('authenticated_with', $transport->getAuthenticatedWith());
}
return [$request, $response];
}
}
| <?php
/*
* This file is part of the Active Collab Authentication project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\Authentication\Adapter;
use ActiveCollab\Authentication\AuthenticationResult\Transport\Authentication\AuthenticationTransportInterface;
use ActiveCollab\Authentication\AuthenticationResult\Transport\Authorization\AuthorizationTransportInterface;
use ActiveCollab\Authentication\AuthenticationResult\Transport\TransportInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* @package ActiveCollab\Authentication\Adapter
*/
abstract class Adapter implements AdapterInterface
{
/**
* {@inheritdoc}
*/
public function applyTo(ServerRequestInterface $request, ResponseInterface $response, TransportInterface $transport)
{
if ($transport instanceof AuthenticationTransportInterface || $transport instanceof AuthorizationTransportInterface) {
$request = $request
->withAttribute('authenticated_user', $transport->getAuthenticatedUser())
->withAttribute('authenticated_with', $transport->getAuthenticatedWith());
}
return [$request, $response];
}
}
|
tests: Use HTTP 1.1 instead of HTTP 1.0
Envoy does not support HTTP 1.0, so use HTTP 1.1 instead.
Signed-off-by: Jarno Rajahalme <0f1ab0ac7dffd9db21aa539af2fd4bb04abc3ad4@covalent.io> | import socket, sys
if len(sys.argv) != 6:
print('Wrong number of arguments. Usage: ./21-ct-clean-up-nc.py <localport> <timeout> <remote-address> <remote-port> <HTTP path>')
localport = int(sys.argv[1])
timeout = int(sys.argv[2])
serverAddr = sys.argv[3]
serverPort = int(sys.argv[4])
httpPath = sys.argv[5]
if ":" not in serverAddr:
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = serverAddr
else:
clientsocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
host = "["+serverAddr+"]"
clientsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clientsocket.bind(('', localport))
clientsocket.settimeout(timeout)
clientsocket.connect((serverAddr, serverPort))
clientsocket.send('GET '+httpPath+' HTTP/1.1\r\nHost: '+host+
'\r\nConnection: close\r\nUser-Agent: curl/7.38.0\r\nAccept: */*\r\n\r\n')
data = clientsocket.recv(4096)
print(data)
| import socket, sys
if len(sys.argv) != 6:
print('Wrong number of arguments. Usage: ./21-ct-clean-up-nc.py <localport> <timeout> <remote-address> <remote-port> <HTTP path>')
localport = int(sys.argv[1])
timeout = int(sys.argv[2])
serverAddr = sys.argv[3]
serverPort = int(sys.argv[4])
httpPath = sys.argv[5]
if ":" not in serverAddr:
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = serverAddr
else:
clientsocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
host = "["+serverAddr+"]"
clientsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clientsocket.bind(('', localport))
clientsocket.settimeout(timeout)
clientsocket.connect((serverAddr, serverPort))
clientsocket.send('GET '+httpPath+' HTTP/1.0\r\nHost: '+host+
'\r\nUser-Agent: curl/7.38.0\r\nAccept: */*\r\n\r\n')
data = clientsocket.recv(4096)
print(data)
|
Fix bad indentation that broke PEP8 ! | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak backend import
This module contains utility tools to import Nagios-like flat files configuration into
an Alignak REST backend.
"""
# Application version and manifest
VERSION = (0, 4, 3)
__application__ = u"Alignak backend import"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016, %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend import tools"
__releasenotes__ = u"""Alignak Backend import tools"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-import"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak backend import
This module contains utility tools to import Nagios-like flat files configuration into
an Alignak REST backend.
"""
# Application version and manifest
VERSION = (0, 4, 3)
__application__ = u"Alignak backend import"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016, %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend import tools"
__releasenotes__ = u"""Alignak Backend import tools"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-import"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Add hooks to plugin API | const attachments = require('./data/attachments');
const { beforeNewThread } = require('./hooks');
module.exports = {
getPluginAPI({ bot, knex, config, commands }) {
return {
bot,
knex,
config,
commands: {
manager: commands.manager,
addGlobalCommand: commands.addGlobalCommand,
addInboxServerCommand: commands.addInboxServerCommand,
addInboxThreadCommand: commands.addInboxThreadCommand,
addAlias: commands.addAlias
},
attachments: {
addStorageType: attachments.addStorageType,
downloadAttachment: attachments.downloadAttachment
},
hooks: {
beforeNewThread,
},
};
},
loadPlugin(plugin, api) {
plugin(api);
}
};
| const attachments = require('./data/attachments');
module.exports = {
getPluginAPI({ bot, knex, config, commands }) {
return {
bot,
knex,
config,
commands: {
manager: commands.manager,
addGlobalCommand: commands.addGlobalCommand,
addInboxServerCommand: commands.addInboxServerCommand,
addInboxThreadCommand: commands.addInboxThreadCommand,
addAlias: commands.addAlias
},
attachments: {
addStorageType: attachments.addStorageType,
downloadAttachment: attachments.downloadAttachment
},
};
},
loadPlugin(plugin, api) {
plugin(api);
}
};
|
Remove comments from Block implementations | Blockly.JavaScript['roll_forward'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
var code = 'alert("forward '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_reverse'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
var code = 'alert("reverse '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_left'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
var code = 'alert("left '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_right'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
var code = 'alert("right '+value_speed+'");';
return code;
};
Blockly.JavaScript['number_value'] = function(block) {
var text_input_value = block.getFieldValue('input_value');
var code = text_input_value;
return [code, Blockly.JavaScript.ORDER_NONE];
};
| Blockly.JavaScript['roll_forward'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
// TODO: Assemble JavaScript into code variable.
var code = 'alert("forward '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_reverse'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
// TODO: Assemble JavaScript into code variable.
var code = 'alert("reverse '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_left'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
// TODO: Assemble JavaScript into code variable.
var code = 'alert("left '+value_speed+'");';
return code;
};
Blockly.JavaScript['roll_right'] = function(block) {
var value_speed = Blockly.JavaScript.valueToCode(block, 'speed', Blockly.JavaScript.ORDER_ATOMIC);
// TODO: Assemble JavaScript into code variable.
var code = 'alert("right '+value_speed+'");';
return code;
};
Blockly.JavaScript['number_value'] = function(block) {
var text_input_value = block.getFieldValue('input_value');
// TODO: Assemble JavaScript into code variable.
var code = text_input_value;
// TODO: Change ORDER_NONE to the correct strength.
return [code, Blockly.JavaScript.ORDER_NONE];
};
|
Clarify demo code comment on channels
In Go, channels always behave as "first in, first out." Setting the
channel's size to 1 makes it behave like a semaphore. | /*
Demonstrate how to use channels and goroutines to keep the program alive.
Iterate over a slice of numbers, passing each each i to a function
that calculates the base10 log of i.
We don't actually care what the return value is.
Instead, the function just signals a channel that its work is done.
Based on package documentation from golang.org.
Code is licensed under a BSD license.
*/
package main
import (
"fmt"
"math/cmplx"
)
// print the decimal log of a number and signal completion
func getLog(c chan bool, i complex128) {
fmt.Printf("%v Log: %v\n", i, cmplx.Log10(i)) // %v for any value
c <- true // Send signal to channel
}
func main() {
// Buffered channel of bool.
// Buffer size of 1 makes the done channel a semaphore.
// All channels behave as a 'first in, first out' queue.
done := make(chan bool, 1)
nums := []complex128{7, 8, cmplx.Sqrt(-9), 10} // slice literal
for _, i := range nums { // _ = 0,1, ...; i = 7, 8, ...
go getLog(done, i) // run getLog() as goroutine; don't wait for return
}
<-done // empty the 'done' channel, discarding its value
}
| /*
Demonstrate how to use channels and goroutines to keep the program alive.
Iterate over a slice of numbers, passing each each i to a function
that calculates the base10 log of i.
We don't actually care what the return value is.
Instead, the function just signals a channel that its work is done.
Based on package documentation from golang.org.
Code is licensed under a BSD license.
*/
package main
import (
"fmt"
"math/cmplx"
)
// print the decimal log of a number and signal completion
func getLog(c chan bool, i complex128) {
fmt.Printf("%v Log: %v\n", i, cmplx.Log10(i)) // %v for any value
c <- true // Send signal to channel
}
func main() {
// buffered channel of bool; doesn't need a receiver
// this effectively makes the done channel a 'first in, first out' queue
done := make(chan bool, 1)
nums := []complex128{7, 8, cmplx.Sqrt(-9), 10} // slice literal
for _, i := range nums { // _ = 0,1, ...; i = 7, 8, ...
go getLog(done, i) // run getLog() as goroutine; don't wait for return
}
<-done // empty the 'done' channel, discarding its value
}
|
Make thread-visiblity icon use thread-icon
Summary: Made it so thread-visiblity uses thread-icon.react.js instead of its own icon.
Test Plan: Checked in thread settings to see if icon still worked. Also checked private threads before and after updates to make sure they still work. And also made sure normal threads still work
Reviewers: ashoat, palys-swm
Reviewed By: ashoat
Subscribers: KatPo, zrebcu411, Adrian, atul
Differential Revision: https://phabricator.ashoat.com/D626 | // @flow
import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { threadTypes, type ThreadType } from 'lib/types/thread-types';
import ThreadIcon from './thread-icon.react';
type Props = {|
+threadType: ThreadType,
+color: string,
|};
function ThreadVisibility(props: Props) {
const { threadType, color } = props;
const visLabelStyle = [styles.visibilityLabel, { color }];
let label;
if (threadType === threadTypes.CHAT_SECRET) {
label = 'Secret';
} else if (threadType === threadTypes.PRIVATE) {
label = 'Private';
} else {
label = 'Open';
}
return (
<View style={styles.container}>
<ThreadIcon threadType={threadType} color={color} />
<Text style={visLabelStyle}>{label}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
flexDirection: 'row',
},
visibilityLabel: {
fontSize: 16,
fontWeight: 'bold',
paddingLeft: 4,
},
});
export default ThreadVisibility;
| // @flow
import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { threadTypes, type ThreadType } from 'lib/types/thread-types';
type Props = {|
+threadType: ThreadType,
+color: string,
|};
function ThreadVisibility(props: Props) {
const { threadType, color } = props;
const visLabelStyle = [styles.visibilityLabel, { color }];
if (threadType === threadTypes.CHAT_SECRET) {
return (
<View style={styles.container}>
<Icon name="lock-outline" size={18} color={color} />
<Text style={visLabelStyle}>Secret</Text>
</View>
);
} else if (threadType === threadTypes.PRIVATE) {
return (
<View style={styles.container}>
<Icon name="person" size={18} color={color} />
<Text style={visLabelStyle}>Private</Text>
</View>
);
} else {
return (
<View style={styles.container}>
<Icon name="public" size={18} color={color} />
<Text style={visLabelStyle}>Open</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
flexDirection: 'row',
},
visibilityLabel: {
fontSize: 16,
fontWeight: 'bold',
paddingLeft: 4,
},
});
export default ThreadVisibility;
|
Add enabled param and move some params from schema to init for socket-control | // TODO: Remove unnecessary bits from schema
AFRAME.registerComponent('socket-controls', {
schema: {
updateRate: {default: 100}, // Dynamic updateRate in Hz
playerId: {default: ''},
socket: {default: null},
enabled: {default: true}
},
init: function() {
const data = this.data;
const socket = window.socket;
this.previousPos = new THREE.Vector3();
this.currentPos = new THREE.Vector3();
this.nextPos = new THREE.Vector3();
this.lastUpdateTime = 0;
this.updateWaiting = false;
this.updateRate = data.updateRate;
if(data.enabled) {
socket.on('simulationUpdate', players => {
this.updateWaiting = true;
this.previousPos = this.nextPos;
this.nextPos = players[data.playerId].position;
});
}
},
tick: function(t, dt) {
if(this.data.enabled && this.updateWaiting) {
this.updateRate = (t - this.lastUpdateTime);
this.lastUpdateTime = t;
this.updateWaiting = false;
// linear interp from data.lastPos to data.nextPos
const alpha = (t - this.lastUpdateTime) / this.updateRate;
this.currentPos.lerpVectors(this.previousPos, this.nextPos, alpha);
this.el.setAttribute('position', this.currentPos);
}
}
});
| // TODO: Remove unnecessary bits from schema
AFRAME.registerComponent('socket-controls', {
schema: {
previousPos: {default: new THREE.Vector3()},
currentPos: {default: new THREE.Vector3()},
nextPos: {default: new THREE.Vector3()},
updateRate: {default: 100}, // Dynamic updateRate in Hz
playerId: {default: ''},
socket: {default: null},
lastUpdateTime: {default: 0},
updateWaiting: {default: false},
},
init: function() {
const data = this.data;
const socket = window.socket;
socket.on('simulationUpdate', players => {
data.updateWaiting = true;
data.previousPos = data.nextPos;
data.nextPos = players[data.playerId].position;
});
},
tick: function(t, dt) {
const data = this.data;
if (data.updateWaiting) {
data.updateRate = (t - data.lastUpdateTime);
data.lastUpdateTime = t;
data.updateWaiting = false;
}
// linear interp from data.lastPos to data.nextPos
data.alpha = (t - data.lastUpdateTime) / data.updateRate;
data.currentPos.lerpVectors(data.previousPos, data.nextPos, data.alpha);
this.el.setAttribute('position', this.data.currentPos);
},
update: function (previousData) {
},
});
|
Fix deleted line during merge | from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
class WorkflowManagerAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
# There can be only one manager
perms = super().has_add_permission(request)
if perms and feedback_models.WorkflowManager.objects.exists():
perms = False
return perms
admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin)
admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportStatus)
admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
| from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
class WorkflowManagerAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
# There can be only one manager
perms = super().has_add_permission(request)
if perms and feedback_models.WorkflowManager.objects.exists():
perms = False
return perms
admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportStatus)
admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin)
admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
|
Allow minor versions of python-telegram-bot dep | #!/usr/bin/env python
from distutils.core import setup
from setuptools import find_packages
REQUIREMENTS = [
'python-telegram-bot~=5.3.0',
'blinker',
'python-dateutil',
'dogpile.cache==0.6.2',
'mongoengine==0.10.6',
'polling',
'pytz',
'ipython',
'ipdb',
'requests',
'apscheduler'
]
setup(name='marvinbot',
version='0.4',
description='Super Duper Telegram Bot - MK. III',
author='BotDevGroup',
author_email='',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
package_data={'': ['*.ini']},
# namespace_packages=["telegrambot",],
install_requires=REQUIREMENTS,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
dependency_links=[
],)
| #!/usr/bin/env python
from distutils.core import setup
from setuptools import find_packages
REQUIREMENTS = [
'python-telegram-bot==5.3.0',
'blinker',
'python-dateutil',
'dogpile.cache==0.6.2',
'mongoengine==0.10.6',
'polling',
'pytz',
'ipython',
'ipdb',
'requests',
'apscheduler'
]
setup(name='marvinbot',
version='0.4',
description='Super Duper Telegram Bot - MK. III',
author='BotDevGroup',
author_email='',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
package_data={'': ['*.ini']},
# namespace_packages=["telegrambot",],
install_requires=REQUIREMENTS,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
dependency_links=[
],)
|
Remove explicit AMD name for greater portability.
See http://requirejs.org/docs/api.html#modulename. | // Public object
SockJS = (function(){
var _document = document;
var _window = window;
var utils = {};
<!-- include lib/reventtarget.js -->
<!-- include lib/simpleevent.js -->
<!-- include lib/eventemitter.js -->
<!-- include lib/utils.js -->
<!-- include lib/dom.js -->
<!-- include lib/dom2.js -->
<!-- include lib/sockjs.js -->
<!-- include lib/trans-websocket.js -->
<!-- include lib/trans-sender.js -->
<!-- include lib/trans-jsonp-receiver.js -->
<!-- include lib/trans-jsonp-polling.js -->
<!-- include lib/trans-xhr.js -->
<!-- include lib/trans-iframe.js -->
<!-- include lib/trans-iframe-within.js -->
<!-- include lib/info.js -->
<!-- include lib/trans-iframe-eventsource.js -->
<!-- include lib/trans-iframe-xhr-polling.js -->
<!-- include lib/trans-iframe-htmlfile.js -->
<!-- include lib/trans-polling.js -->
<!-- include lib/trans-receiver-eventsource.js -->
<!-- include lib/trans-receiver-htmlfile.js -->
<!-- include lib/trans-receiver-xhr.js -->
<!-- include lib/test-hooks.js -->
return SockJS;
})();
if ('_sockjs_onload' in window) setTimeout(_sockjs_onload, 1);
// AMD compliance
if (typeof define === 'function' && define.amd) {
define([], function(){return SockJS;});
}
| // Public object
SockJS = (function(){
var _document = document;
var _window = window;
var utils = {};
<!-- include lib/reventtarget.js -->
<!-- include lib/simpleevent.js -->
<!-- include lib/eventemitter.js -->
<!-- include lib/utils.js -->
<!-- include lib/dom.js -->
<!-- include lib/dom2.js -->
<!-- include lib/sockjs.js -->
<!-- include lib/trans-websocket.js -->
<!-- include lib/trans-sender.js -->
<!-- include lib/trans-jsonp-receiver.js -->
<!-- include lib/trans-jsonp-polling.js -->
<!-- include lib/trans-xhr.js -->
<!-- include lib/trans-iframe.js -->
<!-- include lib/trans-iframe-within.js -->
<!-- include lib/info.js -->
<!-- include lib/trans-iframe-eventsource.js -->
<!-- include lib/trans-iframe-xhr-polling.js -->
<!-- include lib/trans-iframe-htmlfile.js -->
<!-- include lib/trans-polling.js -->
<!-- include lib/trans-receiver-eventsource.js -->
<!-- include lib/trans-receiver-htmlfile.js -->
<!-- include lib/trans-receiver-xhr.js -->
<!-- include lib/test-hooks.js -->
return SockJS;
})();
if ('_sockjs_onload' in window) setTimeout(_sockjs_onload, 1);
// AMD compliance
if (typeof define === 'function' && define.amd) {
define('sockjs', [], function(){return SockJS;});
}
|
Add tideways config to getcomposer.org | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
if (class_exists('Tideways\Profiler')) {
\Tideways\Profiler::start(array('api_key' => trim(file_get_contents(__DIR__.'/tideways.key'))));
}
if (!isset($env) || $env !== 'dev') {
// force ssl
$app->before(function (Request $request) {
// skip SSL & non-GET/HEAD requests
if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
return;
}
return new RedirectResponse('https://'.substr($request->getUri(), 7));
});
$app->after(function (Request $request, Response $response) {
if (!$response->headers->has('Strict-Transport-Security')) {
$response->headers->set('Strict-Transport-Security', 'max-age=31104000');
}
});
}
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
if (!isset($env) || $env !== 'dev') {
// force ssl
$app->before(function (Request $request) {
// skip SSL & non-GET/HEAD requests
if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
return;
}
return new RedirectResponse('https://'.substr($request->getUri(), 7));
});
$app->after(function (Request $request, Response $response) {
if (!$response->headers->has('Strict-Transport-Security')) {
$response->headers->set('Strict-Transport-Security', 'max-age=31104000');
}
});
}
|
Insert Filled Value as Well, otherwise SQLite saves NULL | <?php
$message = ""; // initial message
echo($_POST['request_data']);
if( isset($_POST['request_data']) ){
// Includes database connection
include "db_connect.php";
// Gets the data from post
$name = $_POST['request_data'];
// Makes query with post data
$statement = $db->prepare('INSERT INTO requests(name, filled) VALUES (:name, :filled);');
$statement->bindValue(':name', $name, SQLITE3_TEXT); // Bind Value
$statement->bindValue(':filled', 0, SQLITE3_INTEGER); // Bind Value
// Executes the query
$result = $statement->execute();
// Close Statement
$statement->close();
// Executes the query
// If data inserted then set success message otherwise set error message
// Here $db comes from "db_connection.php"
if( $result ){
$message = "Data is inserted successfully.";
}else{
$message = "Sorry, Data is not inserted.";
}
}
?> | <?php
$message = ""; // initial message
echo($_POST['request_data']);
if( isset($_POST['request_data']) ){
// Includes database connection
include "db_connect.php";
// Gets the data from post
$name = $_POST['request_data'];
// Makes query with post data
$statement = $db->prepare('INSERT INTO requests(name) VALUES (:name);');
$statement->bindValue(':name', $name, SQLITE3_TEXT); // Bind Value
// Executes the query
$result = $statement->execute();
// Close Statement
$statement->close();
// Executes the query
// If data inserted then set success message otherwise set error message
// Here $db comes from "db_connection.php"
if( $result ){
$message = "Data is inserted successfully.";
}else{
$message = "Sorry, Data is not inserted.";
}
}
?> |
Fix noPasswordManager name for docs
Fix `noPasswordManager` for documentation.
https://our.umbraco.com/apidocs/v8/ui/#/api/umbraco.directives.directive:no-password-manager | /**
* @ngdoc directive
* @name umbraco.directives.directive:noPasswordManager
* @attribte
* @function
* @description
* Added attributes to block password manager elements should as LastPass
* @example
* <example module="umbraco.directives">
* <file name="index.html">
* <input type="text" no-password-manager />
* </file>
* </example>
**/
angular.module("umbraco.directives")
.directive('noPasswordManager', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.attr("data-lpignore", "true");
}
}
});
| /**
* @ngdoc directive
* @name umbraco.directives.directive:no-password-manager
* @attribte
* @function
* @description
* Added attributes to block password manager elements should as LastPass
* @example
* <example module="umbraco.directives">
* <file name="index.html">
* <input type="text" no-password-manager />
* </file>
* </example>
**/
angular.module("umbraco.directives")
.directive('noPasswordManager', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.attr("data-lpignore", "true");
}
}
});
|
Remove unused visitor role handing from code. | import { callController } from '../../util/apiConnection';
export const getAvailableRoles = () => {
const route = '/roles/available';
const prefix = 'AVAILABLEROLES_GET_ALL_';
return callController(route, prefix);
}
export const saveRole = (role) => {
const route = '/roles';
const prefix = 'ROLE_SAVE_ONE_';
const method = 'post';
return callController(route, prefix, role, method);
}
export const deleteRole = (role) => {
const route = `/roles/${role.personRoleId}`;
const prefix = 'ROLE_DELETE_ONE_';
const method = 'delete';
return callController(route, prefix, role, method);
}
export const updateRole = (role) => {
const route = '/roles';
const prefix = 'ROLE_UPDATE_ONE_';
const method = 'put';
return callController(route, prefix, role, method);
}
| import { callController } from '../../util/apiConnection';
export const getAvailableRoles = () => {
const route = '/roles/available';
const prefix = 'AVAILABLEROLES_GET_ALL_';
return callController(route, prefix);
}
export const saveRole = (role) => {
const route = '/roles';
const prefix = 'ROLE_SAVE_ONE_';
const method = 'post';
return callController(route, prefix, role, method);
}
export const deleteRole = (role) => {
const route = `/roles/${role.personRoleId}`;
const prefix = 'ROLE_DELETE_ONE_';
const method = 'delete';
return callController(route, prefix, role, method);
}
export const updateRole = (role) => {
const route = '/roles';
const prefix = 'ROLE_UPDATE_ONE_';
const method = 'put';
return callController(route, prefix, role, method);
}
export const updateVisitorRoles = (role) => {
const route = '/roles/visitor';
const prefix = 'ROLE_VISITOR_UPDATE_';
const method = 'put';
return callController(route, prefix, role, method);
}
|
Switch redis to use the from_url method | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def set(self, key, value):
self._data[key] = value
def get(self, key):
return self._data[key]
class RedisStore(BaseStore):
def __init__(self, url=None, prefix=None, *args, **kwargs):
super(RedisStore, self).__init__(*args, **kwargs)
import redis
self.redis = redis.from_url(url)
self.prefix = prefix
def set(self, key, value):
if self.prefix is not None:
key = self.prefix + key
self.redis.set(key, value)
def get(self, key):
if self.prefix is not None:
key = self.prefix + key
return self.redis.get(key)
| class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def set(self, key, value):
self._data[key] = value
def get(self, key):
return self._data[key]
class RedisStore(BaseStore):
def __init__(self, connection=None, prefix=None, *args, **kwargs):
super(RedisStore, self).__init__(*args, **kwargs)
import redis
self.redis = redis.StrictRedis(**connection)
self.prefix = prefix
def set(self, key, value):
if self.prefix is not None:
key = self.prefix + key
self.redis.set(key, value)
def get(self, key):
if self.prefix is not None:
key = self.prefix + key
return self.redis.get(key)
|
Move some functionality into the storage module | import os
import errno
import importlib
from urllib2 import quote
def import_consumer(consumer_name):
# TODO Make suer that consumer_name will always import the correct module
return importlib.import_module('scrapi.consumers.{}'.format(consumer_name))
# :: Str -> Str
def doc_id_to_path(doc_id):
replacements = [
('/', '%2f'),
]
for find, replace in replacements:
doc_id = doc_id.replace(find, replace)
return quote(doc_id)
# Thanks to https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
def make_dir(dirpath):
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno != errno.EEXIST or not os.path.isdir(dirpath):
raise
| import os
import errno
import importlib
from scrapi import settings
def import_consumer(consumer_name):
# TODO Make suer that consumer_name will always import the correct module
return importlib.import_module('scrapi.consumers.{}'.format(consumer_name))
def build_norm_dir(consumer_name, timestamp, norm_doc):
pass # TODO
def build_raw_dir(consumer_name, timestamp, raw_doc):
manifest = settings.MANIFESTS[consumer_name]
base = [
settings.ARCHIVE_DIR,
manifest['directory'],
str(raw_doc.get('doc_id')).replace()
]
# Thanks to https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
def make_dir(dirpath):
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno != errno.EEXIST or not os.path.isdir(dirpath):
raise
|
Add django-filter to the required packages | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='django-rest-surveys',
version='0.1.0',
description='A RESTful backend for giving surveys.',
long_description=readme,
author='Designlab',
author_email='hello@trydesignlab.com',
url='https://github.com/danxshap/django-rest-surveys',
packages=['rest_surveys'],
package_data={'': ['LICENSE']},
package_dir={'rest_surveys': 'rest_surveys'},
install_requires=[
'Django>=1.7',
'django-inline-ordering',
'django-filter<=0.11.0',
'djangorestframework>=3.0',
'djangorestframework-bulk',
],
license=license,
)
| #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='django-rest-surveys',
version='0.1.0',
description='A RESTful backend for giving surveys.',
long_description=readme,
author='Designlab',
author_email='hello@trydesignlab.com',
url='https://github.com/danxshap/django-rest-surveys',
packages=['rest_surveys'],
package_data={'': ['LICENSE']},
package_dir={'rest_surveys': 'rest_surveys'},
install_requires=[
'Django>=1.7',
'djangorestframework>=3.0',
'django-inline-ordering',
'djangorestframework-bulk',
],
license=license,
)
|
Update LUA test to perform interpolation | from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP
class LuaTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
self.env = ["LUA_SCRIPTS_ENABLED=Processed"]
def manifests(self) -> str:
return super().manifests() + self.format('''
---
apiVersion: getambassador.io/v1
kind: Module
metadata:
name: ambassador
spec:
ambassador_id: {self.ambassador_id}
config:
lua_scripts: |
function envoy_on_response(response_handle)
response_handle: headers():add("Lua-Scripts-Enabled", "${LUA_SCRIPTS_ENABLED}")
end
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
name: lua-target-mapping
spec:
ambassador_id: {self.ambassador_id}
prefix: /target/
service: {self.target.path.fqdn}
''')
def queries(self):
yield Query(self.url("target/"))
def check(self):
for r in self.results:
assert r.headers.get('Lua-Scripts-Enabled', None) == ['Processed']
| from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP
class LuaTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
def manifests(self) -> str:
return super().manifests() + self.format('''
---
apiVersion: getambassador.io/v1
kind: Module
metadata:
name: ambassador
spec:
ambassador_id: {self.ambassador_id}
config:
lua_scripts: |
function envoy_on_response(response_handle)
response_handle: headers():add("Lua-Scripts-Enabled", "Processed")
end
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
name: lua-target-mapping
spec:
ambassador_id: {self.ambassador_id}
prefix: /target/
service: {self.target.path.fqdn}
''')
def queries(self):
yield Query(self.url("target/"))
def check(self):
for r in self.results:
assert r.headers.get('Lua-Scripts-Enabled', None) == ['Processed']
|
Enable resolve find brand from multiple directories | 'use strict'
const createDirectoryFlow = require('../../directory/create-flow')
const { accesories, sails } = require('../../directory')
const createAddFactory = require('../create-add')
const category = require('../../category')
const carbon = require('./carbon')
const size = require('./size')
const type = require('./type')
const directory = createDirectoryFlow([sails, accesories])
function factory (log) {
const createAdd = createAddFactory('mast', log)
const addCategory = createAdd('category', (acc) => {
return {
data: category('masts'),
output: acc.input
}
})
const addBrand = createAdd('brand', (acc) => {
return {
data: acc.dir.data.brand,
output: acc.dir.output
}
})
const addType = createAdd('type', (acc) => type(acc.input))
const addCarbon = createAdd('carbon', (acc) => carbon(acc.input))
const addSize = createAdd('size', (acc) => size(acc.input))
function mast (input) {
const dir = directory(input)
const acc = { dir, input, data: {} }
addCategory(acc)
addBrand(acc)
addType(acc)
addCarbon(acc)
addSize(acc)
return {data: acc.data, output: acc.input}
}
return mast
}
module.exports = factory
| 'use strict'
const createAddFactory = require('../create-add')
const { sails } = require('../../directory')
const category = require('../../category')
const carbon = require('./carbon')
const size = require('./size')
const type = require('./type')
function factory (log) {
const createAdd = createAddFactory('mast', log)
const addCategory = createAdd('category', (acc) => {
return {
data: category('masts'),
output: acc.input
}
})
const addBrand = createAdd('brand', (acc) => {
return {
data: acc.dir.data.brand,
output: acc.dir.output
}
})
const addType = createAdd('type', (acc) => type(acc.input))
const addCarbon = createAdd('carbon', (acc) => carbon(acc.input))
const addSize = createAdd('size', (acc) => size(acc.input))
function mast (input) {
const dir = sails(input)
const acc = { dir, input, data: {} }
addCategory(acc)
addBrand(acc)
addType(acc)
addCarbon(acc)
addSize(acc)
return {data: acc.data, output: acc.input}
}
return mast
}
module.exports = factory
|
Add support for extracting the token from request headers
Clients can now set the `Api-Token` header instead of supplying the
token as a GET or POST parameter. | from functools import wraps
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
def get_token(request):
"Attempts to retrieve a token from the request."
if 'token' in request.REQUEST:
return request.REQUEST['token']
if 'HTTP_API_TOKEN' in request.META:
return request.META['HTTP_API_TOKEN']
return ''
def check_auth(func):
@wraps(func)
def inner(self, request, *args, **kwargs):
auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False)
user = getattr(request, 'user', None)
# Attempt to authenticate if a token is present
if not user or not user.is_authenticated():
token = get_token(request)
user = authenticate(token=token)
if user:
login(request, user)
elif auth_required:
return HttpResponse(status=401)
return func(self, request, *args, **kwargs)
return inner
| from functools import wraps
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
def get_token(request):
return request.REQUEST.get('token', '')
def check_auth(func):
@wraps(func)
def inner(self, request, *args, **kwargs):
auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False)
user = getattr(request, 'user', None)
# Attempt to authenticate if a token is present
if not user or not user.is_authenticated():
token = get_token(request)
user = authenticate(token=token)
if user:
login(request, user)
elif auth_required:
return HttpResponse(status=401)
return func(self, request, *args, **kwargs)
return inner
|
Add python_requires to help pip | from setuptools import setup, find_packages
__version__ = "unknown"
# "import" __version__
for line in open("sfs/__init__.py"):
if line.startswith("__version__"):
exec(line)
break
setup(
name="sfs",
version=__version__,
packages=find_packages(),
install_requires=[
'numpy!=1.11.0', # https://github.com/sfstoolbox/sfs-python/issues/11
'scipy',
],
author="SFS Toolbox Developers",
author_email="sfstoolbox@gmail.com",
description="Sound Field Synthesis Toolbox",
long_description=open('README.rst').read(),
license="MIT",
keywords="audio SFS WFS Ambisonics".split(),
url="http://github.com/sfstoolbox/",
platforms='any',
python_requires='>=3.6',
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Scientific/Engineering",
],
zip_safe=True,
)
| from setuptools import setup, find_packages
__version__ = "unknown"
# "import" __version__
for line in open("sfs/__init__.py"):
if line.startswith("__version__"):
exec(line)
break
setup(
name="sfs",
version=__version__,
packages=find_packages(),
install_requires=[
'numpy!=1.11.0', # https://github.com/sfstoolbox/sfs-python/issues/11
'scipy',
],
author="SFS Toolbox Developers",
author_email="sfstoolbox@gmail.com",
description="Sound Field Synthesis Toolbox",
long_description=open('README.rst').read(),
license="MIT",
keywords="audio SFS WFS Ambisonics".split(),
url="http://github.com/sfstoolbox/",
platforms='any',
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Scientific/Engineering",
],
zip_safe=True,
)
|
[BUG] Fix txfee API call with added support for old API calls
[ADD] txfee_auto to API Calls
[ADD] txfee_manual to API Calls
[ADD] confirmations to API Calls | <?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
// Check if the API is activated
$api->isActive();
// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);
// Output JSON format
$data = array(
// coin info
'currency' => $config[currency],
'coinname' => $config[gettingstarted][coinname],
// coin algorithm info
'cointarget' => $config[cointarget],
'coindiffchangetarget' => $config[coindiffchangetarget],
'algorithm' => $config[algorithm],
// stratum
'stratumport' => $config[gettingstarted][stratumport],
// payments
'payout_system' => $config[payout_system],
'confirmations' => $config['confirmations'],
'min_ap_threshold' => $config[ap_threshold][min],
'max_ap_threshold' => $config[ap_threshold][max],
// backwards compatibility for old API calls
'txfee' => $config['txfee_manual'],
'txfee_manual' => $config['txfee_manual'],
'txfee_auto' => $config['txfee_auto'],
'fees' => $config[fees]
);
echo $api->get_json($data);
// Supress master template
$supress_master = 1;
?>
| <?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
// Check if the API is activated
$api->isActive();
// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);
// Output JSON format
$data = array(
// coin info
'currency' => $config[currency],
'coinname' => $config[gettingstarted][coinname],
// coin algorithm info
'cointarget' => $config[cointarget],
'coindiffchangetarget' => $config[coindiffchangetarget],
'algorithm' => $config[algorithm],
// stratum
'stratumport' => $config[gettingstarted][stratumport],
// payments
'payout_system' => $config[payout_system],
'min_ap_threshold' => $config[ap_threshold][min],
'max_ap_threshold' => $config[ap_threshold][max],
'txfee' => $config[txfee],
'fees' => $config[fees],
);
echo $api->get_json($data);
// Supress master template
$supress_master = 1;
?>
|
Reduce included scope for services tests. | 'use strict';
describe('IMS service', function(){
var $httpBackend;
var IMS;
beforeEach(module('Marvin.Services'));
beforeEach(inject(function(_IMS_, _$httpBackend_){
$httpBackend = _$httpBackend_;
IMS = _IMS_;
}));
// Stupid test.
it('returns an object', function(){
expect(typeof(IMS)).toBe('object');
});
describe('search querying', function(){
it('there is a function', function(){
expect(typeof(IMS.search)).toBe('function');
});
it('should pass along a search string correctly', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=hello').respond(200);
IMS.search('hello');
$httpBackend.flush();
});
it('should allow you set count for a number of requests', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=blah&count=10').respond(200);
IMS.search('blah', 10);
$httpBackend.flush();
});
it('should allow one to set a offset for the request', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=thing&count=10&offset=10').respond(200);
IMS.search('thing', 10, 10);
$httpBackend.flush();
});
});
});
| 'use strict';
describe('IMS service', function(){
var $httpBackend;
var IMS;
beforeEach(module('Marvin'));
beforeEach(inject(function(_IMS_, _$httpBackend_){
$httpBackend = _$httpBackend_;
IMS = _IMS_;
}));
// Stupid test.
it('returns an object', function(){
expect(typeof(IMS)).toBe('object');
});
describe('search querying', function(){
it('there is a function', function(){
expect(typeof(IMS.search)).toBe('function');
});
it('should pass along a search string correctly', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=hello').respond(200);
IMS.search('hello');
$httpBackend.flush();
});
it('should allow you set count for a number of requests', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=blah&count=10').respond(200);
IMS.search('blah', 10);
$httpBackend.flush();
});
it('should allow one to set a offset for the request', function(){
$httpBackend.expect('GET', 'http://localhost/search?q=thing&count=10&offset=10').respond(200);
IMS.search('thing', 10, 10);
$httpBackend.flush();
});
});
});
|
Add compare method from com.thaiopensource.relaxng.output.common.
git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@1968 369101cc-9a96-11dd-8e58-870c635edf7a | package com.thaiopensource.xml.util;
public final class Name {
final private String namespaceUri;
final private String localName;
final private int hc;
public Name(String namespaceUri, String localName) {
this.namespaceUri = namespaceUri;
this.localName = localName;
this.hc = namespaceUri.hashCode() ^ localName.hashCode();
}
public String getNamespaceUri() {
return namespaceUri;
}
public String getLocalName() {
return localName;
}
public boolean equals(Object obj) {
if (!(obj instanceof Name))
return false;
Name other = (Name)obj;
return (this.hc == other.hc
&& this.namespaceUri.equals(other.namespaceUri)
&& this.localName.equals(other.localName));
}
public int hashCode() {
return hc;
}
// We include this, but don't derive from Comparator<Name> to avoid a dependency on Java 5.
static public int compare(Name n1, Name n2) {
int ret = n1.namespaceUri.compareTo(n2.namespaceUri);
if (ret != 0)
return ret;
return n1.localName.compareTo(n2.localName);
}
}
| package com.thaiopensource.xml.util;
public final class Name {
final private String namespaceUri;
final private String localName;
final private int hc;
public Name(String namespaceUri, String localName) {
this.namespaceUri = namespaceUri;
this.localName = localName;
this.hc = namespaceUri.hashCode() ^ localName.hashCode();
}
public String getNamespaceUri() {
return namespaceUri;
}
public String getLocalName() {
return localName;
}
public boolean equals(Object obj) {
if (!(obj instanceof Name))
return false;
Name other = (Name)obj;
return (this.hc == other.hc
&& this.namespaceUri.equals(other.namespaceUri)
&& this.localName.equals(other.localName));
}
public int hashCode() {
return hc;
}
}
|
Change the username min length constraint to what BW allows. | // common constants, shared between multiple pieces of code (and likely client and server)
export const EMAIL_PATTERN = /^[^@]+@[^@]+$/
export const EMAIL_MINLENGTH = 3
export const EMAIL_MAXLENGTH = 100
export const LOBBY_NAME_MAXLENGTH = 50
export const PASSWORD_MINLENGTH = 6
export const PORT_MIN_NUMBER = 0
export const PORT_MAX_NUMBER = 65535
export const USERNAME_PATTERN = /^[A-Za-z0-9`~!$^&*()[\]\-_+=.{}]+$/
export const USERNAME_MINLENGTH = 1
export const USERNAME_MAXLENGTH = 16
export function isValidUsername(username) {
return username &&
username.length >= module.exports.USERNAME_MINLENGTH &&
username.length <= module.exports.USERNAME_MAXLENGTH &&
module.exports.USERNAME_PATTERN.test(username)
}
export function isValidEmail(email) {
return email &&
email.length >= module.exports.EMAIL_MINLENGTH &&
email.length <= module.exports.EMAIL_MAXLENGTH &&
module.exports.EMAIL_PATTERN.test(email)
}
export function isValidPassword(password) {
return password &&
password.length >= module.exports.PASSWORD_MINLENGTH
}
| // common constants, shared between multiple pieces of code (and likely client and server)
export const EMAIL_PATTERN = /^[^@]+@[^@]+$/
export const EMAIL_MINLENGTH = 3
export const EMAIL_MAXLENGTH = 100
export const LOBBY_NAME_MAXLENGTH = 50
export const PASSWORD_MINLENGTH = 6
export const PORT_MIN_NUMBER = 0
export const PORT_MAX_NUMBER = 65535
export const USERNAME_PATTERN = /^[A-Za-z0-9`~!$^&*()[\]\-_+=.{}]+$/
export const USERNAME_MINLENGTH = 3
export const USERNAME_MAXLENGTH = 16
export function isValidUsername(username) {
return username &&
username.length >= module.exports.USERNAME_MINLENGTH &&
username.length <= module.exports.USERNAME_MAXLENGTH &&
module.exports.USERNAME_PATTERN.test(username)
}
export function isValidEmail(email) {
return email &&
email.length >= module.exports.EMAIL_MINLENGTH &&
email.length <= module.exports.EMAIL_MAXLENGTH &&
module.exports.EMAIL_PATTERN.test(email)
}
export function isValidPassword(password) {
return password &&
password.length >= module.exports.PASSWORD_MINLENGTH
}
|
Update charms.hadoop reference to follow convention | from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
| from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
|
Add a size option to the ocConfirm service | angular.module('orderCloud')
.factory('ocConfirm', OrderCloudConfirmService)
.controller('ConfirmModalCtrl', ConfirmModalController)
;
function OrderCloudConfirmService($uibModal) {
var service = {
Confirm: _confirm
};
function _confirm(options) {
return $uibModal.open({
animation:false,
backdrop:'static',
templateUrl: 'common/templates/confirm.modal.html',
controller: 'ConfirmModalCtrl',
controllerAs: 'confirmModal',
size: options.size || 'sm',
resolve: {
ConfirmOptions: function() {
return options;
}
}
}).result
}
return service;
}
function ConfirmModalController($uibModalInstance, ConfirmOptions) {
var vm = this;
vm.message = ConfirmOptions.message;
vm.confirmText = ConfirmOptions.confirmText;
vm.cancelText = ConfirmOptions.cancelText;
vm.confirm = function() {
$uibModalInstance.close();
};
vm.cancel = function() {
$uibModalInstance.dismiss();
};
} | angular.module('orderCloud')
.factory('ocConfirm', OrderCloudConfirmService)
.controller('ConfirmModalCtrl', ConfirmModalController)
;
function OrderCloudConfirmService($uibModal) {
var service = {
Confirm: _confirm
};
function _confirm(options) {
return $uibModal.open({
animation:false,
backdrop:'static',
templateUrl: 'common/templates/confirm.modal.html',
controller: 'ConfirmModalCtrl',
controllerAs: 'confirmModal',
size: 'sm',
resolve: {
ConfirmOptions: function() {
return options;
}
}
}).result
}
return service;
}
function ConfirmModalController($uibModalInstance, ConfirmOptions) {
var vm = this;
vm.message = ConfirmOptions.message;
vm.confirmText = ConfirmOptions.confirmText;
vm.cancelText = ConfirmOptions.cancelText;
vm.confirm = function() {
$uibModalInstance.close();
};
vm.cancel = function() {
$uibModalInstance.dismiss();
};
} |
Use the slim jquery file | const minimist = require('minimist');
const options = minimist(process.argv.slice(2));
const isProduction = options.env === 'production';
let config = {
console_options: options,
isProduction: isProduction,
src: {
js: './src/js/**/*.js',
vue: {
// src : dist
'./src/js/app.js': 'app.js',
'./src/js/train-number-calc.js': 'train-number-calc.js',
},
vue_watch: './src/js/**/*.{js,vue}',
eslint: './src/js/**/*.{js,vue}',
scss: './src/scss/**/*.scss',
lib: {
js: [
'./node_modules/jquery/dist/jquery.slim.min.js',
'./node_modules/bootstrap/dist/js/bootstrap.min.js',
],
},
},
dist: {
js: './assets/js',
css: './assets/css',
},
map: './.map',
lib: {
js: 'lib.js',
},
options: {
eslint: {
configFile: '.eslintrc.js',
},
},
plugins: require('gulp-load-plugins')(),
};
module.exports = config;
| const minimist = require('minimist');
const options = minimist(process.argv.slice(2));
const isProduction = options.env === 'production';
let config = {
console_options: options,
isProduction: isProduction,
src: {
js: './src/js/**/*.js',
vue: {
// src : dist
'./src/js/app.js': 'app.js',
'./src/js/train-number-calc.js': 'train-number-calc.js',
},
vue_watch: './src/js/**/*.{js,vue}',
eslint: './src/js/**/*.{js,vue}',
scss: './src/scss/**/*.scss',
lib: {
js: [
'./node_modules/jquery/dist/jquery.min.js',
'./node_modules/bootstrap/dist/js/bootstrap.min.js',
],
},
},
dist: {
js: './assets/js',
css: './assets/css',
},
map: './.map',
lib: {
js: 'lib.js',
},
options: {
eslint: {
configFile: '.eslintrc.js',
},
},
plugins: require('gulp-load-plugins')(),
};
module.exports = config;
|
Use view "title" as default tab title. | /**
* @class SMITHY/DojoBorderView
* View implementation for Dojo Tab Container to support smithy "tabs"
* layout mode.
*/
define([
"../declare",
"dijit/layout/TabContainer"
], function (
declare,
TabContainer
) {
var module = declare(TabContainer, {
constructor: function (config) {
this.implementsMode = "tabs";
},
addChild: function (view) {
this.inherited(arguments);
this.set("title", view.title);
},
removeChild: function (childView) {
this.inherited(arguments);
},
hasChild: function (childView) {
var cidx = this.getIndexOfChild(childView);
return (cidx > -1);
},
startup: function () {
this.inherited(arguments);
}
});
return module;
});
| /**
* @class SMITHY/DojoBorderView
* View implementation for Dojo Tab Container to support smithy "tabs"
* layout mode.
*/
define([
"../declare",
"dijit/layout/TabContainer"
], function (
declare,
TabContainer
) {
var module = declare(TabContainer, {
constructor: function (config) {
this.implementsMode = "tabs";
},
addChild: function (view) {
this.inherited(arguments);
},
removeChild: function (childView) {
this.inherited(arguments);
},
hasChild: function (childView) {
var cidx = this.getIndexOfChild(childView);
return (cidx > -1);
},
startup: function () {
this.inherited(arguments);
}
});
return module;
});
|
Add global package-level declaration to make the whole file example work | package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
var (
noTagLog *log.Logger
)
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
// Global *log.Logger
noTagLog = fnlog.New("")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
noTagLog.Printf("print messages without tag")
// Output:
// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}
| package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
var noTagLog *log.Logger = fnlog.New("")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
noTagLog.Printf("print messages without tag")
// Output:
// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}
|
Support title props in addition to children | import {
ADD,
SHOW,
DISMISS
} from './actions.js'
const INITIAL_STATE = {
items: [],
current: null
}
function transformProps (item) {
const { title } = item
const transformedItem = Object.assign({}, item)
if (title) {
transformedItem.children = title
}
return transformedItem
}
function show (state, payload) {
return {
...state,
current: transformProps(payload)
}
}
function add (state, payload) {
const item = transformProps(payload)
if (!state.current && state.items.length) {
const [current, ...items] = state.items
return {
...state,
items: items.concat([item]),
current
}
}
if (!state.current) {
return {
...state,
current: item
}
}
return {
...state,
items: state.items.concat([item])
}
}
function dismiss (state) {
if (!state.items.length) {
return {
...state,
current: null
}
}
const [current, ...items] = state.items
return {
...state,
items,
current
}
}
export default function snackBarReducer (state = INITIAL_STATE, action) {
switch (action.type) {
case SHOW: return show(state, action.payload)
case ADD: return add(state, action.payload)
case DISMISS: return dismiss(state)
default: return state
}
}
| import {
ADD,
SHOW,
DISMISS
} from './actions.js'
const INITIAL_STATE = {
items: [],
current: null
}
function show (state, payload) {
return {
...state,
current: Object.assign({}, payload)
}
}
function add (state, payload) {
if (!state.current) {
return {
...state,
current: Object.assign({}, payload)
}
}
return {
...state,
items: state.items.concat([payload])
}
}
function dismiss (state) {
if (!state.items.length) {
return {
...state,
current: null
}
}
const [current, ...items] = state.items
return {
...state,
items,
current
}
}
export default function snackBarReducer (state = INITIAL_STATE, action) {
switch (action.type) {
case SHOW: return show(state, action.payload)
case ADD: return add(state, action.payload)
case DISMISS: return dismiss(state)
default: return state
}
}
|
Update bg image extraction to support Safari | (function() {
//
// Avoid sudden background resize on mobile browsers when the address bar is hidden.
//
var homeTop = document.querySelector('.home__top');
var windowWidth;
function onWindowResize() {
if (window.innerWidth !== windowWidth) {
windowWidth = window.innerWidth;
homeTop.style.height = window.innerHeight + 'px';
}
}
window.addEventListener('resize', onWindowResize);
onWindowResize();
//
// Blur high-res background.
//
var bg = document.querySelector('.home__background--high-res');
var bgImage = getComputedStyle(bg).backgroundImage;
var bgImageUrl = /(?:\(['|"]?)(.*?)(?:['|"]?\))/.exec(bgImage)[1];
var img = new Image();
img.addEventListener('load', function() {
bg.className += ' home__background--high-res--loaded';
});
img.src = bgImageUrl;
}());
| (function() {
//
// Avoid sudden background resize on mobile browsers when the address bar is hidden.
//
var homeTop = document.querySelector('.home__top');
var windowWidth;
function onWindowResize() {
if (window.innerWidth !== windowWidth) {
windowWidth = window.innerWidth;
homeTop.style.height = window.innerHeight + 'px';
}
}
window.addEventListener('resize', onWindowResize);
onWindowResize();
//
// Blur high-res background.
//
var bg = document.querySelector('.home__background--high-res');
var bgImage = getComputedStyle(bg).backgroundImage;
var bgImageUrl = bgImage.split('"')[1];
var img = new Image();
img.addEventListener('load', function() {
bg.className += ' home__background--high-res--loaded';
});
img.src = bgImageUrl;
}());
|
Use CUnicode for width and height in ImageWidget | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = CUnicode(sync=True)
height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = Unicode(sync=True) # TODO: C unicode
height = Unicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) |
[MIG] Bump module version to 10.0.1.0.0 | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localization Purchase',
'license': 'AGPL-3',
'category': 'Localisation',
'author': 'Akretion, Odoo Community Association (OCA)',
'website': 'http://odoo-brasil.org',
'version': '10.0.1.0.0',
'depends': [
'l10n_br_stock_account',
'account_fiscal_position_rule_purchase',
],
'data': [
'data/l10n_br_purchase_data.xml',
'views/purchase_view.xml',
'views/res_company_view.xml',
'security/ir.model.access.csv',
'security/l10n_br_purchase_security.xml',
],
'demo': [
# FIXME
# 'test/purchase_order_demo.yml'
],
'installable': False,
'auto_install': False,
}
| # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localization Purchase',
'license': 'AGPL-3',
'category': 'Localisation',
'author': 'Akretion, Odoo Community Association (OCA)',
'website': 'http://odoo-brasil.org',
'version': '8.0.1.0.0',
'depends': [
'l10n_br_stock_account',
'account_fiscal_position_rule_purchase',
],
'data': [
'data/l10n_br_purchase_data.xml',
'views/purchase_view.xml',
'views/res_company_view.xml',
'security/ir.model.access.csv',
'security/l10n_br_purchase_security.xml',
],
'demo': [
# FIXME
# 'test/purchase_order_demo.yml'
],
'installable': False,
'auto_install': False,
}
|
Add addImmediate to Queue class | org.bustany.TrackerBird.Queue = function(delay) {
this._delay = 100;
this._items = [];
this._active = false;
var queue = this;
this._timerEvent = { notify: function(timer) { queue._active = false; queue.process(); } };
}
org.bustany.TrackerBird.Queue.prototype.add = function(item) {
this._items.push(item);
this.process();
}
org.bustany.TrackerBird.Queue.prototype.addImmediate = function(item) {
this._items.unshift(item);
this.process();
}
org.bustany.TrackerBird.Queue.prototype.process = function() {
if (this._active) {
return;
}
if (this._items.length == 0) {
return;
}
this._active = true;
var item = this._items.shift();
item.callback(item.data);
var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(this._timerEvent, this._delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}
org.bustany.TrackerBird.Queue.prototype.size = function() {
return this._items.length;
}
| org.bustany.TrackerBird.Queue = function(delay) {
this._delay = 100;
this._items = [];
this._active = false;
var queue = this;
this._timerEvent = { notify: function(timer) { queue._active = false; queue.process(); } };
}
org.bustany.TrackerBird.Queue.prototype.add = function(item) {
this._items.push(item);
this.process();
}
org.bustany.TrackerBird.Queue.prototype.process = function() {
if (this._active) {
return;
}
if (this._items.length == 0) {
return;
}
this._active = true;
var item = this._items.shift();
item.callback(item.data);
var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(this._timerEvent, this._delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}
org.bustany.TrackerBird.Queue.prototype.size = function() {
return this._items.length;
}
|
Remove test for default options | 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.autoprefixer = {
setUp: function (done) {
// setup here if necessary
done();
},
custom_options: function (test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_options.css');
var expected = grunt.file.read('test/expected/custom_options.css');
test.strictEqual(actual, expected, 'should describe what the custom option(s) behavior is.');
test.done();
},
};
| 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.autoprefixer = {
setUp: function (done) {
// setup here if necessary
done();
},
default_options: function (test) {
test.expect(1);
var actual = grunt.file.read('tmp/default_options.css');
var expected = grunt.file.read('test/expected/default_options.css');
test.strictEqual(actual, expected, 'should describe what the default behavior is.');
test.done();
},
custom_options: function (test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_options.css');
var expected = grunt.file.read('test/expected/custom_options.css');
test.strictEqual(actual, expected, 'should describe what the custom option(s) behavior is.');
test.done();
},
};
|
Add select item packet ID | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
SELECT_ITEM: "5",
LOAD_GAME_OBJ: "6",
PLAYER_UPGRADE: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
} | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
PLAYER_UPGRADE: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
} |
Add ordereddict package for Python 2.6 | #!/usr/bin/env python
import sys
from setuptools import setup
from ts3 import __version__
tests_require = ['mock']
if sys.version < '2.7':
tests_require.append('unittest2')
tests_require.append('ordereddict')
setup(
name="python-ts3",
version=__version__,
description="TS3 ServerQuery library for Python",
author="Andrew Willaims",
author_email="andy@tensixtyone.com",
url="https://github.com/nikdoof/python-ts3/",
keywords="teamspeak ts3 voice serverquery teamspeak3",
packages=['ts3'],
scripts=['examples/gents3privkey.py'],
test_suite='ts3.test.suite',
tests_require=tests_require,
classifiers=[
'License :: OSI Approved :: BSD License',
'Topic :: Internet',
'Topic :: Communications',
'Intended Audience :: Developers',
'Development Status :: 3 - Alpha',
]
)
| #!/usr/bin/env python
import sys
from setuptools import setup
from ts3 import __version__
tests_require = ['mock']
if sys.version < '2.7':
tests_require.append('unittest2')
setup(
name="python-ts3",
version=__version__,
description="TS3 ServerQuery library for Python",
author="Andrew Willaims",
author_email="andy@tensixtyone.com",
url="https://github.com/nikdoof/python-ts3/",
keywords="teamspeak ts3 voice serverquery teamspeak3",
packages=['ts3'],
scripts=['examples/gents3privkey.py'],
test_suite='ts3.test.suite',
tests_require=tests_require,
classifiers=[
'License :: OSI Approved :: BSD License',
'Topic :: Internet',
'Topic :: Communications',
'Intended Audience :: Developers',
'Development Status :: 3 - Alpha',
]
)
|
Refactor image open to with block | #!/usr/local/bin/python3
# Python Challenge - 22
# http://www.pythonchallenge.com/pc/hex/copper.html
# http://www.pythonchallenge.com/pc/hex/white.gif
# Username: butter; Password: fly
# Keyword:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_22.py`
'''
from PIL import Image, ImageDraw
def main():
'''
Hint: emulate (picture of joystick)
<!-- or maybe white.gif would be more bright -->
http://www.pythonchallenge.com/pc/hex/white.gif shows a 200x200 black
square, download has 133 pages in preview (frames?)
'''
img_path = './joystick_chall_22/white.gif'
with Image.open(img_path) as gif:
hist = gif.histogram() # 1 pixel in hist bin 8 (0-255)
print(hist.index(1))
data = list(gif.getdata())
print(data.index(8)) # 20100
return 0
if __name__ == '__main__':
main()
| #!/usr/local/bin/python3
# Python Challenge - 22
# http://www.pythonchallenge.com/pc/hex/copper.html
# http://www.pythonchallenge.com/pc/hex/white.gif
# Username: butter; Password: fly
# Keyword:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_22.py`
'''
from PIL import Image
import numpy as np
def main():
'''
Hint: emulate (picture of joystick)
<!-- or maybe white.gif would be more bright -->
http://www.pythonchallenge.com/pc/hex/white.gif shows a 200x200 black
square, download has 133 pages in preview (frames?)
'''
img_path = './joystick_chall_22/white.gif'
white = Image.open(img_path)
hist = white.histogram()
print(len(hist))
return 0
if __name__ == '__main__':
main()
|
Move importing of source to class setup | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
class TestPathutils(TestCase):
@classmethod
def setUpClass(cls):
super(TestPathutils, cls).setUpClass()
if version < '3000':
from libsass import pathutils
else:
from sublime_libsass.libsass import pathutils
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch('pathutils.os')
def test_grep_r(self, mock_os):
mock_os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
| from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
if version < '3000':
from libsass import pathutils
else:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
@classmethod
def setUpClass(cls):
super(TestPathutils, cls).setUpClass()
import time
time.sleep(3) # Fix for Python3 async importing? Some race condition.
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch('pathutils.os')
def test_grep_r(self, mock_os):
mock_os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
Add optional parameter to optional() | <?php
namespace Structr\Tree\Composite;
use Structr\Tree\Base\PrototypeNode;
use Structr\Exception;
class MapKeyNode extends PrototypeNode
{
private $_required = true;
private $_optional = false;
private $_defaultValue = null;
private $_name;
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function defaultValue($value) {
$this->_required = false;
$this->_defaultValue = $value;
return $this;
}
public function optional($optional = true) {
$this->_optional = $optional;
return $this;
}
public function isOptional() {
return $this->_optional;
}
public function endKey() {
return $this->parent();
}
public function _walk_value_unset() {
if ($this->_required) {
throw new Exception("Missing key '{$this->_name}'");
}
return $this->_defaultValue;
}
}
| <?php
namespace Structr\Tree\Composite;
use Structr\Tree\Base\PrototypeNode;
use Structr\Exception;
class MapKeyNode extends PrototypeNode
{
private $_required = true;
private $_optional = false;
private $_defaultValue = null;
private $_name;
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function defaultValue($value) {
$this->_required = false;
$this->_defaultValue = $value;
return $this;
}
public function optional() {
$this->_optional = true;
return $this;
}
public function isOptional() {
return $this->_optional;
}
public function endKey() {
return $this->parent();
}
public function _walk_value_unset() {
if ($this->_required) {
throw new Exception("Missing key '{$this->_name}'");
}
return $this->_defaultValue;
}
}
|
Fix test file first line | package main
import (
"github.com/stretchr/testify/assert"
"testing"
"github.com/michaelklishin/rabbit-hole"
"reflect"
)
func TestGraphDefinition(t *testing.T){
var rabbitmq RabbitMQPlugin
graphdef := rabbitmq.GraphDefinition()
if len(graphdef) != 2 {
t.Error("GetTempfilename: %d should be 2", len(graphdef))
}
}
func TestParse(t *testing.T){
var rabbitmq RabbitMQPlugin
var stub rabbithole.Overview
stub.QueueTotals.Messages = 1
stub.QueueTotals.MessagesReady = 2
stub.QueueTotals.MessagesUnacknowledged = 3
stub.MessageStats.PublishDetails.Rate = 4
stat, err := rabbitmq.parseStats(stub)
assert.Nil(t, err)
assert.EqualValues(t, reflect.TypeOf(stat["messages"]).String(), "float64")
assert.EqualValues(t, stat["messages"], 1)
assert.EqualValues(t, reflect.TypeOf(stat["publish"]).String(), "float64")
assert.EqualValues(t, stat["publish"], 4)
} | README.mdpackage main
import (
"github.com/stretchr/testify/assert"
"testing"
"github.com/michaelklishin/rabbit-hole"
"reflect"
)
func TestGraphDefinition(t *testing.T){
var rabbitmq RabbitMQPlugin
graphdef := rabbitmq.GraphDefinition()
if len(graphdef) != 2 {
t.Error("GetTempfilename: %d should be 2", len(graphdef))
}
}
func TestParse(t *testing.T){
var rabbitmq RabbitMQPlugin
var stub rabbithole.Overview
stub.QueueTotals.Messages = 1
stub.QueueTotals.MessagesReady = 2
stub.QueueTotals.MessagesUnacknowledged = 3
stub.MessageStats.PublishDetails.Rate = 4
stat, err := rabbitmq.parseStats(stub)
assert.Nil(t, err)
assert.EqualValues(t, reflect.TypeOf(stat["messages"]).String(), "float64")
assert.EqualValues(t, stat["messages"], 1)
assert.EqualValues(t, reflect.TypeOf(stat["publish"]).String(), "float64")
assert.EqualValues(t, stat["publish"], 4)
} |
[fix] Clean javascript. Empty value when cloning inputs. | document.addEventListener('DOMContentLoaded', function() {
// Variables
var liMenu = document.querySelectorAll('#apps a')
, colors = ['bluebg','purplebg','redbg','orangebg','greenbg','darkbluebg','lightbluebg','yellowbg','lightpinkbg']
, addMailAlias = document.getElementById('add-mailalias')
, addMaildrop = document.getElementById('add-maildrop')
;
[].forEach.call(liMenu, function(el, i) {
// Add color class.
el.classList.add(colors[i]);
// Set first-letter data attribute.
el.querySelector('.first-letter').setAttribute('data-first-letter',el.textContent.substring(0, 2));
});
addMailAlias.addEventListener('click', function(){
// Clone last input.
var inputAliasClone = document.querySelector('.mailalias-input').cloneNode(true);
// Empty value.
inputAliasClone.value = '';
// Append to form-group.
addMailAlias.parentNode.insertBefore(inputAliasClone, addMailAlias);
});
addMaildrop.addEventListener('click', function(){
// Clone last input.
var inputDropClone = document.querySelector('.maildrop-input').cloneNode(true);
// Empty value.
inputDropClone.value = '';
// Append to form-group.
addMaildrop.parentNode.insertBefore(inputDropClone, addMaildrop);
});
}); | document.addEventListener('DOMContentLoaded', function() {
var liMenu = document.querySelectorAll('#apps a'),
colors = ['bluebg','purplebg','redbg','orangebg','greenbg','darkbluebg','lightbluebg','yellowbg','lightpinkbg'],
addMailAlias = document.getElementById('add-mailalias'),
addMaildrop = document.getElementById('add-maildrop'),
formMailAlias = document.getElementById('form-add-mail-alias'),
formMailDrop = document.getElementById('form-add-mail-drop');
[].forEach.call(liMenu, function(el, i) {
var text = el.textContent,
splitText = text.split("");
el.classList.add(colors[i]);
el.querySelector('.first-letter').setAttribute('data-first-letter',splitText[0]+splitText[1]);
});
addMailAlias.addEventListener('click', function(){
var inputAlias = document.querySelector('.mailalias-input');
formMailAlias.insertBefore(inputAlias.cloneNode(true), addMailAlias);
});
addMaildrop.addEventListener('click', function(){
var inputDrop = document.querySelector('.maildrop-input');
formMailDrop.insertBefore(inputDrop.cloneNode(true), addMaildrop);
});
}); |
Replace '五輕關廠' with '走入同志家庭' in subnav
Replace the '五輕關廠' link with '走入同志家庭' in sub-navigation menu | export const categoryPath = {
taiwanPath: '/category/taiwan',
reviewPath: '/category/review',
photographyPath: '/photography',
intlPath: '/category/intl',
culturePath: '/category/culture'
}
export const navPath = [
{ title: '台灣', path: '/category/taiwan' },
{ title: '國際兩岸', path:'/category/intl' },
{ title: '文化', path:'/category/culture' },
{ title: '影像', path:'/photography' },
{ title: '專欄', path:'/category/review' }
]
export const subnavPath = [
{ title: '轉型正義', path:'/a/transitional-justice-content' },
{ title: '0206地震', path:'/a/0206earthquake-content' },
{ title: '亞洲森林浩劫', path:'/a/asia-forest-content' },
{ title: '走入同志家庭', path:'/a/homofamily-content' },
{ title: '急診人生', path:'/a/emergency-content' }
]
| export const categoryPath = {
taiwanPath: '/category/taiwan',
reviewPath: '/category/review',
photographyPath: '/photography',
intlPath: '/category/intl',
culturePath: '/category/culture'
}
export const navPath = [
{ title: '台灣', path: '/category/taiwan' },
{ title: '國際兩岸', path:'/category/intl' },
{ title: '文化', path:'/category/culture' },
{ title: '影像', path:'/photography' },
{ title: '專欄', path:'/category/review' }
]
export const subnavPath = [
{ title: '轉型正義', path:'/a/transitional-justice-content' },
{ title: '0206地震', path:'/a/0206earthquake-content' },
{ title: '亞洲森林浩劫', path:'/a/asia-forest-content' },
{ title: '五輕關廠', path:'/a/refinery-content' },
{ title: '急診人生', path:'/a/emergency-content' }
]
|
Fix test json property name again | package main
import (
"fmt"
"net/http"
"testing"
"github.com/urfave/cli"
)
func TestCmdToot(t *testing.T) {
toot := ""
testWithServer(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/statuses":
toot = r.FormValue("status")
fmt.Fprintln(w, `{"id": 2345}`)
return
}
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
},
func(app *cli.App) {
app.Run([]string{"mstdn", "toot", "foo"})
},
)
if toot != "foo" {
t.Fatalf("want %q, got %q", "foo", toot)
}
}
| package main
import (
"fmt"
"net/http"
"testing"
"github.com/urfave/cli"
)
func TestCmdToot(t *testing.T) {
toot := ""
testWithServer(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/statuses":
toot = r.FormValue("status")
fmt.Fprintln(w, `{"ID": 2345}`)
return
}
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
},
func(app *cli.App) {
app.Run([]string{"mstdn", "toot", "foo"})
},
)
if toot != "foo" {
t.Fatalf("want %q, got %q", "foo", toot)
}
}
|
UPDATE age of account now printing out | <h1>Create Bank Account</h1>
<fieldset>
<legend>Account Information</legend>
<?php
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest Rate'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Valid For'));
echo form_input('monthly_deposits', set_value('monthly_deposits', 'Monthly Deposits'));
$options = array(
'1' => 'Yearly',
'12' => 'Monthly',
'365' => 'Daily'
);
echo form_dropdown('compound_frequency', $options, set_value('compound_frequency', 'Compound Rate'));
?>
<label>Start Date</label>
<input type="date" name="start_date">
<?php echo form_submit('submit', 'Add Bank ') ?>
</fieldset>
<?php echo validation_errors('<p class="error"/>'); ?> | <h1>Create Bank Account</h1>
<fieldset>
<legend>Account Information</legend>
<?php
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest Rate'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Valid For'));
echo form_input('monthly_deposits', set_value('monthly_deposits', 'Monthly Deposits'));
$options = array(
'small' => 'Yearly',
'med' => 'Daily test',
'large' => 'Monthly'
);
$shirts_on_sale = array('small', 'large');
echo "<label>Compound Type</label>";
echo form_dropdown('compound_frequency', $options, 'large');
?>
<label>Start Date</label>
<input type="date" name="start_date">
<?php echo form_submit('submit', 'Add Bank ')?>
</fieldset>
<?php echo validation_errors('<p class="error"/>'); ?> |
Use htmlentities in the HTML
git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3404 46e82423-29d8-e211-989e-002590a4cdd4 | <?php
#
# $Id: login.php,v 1.1.2.9 2005-09-05 19:53:24 dan Exp $
#
# Copyright (c) 1998-2003 DVL Software Limited
#
if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
<input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">
<p>User ID:<br>
<input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>"></p>
<p>Password:<br>
<input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20"></p>
<p><input TYPE="submit" VALUE="Login" name=submit> <input TYPE="reset" VALUE="reset form">
</form>
| <?php
#
# $Id: login.php,v 1.1.2.8 2003-12-01 18:17:47 dan Exp $
#
# Copyright (c) 1998-2003 DVL Software Limited
#
if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
<input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">
<p>User ID:<br>
<input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo $UserID ?>"></p>
<p>Password:<br>
<input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo $Password ?>" size="20"></p>
<p><input TYPE="submit" VALUE="Login" name=submit> <input TYPE="reset" VALUE="reset form">
</form>
|
Fix extractEnvelopeInfo breakage due to go-stellar-base api change | package txsub
import (
"github.com/stellar/go-stellar-base/build"
"github.com/stellar/go-stellar-base/strkey"
"github.com/stellar/go-stellar-base/xdr"
"golang.org/x/net/context"
)
type envelopeInfo struct {
Hash string
Sequence uint64
SourceAddress string
}
func extractEnvelopeInfo(ctx context.Context, env string, passphrase string) (result envelopeInfo, err error) {
var tx xdr.TransactionEnvelope
err = xdr.SafeUnmarshalBase64(env, &tx)
if err != nil {
err = &MalformedTransactionError{env}
return
}
txb := build.TransactionBuilder{TX: &tx.Tx}
txb.Mutate(build.Network{passphrase})
result.Hash, err = txb.HashHex()
if err != nil {
return
}
result.Sequence = uint64(tx.Tx.SeqNum)
aid := tx.Tx.SourceAccount.MustEd25519()
result.SourceAddress, err = strkey.Encode(strkey.VersionByteAccountID, aid[:])
return
}
| package txsub
import (
"github.com/stellar/go-stellar-base/build"
"github.com/stellar/go-stellar-base/strkey"
"github.com/stellar/go-stellar-base/xdr"
"golang.org/x/net/context"
)
type envelopeInfo struct {
Hash string
Sequence uint64
SourceAddress string
}
func extractEnvelopeInfo(ctx context.Context, env string, passphrase string) (result envelopeInfo, err error) {
var tx xdr.TransactionEnvelope
err = xdr.SafeUnmarshalBase64(env, &tx)
if err != nil {
err = &MalformedTransactionError{env}
return
}
txb := build.TransactionBuilder{TX: tx.Tx}
txb.Mutate(build.Network{passphrase})
result.Hash, err = txb.HashHex()
if err != nil {
return
}
result.Sequence = uint64(tx.Tx.SeqNum)
aid := tx.Tx.SourceAccount.MustEd25519()
result.SourceAddress, err = strkey.Encode(strkey.VersionByteAccountID, aid[:])
return
}
|
Add javadoc, make position final. | package uk.ac.ebi.quickgo.annotation.validation.loader;
/**
* Specify the columns for Database Cross Reference file.
*
* @author Tony Wardell
* Date: 07/11/2016
* Time: 18:16
* Created with IntelliJ IDEA.
*
* Specify the layout of the DB_XREFS_ENTITIES.dat.gz file.
* DATABASE ENTITY_TYPE_ID ENTITY_TYPE_NAME LOCAL_ID_SYNTAX URL_SYNTAX
*
*/
public enum DBXrefEntityColumns {
COLUMN_DB(0),
COLUMN_ENTITY_TYPE_ID(1),
COLUMN_ENTITY_TYPE_NAME(2),
COLUMN_LOCAL_ID_SYNTAX(3),
COLUMN_URL_SYNTAX(4);
private final int position;
DBXrefEntityColumns(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public static int numColumns() {
return DBXrefEntityColumns.values().length;
}
}
| package uk.ac.ebi.quickgo.annotation.validation.loader;
/**
* @author Tony Wardell
* Date: 07/11/2016
* Time: 18:16
* Created with IntelliJ IDEA.
*
* Specify the layout of the DB_XREFS_ENTITIES.dat.gz file.
* DATABASE ENTITY_TYPE_ID ENTITY_TYPE_NAME LOCAL_ID_SYNTAX URL_SYNTAX
*
*/
public enum DBXrefEntityColumns {
COLUMN_DB(0),
COLUMN_ENTITY_TYPE_ID(1),
COLUMN_ENTITY_TYPE_NAME(2),
COLUMN_LOCAL_ID_SYNTAX(3),
COLUMN_URL_SYNTAX(4);
private int position;
DBXrefEntityColumns(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public static int numColumns() {
return DBXrefEntityColumns.values().length;
}
}
|
Return value of execute method fixed (NoOP). | package aima.basic.vaccum;
import aima.basic.Agent;
import aima.basic.AgentProgram;
import aima.basic.Percept;
/**
* @author Ravi Mohan
*
*/
public class ModelBasedTVEVaccumAgentProgram extends AgentProgram {
VaccumEnvironmentModel myModel;
ModelBasedTVEVaccumAgentProgram(VaccumEnvironmentModel model) {
myModel = model;
}
@Override
public String execute(Percept percept) {
String location = (String) percept.getAttribute("location");
String locationStatus = (String) percept.getAttribute("status");
myModel.setLocationStatus(location, locationStatus);
if (myModel.bothLocationsClean()) {
return Agent.NO_OP;
} else if (locationStatus.equals("Dirty")) {
return "Suck";
} else if (location.equals("A")) {
return "Right";
} else if (location.equals("B")) {
return "Left";
} else
return "None";
}
} | package aima.basic.vaccum;
import aima.basic.AgentProgram;
import aima.basic.Percept;
/**
* @author Ravi Mohan
*
*/
public class ModelBasedTVEVaccumAgentProgram extends AgentProgram {
VaccumEnvironmentModel myModel;
ModelBasedTVEVaccumAgentProgram(VaccumEnvironmentModel model) {
myModel = model;
}
@Override
public String execute(Percept percept) {
String location = (String) percept.getAttribute("location");
String locationStatus = (String) percept.getAttribute("status");
myModel.setLocationStatus(location, locationStatus);
if (myModel.bothLocationsClean()) {
return "NoOp";
} else if (locationStatus.equals("Dirty")) {
return "Suck";
} else if (location.equals("A")) {
return "Right";
} else if (location.equals("B")) {
return "Left";
} else
return "None";
}
} |
Change version checking to only halt on yarn error | import { spawn } from 'cross-spawn';
import hasYarn from './has_yarn';
const packageManager = hasYarn() ? 'yarn' : 'npm';
export default function latestVersion(packageName) {
return new Promise((resolve, reject) => {
const command = spawn(packageManager, ['info', packageName, 'version', '--json', '--silent'], {
cwd: process.cwd(),
env: process.env,
stdio: 'pipe',
encoding: 'utf-8',
silent: true,
});
command.stdout.on('data', data => {
try {
const info = JSON.parse(data);
if (info.error) {
// npm error
reject(new Error(info.error.summary));
} else if (info.type === 'inspect') {
// yarn success
resolve(info.data);
} else {
// npm success
resolve(info);
}
} catch (e) {
// yarn info output
}
});
command.stderr.on('data', data => {
// yarn error
const info = JSON.parse(data);
if (info.type === 'error') {
reject(new Error(info.data));
}
});
});
}
| import { spawn } from 'cross-spawn';
import hasYarn from './has_yarn';
const packageManager = hasYarn() ? 'yarn' : 'npm';
export default function latestVersion(packageName) {
return new Promise((resolve, reject) => {
const command = spawn(packageManager, ['info', packageName, 'version', '--json', '--silent'], {
cwd: process.cwd(),
env: process.env,
stdio: 'pipe',
encoding: 'utf-8',
silent: true,
});
command.stdout.on('data', data => {
try {
const info = JSON.parse(data);
if (info.error) {
// npm error
reject(new Error(info.error.summary));
} else if (info.type === 'inspect') {
// yarn success
resolve(info.data);
} else {
// npm success
resolve(info);
}
} catch (e) {
// yarn info output
}
});
command.stderr.on('data', data => {
// yarn error
const info = JSON.parse(data);
if (info.type !== 'warning') {
reject(new Error(info.data));
}
});
});
}
|
fix: Use new method call for API summary | <?php /** @var \nochso\WriteMe\Markdown\InteractiveTemplate $this */ ?>
<?php $this->ask('composer.name', 'Enter the name as used on packagist', null, '/.+/'); ?>
# @composer.name@
<?php if ($this->ask('composer.description', 'Enter a one-line description of the project (optional)') !== ''): ?>
@composer.description@
<?php endif; ?>
<?php if ($this->getStdio()->confirm('Would you like to add table of contents of all sections?')): ?>
<?php $this->askForCustomPlaceholderOptionList('toc'); ?>
@toc@
<?php endif; ?>
# Installation
Installation through [Composer](https://getcomposer.org/) is preferred:
composer require @composer.name@
<?php if ($this->getStdio()->confirm('Would you like to add a summary of all PHP classes and their methods?')): ?>
<?php $this->askForCustomPlaceholderOptionList('api'); ?>
# API summary
@api('summary')@
<?php endif; ?>
<?php if ($this->ask('license.name', 'Enter the license name e.g. MIT, BSD2, etc. (optional)') !== ''): ?>
# License
This project is released under the @license.name@ license.
<?php endif; ?>
| <?php /** @var \nochso\WriteMe\Markdown\InteractiveTemplate $this */ ?>
<?php $this->ask('composer.name', 'Enter the name as used on packagist', null, '/.+/'); ?>
# @composer.name@
<?php if ($this->ask('composer.description', 'Enter a one-line description of the project (optional)') !== ''): ?>
@composer.description@
<?php endif; ?>
<?php if ($this->getStdio()->confirm('Would you like to add table of contents of all sections?')): ?>
<?php $this->askForCustomPlaceholderOptionList('toc'); ?>
@toc@
<?php endif; ?>
# Installation
Installation through [Composer](https://getcomposer.org/) is preferred:
composer require @composer.name@
<?php if ($this->getStdio()->confirm('Would you like to add a summary of all PHP classes and their methods?')): ?>
<?php $this->askForCustomPlaceholderOptionList('api'); ?>
# API summary
@api.summary@
<?php endif; ?>
<?php if ($this->ask('license.name', 'Enter the license name e.g. MIT, BSD2, etc. (optional)') !== ''): ?>
# License
This project is released under the @license.name@ license.
<?php endif; ?>
|
Add DerbyMagic9600 as another possible timer device (DerbyMagic timer running at 9600 baud). | package org.jeffpiazza.derby.devices;
import java.lang.reflect.Method;
public class AllDeviceTypes {
// The universe of all possible device classes
@SuppressWarnings(value = "unchecked")
public static final Class<? extends TimerDevice>[] allDeviceClasses
= (Class<? extends TimerDevice>[]) new Class[]{
SmartLineDevice.class,
FastTrackDevice.class,
OlderFastTrackDevice.class,
TheJudgeDevice.class,
NewBoldDevice.class,
DerbyTimerDevice.class,
MiscJunkDevice.class,
DerbyMagicDevice.class,
DerbyMagic9600.class
};
public static String toHumanString(Class<? extends TimerDevice> type) {
try {
Method m = type.getMethod("toHumanString");
return (String) m.invoke(null);
} catch (Exception ex) {
return null;
}
}
public static void listDeviceClassNames() {
for (Class<? extends TimerDevice> cl : allDeviceClasses) {
String human = toHumanString(cl);
System.err.println(" " + cl.getSimpleName()
+ (human == null ? "" : (": " + human)));
}
}
}
| package org.jeffpiazza.derby.devices;
import java.lang.reflect.Method;
public class AllDeviceTypes {
// The universe of all possible device classes
@SuppressWarnings(value = "unchecked")
public static final Class<? extends TimerDevice>[] allDeviceClasses
= (Class<? extends TimerDevice>[]) new Class[]{
SmartLineDevice.class,
FastTrackDevice.class,
OlderFastTrackDevice.class,
TheJudgeDevice.class,
NewBoldDevice.class,
DerbyTimerDevice.class,
MiscJunkDevice.class,
DerbyMagicDevice.class
};
public static String toHumanString(Class<? extends TimerDevice> type) {
try {
Method m = type.getMethod("toHumanString");
return (String) m.invoke(null);
} catch (Exception ex) {
return null;
}
}
public static void listDeviceClassNames() {
for (Class<? extends TimerDevice> cl : allDeviceClasses) {
String human = toHumanString(cl);
System.err.println(" " + cl.getSimpleName()
+ (human == null ? "" : (": " + human)));
}
}
}
|
Implement server-side rollback, for daemon versions that support this
Server-side rollback can take advantage of the rollback-specific update
parameters, instead of being treated as a normal update that happens to
go back to a previous version of the spec.
Signed-off-by: Aaron Lehmann <8ecfc6017a87905413dcd7d63696a2a4c351b604@docker.com> | package client
import (
"encoding/json"
"net/url"
"strconv"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"golang.org/x/net/context"
)
// ServiceUpdate updates a Service.
func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) {
var (
headers map[string][]string
query = url.Values{}
)
if options.EncodedRegistryAuth != "" {
headers = map[string][]string{
"X-Registry-Auth": {options.EncodedRegistryAuth},
}
}
if options.RegistryAuthFrom != "" {
query.Set("registryAuthFrom", options.RegistryAuthFrom)
}
if options.Rollback != "" {
query.Set("rollback", options.Rollback)
}
query.Set("version", strconv.FormatUint(version.Index, 10))
var response types.ServiceUpdateResponse
resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers)
if err != nil {
return response, err
}
err = json.NewDecoder(resp.body).Decode(&response)
ensureReaderClosed(resp)
return response, err
}
| package client
import (
"encoding/json"
"net/url"
"strconv"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"golang.org/x/net/context"
)
// ServiceUpdate updates a Service.
func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) {
var (
headers map[string][]string
query = url.Values{}
)
if options.EncodedRegistryAuth != "" {
headers = map[string][]string{
"X-Registry-Auth": {options.EncodedRegistryAuth},
}
}
if options.RegistryAuthFrom != "" {
query.Set("registryAuthFrom", options.RegistryAuthFrom)
}
query.Set("version", strconv.FormatUint(version.Index, 10))
var response types.ServiceUpdateResponse
resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers)
if err != nil {
return response, err
}
err = json.NewDecoder(resp.body).Decode(&response)
ensureReaderClosed(resp)
return response, err
}
|
Fix syntax for node 10 | const REQUIRED_FIELDS = Object.freeze(['to']);
const OPTIONAL_FIELDS = Object.freeze([
'customer_id',
'transactional_message_id',
'message_data',
'from',
'from_id',
'reply_to',
'reply_to_id',
'bcc',
'subject',
'body',
'plaintext_body',
'amp_body',
'fake_bcc',
'hide_body',
]);
module.exports = class TransactionalEmail {
constructor(opts) {
REQUIRED_FIELDS.forEach((field) => {
this[field] = opts[field];
});
OPTIONAL_FIELDS.forEach((field) => {
this[field] = opts[field];
});
this.headers = {};
this.attachments = {};
}
attach(name, data) {
if (data instanceof Buffer) {
this.attachments[name] = data.toString('base64');
} else if (typeof data === 'string') {
this.attachments[name] = fs.readFileSync(data, 'base64');
} else {
throw new Error(`unknown attachment type: ${typeof data}`);
}
}
toObject() {
let attrs = {
attachments: this.attachments,
headers: this.headers,
};
[...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => {
attrs[prop] = this[prop];
});
return attrs;
}
};
| const REQUIRED_FIELDS = Object.freeze(['to']);
const OPTIONAL_FIELDS = Object.freeze([
'customer_id',
'transactional_message_id',
'message_data',
'from',
'from_id',
'reply_to',
'reply_to_id',
'bcc',
'subject',
'body',
'plaintext_body',
'amp_body',
'fake_bcc',
'hide_body',
]);
module.exports = class TransactionalEmail {
headers = {};
attachments = {};
constructor(opts) {
REQUIRED_FIELDS.forEach((field) => {
this[field] = opts[field];
});
OPTIONAL_FIELDS.forEach((field) => {
this[field] = opts[field];
});
}
attach(name, data) {
if (data instanceof Buffer) {
this.attachments[name] = data.toString('base64');
} else if (typeof data === 'string') {
this.attachments[name] = fs.readFileSync(data, 'base64');
} else {
throw new Error(`unknown attachment type: ${typeof data}`);
}
}
toObject() {
let attrs = {
attachments: this.attachments,
headers: this.headers,
};
[...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => {
attrs[prop] = this[prop];
});
return attrs;
}
};
|
Make our failing partial stats test pass | var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("report-stats", function () {
var s = new Sandbox;
var run = s.run("create", "foo");
run.expectExit(0);
s.cd("foo");
// verify that identifier file exists for new apps
var identifier = s.read(".meteor/identifier");
selftest.expectEqual(!! identifier, true);
selftest.expectEqual(identifier.length > 0, true);
// verify that identifier file when running 'meteor bundle' on old
// apps
s.unlink(".meteor/identifier");
run = s.run("bundle", "foo.tar.gz");
run.waitSecs(30);
run.expectExit(0);
identifier = s.read(".meteor/identifier");
selftest.expectEqual(!! identifier, true);
selftest.expectEqual(identifier.length > 0, true);
// TODO:
// - test that we actually send stats
// - opt out
// - test both the logged in state and the logged out state
});
| var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("report-stats", function () {
var s = new Sandbox;
run = s.run("create", "foo");
run.expectExit(0);
s.cd("foo");
// verify that identifier file exists for new apps
var identifier = s.read(".meteor/identifier");
selftest.expectEqual(!! identifier, true);
selftest.expectEqual(identifier.length > 0, true);
// verify that identifier file when running 'meteor bundle' on old
// apps
s.unlink(".meteor/identifier");
s.run("bundle", "foo.tar.gz");
identifier = s.read(".meteor/identifier");
selftest.expectEqual(!! identifier, true);
selftest.expectEqual(identifier.length > 0, true);
// TODO:
// - test that we actually send stats
// - opt out
// - test both the logged in state and the logged out state
});
|
Update Adapter to match API | Ember.Adapter = Ember.Object.extend({
find: function(record, id) {
throw new Error('Ember.Adapter subclasses must implement find');
},
findQuery: function(klass, records, params) {
throw new Error('Ember.Adapter subclasses must implement findQuery');
},
findMany: function(klass, records, ids) {
throw new Error('Ember.Adapter subclasses must implement findMany');
},
findAll: function(klass, records) {
throw new Error('Ember.Adapter subclasses must implement findAll');
},
load: function(record, id, data) {
record.load(id, data);
},
createRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement createRecord');
},
saveRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement saveRecord');
},
deleteRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement deleteRecord');
}
}); | Ember.Adapter = Ember.Object.extend({
find: function(record, id) {
throw new Error('Ember.Adapter subclasses must implement find');
},
findQuery: function(record, id) {
throw new Error('Ember.Adapter subclasses must implement findQuery');
},
findMany: function(record, id) {
throw new Error('Ember.Adapter subclasses must implement findMany');
},
findAll: function(klass, records) {
throw new Error('Ember.Adapter subclasses must implement findAll');
},
load: function(record, id, data) {
record.load(id, data);
},
createRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement createRecord');
},
saveRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement saveRecord');
},
deleteRecord: function(record) {
throw new Error('Ember.Adapter subclasses must implement deleteRecord');
}
}); |
UPDATE: Use services by service const's | <?php
namespace Heystack\Subsystem\Ecommerce\Traits;
use Heystack\Subsystem\Core\ServiceStore;
use Heystack\Subsystem\Core\Services;
trait OutputHandlerControllerTrait
{
/**
* Process the request to the controller and direct it to the correct input
* and output controllers via the input and output processor services.
*
* @return mixed
*/
public function process()
{
$inputHandlerService = ServiceStore::getService(Services::INPUT_PROCESSOR_HANDLER);
$outputHandlerService = ServiceStore::getService(Services::OUTPUT_PROCESSOR_HANDLER);
$request = $this->getRequest();
$identifier = $request->param('Processor');
return $outputHandlerService->process(
$identifier,
$this,
$inputHandlerService->process($identifier, $request)
);
}
}
| <?php
namespace Heystack\Subsystem\Ecommerce\Traits;
use Heystack\Subsystem\Core\ServiceStore;
trait OutputHandlerControllerTrait
{
/**
* Process the request to the controller and direct it to the correct input
* and output controllers via the input and output processor services.
*
* @return mixed
*/
public function process()
{
$inputHandlerService = ServiceStore::getService('input_processor_handler'); //TODO
$outputHandlerService = ServiceStore::getService('output_processor_handler'); //TODO
$request = $this->getRequest();
$identifier = $request->param('Processor');
return $outputHandlerService->process(
$identifier,
$this,
$inputHandlerService->process($identifier, $request)
);
}
}
|
Documentation: Change wording from future to present tense | # -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if two objects are equal. |
+-----------+--------------------------------------+
| x != y | Checks if two objects are not equal. |
+-----------+--------------------------------------+
This class is the base class of most objects, since most
have an ID number.
id : int
The ID of the object
"""
def __init__(self, id):
self.id = int(id)
def __eq__(self, other):
return isinstance(other, self.__class__) and other.id == self.id
def __ne__(self, other):
if isinstance(other, self.__class__):
return other.id != self.id
return True
| # -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if two objects are equal. |
+-----------+--------------------------------------+
| x != y | Checks if two objects are not equal. |
+-----------+--------------------------------------+
This is the class that will be the base class of most objects, since most
have an ID number.
id : int
The ID of the object
"""
def __init__(self, id):
self.id = int(id)
def __eq__(self, other):
return isinstance(other, self.__class__) and other.id == self.id
def __ne__(self, other):
if isinstance(other, self.__class__):
return other.id != self.id
return True
|
Fix error in watch mode | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var DependenciesBlock = require("./DependenciesBlock");
function AsyncDependenciesBlock(name, module, loc) {
DependenciesBlock.call(this);
this.chunkName = name;
this.chunks = null;
this.module = module;
this.loc = loc;
Object.defineProperty(this, "chunk", {
get: function() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
},
set: function() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
});
}
module.exports = AsyncDependenciesBlock;
AsyncDependenciesBlock.prototype = Object.create(DependenciesBlock.prototype);
AsyncDependenciesBlock.prototype.updateHash = function updateHash(hash) {
hash.update(this.chunkName || "");
DependenciesBlock.prototype.updateHash.call(this, hash);
};
AsyncDependenciesBlock.prototype.disconnect = function() {
this.chunks = null;
DependenciesBlock.prototype.disconnect.call(this);
};
| /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var DependenciesBlock = require("./DependenciesBlock");
function AsyncDependenciesBlock(name, module, loc) {
DependenciesBlock.call(this);
this.chunkName = name;
this.chunks = null;
this.module = module;
this.loc = loc;
Object.defineProperty(this, "chunk", {
get: function() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
},
set: function() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
});
}
module.exports = AsyncDependenciesBlock;
AsyncDependenciesBlock.prototype = Object.create(DependenciesBlock.prototype);
AsyncDependenciesBlock.prototype.updateHash = function updateHash(hash) {
hash.update(this.chunkName || "");
DependenciesBlock.prototype.updateHash.call(this, hash);
};
AsyncDependenciesBlock.prototype.disconnect = function() {
this.chunk = null;
DependenciesBlock.prototype.disconnect.call(this);
}; |
Support document object as first argument | export default createNodeIterator
function createNodeIterator(root, whatToShow = 0xFFFFFFFF, filter = null) {
const doc = (root.nodeType == 9) || root.ownerDocument
const iter = doc.createNodeIterator(root, whatToShow, filter, false)
return new NodeIterator(iter, root, whatToShow, filter)
}
class NodeIterator {
constructor(iter, root, whatToShow, filter) {
this.root = root
this.whatToShow = whatToShow
this.filter = filter
this.referenceNode = root
this.pointerBeforeReferenceNode = true
this._iter = iter
}
nextNode() {
const result = this._iter.nextNode()
this.pointerBeforeReferenceNode = false
if (result === null) return null
this.referenceNode = result
return this.referenceNode
}
previousNode() {
const result = this._iter.previousNode()
this.pointerBeforeReferenceNode = true
if (result === null) return null
this.referenceNode = result
return this.referenceNode
}
toString() {
return '[object NodeIterator]'
}
}
| export default createNodeIterator
function createNodeIterator(root, whatToShow = 0xFFFFFFFF, filter = null) {
const doc = root.ownerDocument
const iter = doc.createNodeIterator(root, whatToShow, filter, false)
return new NodeIterator(iter, root, whatToShow, filter)
}
class NodeIterator {
constructor(iter, root, whatToShow, filter) {
this.root = root
this.whatToShow = whatToShow
this.filter = filter
this.referenceNode = root
this.pointerBeforeReferenceNode = true
this._iter = iter
}
nextNode() {
const result = this._iter.nextNode()
this.pointerBeforeReferenceNode = false
if (result === null) return null
this.referenceNode = result
return this.referenceNode
}
previousNode() {
const result = this._iter.previousNode()
this.pointerBeforeReferenceNode = true
if (result === null) return null
this.referenceNode = result
return this.referenceNode
}
toString() {
return '[object NodeIterator]'
}
}
|
Sort lists prior to computing len of candidates |
# A special triplet is defined as: a <= b <= c for
# a in list_a, b in list_b, and c in list_c
def get_num_special_triplets(list_a, list_b, list_c):
# remove duplicates and sort lists
list_a = sorted(set(list_a))
list_b = sorted(set(list_b))
list_c = sorted(set(list_c))
num_special_triplets = 0
for b in list_b:
len_a_candidates = num_elements_less_than(b, list_a)
len_c_candidates = num_elements_less_than(b, list_c)
num_special_triplets += 1 * len_a_candidates * len_c_candidates
return num_special_triplets
def num_elements_less_than(target, sorted_list):
for index, candidate in enumerate(sorted_list):
if candidate > target:
return index
return len(sorted_list)
if __name__ == '__main__':
_ = input().split()
list_a = list(map(int, input().rstrip().split()))
list_b = list(map(int, input().rstrip().split()))
list_c = list(map(int, input().rstrip().split()))
num_special_triplets = get_num_special_triplets(list_a, list_b, list_c)
print(num_special_triplets)
|
# A special triplet is defined as: a <= b <= c for
# a in list_a, b in list_b, and c in list_c
def get_num_special_triplets(list_a, list_b, list_c):
num_special_triplets = 0
for b in list_b:
len_a_candidates = len([a for a in list_a if a <= b])
len_c_candidates = len([c for c in list_c if c <= b])
num_special_triplets += 1 * len_a_candidates * len_c_candidates
return num_special_triplets
if __name__ == '__main__':
_ = input().split()
list_a = list(set(map(int, input().rstrip().split())))
list_b = list(set(map(int, input().rstrip().split())))
list_c = list(set(map(int, input().rstrip().split())))
num_special_triplets = get_num_special_triplets(list_a, list_b, list_c)
print(num_special_triplets)
|
Fix test, text it not outputted anymore - assert class value instead | <?php
/**
* @group Advanced_SocialBookmarks
*/
class Kwc_Advanced_SocialBookmarks_Test extends Kwc_TestAbstract
{
public function testIt()
{
$this->_init('Kwc_Advanced_SocialBookmarks_Root');
$page1 = $this->_root->getChildComponent('_page1');
$page2 = $page1->getChildComponent('_page2');
$this->assertTrue(strpos($page1->render(true, true), 'twitter') !== false);
$this->assertTrue(strpos($page2->render(true, true), 'twitter') !== false);
Kwf_Model_Abstract::getInstance('Kwc_Advanced_SocialBookmarks_TestModel')
->getRow('root-socialBookmarks')
->getChildRows('Networks', 2)->current()->delete();
$this->_process();
$this->assertTrue(strpos($page1->render(false, true), 'twitter') === false);
$this->assertTrue(strpos($page2->render(false, true), 'twitter') === false);
$this->assertTrue(strpos($page1->render(true, true), 'twitter') === false);
$this->assertTrue(strpos($page2->render(true, true), 'twitter') === false);
}
}
| <?php
/**
* @group Advanced_SocialBookmarks
*/
class Kwc_Advanced_SocialBookmarks_Test extends Kwc_TestAbstract
{
public function testIt()
{
$this->_init('Kwc_Advanced_SocialBookmarks_Root');
$page1 = $this->_root->getChildComponent('_page1');
$page2 = $page1->getChildComponent('_page2');
$this->assertTrue(strpos($page1->render(true, true), 'Twitter') !== false);
$this->assertTrue(strpos($page2->render(true, true), 'Twitter') !== false);
Kwf_Model_Abstract::getInstance('Kwc_Advanced_SocialBookmarks_TestModel')
->getRow('root-socialBookmarks')
->getChildRows('Networks', 2)->current()->delete();
$this->_process();
$this->assertTrue(strpos($page1->render(false, true), 'Twitter') === false);
$this->assertTrue(strpos($page2->render(false, true), 'Twitter') === false);
$this->assertTrue(strpos($page1->render(true, true), 'Twitter') === false);
$this->assertTrue(strpos($page2->render(true, true), 'Twitter') === false);
}
}
|
Add tab for filling logbook | <?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\bootstrap\Tabs;
use app\models\ProfileForm;
$this->title = 'Home';
?>
<title>Home</title> <!-- For Pjax's sake -->
<div class="site-index">
<?=
Tabs::widget([
'items' => [
[
'label' => 'Profile',
'content' => $this->render('profile', ['model' => new ProfileForm()]),
'headerOptions' => ['id' => 'profile-tab'],
'active' => true
],
[
'label' => 'Log Book',
'content' => $this->render('logbook'),
'headerOptions' => ['id' => 'logbook-tab'],
'options' => ['id' => 'tab-logbook'],
],
[
'label' => 'Notifications',
'content' => $this->render('notifications'),
'headerOptions' => ['id' => 'notifications-tab'],
'options' => ['id' => 'tab-notifications'],
],
],
]);
?>
</div>
| <?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\bootstrap\Tabs;
$this->title = 'Home';
?>
<title>Home</title> <!-- For Pjax's sake -->
<div class="site-index">
<?=
Tabs::widget([
'items' => [
[
'label' => 'Profile',
'content' => $this->render('profile'),
'active' => true
],
[
'label' => 'Notifications',
'content' => $this->render('notifications'),
'headerOptions' => [],
'options' => ['id' => 'tab-notifications'],
],
],
]);
?>
</div>
|
Make settings a plugin global. | (function ($) {
var defaults = {
};
var settings = {};
var slides = [];
var root, header, footer;
var current = 0;
var invisible = "slides-invisible";
function initslides (element) {
root = $(element);
header = root.find("> header");
footer = root.find("> footer");
/* Make header, footer and (slides > 1) invisible. */
slides = [root, header, footer];
root.addClass("slides").children("section").each(function () {
slides.push($(this));
});
$.each(slides.slice(4), function () {
$(this).addClass(invisible);
});
};
$.fn.slides = function (options) {
$.extend(settings, defaults, options);
return this.each(function () {
initslides(this, settings);
});
};
})(jQuery);
| (function ($) {
var defaults = {
};
var slides = [];
var root, header, footer;
var current = 0;
var invisible = "slides-invisible";
function initslides (element, settings) {
root = $(element);
header = root.find("> header");
footer = root.find("> footer");
/* Make header, footer and (slides > 1) invisible. */
slides = [root, header, footer];
root.addClass("slides").children("section").each(function () {
slides.push($(this));
});
$.each(slides.slice(4), function () {
$(this).addClass(invisible);
});
};
$.fn.slides = function (options) {
var settings = $.extend({}, defaults, options);
return this.each(function () {
initslides(this, settings);
});
};
})(jQuery);
|
Add filter text to signs | def playerIcons(poi):
if poi['id'] == 'Player':
poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId']
return "Last known location for %s" % poi['EntityId']
# Only signs with "-- RENDER --" on the last line will be shown
# Otherwise, people can't have secret bases and the render is too busy anyways.
def signFilter(poi):
if poi['id'] == 'Sign':
if poi['Text4'] == '-- RENDER --':
return "\n".join([poi['Text1'], poi['Text2'], poi['Text3'], poi['Text4']])
worlds['minecraft'] = "/home/minecraft/server/world"
outputdir = "/home/minecraft/render/"
markers = [
dict(name="Players", filterFunction=playerIcons),
dict(name="Signs", filterFunction=signFilter)
]
renders["day"] = {
'world': 'minecraft',
'title': 'Day',
'rendermode': 'smooth_lighting',
'markers': markers
}
renders["night"] = {
'world': 'minecraft',
'title': 'Night',
'rendermode': 'smooth_night',
'markers': markers
}
| def playerIcons(poi):
if poi['id'] == 'Player':
poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId']
return "Last known location for %s" % poi['EntityId']
def signFilter(poi):
if poi['id'] == 'Sign':
return "\n".join([poi['Text1'], poi['Text2'], poi['Text3'], poi['Text4']])
worlds['minecraft'] = "/home/minecraft/server/world"
outputdir = "/home/minecraft/render/"
markers = [
dict(name="Players", filterFunction=playerIcons),
dict(name="Signs", filterFunction=signFilter)
]
renders["day"] = {
'world': 'minecraft',
'title': 'Day',
'rendermode': 'smooth_lighting',
'markers': markers
}
renders["night"] = {
'world': 'minecraft',
'title': 'Night',
'rendermode': 'smooth_night',
'markers': markers
}
|
Read posts per page from metadata collection | Meteor.publish("post_list", function(page_num){
const posts_per_page = MetaData.findOne({type: "posts"}).posts_per_page;
//validating the page number
var page_number = page_num;
if(!/^[0-9]+$/gi.test(page_num)){
return [];
} else if(page_num <= 0) {
return [];
}
return Posts.find({},{
limit: posts_per_page,
skip: (parseInt(page_number) - 1) * posts_per_page,
sort: {
createdAt: -1
}
})
})
Meteor.publish("get_post", function(post_id){
//validating the id
if(!post_id.match(/^[0-9A-Za-z]{17}(?=(#[0-9a-zA-Z_-]+)?$)/gi)){
return [];
}
return Posts.find(post_id, {
limit: 1,
})
})
Meteor.publish("metadata", function(type){
if(type === "posts" || type === "works"){
return MetaData.find({
type: type
});
} else {
return [];
}
})
| Meteor.publish("post_list", function(page_num){
const posts_per_page = 10;
//validating the page number
var page_number = page_num;
if(!/^[0-9]+$/gi.test(page_num)){
return [];
} else if(page_num <= 0) {
return [];
}
return Posts.find({},{
limit: posts_per_page,
skip: (parseInt(page_number) - 1) * posts_per_page,
sort: {
createdAt: -1
}
})
})
Meteor.publish("get_post", function(post_id){
//validating the id
if(!post_id.match(/^[0-9A-Za-z]{17}(?=(#[0-9a-zA-Z_-]+)?$)/gi)){
return [];
}
return Posts.find(post_id, {
limit: 1,
})
})
Meteor.publish("metadata", function(type){
if(type === "posts" || type === "works"){
return MetaData.find({
type: type
});
} else {
return [];
}
})
|
Store IDs as signed integers | package instana
// SpanContext holds the basic Span metadata.
type SpanContext struct {
// A probabilistically unique identifier for a [multi-span] trace.
TraceID int64
// A probabilistically unique identifier for a span.
SpanID int64
// Whether the trace is sampled.
Sampled bool
// The span's associated baggage.
Baggage map[string]string // initialized on first use
}
// ForeachBaggageItem belongs to the opentracing.SpanContext interface
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
for k, v := range c.Baggage {
if !handler(k, v) {
break
}
}
}
// WithBaggageItem returns an entirely new SpanContext with the
// given key:value baggage pair set.
func (c SpanContext) WithBaggageItem(key, val string) SpanContext {
var newBaggage map[string]string
if c.Baggage == nil {
newBaggage = map[string]string{key: val}
} else {
newBaggage = make(map[string]string, len(c.Baggage)+1)
for k, v := range c.Baggage {
newBaggage[k] = v
}
newBaggage[key] = val
}
// Use positional parameters so the compiler will help catch new fields.
return SpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}
| package instana
// SpanContext holds the basic Span metadata.
type SpanContext struct {
// A probabilistically unique identifier for a [multi-span] trace.
TraceID uint64
// A probabilistically unique identifier for a span.
SpanID uint64
// Whether the trace is sampled.
Sampled bool
// The span's associated baggage.
Baggage map[string]string // initialized on first use
}
// ForeachBaggageItem belongs to the opentracing.SpanContext interface
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
for k, v := range c.Baggage {
if !handler(k, v) {
break
}
}
}
// WithBaggageItem returns an entirely new SpanContext with the
// given key:value baggage pair set.
func (c SpanContext) WithBaggageItem(key, val string) SpanContext {
var newBaggage map[string]string
if c.Baggage == nil {
newBaggage = map[string]string{key: val}
} else {
newBaggage = make(map[string]string, len(c.Baggage)+1)
for k, v := range c.Baggage {
newBaggage[k] = v
}
newBaggage[key] = val
}
// Use positional parameters so the compiler will help catch new fields.
return SpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}
|
Fix build breakage due to api change
Change-Id: I72661c51f277cb9aa3df0bd5a16756408b53ab7f | /*
* Copyright (C) 2009 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 com.android.inputmethod.latin;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Backs up the Latin IME shared preferences.
*/
public class LatinIMEBackupAgent extends BackupAgentHelper {
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
getPackageName() + "_preferences"));
}
}
| /*
* Copyright (C) 2009 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 com.android.inputmethod.latin;
import android.app.backup.BackupHelperAgent;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Backs up the Latin IME shared preferences.
*/
public class LatinIMEBackupAgent extends BackupHelperAgent {
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
getPackageName() + "_preferences"));
}
}
|
Set up for v0.23 development | """SoCo (Sonos Controller) is a simple library to control Sonos speakers."""
# There is no need for all strings here to be unicode, and Py2 cannot import
# modules with unicode names so do not use from __future__ import
# unicode_literals
# https://github.com/SoCo/SoCo/issues/98
#
import logging
from .core import SoCo
from .discovery import discover
from .exceptions import SoCoException, UnknownSoCoException
# Will be parsed by setup.py to determine package metadata
__author__ = "The SoCo-Team <python-soco@googlegroups.com>"
# Please increment the version number and add the suffix "-dev" after
# a release, to make it possible to identify in-development code
__version__ = "0.23-dev"
__website__ = "https://github.com/SoCo/SoCo"
__license__ = "MIT License"
# You really should not `import *` - it is poor practice
# but if you do, here is what you get:
__all__ = [
"discover",
"SoCo",
"SoCoException",
"UnknownSoCoException",
]
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
logging.getLogger(__name__).addHandler(logging.NullHandler())
| """SoCo (Sonos Controller) is a simple library to control Sonos speakers."""
# There is no need for all strings here to be unicode, and Py2 cannot import
# modules with unicode names so do not use from __future__ import
# unicode_literals
# https://github.com/SoCo/SoCo/issues/98
#
import logging
from .core import SoCo
from .discovery import discover
from .exceptions import SoCoException, UnknownSoCoException
# Will be parsed by setup.py to determine package metadata
__author__ = "The SoCo-Team <python-soco@googlegroups.com>"
# Please increment the version number and add the suffix "-dev" after
# a release, to make it possible to identify in-development code
__version__ = "0.22.0"
__website__ = "https://github.com/SoCo/SoCo"
__license__ = "MIT License"
# You really should not `import *` - it is poor practice
# but if you do, here is what you get:
__all__ = [
"discover",
"SoCo",
"SoCoException",
"UnknownSoCoException",
]
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
fix: Fix an issue with navigation button types. | import React, { PropTypes } from 'react';
import { PersianNumber } from 'react-persian';
export default class Heading extends React.Component {
static propTypes = {
month: PropTypes.object.isRequired,
onNext: PropTypes.func.isRequired,
onPrev: PropTypes.func.isRequired,
prevMonthElement: PropTypes.element.isRequired,
nextMonthElement: PropTypes.element.isRequired
};
render() {
const { month, onPrev, onNext, prevMonthElement, nextMonthElement } = this.props;
return (<div className="heading">
<PersianNumber>{month.format('jMMMM jYYYY')}</PersianNumber>
<button type="button" className="prev-month" onClick={onPrev}>{prevMonthElement}</button>
<button type="button" className="next-month" onClick={onNext}>{nextMonthElement}</button>
</div>);
}
}
| import React, { PropTypes } from 'react';
import { PersianNumber } from 'react-persian';
export default class Heading extends React.Component {
static propTypes = {
month: PropTypes.object.isRequired,
onNext: PropTypes.func.isRequired,
onPrev: PropTypes.func.isRequired,
prevMonthElement: PropTypes.element.isRequired,
nextMonthElement: PropTypes.element.isRequired
};
render() {
const { month, onPrev, onNext, prevMonthElement, nextMonthElement } = this.props;
return (<div className="heading">
<PersianNumber>{month.format('jMMMM jYYYY')}</PersianNumber>
<button className="prev-month" onClick={onPrev}>{prevMonthElement}</button>
<button className="next-month" onClick={onNext}>{nextMonthElement}</button>
</div>);
}
}
|
Revert "Look for description in error caught"
This reverts commit 18171100cc4cdf32d31dcf526254c708fd42812d. | var context;
window.addEventListener('load', init, false);
function init() {
try {
var dogBarkingUrl = 'https://upload.wikimedia.org/wikipedia/commons/c/ce/Sound-of-dog.ogg';
var dogBarkingBuffer = null;
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
loadDogSound(dogBarkingUrl);
alert('Sound Loaded');
playSound(dogBarkingBuffer);
}
catch(e) {
alert('Web Audio API is not supported in this browser');
}
}
function loadDogSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(
request.response,
playSound,
function(e){"Error with decoding audio data" + e.err}
);
}
request.send();
}
function playSound(buffer) {
var source = context.createBufferSource(); // creates a sound source
source.buffer = buffer; // tell the source which sound to play
source.connect(context.destination); // connect the source to the context's destination (the speakers)
source.start(0); // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
}
| var context;
window.addEventListener('load', init, false);
function init() {
try {
var dogBarkingUrl = 'https://upload.wikimedia.org/wikipedia/commons/c/ce/Sound-of-dog.ogg';
var dogBarkingBuffer = null;
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
loadDogSound(dogBarkingUrl);
playSound(dogBarkingBuffer);
}
catch(e) {
alert('Web Audio API is not supported in this browser' + e.err);
}
}
function loadDogSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(
request.response,
playSound,
function(e){'Error with decoding audio data' + e.err}
);
}
request.send();
}
function playSound(buffer) {
var source = context.createBufferSource(); // creates a sound source
source.buffer = buffer; // tell the source which sound to play
source.connect(context.destination); // connect the source to the context's destination (the speakers)
source.start(0); // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
}
|
Add enrollment_code to U2F client | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.client.fido.u2f;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterRequestMessage;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterStatus;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
/**
* Еhe endpoint allows to start and finish U2F registration process
*
* @author Yuriy Movchan
* @version August 9, 2017
*/
public interface RegistrationRequestService {
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId);
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId, @QueryParam("enrollment_code") String enrollmentCode);
@POST
@Produces({"application/json"})
public RegisterStatus finishRegistration(@FormParam("username") String userName, @FormParam("tokenResponse") String registerResponseString);
} | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.client.fido.u2f;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterRequestMessage;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterStatus;
import javax.ws.rs.*;
/**
* Еhe endpoint allows to start and finish U2F registration process
*
* @author Yuriy Movchan
* @version August 9, 2017
*/
public interface RegistrationRequestService {
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId);
@POST
@Produces({"application/json"})
public RegisterStatus finishRegistration(@FormParam("username") String userName, @FormParam("tokenResponse") String registerResponseString);
} |
Change upload file to public read | package uploader
import (
"fmt"
"os"
"launchpad.net/goamz/aws"
"launchpad.net/goamz/s3"
)
const (
defaultS3BufferSize = 5 * 1024 * 1024
)
type S3 struct {
Bucket *s3.Bucket
BufferSize int64
}
func (s3Uploader *S3) Init() error {
s3Region := os.Getenv("S3_REGION")
region, ok := aws.Regions[s3Region]
if !ok {
return fmt.Errorf("Fail to find S3 region %s\n", s3Region)
}
auth := aws.Auth{AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"), SecretKey: os.Getenv("AWS_SECRET_KEY")}
s := s3.New(auth, region)
s3Uploader.Bucket = s.Bucket(os.Getenv("S3_BUCKET"))
s3Uploader.BufferSize = defaultS3BufferSize
return nil
}
func (s3Uploader *S3) Upload(destPath, contentType string, f *os.File) error {
writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.PublicRead)
if err != nil {
return err
}
parts, err := writer.PutAll(f, s3Uploader.BufferSize)
if err != nil {
return err
}
return writer.Complete(parts)
}
| package uploader
import (
"fmt"
"os"
"launchpad.net/goamz/aws"
"launchpad.net/goamz/s3"
)
const (
defaultS3BufferSize = 5 * 1024 * 1024
)
type S3 struct {
Bucket *s3.Bucket
BufferSize int64
}
func (s3Uploader *S3) Init() error {
s3Region := os.Getenv("S3_REGION")
region, ok := aws.Regions[s3Region]
if !ok {
return fmt.Errorf("Fail to find S3 region %s\n", s3Region)
}
auth := aws.Auth{AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"), SecretKey: os.Getenv("AWS_SECRET_KEY")}
s := s3.New(auth, region)
s3Uploader.Bucket = s.Bucket(os.Getenv("S3_BUCKET"))
s3Uploader.BufferSize = defaultS3BufferSize
return nil
}
func (s3Uploader *S3) Upload(destPath, contentType string, f *os.File) error {
writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.AuthenticatedRead)
if err != nil {
return err
}
parts, err := writer.PutAll(f, s3Uploader.BufferSize)
if err != nil {
return err
}
return writer.Complete(parts)
}
|
Use same order as matplotlib for PySize/PyQT | import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
try:
import PySide
qt_api = 'pyside'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
if qt_api is not None:
os.environ['QT_API'] = qt_api
| import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
if qt_api is not None:
os.environ['QT_API'] = qt_api
|
Add error for invalid pda transitions | export class UnknownCharError extends Error {
constructor(unknownChar) {
super(`Character '${unknownChar}' is not a part of the alphabet.`)
}
}
export class UnknownStateError extends Error {
constructor(stateName) {
super(`State '${stateName}' doesn't exist in the automata.`)
}
}
export class DeterminismError extends Error {
constructor(state, a) {
super(`State '${state}' already has a transition with character '${a}'.`)
}
}
export class NoInitialStateError extends Error {
constructor() {
super('No initial state has been set.')
}
}
export class DuplicateStateError extends Error {
constructor(name) {
super(`State '${name}' already exists.`)
}
}
export class DuplicateTransitionError extends Error {
constructor({ from, a, to }) {
super(`A transition from state '${from}' with char '${a}' to state '${to}' already exists.`)
}
}
export class NoFinalStatesError extends Error {
constructor() {
super('No final states have been defined.')
}
}
export class InvalidPDATransition extends Error {
constructor(str) {
super(`Invalid transition symbol '${str}'.`)
}
} | export class UnknownCharError extends Error {
constructor(unknownChar) {
super(`Character '${unknownChar}' is not a part of the alphabet.`)
}
}
export class UnknownStateError extends Error {
constructor(stateName) {
super(`State '${stateName}' doesn't exist in the automata.`)
}
}
export class DeterminismError extends Error {
constructor(state, a) {
super(`State '${state}' already has a transition with character '${a}'.`)
}
}
export class NoInitialStateError extends Error {
constructor() {
super('No initial state has been set.')
}
}
export class DuplicateStateError extends Error {
constructor(name) {
super(`State '${name}' already exists.`)
}
}
export class DuplicateTransitionError extends Error {
constructor({ from, a, to }) {
super(`A transition from state '${from}' with char '${a}' to state '${to}' already exists.`)
}
}
export class NoFinalStatesError extends Error {
constructor() {
super('No final states have been defined.')
}
} |
Fix tokenizing of comment after closing brace of last message | module.exports = function (sch) {
var noComments = function (line) {
var i = line.indexOf('//')
return i > -1 ? line.slice(0, i) : line
}
var noMultilineComments = function () {
var inside = false
return function (token) {
if (token === '/*') {
inside = true
return false
}
if (token === '*/') {
inside = false
return false
}
return !inside
}
}
var trim = function (line) {
return line.trim()
}
return sch
.replace(/([;,{}=\[\]<>]|\/\*|\*\/)/g, ' $1 ')
.split(/\n/)
.map(trim)
.filter(Boolean)
.map(noComments)
.map(trim)
.filter(Boolean)
.join('\n')
.split(/\s+|\n+/gm)
.filter(noMultilineComments())
}
| module.exports = function (sch) {
var noComments = function (line) {
var i = line.indexOf('//')
return i > -1 ? line.slice(0, i) : line
}
var noMultilineComments = function () {
var inside = false
return function (token) {
if (token === '/*') {
inside = true
return false
}
if (token === '*/') {
inside = false
return false
}
return !inside
}
}
var trim = function (line) {
return line.trim()
}
return sch
.replace(/([;,{}=\[\]<>]|\/\*|\*\/)/g, ' $1 ')
.split(/\n/)
.map(trim)
.filter(Boolean)
.map(noComments)
.filter(Boolean)
.join('\n')
.split(/\s+|\n+/gm)
.filter(noMultilineComments())
}
|
Fix issue with HDF5 objects that don't have a value | import os
import h5py
from glue.core import Data
def read_step_to_data(filename, step_id=0):
"""
Given a filename and a step ID, read in the data into a new Data object.
"""
f = h5py.File(filename, 'r')
try:
group = f['Step#{0}'.format(step_id)]
except KeyError:
raise ValueError("Step ID {0} not found in file: {1}".format(step_id, filename))
data = Data()
for attribute in group:
try:
data[attribute] = group[attribute].value
except AttributeError:
pass
data.label = os.path.basename(filename.rsplit('.', 1)[0])
return data
def find_n_steps(filename):
"""
Given a filename, find how many steps exist in the file.
"""
f = h5py.File(filename, 'r')
if 'Step#0' not in f:
raise ValueError("File does not contain Step#n entries")
# Some groups may not be 'Step' groups so we have to work backwards. The
# absolute maximum number of steps is the number of groups at the root level.
n_max = len(f)
for n_max in range(n_max - 1, -1, -1):
if 'Step#{0}'.format(n_max) in f:
return n_max
| import os
import h5py
from glue.core import Data
def read_step_to_data(filename, step_id=0):
"""
Given a filename and a step ID, read in the data into a new Data object.
"""
f = h5py.File(filename, 'r')
try:
group = f['Step#{0}'.format(step_id)]
except KeyError:
raise ValueError("Step ID {0} not found in file: {1}".format(step_id, filename))
data = Data()
for attribute in group:
data[attribute] = group[attribute].value
data.label = os.path.basename(filename.rsplit('.', 1)[0])
return data
def find_n_steps(filename):
"""
Given a filename, find how many steps exist in the file.
"""
f = h5py.File(filename, 'r')
if 'Step#0' not in f:
raise ValueError("File does not contain Step#n entries")
# Some groups may not be 'Step' groups so we have to work backwards. The
# absolute maximum number of steps is the number of groups at the root level.
n_max = len(f)
for n_max in range(n_max - 1, -1, -1):
if 'Step#{0}'.format(n_max) in f:
return n_max
|
BAP-11558: Add force Resync parameter for IMAP synchronization command | <?php
namespace Oro\Bundle\EmailBundle\Sync\Model;
class SynchronizationProcessorSettings
{
/** @var bool In this mode all emails will be re-synced again for checked folders */
protected $forceMode = false;
/** @var bool Allows to define show or hide log messages during resync of emails */
protected $showMessage = false;
/**
* @param bool $forceMode
* @param bool $showMessage
*/
public function __construct($forceMode = false, $showMessage = false)
{
$this->forceMode = $forceMode;
$this->showMessage = $showMessage;
}
/**
* Set force mode.
*
* @param bool $mode
*/
public function setForceMode($mode)
{
$this->forceMode = $mode;
}
/**
* Check is force mode enabled.
*/
public function isForceMode()
{
return $this->forceMode === true;
}
/**
* Set value to show or hide log messages
*
* @param bool $value
*/
public function setShowMessage($value)
{
$this->showMessage = $value;
}
/**
* Check value is true.
*
* @return bool
*/
public function needShowMessage()
{
return $this->showMessage === true;
}
}
| <?php
namespace Oro\Bundle\EmailBundle\Sync\Model;
class SynchronizationProcessorSettings
{
/** @var bool In this mode all emails will be re-synced again for checked folders */
protected $forceMode = false;
/** @var bool Allows to define show or hide log messages during resync of emails */
protected $showMessage = false;
public function __construct($forceMode = false, $showMessage = false)
{
$this->forceMode = $forceMode;
$this->showMessage = $showMessage;
}
/**
* Set force mode.
*
* @param bool $mode
*/
public function setForceMode($mode)
{
$this->forceMode = $mode;
}
/**
* Check is force mode enabled.
*/
public function isForceMode()
{
return $this->forceMode === true;
}
/**
* Set value to show or hide log messages
*
* @param bool $value
*/
public function setShowMessage($value)
{
$this->showMessage = $value;
}
/**
* Check value is true.
*
* @return bool
*/
public function needShowMessage()
{
return $this->showMessage === true;
}
}
|
Add check to not add messages twice | /**
* @class Denkmal_Component_MessageList_All
* @extends Denkmal_Component_MessageList_Abstract
*/
var Denkmal_Component_MessageList_All = Denkmal_Component_MessageList_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageList_All',
ready: function() {
this.bindStream('global-internal', cm.model.types.CM_Model_StreamChannel_Message, 'message-create', function(message) {
this._addMessage(message);
});
},
/**
* @param {Object} message
*/
_addMessage: function(message) {
if (this.$('.messageList > .message[data-id="' + message.id + '"]').length > 0) {
return;
}
this.renderTemplate('template-message', {
id: message.id,
created: message.created,
venue: message.venue.name,
hasText: message.text !== null,
text: message.text,
hasImage: message.image !== null,
imageUrl: (message.image !== null) ? message.image['url-thumb'] : null
}).appendTo(this.$('.messageList'));
}
});
| /**
* @class Denkmal_Component_MessageList_All
* @extends Denkmal_Component_MessageList_Abstract
*/
var Denkmal_Component_MessageList_All = Denkmal_Component_MessageList_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageList_All',
ready: function() {
this.bindStream('global-internal', cm.model.types.CM_Model_StreamChannel_Message, 'message-create', function(message) {
this._addMessage(message);
});
},
/**
* @param {Object} message
*/
_addMessage: function(message) {
this.renderTemplate('template-message', {
id: message.id,
created: message.created,
venue: message.venue.name,
hasText: message.text !== null,
text: message.text,
hasImage: message.image !== null,
imageUrl: (message.image !== null) ? message.image['url-thumb'] : null
}).appendTo(this.$('.messageList'));
}
});
|
Remove script defer to see if it fixes travis visual regression tests | var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
| var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script defer src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
|
Rename 'util' to 'GipsyUtil' in overlay. | {
let GipsyUtil = {};
Components.utils.import("resource://gipsy/util.jsm", GipsyUtil);
let myId = "gipsy-button"; // ID of button to add
let afterId = "search-container"; // ID of element to insert after
let navBar = document.getElementById("nav-bar");
if (navBar && !GipsyUtil.get_bool_pref('btn_toolbar_added')) {
let curSet = navBar.currentSet.split(",");
if (curSet.indexOf(myId) == -1) {
let pos = curSet.indexOf(afterId) + 1 || curSet.length;
let set = curSet.slice(0, pos).concat(myId).concat(curSet.slice(pos));
navBar.setAttribute("currentset", set.join(","));
navBar.currentSet = set.join(",");
document.persist(navBar.id, "currentset");
try {
BrowserToolboxCustomizeDone(true);
} catch (e) {}
GipsyUtil.set_bool_pref('btn_toolbar_added', true);
}
}
}
| {
let util = {};
Components.utils.import("resource://gipsy/util.jsm", util);
let myId = "gipsy-button"; // ID of button to add
let afterId = "search-container"; // ID of element to insert after
let navBar = document.getElementById("nav-bar");
if (navBar && !util.get_bool_pref('btn_toolbar_added')) {
let curSet = navBar.currentSet.split(",");
if (curSet.indexOf(myId) == -1) {
let pos = curSet.indexOf(afterId) + 1 || curSet.length;
let set = curSet.slice(0, pos).concat(myId).concat(curSet.slice(pos));
navBar.setAttribute("currentset", set.join(","));
navBar.currentSet = set.join(",");
document.persist(navBar.id, "currentset");
try {
BrowserToolboxCustomizeDone(true);
} catch (e) {}
util.set_bool_pref('btn_toolbar_added', true);
}
}
}
|
Add more directories to narrow by default | "use babel";
export const DEFAULT_ACTIVE_FILE_DIR = 'Active file\'s directory';
export const DEFAULT_PROJECT_ROOT = 'Project root';
export const DEFAULT_EMPTY = 'Empty';
export let config = {
helmDirSwitch: {
title: 'Shortcuts for fast directory switching',
description: 'See README for details.',
type: 'boolean',
default: false,
},
defaultInputValue: {
title: 'Default input value',
description: `What should the path input default to when the dialog
is opened?`,
type: 'string',
enum: [DEFAULT_ACTIVE_FILE_DIR, DEFAULT_PROJECT_ROOT, DEFAULT_EMPTY],
default: DEFAULT_ACTIVE_FILE_DIR,
},
defaultMWdirNarrowing: {
title: 'Default directory narrowing for The MathWorks codebase',
description: `What paths should I search in within your sandbox?`,
type: 'string',
default: ['matlab/src/cg_ir matlab/src/cgir_xform',
'matlab/src/cgir_support',
'matlab/src/cgir_vm matlab/src/cgir_vm_rt'].join(' ')
},
};
| "use babel";
export const DEFAULT_ACTIVE_FILE_DIR = 'Active file\'s directory';
export const DEFAULT_PROJECT_ROOT = 'Project root';
export const DEFAULT_EMPTY = 'Empty';
export let config = {
helmDirSwitch: {
title: 'Shortcuts for fast directory switching',
description: 'See README for details.',
type: 'boolean',
default: false,
},
defaultInputValue: {
title: 'Default input value',
description: `What should the path input default to when the dialog
is opened?`,
type: 'string',
enum: [DEFAULT_ACTIVE_FILE_DIR, DEFAULT_PROJECT_ROOT, DEFAULT_EMPTY],
default: DEFAULT_ACTIVE_FILE_DIR,
},
defaultMWdirNarrowing: {
title: 'Default directory narrowing for The MathWorks codebase',
description: `What paths should I search in within your sandbox?`,
type: 'string',
default: 'matlab/src/cg_ir matlab/src/cgir_xform matlab/src/cgir_vm'
},
};
|
Remove description for config options | package com.crowdin.cli.commands.parts;
import com.crowdin.cli.commands.functionality.PropertiesBuilder;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import picocli.CommandLine;
import java.io.File;
public abstract class PropertiesBuilderCommandPart extends Command {
@CommandLine.Option(names = {"--identity"}, paramLabel = "...", description = "Set a path to user-specific credentials")
private File identityFile;
@CommandLine.ArgGroup(exclusive = false, heading = "@|underline CONFIG OPTIONS|@:%n")
private Params params;
@CommandLine.Option(names = {"-c", "--config"}, paramLabel = "...", description = "Set a path to the configuration file. Default: crowdin.yml", defaultValue = "crowdin.yml")
private File configFile;
protected PropertiesBean buildPropertiesBean() {
return (new PropertiesBuilder(configFile, identityFile, params)).build();
}
}
| package com.crowdin.cli.commands.parts;
import com.crowdin.cli.commands.functionality.PropertiesBuilder;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import picocli.CommandLine;
import java.io.File;
public abstract class PropertiesBuilderCommandPart extends Command {
@CommandLine.Option(names = {"--identity"}, paramLabel = "...", description = "Set a path to user-specific credentials")
private File identityFile;
@CommandLine.ArgGroup(exclusive = false, heading = "@|underline CONFIG OPTIONS|@(to use instead configuration file):%n")
private Params params;
@CommandLine.Option(names = {"-c", "--config"}, paramLabel = "...", description = "Set a path to the configuration file. Default: crowdin.yml", defaultValue = "crowdin.yml")
private File configFile;
protected PropertiesBean buildPropertiesBean() {
return (new PropertiesBuilder(configFile, identityFile, params)).build();
}
}
|
Revert "Logging on cli mode"
This reverts commit 66dbfea49de3584da69436f9ca9f719b66875617. | <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;
/**
* Additional bootstrapping and configuration for CLI environments should
* be put here.
*/
// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');
try {
Plugin::load('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
| <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;
/**
* Additional bootstrapping and configuration for CLI environments should
* be put here.
*/
// Set logs to default file mode.
Configure::write('Log', [
'debug' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'cli-debug',
'levels' => ['debug'],
],
'error' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'cli-error',
'levels' => ['notice', 'info', 'warning', 'error', 'critical', 'alert', 'emergency']
],
]);
try {
Plugin::load('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.