text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Make get_signature support unicode characters by encoding to utf-8 instead of ascii.
|
import hashlib
import hmac
import urllib, urllib2
KEY_STATUSES = (
('U', 'Unactivated'),
('A', 'Active'),
('S', 'Suspended')
)
UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3)
PUB_STATUSES = (
(UNPUBLISHED, 'Unpublished'),
(PUBLISHED, 'Published'),
(NEEDS_UPDATE, 'Needs Update'),
)
def get_signature(params, signkey):
# sorted k,v pairs of everything but signature
data = sorted([(k,v.encode('utf-8')) for k,v in params.iteritems() if k != 'signature'])
qs = urllib.urlencode(data)
return hmac.new(str(signkey), qs, hashlib.sha1).hexdigest()
def apicall(url, signkey, **params):
params['signature'] = get_signature(params, signkey)
data = sorted([(k,v) for k,v in params.iteritems()])
body = urllib.urlencode(data)
urllib2.urlopen(url, body)
|
import hashlib
import hmac
import urllib, urllib2
KEY_STATUSES = (
('U', 'Unactivated'),
('A', 'Active'),
('S', 'Suspended')
)
UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3)
PUB_STATUSES = (
(UNPUBLISHED, 'Unpublished'),
(PUBLISHED, 'Published'),
(NEEDS_UPDATE, 'Needs Update'),
)
def get_signature(params, signkey):
# sorted k,v pairs of everything but signature
data = sorted([(k,v) for k,v in params.iteritems() if k != 'signature'])
qs = urllib.urlencode(data)
return hmac.new(str(signkey), qs, hashlib.sha1).hexdigest()
def apicall(url, signkey, **params):
params['signature'] = get_signature(params, signkey)
data = sorted([(k,v) for k,v in params.iteritems()])
body = urllib.urlencode(data)
urllib2.urlopen(url, body)
|
Revert URL redirect (didn't work)
|
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.views.upload', name="fb_upload"),
url(r'^rename/$', 'filebrowser.views.rename', name="fb_rename"),
url(r'^delete/$', 'filebrowser.views.delete', name="fb_delete"),
url(r'^versions/$', 'filebrowser.views.versions', name="fb_versions"),
url(r'^check_file/$', 'filebrowser.views._check_file', name="fb_check"),
url(r'^upload_file/$', 'filebrowser.views._upload_file', name="fb_do_upload"),
)
|
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1'}, name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.views.upload', name="fb_upload"),
url(r'^rename/$', 'filebrowser.views.rename', name="fb_rename"),
url(r'^delete/$', 'filebrowser.views.delete', name="fb_delete"),
url(r'^versions/$', 'filebrowser.views.versions', name="fb_versions"),
url(r'^check_file/$', 'filebrowser.views._check_file', name="fb_check"),
url(r'^upload_file/$', 'filebrowser.views._upload_file', name="fb_do_upload"),
)
|
Put in correct jelly DXS paths
|
package com.walkertribe.ian.enums;
import com.walkertribe.ian.Context;
import com.walkertribe.ian.model.Model;
/**
* The types of creatures. Note: For some reason, wrecks count as creatures.
* @author rwalker
*/
public enum CreatureType {
TYPHON(null),
WHALE("dat/whale.dxs"),
SHARK("dat/monster-sha.dxs"),
DRAGON("dat/monster-drag.dxs"),
PIRANHA("dat/monster-pira.dxs,dat/monster-pira-jaw.dxs"),
CHARYBDIS("dat/monster-cone.dxs"),
NSECT("dat/monster-bug.dxs"),
JELLY("dat/jelly-body.dxs,dat/jelly-crown.dxs"),
WRECK("dat/derelict.dxs");
private String modelPaths;
CreatureType(String modelPaths) {
this.modelPaths = modelPaths;
}
/**
* Returns the Model object for this creature, using the PathResolver from
* the given VesselData, or null if it has no model. (The "classic" space
* monster is made of multiple rotating parts and is not a simple model,
* thus it will return null.)
*/
public Model getModel(Context ctx) {
return modelPaths != null ? ctx.getModel(modelPaths) : null;
}
}
|
package com.walkertribe.ian.enums;
import com.walkertribe.ian.Context;
import com.walkertribe.ian.model.Model;
/**
* The types of creatures. Note: For some reason, wrecks count as creatures.
* @author rwalker
*/
public enum CreatureType {
TYPHON(null),
WHALE("dat/whale.dxs"),
SHARK("dat/monster-sha.dxs"),
DRAGON("dat/monster-drag.dxs"),
PIRANHA("dat/monster-pira.dxs,dat/monster-pira-jaw.dxs"),
CHARYBDIS("dat/monster-cone.dxs"),
NSECT("dat/monster-bug.dxs"),
JELLY("dat/monster-jelly.dxs"), // TODO confirm jelly DXS
WRECK("dat/derelict.dxs");
private String modelPaths;
CreatureType(String modelPaths) {
this.modelPaths = modelPaths;
}
/**
* Returns the Model object for this creature, using the PathResolver from
* the given VesselData, or null if it has no model. (The "classic" space
* monster is made of multiple rotating parts and is not a simple model,
* thus it will return null.)
*/
public Model getModel(Context ctx) {
return modelPaths != null ? ctx.getModel(modelPaths) : null;
}
}
|
Add `delimiter` and `html_map` to HTML formatter and do not register it by default
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
|
Fix data serialization causing app not to receive data when launched from notification
|
package se.hyperlab.tigcm;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.KrollDict;
import java.util.HashMap;
public class NotificationActivity extends Activity {
private static final String TAG = "NotificationActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);
TiGCMModule module = TiGCMModule.getInstance();
TiApplication instance = TiApplication.getInstance();
if(module != null) {
module.fireMessage(data, false);
} else {
KrollDict kdata = new KrollDict(data);
TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, kdata.toString());
Log.d(TAG, "Saving data in props: " + kdata.toString());
}
String pkg = instance.getApplicationContext().getPackageName();
Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);
startActivity(launcherIntent);
finish();
}
}
|
package se.hyperlab.tigcm;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import java.util.HashMap;
public class NotificationActivity extends Activity {
private static final String TAG = "NotificationActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);
TiGCMModule module = TiGCMModule.getInstance();
TiApplication instance = TiApplication.getInstance();
if(module != null) {
module.fireMessage(data, false);
} else {
TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, data.toString());
Log.d(TAG, "Saving data in props: " + data.toString());
}
String pkg = instance.getApplicationContext().getPackageName();
Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);
startActivity(launcherIntent);
finish();
}
}
|
Remove one more obsolete match
|
// Documents list and user data
'use strict';
var renderDocumentsList = require('./components/business-process-documents-list')
, renderCertificateList = require('./components/business-process-certificates-list')
, renderPaymentList = require('./components/business-process-payments-list');
exports._parent = require('./business-process-official');
exports['tab-business-process-documents'] = { class: { active: true } };
exports['tab-content'] = function () {
var options = { urlPrefix: '/' + this.businessProcess.__id__ + '/' };
return section(
{ class: 'section-primary' },
div(
{ class: "section-primary-sub all-documents-table" },
div(renderCertificateList(this.businessProcess, options)),
div(renderDocumentsList(this.businessProcess, options)),
div(renderPaymentList(this.businessProcess, options))
),
div({ id: 'selection-preview' })
);
};
|
// Documents list and user data
'use strict';
var renderDocumentsList = require('./components/business-process-documents-list')
, renderCertificateList = require('./components/business-process-certificates-list')
, renderPaymentList = require('./components/business-process-payments-list');
exports._parent = require('./business-process-official');
exports._match = 'businessProcess';
exports['tab-business-process-documents'] = { class: { active: true } };
exports['tab-content'] = function () {
var options = { urlPrefix: '/' + this.businessProcess.__id__ + '/' };
return section(
{ class: 'section-primary' },
div(
{ class: "section-primary-sub all-documents-table" },
div(renderCertificateList(this.businessProcess, options)),
div(renderDocumentsList(this.businessProcess, options)),
div(renderPaymentList(this.businessProcess, options))
),
div({ id: 'selection-preview' })
);
};
|
Allow disabling password and token auth on jupyter notebooks
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
password = os.environ['PASSWORD']
if password:
c.NotebookApp.password = passwd(password)
else:
c.NotebookApp.password = ''
c.NotebookApp.token = ''
del os.environ['PASSWORD']
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
|
Add fallback to api-usage example
|
import React from 'react'
import ReactDOM from 'react-dom'
import ReactSVG from 'react-svg'
ReactDOM.render(
<ReactSVG
// Required props.
src="svg.svg"
// Optional props.
evalScripts="always"
fallback={<span>Error!</span>}
onInjected={(error, svg) => {
if (error) {
console.error(error)
return
}
console.log(svg)
}}
renumerateIRIElements={false}
svgClassName="svg-class-name"
svgStyle={{ width: 200 }}
// Non-documented props.
className="wrapper-class-name"
onClick={() => {
console.log('wrapper onClick')
}}
/>,
document.getElementById('root')
)
|
import React from 'react'
import ReactDOM from 'react-dom'
import ReactSVG from 'react-svg'
ReactDOM.render(
<ReactSVG
// Required props.
src="svg.svg"
// Optional props.
evalScripts="always"
onInjected={(error, svg) => {
if (error) {
console.error(error)
return
}
console.log(svg)
}}
renumerateIRIElements={false}
svgClassName="svg-class-name"
svgStyle={{ width: 200 }}
// Non-documented props.
className="wrapper-class-name"
onClick={() => {
console.log('wrapper onClick')
}}
/>,
document.getElementById('root')
)
|
Fix & cleanup profile genesis tests
|
from pprint import pprint
import pytest
from ethereum import blocks
from ethereum.db import DB
from ethereum.config import Env
from pyethapp.utils import merge_dict
from pyethapp.utils import update_config_from_genesis_json
import pyethapp.config as konfig
from pyethapp.profiles import PROFILES
@pytest.mark.parametrize('profile', PROFILES.keys())
def test_profile(profile):
config = dict(eth=dict())
konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}})
# Set config values based on profile selection
merge_dict(config, PROFILES[profile])
# Load genesis config
update_config_from_genesis_json(config, config['eth']['genesis'])
bc = config['eth']['block']
pprint(bc)
env = Env(DB(), bc)
genesis = blocks.genesis(env)
assert genesis.hash.encode('hex') == config['eth']['genesis_hash']
|
import pytest
from ethereum import blocks
from ethereum.db import DB
from ethereum.config import Env
from pyethapp.utils import merge_dict
from pyethapp.utils import update_config_from_genesis_json
import pyethapp.config as konfig
from pyethapp.profiles import PROFILES
def check_genesis(profile):
config = dict(eth=dict())
# Set config values based on profile selection
merge_dict(config, PROFILES[profile])
# Load genesis config
update_config_from_genesis_json(config, config['eth']['genesis'])
konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}})
print config['eth'].keys()
bc = config['eth']['block']
print bc.keys()
env = Env(DB(), bc)
genesis = blocks.genesis(env)
print 'genesis.hash', genesis.hash.encode('hex')
print 'expected', config['eth']['genesis_hash']
assert genesis.hash == config['eth']['genesis_hash'].decode('hex')
@pytest.mark.xfail # FIXME
def test_olympic():
check_genesis('olympic')
def test_frontier():
check_genesis('frontier')
if __name__ == '__main__':
test_genesis()
|
Add hooks for element add and remove.
|
define(['dib',
'events',
'class'],
function(Dib, Emitter, clazz) {
function Controller() {
Emitter.call(this);
this._init();
}
clazz.inherits(Controller, Emitter);
Controller.prototype._init = function() {
var dib = new Dib(this.template)
, locals = this.willLoadDib()
, element;
if (this.tagName || this.className || this.attributes || this.id) {
element = {}
element.tag = this.tagName || 'div';
element.attrs = this.attributes || {};
if (this.id) element.attrs['id'] = this.id;
if (this.className) element.attrs['class'] = this.className;
}
dib.container(element)
.events(this.events, this);
// TODO: Implement support in `Dib` for automatically instantiating views,
// which will work similarly to automatic event binding.
this.el = dib.create(locals);
this.didLoadDib();
}
Controller.prototype.willLoadDib = function() {};
Controller.prototype.didLoadDib = function() {};
Controller.prototype.willAddEl = function() {};
Controller.prototype.didAddEl = function() {};
Controller.prototype.willRemoveEl = function() {};
Controller.prototype.didRemoveEl = function() {};
return Controller;
});
|
define(['dib',
'events',
'class'],
function(Dib, Emitter, clazz) {
function Controller() {
Emitter.call(this);
this._init();
}
clazz.inherits(Controller, Emitter);
Controller.prototype._init = function() {
var dib = new Dib(this.template)
, locals = this.willLoadDib()
, element;
if (this.tagName || this.className || this.attributes || this.id) {
element = {}
element.tag = this.tagName || 'div';
element.attrs = this.attributes || {};
if (this.id) element.attrs['id'] = this.id;
if (this.className) element.attrs['class'] = this.className;
}
dib.container(element)
.events(this.events, this);
// TODO: Implement support in `Dib` for automatically instantiating views,
// which will work similarly to automatic event binding.
this.el = dib.create(locals);
this.didLoadDib();
}
Controller.prototype.willLoadDib = function() {};
Controller.prototype.didLoadDib = function() {};
return Controller;
});
|
Modify initialization to be more properly for CsvTableWriter class
|
from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
|
from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
|
:tada: Add optional dependency for collation
|
# -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = [
'jinja2',
'lxml',
]
collation_requires = [
'cnx-easybake',
]
tests_require = [
]
tests_require.extend(collation_requires)
extras_require = {
'collation': collation_requires,
'test': tests_require,
}
description = "Library for building and paring Connexions' EPUBs."
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-epub',
version='0.8.0',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-epub",
license='AGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
packages=find_packages(),
include_package_data=True,
entry_points={
'console_scripts': [
'cnx-epub-single_html = cnxepub.scripts.single_html.main:main',
],
},
test_suite='cnxepub.tests',
zip_safe=False,
)
|
# -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = [
'jinja2',
'lxml',
]
tests_require = [
]
extras_require = {
'test': tests_require,
}
description = "Library for building and paring Connexions' EPUBs."
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-epub',
version='0.8.0',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-epub",
license='AGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
packages=find_packages(),
include_package_data=True,
entry_points={
'console_scripts': [
'cnx-epub-single_html = cnxepub.scripts.single_html.main:main',
],
},
test_suite='cnxepub.tests',
zip_safe=False,
)
|
Check and create the tests file folder using an absolute path
|
from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import mock_requests
# make pyflakes STFU
assert mock_requests
class BaseTest(object):
files = 'tests/files'
organised = 'tests/data/organised'
renamed = 'tests/data/renamed'
def setup(self):
# absolute path to the file is pretty useful
self.path = abspath(dirname(__file__))
# if `file` isn't there, make it
if not exists(join(self.path, self.files)):
mkdir(join(self.path, self.files))
# build the file list
with open(join(self.path, 'file_list'), 'r') as f:
for fn in f.readlines():
with open(abspath(join(self.files, fn.strip())), 'w') as f:
f.write('')
# instantiate tvr
self.config = Config(join(self.path, 'config.yml'))
self.tv = TvRenamr(self.files, self.config)
def teardown(self):
rmtree(self.files)
|
from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import mock_requests
# make pyflakes STFU
assert mock_requests
class BaseTest(object):
files = 'tests/files'
organised = 'tests/data/organised'
renamed = 'tests/data/renamed'
def setup(self):
# if `file` isn't there, make it
if not exists(self.files):
mkdir(self.files)
# absolute path to the file is pretty useful
self.path = abspath(dirname(__file__))
# build the file list
with open(join(self.path, 'file_list'), 'r') as f:
for fn in f.readlines():
with open(abspath(join(self.files, fn.strip())), 'w') as f:
f.write('')
# instantiate tvr
self.config = Config(join(self.path, 'config.yml'))
self.tv = TvRenamr(self.files, self.config)
def teardown(self):
rmtree(self.files)
|
Speed up test runs in `WaitForResult`
|
package testutil
import (
"time"
"testing"
"github.com/hashicorp/consul/consul/structs"
)
type testFn func() (bool, error)
type errorFn func(error)
func WaitForResult(test testFn, error errorFn) {
retries := 1000
for retries > 0 {
time.Sleep(10 * time.Millisecond)
retries--
success, err := test()
if success {
return
}
if retries == 0 {
error(err)
}
}
}
type rpcFn func(string, interface {}, interface {}) error
func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
var out structs.IndexedNodes
WaitForResult(func() (bool, error) {
args := &structs.RegisterRequest{
Datacenter: dc,
}
err := rpc("Catalog.ListNodes", args, &out)
return out.QueryMeta.KnownLeader, err
}, func(err error) {
t.Fatalf("failed to find leader: %v", err)
})
return out
}
|
package testutil
import (
"time"
"testing"
"github.com/hashicorp/consul/consul/structs"
)
type testFn func() (bool, error)
type errorFn func(error)
func WaitForResult(test testFn, error errorFn) {
retries := 100
for retries > 0 {
time.Sleep(100 * time.Millisecond)
retries--
success, err := test()
if success {
return
}
if retries == 0 {
error(err)
}
}
}
type rpcFn func(string, interface {}, interface {}) error
func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
var out structs.IndexedNodes
WaitForResult(func() (bool, error) {
args := &structs.RegisterRequest{
Datacenter: dc,
}
err := rpc("Catalog.ListNodes", args, &out)
return out.QueryMeta.KnownLeader, err
}, func(err error) {
t.Fatalf("failed to find leader: %v", err)
})
return out
}
|
Switch to new spec update command.
|
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SetupCommand extends Command
{
protected $signature = 'setup';
protected $description = 'Runs all commands necessary for initial setup of the application.';
public function handle()
{
$this->info('Setting up the application...');
$this->call('down');
if (!file_exists(base_path('.env'))) {
copy(base_path('.env.example'), base_path('.env'));
}
touch(storage_path('database.sqlite'));
$this->call('migrate');
$this->call('oparl:update:specification');
$this->call('optimize');
$this->call('up');
}
}
|
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SetupCommand extends Command
{
protected $signature = 'setup';
protected $description = 'Runs all commands necessary for initial setup of the application.';
public function handle()
{
$this->info('Setting up the application...');
$this->call('down');
if (!file_exists(base_path('.env'))) {
copy(base_path('.env.example'), base_path('.env'));
}
touch(storage_path('database.sqlite'));
$this->call('migrate');
$this->call('specification:live', ['--force']);
$this->call('specification:update');
$this->call('optimize');
$this->call('up');
}
}
|
Fix Lexer [else with subject] exception
|
<?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\State;
use Phug\Lexer\Token\ConditionalToken;
class ConditionalScanner extends ControlStatementScanner
{
public function __construct()
{
parent::__construct(
ConditionalToken::class,
['if', 'unless', 'else[ \t]*if', 'else']
);
}
public function scan(State $state)
{
foreach (parent::scan($state) as $token) {
if ($token instanceof ConditionalToken) {
//Make sure spaces are replaced from `elseif`/`else if` to make a final keyword, "elseif"
$token->setName(preg_replace('/[ \t]/', '', $token->getName()));
if ($token->getName() === 'else' && !in_array($token->getSubject(), ['', false, null])) {
$state->throwException(
'The `else`-conditional statement can\'t have a subject'
);
}
}
yield $token;
}
}
}
|
<?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\State;
use Phug\Lexer\Token\ConditionalToken;
class ConditionalScanner extends ControlStatementScanner
{
public function __construct()
{
parent::__construct(
ConditionalToken::class,
['if', 'unless', 'else[ \t]*if', 'else']
);
}
public function scan(State $state)
{
foreach (parent::scan($state) as $token) {
if ($token instanceof ConditionalToken) {
//Make sure spaces are replaced from `elseif`/`else if` to make a final keyword, "elseif"
$token->setName(preg_replace('/[ \t]/', '', $token->getName()));
if ($token->getName() === 'else' && !in_array($token->getSubject(), ['', false, null])) {
$state->throwException(
'The `else`-conditional statement can\'t have a subject',
$token
);
}
}
yield $token;
}
}
}
|
Make use of auto generated table classes.
|
from cruditor.contrib.collection import CollectionViewMixin
from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView
from django.urls import reverse, reverse_lazy
from examples.mixins import ExamplesMixin
from store.models import Person
from .filters import PersonFilter
from .forms import PersonForm
from .tables import PersonTable
class PersonViewMixin(ExamplesMixin, CollectionViewMixin):
model = Person
collection_list_title = 'Persons'
collection_list_urlname = 'collection:list'
collection_detail_urlname = 'collection:change'
class PersonListView(PersonViewMixin, CruditorListView):
title = 'Persons'
def get_titlebuttons(self):
return [{'url': reverse('collection:add'), 'label': 'Add person'}]
class PersonFilterView(PersonListView):
filter_class = PersonFilter
table_class = PersonTable
class PersonAddView(PersonViewMixin, CruditorAddView):
success_url = reverse_lazy('collection:lits')
form_class = PersonForm
class PersonChangeView(PersonViewMixin, CruditorChangeView):
form_class = PersonForm
def get_delete_url(self):
return reverse('collection:delete', args=(self.object.pk,))
class PersonDeleteView(PersonViewMixin, CruditorDeleteView):
pass
|
from cruditor.contrib.collection import CollectionViewMixin
from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView
from django.urls import reverse, reverse_lazy
from examples.mixins import ExamplesMixin
from store.models import Person
from .filters import PersonFilter
from .forms import PersonForm
from .tables import PersonTable
class PersonViewMixin(ExamplesMixin, CollectionViewMixin):
model = Person
collection_list_title = 'Persons'
collection_list_urlname = 'collection:list'
collection_detail_urlname = 'collection:change'
class PersonListView(PersonViewMixin, CruditorListView):
title = 'Persons'
table_class = PersonTable
def get_titlebuttons(self):
return [{'url': reverse('collection:add'), 'label': 'Add person'}]
class PersonFilterView(PersonListView):
filter_class = PersonFilter
class PersonAddView(PersonViewMixin, CruditorAddView):
success_url = reverse_lazy('collection:lits')
form_class = PersonForm
class PersonChangeView(PersonViewMixin, CruditorChangeView):
form_class = PersonForm
def get_delete_url(self):
return reverse('collection:delete', args=(self.object.pk,))
class PersonDeleteView(PersonViewMixin, CruditorDeleteView):
pass
|
Add missing requirement to example app
|
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = TEMPLATE_DEBUG = True
SECRET_KEY = 'example-app!'
ROOT_URLCONF = 'example.urls'
STATIC_URL = '/static/'
DATABASES = {'default': dj_database_url.config(
default='postgres://localhost/conman_example',
)}
DATABASES['default']['ATOMIC_REQUESTS'] = True
INSTALLED_APPS = (
'conman.routes',
'conman.pages',
'conman.redirects',
'polymorphic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
|
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = TEMPLATE_DEBUG = True
SECRET_KEY = 'example-app!'
ROOT_URLCONF = 'example.urls'
STATIC_URL = '/static/'
DATABASES = {'default': dj_database_url.config(
default='postgres://localhost/conman_example',
)}
DATABASES['default']['ATOMIC_REQUESTS'] = True
INSTALLED_APPS = (
'conman.routes',
'conman.pages',
'conman.redirects',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
|
Change old IETF reference link
Old link will throw 404, so it could be replaced with new working one
|
/*
* Copyright (C) 2013 Square, 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Denotes that the request body will use form URL encoding. Fields should be declared as parameters
* and annotated with {@link Field @Field}.
*
* <p>Requests made with this annotation will have {@code application/x-www-form-urlencoded} MIME
* type. Field names and values will be UTF-8 encoded before being URI-encoded in accordance to <a
* href="https://datatracker.ietf.org/doc/html/rfc3986">RFC-3986</a>.
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface FormUrlEncoded {}
|
/*
* Copyright (C) 2013 Square, 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Denotes that the request body will use form URL encoding. Fields should be declared as parameters
* and annotated with {@link Field @Field}.
*
* <p>Requests made with this annotation will have {@code application/x-www-form-urlencoded} MIME
* type. Field names and values will be UTF-8 encoded before being URI-encoded in accordance to <a
* href="http://tools.ietf.org/html/rfc3986">RFC-3986</a>.
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface FormUrlEncoded {}
|
Include recommended on eslint config
|
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'eslint:recommended',
'vue'
],
// add your custom rules here
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
|
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
|
Change to the Stripes test fixture to supply the new init-param ActionResolver.Packages
git-svn-id: eee8cf2eb4cac5fd9f9d7b672efb1c285d99a606@436 d471f07e-d8fc-0310-a67b-dd4c8ff0e7cd
|
package net.sourceforge.stripes;
import net.sourceforge.stripes.mock.MockServletContext;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.controller.DispatcherServlet;
import java.util.Map;
import java.util.HashMap;
/**
* Test fixture that sets up a MockServletContext in a way that it can then be
* used be any test in Stripes.
*
* @author Tim Fennell
*/
public class StripesTestFixture {
private static MockServletContext context;
/**
* Gets a reference to the test MockServletContext. If the context is not already
* instantiated and setup, it will be built lazily.
*
* @return an instance of MockServletContext for testing wiith
*/
public static synchronized MockServletContext getServletContext() {
if (context == null) {
context = new MockServletContext("test");
// Add the Stripes Filter
Map<String,String> filterParams = new HashMap<String,String>();
filterParams.put("ActionResolver.Packages", "net.sourceforge.stripes");
context.addFilter(StripesFilter.class, "StripesFilter", filterParams);
// Add the Stripes Dispatcher
context.setServlet(DispatcherServlet.class, "StripesDispatcher", null);
}
return context;
}
}
|
package net.sourceforge.stripes;
import net.sourceforge.stripes.mock.MockServletContext;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.controller.DispatcherServlet;
import java.util.Map;
import java.util.HashMap;
/**
* Test fixture that sets up a MockServletContext in a way that it can then be
* used be any test in Stripes.
*
* @author Tim Fennell
*/
public class StripesTestFixture {
private static MockServletContext context;
/**
* Gets a reference to the test MockServletContext. If the context is not already
* instantiated and setup, it will be built lazily.
*
* @return an instance of MockServletContext for testing wiith
*/
public static synchronized MockServletContext getServletContext() {
if (context == null) {
context = new MockServletContext("test");
// Add the Stripes Filter
Map<String,String> filterParams = new HashMap<String,String>();
filterParams.put("ActionResolver.UrlFilters", "tests");
filterParams.put("ActionResolver.PackageFilters", "net.sourceforge.stripes.*");
context.addFilter(StripesFilter.class, "StripesFilter", filterParams);
// Add the Stripes Dispatcher
context.setServlet(DispatcherServlet.class, "StripesDispatcher", null);
}
return context;
}
}
|
Drop alpha tag from package
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
fix: Remove misleading and unnecessary comments
|
angular.module('snap')
.factory('snapRemote', ['$q', function($q) {
'use strict';
// Provide direct access to the snapper object and a few convenience methods
// for our directives.
var deferred = $q.defer()
, exports;
exports = {
get: function() {
return deferred.promise;
},
register: function(snapper) {
deferred.resolve(snapper);
},
toggle: function(side) {
exports.get().then(function(snapper) {
if(side === snapper.state().state) {
exports.close(side);
} else {
exports.open(side);
}
});
},
open: function(side) {
exports.get().then(function(snapper) {
snapper.open(side);
});
},
close: function() {
exports.get().then(function(snapper) {
snapper.close();
});
}
};
return exports;
}]);
|
angular.module('snap')
.factory('snapRemote', ['$q', function($q) {
'use strict';
// Provide direct access to the snapper object and a few convenience methods
// for our directives.
var deferred = $q.defer()
, exports;
exports = {
// Returns null until our `snap-content` initializes
get: function() {
return deferred.promise;
},
// Eventually we may want to allow for multiple snap instances
register: function(snapper) {
deferred.resolve(snapper);
},
toggle: function(side) {
exports.get().then(function(snapper) {
if(side === snapper.state().state) {
exports.close(side);
} else {
exports.open(side);
}
});
},
open: function(side) {
exports.get().then(function(snapper) {
snapper.open(side);
});
},
close: function() {
exports.get().then(function(snapper) {
snapper.close();
});
}
};
return exports;
}]);
|
fs: Add MimeTypeDirEntry to return the MimeType of a DirEntry
|
package fs
import (
"mime"
"path"
"strings"
)
// MimeTypeFromName returns a guess at the mime type from the name
func MimeTypeFromName(remote string) (mimeType string) {
mimeType = mime.TypeByExtension(path.Ext(remote))
if !strings.ContainsRune(mimeType, '/') {
mimeType = "application/octet-stream"
}
return mimeType
}
// MimeType returns the MimeType from the object, either by calling
// the MimeTyper interface or using MimeTypeFromName
func MimeType(o ObjectInfo) (mimeType string) {
// Read the MimeType from the optional interface if available
if do, ok := o.(MimeTyper); ok {
mimeType = do.MimeType()
// Debugf(o, "Read MimeType as %q", mimeType)
if mimeType != "" {
return mimeType
}
}
return MimeTypeFromName(o.Remote())
}
// MimeTypeDirEntry returns the MimeType of a DirEntry
//
// It returns "inode/directory" for directories, or uses
// MimeType(Object)
func MimeTypeDirEntry(item DirEntry) string {
switch x := item.(type) {
case Object:
return MimeType(x)
case Directory:
return "inode/directory"
}
return ""
}
|
package fs
import (
"mime"
"path"
"strings"
)
// MimeTypeFromName returns a guess at the mime type from the name
func MimeTypeFromName(remote string) (mimeType string) {
mimeType = mime.TypeByExtension(path.Ext(remote))
if !strings.ContainsRune(mimeType, '/') {
mimeType = "application/octet-stream"
}
return mimeType
}
// MimeType returns the MimeType from the object, either by calling
// the MimeTyper interface or using MimeTypeFromName
func MimeType(o ObjectInfo) (mimeType string) {
// Read the MimeType from the optional interface if available
if do, ok := o.(MimeTyper); ok {
mimeType = do.MimeType()
// Debugf(o, "Read MimeType as %q", mimeType)
if mimeType != "" {
return mimeType
}
}
return MimeTypeFromName(o.Remote())
}
|
social/handler: Delete endpoint is added for notification setting
|
package notificationsettings
import (
"socialapi/workers/common/handler"
"socialapi/workers/common/mux"
)
func AddHandlers(m *mux.Mux) {
m.AddHandler(
handler.Request{
Handler: Create,
Name: "notification-settings-create",
Type: handler.PostRequest,
Endpoint: "/channel/{id}/notificationsettings",
},
)
m.AddHandler(
handler.Request{
Handler: Get,
Name: "notification-settings-get",
Type: handler.GetRequest,
Endpoint: "/channel/{id}/notificationsettings",
},
)
m.AddHandler(
handler.Request{
Handler: Update,
Name: "notification-settings-update",
Type: handler.PostRequest,
Endpoint: "/notificationsettings/{id}",
},
)
m.AddHandler(
handler.Request{
Handler: Delete,
Name: "notification-settings-delete",
Type: handler.DeleteRequest,
Endpoint: "/channel/{id}/notificationsettings",
},
)
}
|
package notificationsettings
import (
"socialapi/workers/common/handler"
"socialapi/workers/common/mux"
)
func AddHandlers(m *mux.Mux) {
m.AddHandler(
handler.Request{
Handler: Create,
Name: "notification-settings-create",
Type: handler.PostRequest,
Endpoint: "/channel/{id}/notificationsettings",
},
)
m.AddHandler(
handler.Request{
Handler: Get,
Name: "notification-settings-list",
Type: handler.GetRequest,
Endpoint: "/notificationsettings/{id}",
},
)
m.AddHandler(
handler.Request{
Handler: Update,
Name: "notification-settings-update",
Type: handler.PostRequest,
Endpoint: "/notificationsettings/{id}",
},
)
}
|
:shirt: Fix lint issue for spec
|
'use babel'
import { React, TestUtils } from 'react-for-atom'
import TagsComponent from '../../../lib/react/cells/tags-component'
describe('react/cells/tags-component', function () {
let renderer, r, tags
beforeEach(function () {
renderer = TestUtils.createRenderer()
tags = 'a b c'
})
it('renders tags as indidvidual items', function () {
renderer.render(<TagsComponent tags={tags} isSelected={false} />)
r = renderer.getRenderOutput()
expect(r.props.children.length).toBe(3)
expect(r.props.children[0]).toEqual(<span key='a' className='inline-block highlight'>a</span>)
expect(r.props.children[1]).toEqual(<span key='b' className='inline-block highlight'>b</span>)
expect(r.props.children[2]).toEqual(<span key='c' className='inline-block highlight'>c</span>)
})
it('does nothing on click since not selected', function () {
r.props.onClick()
expect(r.props.children.length).toBe(3)
})
describe('when clicked and is selected', function () {
beforeEach(function () {
renderer.render(<TagsComponent tags={tags} isSelected />)
r = renderer.getRenderOutput()
r.props.onClick()
r = renderer.getRenderOutput() // to get updated output
})
it('should render an edit component instead', function () {
expect(r.props.children.type.displayName).toEqual('edit-component')
})
})
})
|
'use babel'
import { React, TestUtils } from 'react-for-atom'
import TagsComponent from '../../../lib/react/cells/tags-component'
describe('react/cells/tags-component', function () {
let renderer, r, tags
beforeEach(function () {
renderer = TestUtils.createRenderer()
tags = 'a b c'
})
it('renders tags as indidvidual items', function () {
renderer.render(<TagsComponent tags={tags} isSelected={false} />)
r = renderer.getRenderOutput()
expect(r.props.children.length).toBe(3)
expect(r.props.children[0]).toEqual(<span key='a' className='inline-block highlight'>a</span>)
expect(r.props.children[1]).toEqual(<span key='b' className='inline-block highlight'>b</span>)
expect(r.props.children[2]).toEqual(<span key='c' className='inline-block highlight'>c</span>)
})
it('does nothing on click since not selected', function () {
r.props.onClick()
expect(r.props.children.length).toBe(3)
})
describe('when clicked and is selected', function () {
beforeEach(function () {
renderer.render(<TagsComponent tags={tags} isSelected={true} />)
r = renderer.getRenderOutput()
r.props.onClick()
r = renderer.getRenderOutput() // to get updated output
})
it('should render an edit component instead', function () {
expect(r.props.children.type.displayName).toEqual('edit-component')
})
})
})
|
Add godoc to Persist method.
|
// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package index
import (
"encoding/json"
"io"
"os"
)
// PersistStore is a type which defines a simple persistence store.
type PersistStore string
// NewPersistStore creates a new PersistStore. By default PersistStore uses
// JSON to persist data.
func NewPersistStore(path string, data interface{}) (PersistStore, error) {
f, err := os.Open(path)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
f, err = os.Create(path)
if err != nil {
return "", err
}
}
defer f.Close()
dec := json.NewDecoder(f)
err = dec.Decode(data)
if err != nil && err != io.EOF {
return "", err
}
return PersistStore(path), nil
}
// Persist writes the data to the underlying data store, overwriting any previous data.
func (p PersistStore) Persist(data interface{}) error {
f, err := os.Create(string(p))
if err != nil {
return err
}
defer f.Close()
b, err := json.Marshal(data)
if err != nil {
return err
}
_, err = f.Write(b)
return err
}
|
// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package index
import (
"encoding/json"
"io"
"os"
)
// PersistStore is a type which defines a simple persistence store.
type PersistStore string
// NewPersistStore creates a new PersistStore. By default PersistStore uses
// JSON to persist data.
func NewPersistStore(path string, data interface{}) (PersistStore, error) {
f, err := os.Open(path)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
f, err = os.Create(path)
if err != nil {
return "", err
}
}
defer f.Close()
dec := json.NewDecoder(f)
err = dec.Decode(data)
if err != nil && err != io.EOF {
return "", err
}
return PersistStore(path), nil
}
func (p PersistStore) Persist(data interface{}) error {
f, err := os.Create(string(p))
if err != nil {
return err
}
defer f.Close()
b, err := json.Marshal(data)
if err != nil {
return err
}
_, err = f.Write(b)
return err
}
|
Logs: Set stdout log level to trace
|
/**
* This file sets up the logging system and also sets up the
* external logs system if enabled in the config.
*
* The log module will be called by the whole application a lot
* during its lifetime and is expected to implement the following methods:
* child(), trace(), debug(), info(), warn(), error(), fatal(), flushQueue().
*/
let bunyan = require("bunyan");
let streams = [{
level: "trace",
stream: process.stdout,
}];
let externalSystem;
let reqSerializer = (req) => {
var filteredReq = {
method: req.method,
url: req.url,
ip: req.ip,
};
return filteredReq;
};
let logger = bunyan.createLogger({
name: "ratp-api",
streams: streams,
serializers: {
req: reqSerializer,
res: bunyan.stdSerializers.res,
err: bunyan.stdSerializers.err,
},
});
logger.flushQueue = () => {
if (externalSystem) {
externalSystem.flushQueue();
}
};
module.exports = logger;
|
/**
* This file sets up the logging system and also sets up the
* external logs system if enabled in the config.
*
* The log module will be called by the whole application a lot
* during its lifetime and is expected to implement the following methods:
* child(), trace(), debug(), info(), warn(), error(), fatal(), flushQueue().
*/
let bunyan = require("bunyan");
let streams = [{
level: "debug",
stream: process.stdout,
}];
let externalSystem;
let reqSerializer = (req) => {
var filteredReq = {
method: req.method,
url: req.url,
ip: req.ip,
};
return filteredReq;
};
let logger = bunyan.createLogger({
name: "ratp-api",
streams: streams,
serializers: {
req: reqSerializer,
res: bunyan.stdSerializers.res,
err: bunyan.stdSerializers.err,
},
});
logger.flushQueue = () => {
if (externalSystem) {
externalSystem.flushQueue();
}
};
module.exports = logger;
|
Remove mocked dependencies for readthedocs
|
import os
import re
from setuptools import find_packages, setup
from dichalcogenides import __version__
with open('README.rst', 'r') as f:
long_description = f.read()
if os.environ.get('READTHEDOCS') == 'True':
mocked = ['numpy', 'scipy']
mock_filter = lambda x: re.sub(r'>.+', '', x) not in mocked
else:
mock_filter = lambda p: True
setup(
name='dichalcogenides',
version=__version__,
author='Evan Sosenko',
author_email='razorx@evansosenko.com',
packages=find_packages(exclude=['docs']),
url='https://github.com/razor-x/dichalcogenides',
license='MIT',
description='Python analysis code for dichalcogenide systems.',
long_description=long_description,
install_requires=list(filter(mock_filter, [
'numpy>=1.11.0,<2.0.0',
'scipy>=0.17.0,<1.0.0',
'pyyaml>=3.11,<4.0'
]))
)
|
from setuptools import find_packages, setup
from dichalcogenides import __version__
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='dichalcogenides',
version=__version__,
author='Evan Sosenko',
author_email='razorx@evansosenko.com',
packages=find_packages(exclude=['docs']),
url='https://github.com/razor-x/dichalcogenides',
license='MIT',
description='Python analysis code for dichalcogenide systems.',
long_description=long_description,
install_requires=[
'numpy>=1.11.0,<2.0.0',
'scipy>=0.17.0,<1.0.0',
'pyyaml>=3.11,<4.0'
]
)
|
Clean up un-needed commented line after jkrzywon fixed subprocess bad behaviour
|
__version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subprocess.check_output(args,
stderr=FNULL,
shell=True)
__build__ = str(git_revision).strip()
except subprocess.CalledProcessError as cpe:
logging.warning("Error while determining build number\n Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
|
__version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subprocess.check_output(args,
#git_revision = subprocess.check_output(['pwd'],
stderr=FNULL,
shell=True)
__build__ = str(git_revision).strip()
except subprocess.CalledProcessError as cpe:
logging.warning("Error while determining build number\n Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
|
Remove AWS credentioals from build cache config
The plugin uses the AWS CLI default credentials chain to find
the necessary AWS access and secret keys.
|
/*
* Copyright 2017 the original author or authors.
*
* 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 ch.myniva.gradle.caching.s3;
import org.gradle.caching.configuration.AbstractBuildCache;
public class AwsS3BuildCache extends AbstractBuildCache {
private String region;
private String bucket;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
}
|
/*
* Copyright 2017 the original author or authors.
*
* 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 ch.myniva.gradle.caching.s3;
import org.gradle.api.Action;
import org.gradle.api.credentials.AwsCredentials;
import org.gradle.caching.configuration.AbstractBuildCache;
public class AwsS3BuildCache extends AbstractBuildCache {
private AwsCredentials credentials;
private String region;
private String bucket;
/**
* Returns the credentials used to access the AWS S3 bucket.
*/
public AwsCredentials getCredentials() {
return credentials;
}
/**
* Configures the credentials used to access the AWS S3 bucket.
*/
public void credentials(Action<? super AwsCredentials> configuration) {
configuration.execute(credentials);
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
}
|
Fix typo on constructor method name
refs #31
|
<?php
namespace Pragma\Router;
class RouterException extends \Exception{
const GET_CONFIG_ERROR = 1;
const POST_CONFIG_ERROR = 2;
const DELETE_CONFIG_ERROR = 3;
const PATCH_CONFIG_ERROR = 4;
const PUT_CONFIG_ERROR = 5;
const NO_ROUTE_CODE = 6;
const NO_ROUTE_FOR_CODE = 7;
const WRONG_NUMBER_PARAMS_CODE = 8;
const ALREADY_USED_ALIAS_CODE = 9;
const CLI_CONFIG_ERROR = 10;
const WRONG_MAPPING = 'Wrong number of args for route mapping';
const NO_ROUTE = 'No route found';
const NO_ROUTE_FOR = 'This alias doesn\'t seem to exists';
const WRONG_NUMBER_PARAMS = 'Wrong number of parameters for the url_for call';
const ALREADY_USED_ALIAS = 'Alias already used';
public function __construct($message, $code = 0, \Exception $previous = null){
parent::__construct($message, $code, $previous);
}
public function __toString(){
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
|
<?php
namespace Pragma\Router;
class RouterException extends \Exception{
const GET_CONFIG_ERROR = 1;
const POST_CONFIG_ERROR = 2;
const DELETE_CONFIG_ERROR = 3;
const PATCH_CONFIG_ERROR = 4;
const PUT_CONFIG_ERROR = 5;
const NO_ROUTE_CODE = 6;
const NO_ROUTE_FOR_CODE = 7;
const WRONG_NUMBER_PARAMS_CODE = 8;
const ALREADY_USED_ALIAS_CODE = 9;
const CLI_CONFIG_ERROR = 10;
const WRONG_MAPPING = 'Wrong number of args for route mapping';
const NO_ROUTE = 'No route found';
const NO_ROUTE_FOR = 'This alias doesn\'t seem to exists';
const WRONG_NUMBER_PARAMS = 'Wrong number of parameters for the url_for call';
const ALREADY_USED_ALIAS = 'Alias already used';
public function __constructor($message, $code = 0, \Exception $previous = null){
parent::__constructor($message, $code, $previous);
}
public function __toString(){
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
|
Add check on curl extension
|
<?php
// PHP 5.3 minimum
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
die('This software require PHP 5.3.0 minimum');
}
// Short tags must be enabled for PHP < 5.4
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
if (! ini_get('short_open_tag')) {
die('This software require to have short tags enabled, check your php.ini => "short_open_tag = On"');
}
}
// Check XML functions
if (! function_exists('simplexml_load_string')) {
die('PHP extension required: SimpleXML');
}
if (! function_exists('xml_parser_create')) {
die('PHP extension required: XML Parser');
}
if (! function_exists('dom_import_simplexml')) {
die('PHP extension required: DOM');
}
// Check PDO Sqlite
if (! extension_loaded('pdo_sqlite')) {
die('PHP extension required: pdo_sqlite');
}
// Check for curl
if (! function_exists('curl_init')) {
die('PHP extension required: curl');
}
// Check if /data is writeable
if (! is_writable('data')) {
die('The directory "data" must be writeable by your web server user');
}
|
<?php
// PHP 5.3 minimum
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
die('This software require PHP 5.3.0 minimum');
}
// Short tags must be enabled for PHP < 5.4
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
if (! ini_get('short_open_tag')) {
die('This software require to have short tags enabled, check your php.ini => "short_open_tag = On"');
}
}
// Check XML functions
if (! function_exists('simplexml_load_string')) {
die('PHP extension required: SimpleXML');
}
if (! function_exists('xml_parser_create')) {
die('PHP extension required: XML Parser');
}
if (! function_exists('dom_import_simplexml')) {
die('PHP extension required: DOM');
}
// Check PDO Sqlite
if (! extension_loaded('pdo_sqlite')) {
die('PHP extension required: pdo_sqlite');
}
// Check if /data is writeable
if (! is_writable('data')) {
die('The directory "data" must be writeable by your web server user');
}
|
Add stat update packet code
|
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",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
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",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
CLAN_REQ_JOIN: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
DISCONN: "d"
}
|
Solve bug when creating new pages
|
function loadCreator (collectionId) {
var pageType, releaseDate;
getCollection(collectionId,
success = function (response) {
if (!response.publishDate) {
releaseDate = null;
} else {
releaseDate = response.publishDate;
}
},
error = function (response) {
handleApiError(response);
}
);
$('select').off().change(function () {
pageType = $(this).val();
//var parentUrl = localStorage.getItem("pageurl");
var parentUrl = Florence.globalVars.pagePath;
$('.edition').empty();
if (pageType === 'bulletin' || pageType === 'article') {
loadT4Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType.match(/compendium_.+/)) {
loadT6Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType.match(/static_.+/)) {
loadT7Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType === 'reference_tables' || pageType === 'dataset') {
loadT8Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType === 'release') {
loadT16Creator(collectionId, releaseDate, pageType, parentUrl);
}
});
}
|
function loadCreator (collectionId) {
var pageType, releaseDate;
getCollection(collectionId,
success = function (response) {
if (!response.publishDate) {
releaseDate = null;
} else {
releaseDate = response.publishDate;
}
},
error = function (response) {
handleApiError(response);
}
);
$('select').off().change(function () {
pageType = $(this).val();
//var parentUrl = localStorage.getItem("pageurl");
var parentUrl = Florence.globalVars.pagePath;
if (pageType === 'bulletin' || pageType === 'article') {
$('.edition').empty();
loadT4Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType.match(/compendium_.+/)) {
$('.edition').empty();
loadT6Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType.match(/static_.+/)) {
$('.edition').empty();
loadT7Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType === 'reference_tables' || pageType === 'dataset') {
$('.edition').empty();
loadT8Creator(collectionId, releaseDate, pageType, parentUrl);
}
else if (pageType === 'release') {
$('.edition').empty();
loadT16Creator(collectionId, releaseDate, pageType, parentUrl);
}
});
}
|
Remove redundant 'slides' var from test
|
(function() {
'use strict';
describe("<%= pluginFullName %>", function() {
var deck,
createDeck = function() {
slides = [];
var parent = document.createElement('article');
for (var i = 0; i < 10; i++) {
parent.appendChild(document.createElement('section'));
}
deck = bespoke.from(parent, {
<%= pluginNameCamelized %>: true
});
};
beforeEach(createDeck);
describe("deck.slide", function() {
beforeEach(function() {
deck.slide(0);
});
it("should not add a useless 'foobar' class to the slide", function() {
expect(deck.slides[0].classList.contains('foobar')).toBe(false);
});
});
});
}());
|
(function() {
'use strict';
describe("<%= pluginFullName %>", function() {
var slides, deck,
createDeck = function() {
slides = [];
var parent = document.createElement('article');
for (var i = 0; i < 10; i++) {
slides.push(document.createElement('section'));
parent.appendChild(slides[i]);
}
deck = bespoke.from(parent, {
<%= pluginNameCamelized %>: true
});
};
beforeEach(createDeck);
describe("deck.slide", function() {
beforeEach(function() {
deck.slide(0);
});
it("should not add a useless 'foobar' class to the slide", function() {
expect(slides[0].classList.contains('foobar')).toBe(false);
});
});
});
}());
|
Update du nombre de legendaries max
|
import React from 'react';
import ItemLink from 'common/ItemLink';
import ITEM_QUALITIES from 'common/ITEM_QUALITIES';
import SPELLS from 'common/SPELLS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';
const MAX_NUMBER_OF_LEGENDARIES = 2;
class LegendaryCountChecker extends Analyzer {
static dependencies = {
combatants: Combatants,
};
suggestions(when) {
const slots = this.combatants.selected._gearItemsBySlotId;
const legendaryCount = Object.values(slots).filter(item => item.quality === ITEM_QUALITIES.LEGENDARY).length;
when(legendaryCount).isLessThan(MAX_NUMBER_OF_LEGENDARIES)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You are not wearing the maximum number of legendaries.</span>)
.icon(SPELLS.SHADOW_WORD_PAIN.icon)
.actual(`You're wearing ${actual}`)
.recommended(`the current maximum is ${recommended}`)
.staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
});
}
}
export default LegendaryCountChecker;
|
import React from 'react';
import ItemLink from 'common/ItemLink';
import ITEM_QUALITIES from 'common/ITEM_QUALITIES';
import SPELLS from 'common/SPELLS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';
const MAX_NUMBER_OF_LEGENDARIES = 3;
class LegendaryCountChecker extends Analyzer {
static dependencies = {
combatants: Combatants,
};
suggestions(when) {
const slots = this.combatants.selected._gearItemsBySlotId;
const legendaryCount = Object.values(slots).filter(item => item.quality === ITEM_QUALITIES.LEGENDARY).length;
when(legendaryCount).isLessThan(MAX_NUMBER_OF_LEGENDARIES)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You are not wearing the maximum number of legendaries.</span>)
.icon(SPELLS.SHADOW_WORD_PAIN.icon)
.actual(`You're wearing ${actual}`)
.recommended(`the current maximum is ${recommended}`)
.staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
});
}
}
export default LegendaryCountChecker;
|
Switch to denydisconnect simply cos early talkers are RUDE!
|
// This plugin checks for clients that talk before we sent a response
var constants = require('../constants');
var config = require('../config');
exports.register = function() {
this.pause = config.get('early_talker.pause', 'value');
this.register_hook('data', 'check_early_talker');
};
exports.check_early_talker = function(callback) {
if (this.pause) {
var connection = this.connection;
setTimeout(function () { _check_early_talker(connection, callback) }, this.pause);
}
else {
_check_early_talker(self, callback);
}
};
var _check_early_talker = function (connection, callback) {
if (connection.early_talker) {
callback(constants.denydisconnect, "You talk too soon");
}
else {
callback(constants.cont);
}
};
|
// This plugin checks for clients that talk before we sent a response
var constants = require('../constants');
var config = require('../config');
exports.register = function() {
this.pause = config.get('early_talker.pause', 'value');
this.register_hook('data', 'check_early_talker');
};
exports.check_early_talker = function(callback) {
if (this.pause) {
var connection = this.connection;
setTimeout(function () { _check_early_talker(connection, callback) }, this.pause);
}
else {
_check_early_talker(self, callback);
}
};
var _check_early_talker = function (connection, callback) {
if (connection.early_talker) {
callback(constants.deny, "You talk too soon");
}
else {
callback(constants.cont);
}
};
|
[TACHYON-1559] Fix the two checkstyle errors originating out of the additional assertion
|
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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 tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
* Also tests for randomness property.
*
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
long first = ClientUtils.getRandomNonNegativeLong();
long second = ClientUtils.getRandomNonNegativeLong();
Assert.assertTrue(first > 0);
Assert.assertTrue(second > 0);
Assert.assertTrue(first != second);
}
}
|
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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 tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
* Also tests for randomness property.
*
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() != ClientUtils.getRandomNonNegativeLong());
}
}
|
Update meow options to be in line with v4.0.0
|
#!/usr/bin/env node
'use strict';
// foreign modules
const meow = require('meow');
// local modules
const error = require('../lib/error.js');
const logger = require('../lib/utils/logger.js');
const main = require('../index.js');
// this module
const cli = meow({
help: main.help,
version: true
}, {
flags: {
only: {type: 'boolean', default: false},
prune: {type: 'boolean', default: false},
remote: {type: 'boolean', default: false},
type: {type: 'string', default: 'madl'}
}
});
main(cli.input, cli.flags)
.catch((err) => {
error.handle404(err);
error.handleOnlyNoMatches(err);
error.handleScopeContentMismatch(err);
error.handleScopeInvalid(err);
error.handleScopeNotSet(err);
logger.error(err);
process.exit(1);
});
|
#!/usr/bin/env node
'use strict';
// foreign modules
const meow = require('meow');
// local modules
const error = require('../lib/error.js');
const logger = require('../lib/utils/logger.js');
const main = require('../index.js');
// this module
const cli = meow({
help: main.help,
version: true
}, {
boolean: [
'only',
'prune',
'remote'
],
defaults: {
only: false,
prune: false,
remote: false
},
type: [ 'type' ]
});
main(cli.input, cli.flags)
.catch((err) => {
error.handle404(err);
error.handleOnlyNoMatches(err);
error.handleScopeContentMismatch(err);
error.handleScopeInvalid(err);
error.handleScopeNotSet(err);
logger.error(err);
process.exit(1);
});
|
Add dotted notation key support (ie. themes)
|
const appendUnit = (value, unit) => (
value ? `${value}${unit}` : '0'
);
const getPropValue = (obj, keys) => {
const [key, balance] = keys.split(/\.(.+)/);
const value = obj[key];
if (balance) {
return getPropValue(value, balance);
}
return value;
};
const mapStringTemplateToGetter = (value) => {
if (typeof value === 'string') {
const [key, unit] = value.split(':');
return unit
? props => appendUnit(getPropValue(props, key), unit)
: props => getPropValue(props, key);
}
return value;
};
const withStyledShortcuts = styled => (
(strings, ...values) => {
const newValues = values.map(mapStringTemplateToGetter);
return styled(strings, ...newValues);
}
);
const withStyledShortcutsFunction = styled => (...args) => (
withStyledShortcuts(styled(...args))
);
const wrapStyled = (styled) => {
const styledShortcuts = withStyledShortcutsFunction(styled); // styled(Component)
Object.keys(styled).forEach((key) => {
if (typeof styled[key] === 'function' && styled[key].attrs) { // styled.div
styledShortcuts[key] = withStyledShortcuts(styled[key]);
styledShortcuts[key].attrs = withStyledShortcutsFunction(styled[key].attrs);
} else {
styledShortcuts[key] = styled[key];
}
});
return styledShortcuts;
};
export default wrapStyled;
|
const appendUnit = (value, unit) => (
value ? `${value}${unit}` : '0'
);
const mapStringTemplateToGetter = (value) => {
if (typeof value === 'string') {
const [key, unit] = value.split(':');
return unit
? props => appendUnit(props[key], unit)
: props => props[key];
}
return value;
};
const withStyledShortcuts = styled => (
(strings, ...values) => {
const newValues = values.map(mapStringTemplateToGetter);
return styled(strings, ...newValues);
}
);
const withStyledShortcutsFunction = styled => (...args) => (
withStyledShortcuts(styled(...args))
);
const wrapStyled = (styled) => {
const styledShortcuts = withStyledShortcutsFunction(styled); // styled(Component)
Object.keys(styled).forEach((key) => {
if (typeof styled[key] === 'function' && styled[key].attrs) { // styled.div
styledShortcuts[key] = withStyledShortcuts(styled[key]);
styledShortcuts[key].attrs = withStyledShortcutsFunction(styled[key].attrs);
} else {
styledShortcuts[key] = styled[key];
}
});
return styledShortcuts;
};
export default wrapStyled;
|
Add new icons to tests
|
import { moduleForComponent, test } from 'ember-qunit'
import hbs from 'htmlbars-inline-precompile'
moduleForComponent('svg-icon', 'Integration | Component | svg icon', {
integration: true
})
const icons = [
'arrow-left',
'arrow-right',
'bubble',
'check',
'checkmark-circle',
'clipboard-check',
'cog',
'ellipsis-horz',
'envelope',
'lifebuoy',
'lock-solid',
'lock',
'menu',
'paper-plane',
'paper-stack',
'pencil',
'reply',
'sync',
'thumbs-up',
'times'
]
const testSVG = icon => {
test(`'${icon}' renders and has class`, function(assert) {
assert.expect(2)
this.set('icon', icon)
this.render(hbs`{{svg-icon icon=icon}}`)
assert.ok(this.$('svg path'), '<path> renders')
assert.ok(this.$('svg').hasClass(`svg-icon-${icon}`), 'has class')
})
}
const runTests = () => {
icons.forEach(icon => {
testSVG(icon)
})
}
runTests()
|
import { moduleForComponent, test } from 'ember-qunit'
import hbs from 'htmlbars-inline-precompile'
moduleForComponent('svg-icon', 'Integration | Component | svg icon', {
integration: true
})
const icons = [
'arrow-left',
'arrow-right',
'bubble',
'check',
'ellipsis-horz',
'menu',
'paper-plane',
'pencil',
'reply',
'thumbs-up',
'times',
'cog',
'envelope',
'lifebuoy',
'paper-stack',
'clipboard-check',
'lock',
'lock-solid'
]
const testSVG = icon => {
test(`'${icon}' renders and has class`, function(assert) {
assert.expect(2)
this.set('icon', icon)
this.render(hbs`{{svg-icon icon=icon}}`)
assert.ok(this.$('svg path'), '<path> renders')
assert.ok(this.$('svg').hasClass(`svg-icon-${icon}`), 'has class')
})
}
const runTests = () => {
icons.forEach(icon => {
testSVG(icon)
})
}
runTests()
|
Clean up unused folders. Clean up css message
|
module.exports = {
modules: {
definition: 'commonjs',
wrapper: 'commonjs'
},
paths: {
'public': 'www'
},
files: {
javascripts: {
joinTo: {
'js/app.js': [/^(?!app)/,/^app/]
}
},
stylesheets: {
joinTo: {
'css/app.css': /^(app)/
}
}
},
plugins: {
sass: {
mode: 'native'
},
uglify: {
mangle: false,
compress: {
global_defs: {
DEBUG: false
}
}
},
cleancss: {
keepSpecialComments: 0,
removeEmpty: true
},
babel: {
presets: ["es2015"],
pattern: /\.(es6|js)$/
}
},
sourceMaps: false,
optimize: false
};
|
module.exports = {
modules: {
definition: 'commonjs',
wrapper: 'commonjs'
},
paths: {
'public': 'www'
},
files: {
javascripts: {
joinTo: {
'js/app.js': [/^(?!app)/,/^app/]
}
},
stylesheets: {
defaultExtension: 'scss',
joinTo: {
'css/app.css': /^app\/app\.scss$/
}
}
},
plugins: {
sass: {
mode: 'native'
},
uglify: {
mangle: false,
compress: {
global_defs: {
DEBUG: false
}
}
},
cleancss: {
keepSpecialComments: 0,
removeEmpty: true
},
babel: {
presets: ["es2015"],
pattern: /\.(es6|js)$/
}
},
sourceMaps: false,
optimize: false
};
|
Use `$ which bower` by default
@benrudolph
What do you think of this approach?
|
"""
This is a home for shared dev settings. Feel free to add anything that all
devs should have set.
Add `from dev_settings import *` to the top of your localsettings file to use.
You can then override or append to any of these settings there.
"""
import os
LOCAL_APPS = (
'django_extensions',
)
####### Django Extensions #######
# These things will be imported when you run ./manage.py shell_plus
SHELL_PLUS_POST_IMPORTS = (
# Models
('corehq.apps.domain.models', 'Domain'),
('corehq.apps.groups.models', 'Group'),
('corehq.apps.locations.models', 'Location'),
('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')),
('couchforms.models', 'XFormInstance'),
# Data querying utils
('dimagi.utils.couch.database', 'get_db'),
('corehq.apps.sofabed.models', ('FormData', 'CaseData')),
('corehq.apps.es', '*'),
)
ALLOWED_HOSTS = ['*']
FIX_LOGGER_ERROR_OBFUSCATION = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'commcarehq',
'USER': 'commcarehq',
'PASSWORD': 'commcarehq',
'HOST': 'localhost',
'PORT': '5432'
}
}
BOWER_PATH = os.popen('which bower').read().strip()
|
"""
This is a home for shared dev settings. Feel free to add anything that all
devs should have set.
Add `from dev_settings import *` to the top of your localsettings file to use.
You can then override or append to any of these settings there.
"""
LOCAL_APPS = (
'django_extensions',
)
####### Django Extensions #######
# These things will be imported when you run ./manage.py shell_plus
SHELL_PLUS_POST_IMPORTS = (
# Models
('corehq.apps.domain.models', 'Domain'),
('corehq.apps.groups.models', 'Group'),
('corehq.apps.locations.models', 'Location'),
('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')),
('couchforms.models', 'XFormInstance'),
# Data querying utils
('dimagi.utils.couch.database', 'get_db'),
('corehq.apps.sofabed.models', ('FormData', 'CaseData')),
('corehq.apps.es', '*'),
)
ALLOWED_HOSTS = ['*']
FIX_LOGGER_ERROR_OBFUSCATION = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'commcarehq',
'USER': 'commcarehq',
'PASSWORD': 'commcarehq',
'HOST': 'localhost',
'PORT': '5432'
}
}
|
Increase job graph poll interval.
|
define([
'underscore'
],
function(_) {
var namespace = "_pollable",
defaultInterval = 200000;
function get(t, k) {
if (!(t[namespace] && t[namespace][k])) { return null; }
return t[namespace][k];
}
function set(t, k, v) {
if (!t[namespace]) { t[namespace] = {}; }
if (_.isObject(k)) { _.merge(t[namespace], k); }
else { t[namespace][k] = v; }
}
return {
startPolling: function() {
if (get(this, 'pollingEnabled')) { return; }
set(this, 'pollingEnabled', true);
this.poll();
},
poll: function(interval) {
interval || (interval = defaultInterval);
var coll = this;
set(this, 'lastTimeout', setTimeout(function() {
coll.fetch({update: true});
coll.poll();
}, interval));
},
stopPolling: function() {
var lastTimeout = get(this, 'lastTimeout');
if (!lastTimeout) { return; }
clearTimeout(lastTimeout);
set(this, {
pollingEnabled: false,
lastTimeout: null
});
}
};
});
|
define([
'underscore'
],
function(_) {
var namespace = "_pollable",
defaultInterval = 60000;
function get(t, k) {
if (!(t[namespace] && t[namespace][k])) { return null; }
return t[namespace][k];
}
function set(t, k, v) {
if (!t[namespace]) { t[namespace] = {}; }
if (_.isObject(k)) { _.merge(t[namespace], k); }
else { t[namespace][k] = v; }
}
return {
startPolling: function() {
if (get(this, 'pollingEnabled')) { return; }
set(this, 'pollingEnabled', true);
this.poll();
},
poll: function(interval) {
interval || (interval = defaultInterval);
var coll = this;
set(this, 'lastTimeout', setTimeout(function() {
coll.fetch({update: true});
coll.poll();
}, interval));
},
stopPolling: function() {
var lastTimeout = get(this, 'lastTimeout');
if (!lastTimeout) { return; }
clearTimeout(lastTimeout);
set(this, {
pollingEnabled: false,
lastTimeout: null
});
}
};
});
|
Update trigger rtd build script - use https instead of http.
|
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import urllib2
key = sys.argv[1]
url = 'https://readthedocs.org/build/%s' % (key)
req = urllib2.Request(url, '')
f = urllib2.urlopen(req)
print f.read()
|
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import urllib2
key = sys.argv[1]
url = 'http://readthedocs.org/build/%s' % (key)
req = urllib2.Request(url, '')
f = urllib2.urlopen(req)
print f.read()
|
Fix support check that skips tests on ALL browsers
Mistake and poor checking on my part.
|
const html = require('choo/html');
const callcount = require('./callcount.js');
const chai = require('chai');
const expect = chai.expect;
// Skip a test if the browser does not support locale-based number formatting
function ifLocaleSupportedIt (name, test) {
if (window.Intl && window.Intl.NumberFormat) {
it(name, test);
}
else {
it.skip(name, test);
}
}
describe('callcount component', () => {
ifLocaleSupportedIt('should properly format call total >=1000 with commas', () => {
let state = {totalCalls: '123456789'};
let result = callcount(state);
expect(result.textContent).to.contain('123,456,789');
});
ifLocaleSupportedIt('should properly format call total < 1000 without commas', () => {
const totals = '123';
let state = {totalCalls: totals};
let result = callcount(state);
expect(result.textContent).to.contain(totals);
expect(result.textContent).to.not.contain(',');
});
ifLocaleSupportedIt('should not format zero call total', () => {
const totals = '0';
let state = {totalCalls: totals};
let result = callcount(state);
expect(result.textContent).to.contain(totals);
expect(result.textContent).to.not.contain(',');
});
});
|
const html = require('choo/html');
const callcount = require('./callcount.js');
const chai = require('chai');
const expect = chai.expect;
// Skip a test if the browser does not support locale-based number formatting
function ifLocaleSupportedIt (test) {
if (window.Intl && window.Intl.NumberFormat) {
it(test);
}
else {
it.skip(test);
}
}
describe('callcount component', () => {
ifLocaleSupportedIt('should properly format call total >=1000 with commas', () => {
let state = {totalCalls: '123456789'};
let result = callcount(state);
expect(result.textContent).to.contain('123,456,789');
});
ifLocaleSupportedIt('should properly format call total < 1000 without commas', () => {
const totals = '123';
let state = {totalCalls: totals};
let result = callcount(state);
expect(result.textContent).to.contain(totals);
expect(result.textContent).to.not.contain(',');
});
ifLocaleSupportedIt('should not format zero call total', () => {
const totals = '0';
let state = {totalCalls: totals};
let result = callcount(state);
expect(result.textContent).to.contain(totals);
expect(result.textContent).to.not.contain(',');
});
});
|
Add missing 'process' global for settings tests
|
const chai = require('chai')
const { expect } = chai
const SandboxedModule = require('sandboxed-module')
describe('Settings', function() {
describe('s3', function() {
it('should use JSONified env var if present', function() {
const s3Settings = {
bucket1: {
auth_key: 'bucket1_key',
auth_secret: 'bucket1_secret'
}
}
process.env.S3_BUCKET_CREDENTIALS = JSON.stringify(s3Settings)
const settings = SandboxedModule.require('settings-sharelatex', {
globals: { console, process }
})
expect(settings.filestore.s3BucketCreds).to.deep.equal(s3Settings)
})
})
})
|
const chai = require('chai')
const { expect } = chai
const SandboxedModule = require('sandboxed-module')
describe('Settings', function() {
describe('s3', function() {
it('should use JSONified env var if present', function() {
const s3Settings = {
bucket1: {
auth_key: 'bucket1_key',
auth_secret: 'bucket1_secret'
}
}
process.env.S3_BUCKET_CREDENTIALS = JSON.stringify(s3Settings)
const settings = SandboxedModule.require('settings-sharelatex', {
globals: { console }
})
expect(settings.filestore.s3BucketCreds).to.deep.equal(s3Settings)
})
})
})
|
Fix the spore test, as some functions were added by restjson
|
import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.tests.test_restjson
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print spore
spore = json.loads(spore)
assert len(spore['methods']) == 40, str(len(spore['methods']))
m = spore['methods']['argtypes_setbytesarray']
assert m['path'] == '/argtypes/setbytesarray'
assert m['optional_params'] == ['value']
assert m['method'] == 'POST'
m = spore['methods']['argtypes_setdecimal']
assert m['path'] == '/argtypes/setdecimal'
assert m['required_params'] == ['value']
assert m['method'] == 'GET'
|
import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print spore
spore = json.loads(spore)
assert len(spore['methods']) == 36, len(spore['methods'])
m = spore['methods']['argtypes_setbytesarray']
assert m['path'] == '/argtypes/setbytesarray'
assert m['optional_params'] == ['value']
assert m['method'] == 'POST'
m = spore['methods']['argtypes_setdecimal']
assert m['path'] == '/argtypes/setdecimal'
assert m['required_params'] == ['value']
assert m['method'] == 'GET'
|
Remove extra line already handle by the route xml
|
package io.openex.email.attachment;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultAttachment;
import javax.mail.util.ByteArrayDataSource;
import java.util.ArrayList;
import java.util.List;
import static io.openex.email.attachment.EmailDownloader.ATTACHMENTS_CONTENT;
/**
* Created by Julien on 19/12/2016.
*/
@SuppressWarnings({"PackageAccessibility", "WeakerAccess"})
public class EmailAttacher {
@SuppressWarnings({"unused", "unchecked"})
public void process(Exchange exchange) {
List<EmailAttachment> filesContent = (List) exchange.getProperty(ATTACHMENTS_CONTENT, new ArrayList<>());
for (EmailAttachment attachment : filesContent) {
ByteArrayDataSource bds = new ByteArrayDataSource(attachment.getData(), attachment.getContentType());
exchange.getIn().addAttachmentObject(attachment.getName(), new DefaultAttachment(bds));
}
}
}
|
package io.openex.email.attachment;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultAttachment;
import javax.mail.util.ByteArrayDataSource;
import java.util.ArrayList;
import java.util.List;
import static io.openex.email.attachment.EmailDownloader.ATTACHMENTS_CONTENT;
/**
* Created by Julien on 19/12/2016.
*/
@SuppressWarnings({"PackageAccessibility", "WeakerAccess"})
public class EmailAttacher {
@SuppressWarnings({"unused", "unchecked"})
public void process(Exchange exchange) {
List<EmailAttachment> filesContent = (List) exchange.getProperty(ATTACHMENTS_CONTENT, new ArrayList<>());exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");
for (EmailAttachment attachment : filesContent) {
ByteArrayDataSource bds = new ByteArrayDataSource(attachment.getData(), attachment.getContentType());
exchange.getIn().addAttachmentObject(attachment.getName(), new DefaultAttachment(bds));
}
}
}
|
Add support for unkeyed params array.
|
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
arrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? arrayKey : tag.replace(/\{|\}/gi, '');
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
arrayKey++;
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = tag.replace(/\{|\}/gi, '');
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
Update the Edge example test
|
"""
This test is only for Microsoft Edge (Chromium)!
(Tested on Edge Version 89.0.774.54)
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run this test using "--edge" or "--browser=edge")')
self.skip('Use "--edge" or "--browser=edge"')
self.open("edge://settings/help")
self.highlight('div[role="main"]')
self.highlight('img[srcset*="logo"]')
self.assert_text("Microsoft Edge", 'img[srcset*="logo"] + div')
self.highlight('img[srcset*="logo"] + div span:nth-of-type(1)')
self.highlight('img[srcset*="logo"] + div span:nth-of-type(2)')
self.highlight('span[aria-live="assertive"]')
self.highlight('a[href*="chromium"]')
|
"""
This test is only for Microsoft Edge (Chromium)!
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run this test using "--edge" or "--browser=edge")')
self.skip('Use "--edge" or "--browser=edge"')
self.open("edge://settings/help")
self.assert_element('img[alt="Edge logo"] + span')
self.highlight('#section_about div + div')
self.highlight('#section_about div + div > div')
self.highlight('img[alt="Edge logo"]')
self.highlight('img[alt="Edge logo"] + span')
self.highlight('#section_about div + div > div + div')
self.highlight('#section_about div + div > div + div + div > div')
|
Test extension with mock registry
|
import mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
|
Add doc task to build
|
'use strict';
var gulp = require('gulp');
var runSequence = require('run-sequence');
var taskLoader = require('gulp-task-loader');
var $ = require('./gulp.config.js');
// load all tasks from folder 'tasks'
// tasks named after task file name
taskLoader('tasks');
gulp.task('default', function(cb){
runSequence('build', cb);
});
/**
* Clean dist folders
* Test and validate code
* Optimize angular files
* Create dist module
*
* @param {Function} done - callback when complete
*/
gulp.task('build', function(cb) {
runSequence('clean', 'test', 'angular', 'doc', cb);
});
/**
* Vet the code
* Start the tests using karma
*
* @param {Function} done - callback when complete
*/
gulp.task('test', function(cb) {
runSequence('vet', 'karma', cb);
});
/**
* Bump the version and create dist module
* --type=pre will bump the prerelease version *.*.*-x
* --type=patch or no flag will bump the patch version *.*.x
* --type=minor will bump the minor version *.x.*
* --type=major will bump the major version x.*.*
* --version=1.2.3 will bump to a specific version and ignore other flags
*
* @param {Function} done - callback when complete
*/
gulp.task('release', function(cb) {
runSequence('bump', 'module', cb);
});
|
'use strict';
var gulp = require('gulp');
var runSequence = require('run-sequence');
var taskLoader = require('gulp-task-loader');
var $ = require('./gulp.config.js');
// load all tasks from folder 'tasks'
// tasks named after task file name
taskLoader('tasks');
gulp.task('default', function(cb){
runSequence('build', cb);
});
/**
* Clean dist folders
* Test and validate code
* Optimize angular files
* Create dist module
*
* @param {Function} done - callback when complete
*/
gulp.task('build', function(cb) {
runSequence('clean', 'test', 'angular', cb);
});
/**
* Vet the code
* Start the tests using karma
*
* @param {Function} done - callback when complete
*/
gulp.task('test', function(cb) {
runSequence('vet', 'karma', cb);
});
/**
* Bump the version and create dist module
* --type=pre will bump the prerelease version *.*.*-x
* --type=patch or no flag will bump the patch version *.*.x
* --type=minor will bump the minor version *.x.*
* --type=major will bump the major version x.*.*
* --version=1.2.3 will bump to a specific version and ignore other flags
*
* @param {Function} done - callback when complete
*/
gulp.task('release', function(cb) {
runSequence('bump', 'module', cb);
});
|
Add js extension required for proper jspm importing
|
/**
* @overview A module that initializes the Gallery with Flickity
* @module Gallery.js
*/
import Flickity from 'flickity';
import { ImgixSettings } from '../media/ImgixSettings.js';
export const Gallery = {
/**
* Sets up any galleries on the page
* @returns {void}
*/
init() {
const galleryEls = document.querySelectorAll(`.js-gallery`);
this.setupGalleries(galleryEls);
this.setupImageGalleries();
},
/**
* Instantiates Flickity on each gallery, with their respective options
* @param {object} Gallery DOM elements to setup
* @returns {void}
*/
setupGalleries(galleryEls) {
[...galleryEls].forEach((el) => {
const options = JSON.parse(el.getAttribute(`data-options`));
new Flickity(el, options);
});
},
/**
* Sets custom imgix settings for gallery images, instantiating Flickity and
* fading in the gallery once the first image has loaded
* @returns {void}
*/
setupImageGalleries() {
ImgixSettings.init({
fluidClass: `imgix-fluid--gallery`,
onLoad: (el) => {
const currentGallery = el.closest(`.js-gallery--images`);
if (el === currentGallery.firstElementChild) {
this.setupGalleries([currentGallery]);
currentGallery.classList.add(`is-loaded`);
}
},
});
},
};
|
/**
* @overview A module that initializes the Gallery with Flickity
* @module Gallery.js
*/
import Flickity from 'flickity';
import { ImgixSettings } from '../media/ImgixSettings';
export const Gallery = {
/**
* Sets up any galleries on the page
* @returns {void}
*/
init() {
const galleryEls = document.querySelectorAll(`.js-gallery`);
this.setupGalleries(galleryEls);
this.setupImageGalleries();
},
/**
* Instantiates Flickity on each gallery, with their respective options
* @param {object} Gallery DOM elements to setup
* @returns {void}
*/
setupGalleries(galleryEls) {
[...galleryEls].forEach((el) => {
const options = JSON.parse(el.getAttribute(`data-options`));
new Flickity(el, options);
});
},
/**
* Sets custom imgix settings for gallery images, instantiating Flickity and
* fading in the gallery once the first image has loaded
* @returns {void}
*/
setupImageGalleries() {
ImgixSettings.init({
fluidClass: `imgix-fluid--gallery`,
onLoad: (el) => {
const currentGallery = el.closest(`.js-gallery--images`);
if (el === currentGallery.firstElementChild) {
this.setupGalleries([currentGallery]);
currentGallery.classList.add(`is-loaded`);
}
},
});
},
};
|
[AdminBundle] Test console exception subscriber without instantiating a specific command
|
<?php
namespace Kunstmaan\AdminBundle\Tests\EventListener;
use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionSubscriberTest extends TestCase
{
public function testListener()
{
// Remove when sf3.4 support is removed
if (!class_exists(ConsoleErrorEvent::class)) {
// Nothing to test
return;
}
$error = new \TypeError('An error occurred');
$output = $this->createMock(OutputInterface::class);
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('critical');
$subscriber = new ConsoleExceptionSubscriber($logger);
$subscriber->onConsoleError(new ConsoleErrorEvent(new ArgvInput(['console.php', 'test:run', '--foo=baz', 'buzz']), $output, $error, new Command('test:run')));
}
}
|
<?php
namespace Kunstmaan\AdminBundle\Tests\EventListener;
use Kunstmaan\AdminBundle\Command\ApplyAclCommand;
use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionSubscriberTest extends TestCase
{
public function testListener()
{
if (!class_exists(ConsoleErrorEvent::class)) {
// Nothing to test
return;
}
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('critical')->willReturn(true);
$subscriber = new ConsoleExceptionSubscriber($logger);
$command = new ApplyAclCommand();
$exception = new \Exception();
$input = $this->createMock(InputInterface::class);
$output = $this->createMock(OutputInterface::class);
$event = new ConsoleErrorEvent($input, $output, $exception, $command);
$subscriber->onConsoleError($event);
}
}
|
Add more logging as default in production
|
'use strict';
// Exports
export default function defaultConfig(env = 'development') {
return {
env: env,
loggers: [
{
name: 'stdout',
level: 'info',
stream: process.stdout
},
{
name: 'stderr',
level: 'warn',
stream: process.stderr
}
],
name: 'Komapi application',
proxy: false,
routePrefix: '/',
subdomainOffset: 2
};
}
|
'use strict';
// Exports
export default function defaultConfig(env = 'development') {
return {
env: env,
loggers: [
{
name: 'stdout',
level: (env === 'production') ? 'warn' : 'info',
stream: process.stdout
},
{
name: 'stderr',
level: 'warn',
stream: process.stderr
}
],
name: 'Komapi application',
proxy: false,
routePrefix: '/',
subdomainOffset: 2
};
}
|
Add delete mapping for family.
|
package arnelid.bjorn.redo.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import arnelid.bjorn.redo.model.Family;
import arnelid.bjorn.redo.repository.FamilyRepository;
@RestController
public class FamilyController {
@Autowired
FamilyRepository familyRepository;
@PostMapping(path = "/family", consumes = MediaType.APPLICATION_JSON_VALUE)
void postFamily(@RequestBody Family newFamily) {
familyRepository.save(newFamily);
}
@DeleteMapping("/{name}")
void deleteFAmily(@PathVariable String name) {
Family toBeDeleted = familyRepository.findByName(name);
familyRepository.delete(toBeDeleted);
}
@GetMapping("/{name}")
Family getFamily(@PathVariable String name) {
return familyRepository.findByName(name);
}
}
|
package arnelid.bjorn.redo.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import arnelid.bjorn.redo.model.Family;
import arnelid.bjorn.redo.repository.FamilyRepository;
@RestController
public class FamilyController {
@Autowired
FamilyRepository familyRepository;
@GetMapping("/{name}")
Family getFamily(@PathVariable String name) {
return familyRepository.findByName(name);
}
@PostMapping(path = "/Family", consumes = MediaType.APPLICATION_JSON_VALUE)
void postFamily(@RequestBody Family newFamily) {
familyRepository.save(newFamily);
}
}
|
Fix bad calculations in challenge 41
|
// Challenge 41 - Implement unpadded message recovery oracle
// http://cryptopals.com/sets/6/challenges/41
package cryptopals
import (
"crypto/rand"
"math/big"
)
type challenge41 struct {
}
func (challenge41) Client(key *publicKey, net Network) string {
c := readInt(net)
S, _ := rand.Int(rand.Reader, key.n)
C := new(big.Int).Exp(S, key.e, key.n)
C = C.Mul(C, c).Mod(C, key.n)
net.Write(C)
p := readInt(net)
P := new(big.Int).ModInverse(S, key.n)
P = P.Mul(p, P).Mod(P, key.n)
return string(P.Bytes())
}
func (challenge41) Server(message string, key *privateKey, net Network) {
p := new(big.Int).SetBytes([]byte(message))
c := key.publicKey().encrypt(p)
net.Write(c)
C := readInt(net)
P := key.decrypt(C)
net.Write(P)
}
|
// Challenge 41 - Implement unpadded message recovery oracle
// http://cryptopals.com/sets/6/challenges/41
package cryptopals
import (
"crypto/rand"
"math/big"
)
type challenge41 struct {
}
func (challenge41) Client(key *publicKey, net Network) string {
c := readInt(net)
S, _ := rand.Int(rand.Reader, key.n)
C := new(big.Int).Exp(S, key.e, key.n)
C = C.Mul(C, c).Mod(C, key.n)
net.Write(C)
p := readInt(net)
P := new(big.Int).ModInverse(p, key.n)
P = P.Mul(P, p).Mod(P, key.n)
return string(P.Bytes())
}
func (challenge41) Server(message string, key *privateKey, net Network) {
p := new(big.Int).SetBytes([]byte(message))
c := key.publicKey().encrypt(p)
net.Write(c)
C := readInt(net)
P := key.decrypt(C)
net.Write(P)
}
|
Modify required package list to minimal pakcages.
|
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='im@john.hu, kilik.kuo@gmail.com',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'numpy',
'pyopencl'
],
zip_safe=False)
|
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='im@john.hu, kilik.kuo@gmail.com',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'pycparser',
'cffi',
'numpy',
'wheel',
#'pyopencl'
],
zip_safe=False)
|
Fix typo in error handling, preventing an error to be thrown while catching a top level error
|
import { initOptions, keycloak } from "keycloak"
;(async() => {
keycloak.onTokenExpired = () =>
keycloak
.updateToken()
.then(() => {
console.info("Token refreshed")
})
.catch(error => {
console.warn(
"Keycloak client failed to refresh token, re-authentication is needed"
)
console.warn(error)
})
try {
const authenticated = await keycloak.init({ onLoad: initOptions.onLoad })
if (!authenticated) {
console.info("Keycloak client not authenticated, reloading page...")
window.location.reload()
return
}
} catch (error) {
console.info("Error occurred during Keycloak client initialization")
console.error(error)
return
}
console.info("Authenticated successfully")
try {
require("index.js")
} catch (error) {
console.error(error)
}
})()
export default keycloak
|
import { initOptions, keycloak } from "keycloak"
;(async() => {
keycloak.onTokenExpired = () =>
keycloak
.updateToken()
.then(() => {
console.info("Token refreshed")
})
.catch(error => {
console.warn(
"Keycloak client failed to refresh token, re-authentication is needed"
)
console.warn(error)
})
try {
const authenticated = await keycloak.init({ onLoad: initOptions.onLoad })
if (!authenticated) {
console.info("Keycloak client not authenticated, reloading page...")
window.location.reload()
return
}
} catch (error) {
console.info("Error occurred during Keycloak client initialization")
console.err(error)
return
}
console.info("Authenticated successfully")
try {
require("index.js")
} catch (error) {
console.error(error)
}
})()
export default keycloak
|
Use caller as key for subfolder runtime deps
|
import caller from 'caller'
import { _resolveFilename } from 'module'
import { dirname } from 'path'
export default class RuntimeDependencyManager {
constructor() {
this.dependencies = {}
this.subFolderDependencies = {}
}
selfTransitiveThenUpdate (subfolder) {
const callingModule = caller()
if (!this.subFolderDependencies[callingModule]) {
this.subFolderDependencies[callingModule] = relativeModuleFrom(subfolder, callingModule)
}
}
transitiveThenUpdate (module) {
if (!this.dependencies[module]) {
this.dependencies[module] = moduleRootFrom(module, caller())
}
}
mapDependencies (fn) {
return Object.values(this.dependencies).map(fn)
}
mapSubfolderDependencies (fn) {
return Object.values(this.subFolderDependencies).map(fn)
}
}
function relativeModuleFrom (module, from) {
// Assume that the "from" module root is the directory immediately following
// the final "node_modules/".
const fromRoot = from.match(/(.+node_modules\/[^\/]+)\/.+/)[1]
return `${fromRoot}/${module}`
}
function moduleRootFrom (module, from) {
return dirname(
_resolveFilename(`${module}/package.json`, require.cache[from])
)
}
|
import caller from 'caller'
import { _resolveFilename } from 'module'
import { dirname } from 'path'
export default class RuntimeDependencyManager {
constructor() {
this.dependencies = {}
this.subFolderDependencies = {}
}
selfTransitiveThenUpdate (module) {
if (!this.subFolderDependencies[module]) {
this.subFolderDependencies[module] = relativeModuleFrom(module, caller())
}
}
transitiveThenUpdate (module) {
if (!this.dependencies[module]) {
this.dependencies[module] = moduleRootFrom(module, caller())
}
}
mapDependencies (fn) {
return Object.values(this.dependencies).map(fn)
}
mapSubfolderDependencies (fn) {
return Object.values(this.subFolderDependencies).map(fn)
}
}
function relativeModuleFrom (module, from) {
// Assume that the "from" module root is the directory immediately following
// the final "node_modules/".
const fromRoot = from.match(/(.+node_modules\/[^\/]+)\/.+/)[1]
return `${fromRoot}/${module}`
}
function moduleRootFrom (module, from) {
return dirname(
_resolveFilename(`${module}/package.json`, require.cache[from])
)
}
|
Fix the FileNotFoundError when data director is not exist
|
#-*- coding: utf-8 -*-
import pandas as pd
import pandas_datareader.data as web
import datetime
import config
import os
import re
import pickle
def get_file_path(code):
if not os.path.exists(config.DATA_PATH):
try:
os.makedirs(config.DATA_PATH)
except:
pass
return os.path.join(config.DATA_PATH, 'data', code + '.pkl')
def download(code, year1, month1, day1, year2, month2, day2):
start = datetime.datetime(year1, month1, day1)
end = datetime.datetime(year2, month2, day2)
df = web.DataReader('%s.KS' % code, 'yahoo', start, end)
save(code, df)
return df
def load(code):
try:
return pd.read_pickle(code)
except:
pass
return None
def save(code, df):
df.to_pickle(code)
def dump(code, df):
with open(get_file_path(code), 'wb') as handle:
pickle.dump(df, handle)
|
#-*- coding: utf-8 -*-
import pandas as pd
import pandas_datareader.data as web
import datetime
import config
import os
import re
import pickle
def get_file_path(code):
return os.path.join(config.DATA_PATH, 'data', code + '.pkl')
def download(code, year1, month1, day1, year2, month2, day2):
start = datetime.datetime(year1, month1, day1)
end = datetime.datetime(year2, month2, day2)
df = web.DataReader('%s.KS' % code, 'yahoo', start, end)
save(code, df)
return df
def load(code):
try:
return pd.read_pickle(code)
except:
pass
return None
def save(code, df):
df.to_pickle(code)
def dump(code, df):
with open(get_file_path(code), 'wb') as handle:
pickle.dump(df, handle)
|
Add & comment out --harmony_arrow_functions
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--es-staging',
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
// '--harmony_arrow_functions', // No lexical `this`; (function (){return(()=>this)()}.bind(2))() === 2
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--es-staging',
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
Add location to user profile post
|
#from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'email', 'phone', 'faircoin_address', 'telegram_id')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
uuid = serializers.CharField(read_only=True)
location = PointField(required=False)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email', 'uuid', 'faircoin_address', 'telegram_id', 'location')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
|
#from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'email', 'phone', 'faircoin_address', 'telegram_id')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
uuid = serializers.CharField(read_only=True)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email', 'uuid', 'faircoin_address', 'telegram_id')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
|
Fix build on RPi. Building from source timesout on karma tests so increase timeouts
|
module.exports = function(config) {
'use strict';
config.set({
basePath: __dirname + '/public_gen',
frameworks: ['mocha', 'expect', 'sinon'],
// list of files / patterns to load in the browser
files: [
'vendor/npm/es6-shim/es6-shim.js',
'vendor/npm/systemjs/dist/system.src.js',
'test/test-main.js',
{pattern: '**/*.js', included: false},
],
// list of files to exclude
exclude: [],
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
captureTimeout: 20000,
singleRun: true,
autoWatchBatchDelay: 10000,
browserNoActivityTimeout: 60000,
});
};
|
module.exports = function(config) {
'use strict';
config.set({
basePath: __dirname + '/public_gen',
frameworks: ['mocha', 'expect', 'sinon'],
// list of files / patterns to load in the browser
files: [
'vendor/npm/es6-shim/es6-shim.js',
'vendor/npm/systemjs/dist/system.src.js',
'test/test-main.js',
{pattern: '**/*.js', included: false},
],
// list of files to exclude
exclude: [],
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
captureTimeout: 2000,
singleRun: true,
autoWatchBatchDelay: 1000,
});
};
|
Fix getting product in build_dashboard task
|
from __future__ import annotations
from typing import TYPE_CHECKING
from celery.utils.log import get_task_logger
from keeper.celery import celery_app
from keeper.models import Product
from keeper.services.dashboard import build_dashboard as build_dashboard_svc
if TYPE_CHECKING:
import celery.task
__all__ = ["build_dashboard"]
logger = get_task_logger(__name__)
@celery_app.task(bind=True)
def build_dashboard(self: celery.task.Task, product_id: str) -> None:
"""Build a product's dashboard as a Celery task.
Parameters
----------
product_url : `str`
URL of the product resource.
"""
logger.info(
"Starting dashboard build product_id=%s retry=%d",
product_id,
self.request.retries,
)
product = Product.query.get(product_id)
build_dashboard_svc(product, logger)
logger.info("Finished triggering dashboard build")
|
from __future__ import annotations
from typing import TYPE_CHECKING
from celery.utils.log import get_task_logger
from keeper.celery import celery_app
from keeper.models import Product
from keeper.services.dashboard import build_dashboard as build_dashboard_svc
if TYPE_CHECKING:
import celery.task
__all__ = ["build_dashboard"]
logger = get_task_logger(__name__)
@celery_app.task(bind=True)
def build_dashboard(self: celery.task.Task, product_id: str) -> None:
"""Build a product's dashboard as a Celery task.
Parameters
----------
product_url : `str`
URL of the product resource.
"""
logger.info(
"Starting dashboard build product_id=%s retry=%d",
product_id,
self.request.retries,
)
product = Product.query(id=product_id).one()
build_dashboard_svc(product, logger)
logger.info("Finished triggering dashboard build")
|
Fix regex to include .jsx
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}, {
test: /\.css?$/,
loaders: ['style', 'raw']
}]
}
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.js?$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}, {
test: /\.css?$/,
loaders: ['style', 'raw']
}]
}
};
|
Fix typo in @return annotation
|
<?php
/**
* @author @fabfuel <fabian@fabfuel.de>
* @created 25.11.14, 08:12
*/
namespace Fabfuel\Prophiler\Plugin\Phalcon\Mvc;
use Phalcon\Events\Event;
use Phalcon\Mvc\ViewInterface;
interface ViewPluginInterface
{
/**
* @param Event $event
* @param ViewInterface $view
* @return void
*/
public function beforeRenderView(Event $event, ViewInterface $view);
/**
* @param Event $event
* @param ViewInterface $view
* @return void
*/
public function afterRenderView(Event $event, ViewInterface $view);
/**
* @param Event $event
* @param ViewInterface $view
* @return void
*/
public function afterRender(Event $event, ViewInterface $view);
}
|
<?php
/**
* @author @fabfuel <fabian@fabfuel.de>
* @created 25.11.14, 08:12
*/
namespace Fabfuel\Prophiler\Plugin\Phalcon\Mvc;
use Phalcon\Events\Event;
use Phalcon\Mvc\ViewInterface;
interface ViewPluginInterface
{
/**
* @param Event $event
* @param ViewInterface $view
* @return void()
*/
public function beforeRenderView(Event $event, ViewInterface $view);
/**
* @param Event $event
* @param ViewInterface $view
* @return void()
*/
public function afterRenderView(Event $event, ViewInterface $view);
/**
* @param Event $event
* @param ViewInterface $view
* @return void()
*/
public function afterRender(Event $event, ViewInterface $view);
}
|
Fix pushing the original files back on the stream
|
var through = require('through2');
var gutil = require('gulp-util');
var extend = require('extend');
var vinylFile = require('vinyl-file');
var StringDecoder = require('string_decoder').StringDecoder;
var Analyzer = require('./Analyzer');
var Logger = require('./Logger');
var resolver = null;
module.exports = function(config) {
var firstRun = false;
config = extend(true, {
stopperOnFirstRun: true,
debug: false
}, config);
Logger.level = config.debug ? Logger.DEBUG : Logger.WARN;
if (resolver === null) {
resolver = new Analyzer(config);
firstRun = true;
}
return through.obj(function(file, enc, cb) {
var decoder = new StringDecoder(enc);
var content = decoder.write(file.contents);
var dependencies = resolver.resolveDependencies(content, file.path);
if (!firstRun) {
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
var dependencyFile = vinylFile.readSync(dependency, {
cwd: file.cwd,
base: file.base
});
this.push(dependencyFile);
}
}
if (!firstRun || !config.stopperOnFirstRun) {
this.push(file);
}
cb();
});
};
|
var through = require('through2');
var gutil = require('gulp-util');
var extend = require('extend');
var vinylFile = require('vinyl-file');
var StringDecoder = require('string_decoder').StringDecoder;
var Analyzer = require('./Analyzer');
var Logger = require('./Logger');
var resolver = null;
module.exports = function(config) {
var firstRun = false;
config = extend(true, {
stopperOnFirstRun: true,
debug: false
}, config);
Logger.level = config.debug ? Logger.DEBUG : Logger.WARN;
if (resolver === null) {
resolver = new Analyzer(config);
firstRun = true;
}
return through.obj(function(file, enc, cb) {
var decoder = new StringDecoder(enc);
var content = decoder.write(file.contents);
var dependencies = resolver.resolveDependencies(content, file.path);
if (!firstRun) {
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
var dependencyFile = vinylFile.readSync(dependency, {
cwd: file.cwd,
base: file.base
});
this.push(dependencyFile);
}
}
if (!config.stopperOnFirstRun) {
this.push(file);
}
cb();
});
};
|
Reset filter query params on "Members" click in sidebar
closes https://github.com/TryGhost/Team/issues/967
Member filters is reset when clicked on "Members" in the left sidebar.
|
import {helper} from '@ember/component/helper';
export const DEFAULT_QUERY_PARAMS = {
posts: {
type: null,
visibility: null,
author: null,
tag: null,
order: null
},
pages: {
type: null,
visibility: null,
author: null,
tag: null,
order: null
},
'members.index': {
label: null,
paid: null,
search: '',
filter: null,
order: null
}
};
// in order to reset query params to their defaults when using <LinkTo> or
// `transitionTo` it's necessary to explicitly set each param. This helper makes
// it easier to provide a "resetting" link, especially when used with custom views
export function resetQueryParams(routeName, newParams) {
return Object.assign({}, DEFAULT_QUERY_PARAMS[routeName], newParams);
}
export default helper(function (params/*, hash*/) {
return resetQueryParams(...params);
});
|
import {helper} from '@ember/component/helper';
export const DEFAULT_QUERY_PARAMS = {
posts: {
type: null,
visibility: null,
author: null,
tag: null,
order: null
},
pages: {
type: null,
visibility: null,
author: null,
tag: null,
order: null
},
'members.index': {
label: null,
paid: null,
search: '',
order: null
}
};
// in order to reset query params to their defaults when using <LinkTo> or
// `transitionTo` it's necessary to explicitly set each param. This helper makes
// it easier to provide a "resetting" link, especially when used with custom views
export function resetQueryParams(routeName, newParams) {
return Object.assign({}, DEFAULT_QUERY_PARAMS[routeName], newParams);
}
export default helper(function (params/*, hash*/) {
return resetQueryParams(...params);
});
|
Remove escapeRegExp in favor of lodash.escapeRegExp
|
exports._regExpRegExp = /^\/(.+)\/([im]?)$/;
exports._lineRegExp = /\r\n|\r|\n/;
exports.splitLines = function (text) {
var lines = [];
var match, line;
while (match = exports._lineRegExp.exec(text)) {
line = text.slice(0, match.index) + match[0];
text = text.slice(line.length);
lines.push(line);
}
lines.push(text);
return lines;
};
exports.regExpIndexOf = function(str, regex, index) {
index = index || 0;
var offset = str.slice(index).search(regex);
return (offset >= 0) ? (index + offset) : offset;
};
exports.regExpLastIndexOf = function (str, regex, index) {
if (index === 0 || index) str = str.slice(0, Math.max(0, index));
var i;
var offset = -1;
while ((i = str.search(regex)) !== -1) {
offset += i + 1;
str = str.slice(i + 1);
}
return offset;
};
|
exports._regExpRegExp = /^\/(.+)\/([im]?)$/;
exports._lineRegExp = /\r\n|\r|\n/;
exports.splitLines = function (text) {
var lines = [];
var match, line;
while (match = exports._lineRegExp.exec(text)) {
line = text.slice(0, match.index) + match[0];
text = text.slice(line.length);
lines.push(line);
}
lines.push(text);
return lines;
};
exports.escapeRegExp = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
exports.regExpIndexOf = function(str, regex, index) {
index = index || 0;
var offset = str.slice(index).search(regex);
return (offset >= 0) ? (index + offset) : offset;
};
exports.regExpLastIndexOf = function (str, regex, index) {
if (index === 0 || index) str = str.slice(0, Math.max(0, index));
var i;
var offset = -1;
while ((i = str.search(regex)) !== -1) {
offset += i + 1;
str = str.slice(i + 1);
}
return offset;
};
|
Change string to check in test
|
<?php
/*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace ZfTwitterWidgetTests\View;
use ZfTwitterWidget\View\OneTimeJsViewHelper;
class OneTimeJsViewHelperTest extends \PHPUnit_Framework_TestCase
{
public function testOneTimeJsViewHelper()
{
$oneTimeJsVH = new OneTimeJsViewHelper();
$this->assertGreaterThan(0, strpos($oneTimeJsVH(), 'widgets.js'));
}
}
|
<?php
/*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace ZfTwitterWidgetTests\View;
use ZfTwitterWidget\View\OneTimeJsViewHelper;
class OneTimeJsViewHelperTest extends \PHPUnit_Framework_TestCase
{
public function testOneTimeJsViewHelper()
{
$oneTimeJsVH = new OneTimeJsViewHelper();
$this->assertGreaterThan(0, strpos($oneTimeJsVH(), 'window.twttr'));
}
}
|
Increase turn timer to avoid flaky test
Longer turn timer for Tic Tac Toe game test
|
package com.github.sandorw.mocabogaso.games.tictactoe;
import static org.junit.Assert.*;
import org.junit.Test;
import com.github.sandorw.mocabogaso.Game;
import com.github.sandorw.mocabogaso.games.GameResult;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameMove;
import com.github.sandorw.mocabogaso.games.mnkgame.MNKGameState;
import com.github.sandorw.mocabogaso.players.AIPlayerFactory;
public class TicTacToeGameStateTest {
@Test
public void playFullGameTest() {
TicTacToeGameState gameState = TicTacToeGameState.of();
Game<DefaultGameMove, MNKGameState> game = new Game<>(gameState);
game.addPlayer("X", AIPlayerFactory.getNewAIPlayer(gameState, 150));
game.addPlayer("O", AIPlayerFactory.getNewAIPlayer(gameState, 150));
game.playGame();
assertTrue(game.isGameOver());
GameResult gameResult = game.getGameResult();
assertTrue(gameResult.isTie());
}
}
|
package com.github.sandorw.mocabogaso.games.tictactoe;
import static org.junit.Assert.*;
import org.junit.Test;
import com.github.sandorw.mocabogaso.Game;
import com.github.sandorw.mocabogaso.games.GameResult;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameMove;
import com.github.sandorw.mocabogaso.games.mnkgame.MNKGameState;
import com.github.sandorw.mocabogaso.players.AIPlayerFactory;
public class TicTacToeGameStateTest {
@Test
public void playFullGameTest() {
TicTacToeGameState gameState = TicTacToeGameState.of();
Game<DefaultGameMove, MNKGameState> game = new Game<>(gameState);
game.addPlayer("X", AIPlayerFactory.getNewAIPlayer(gameState, 50));
game.addPlayer("O", AIPlayerFactory.getNewAIPlayer(gameState, 50));
game.playGame();
assertTrue(game.isGameOver());
GameResult gameResult = game.getGameResult();
assertTrue(gameResult.isTie());
}
}
|
Use a more precise pattern to id ^R ezproxy url tokens.
|
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^u/(?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_u'
),
url(r'^r/(?P<token>ezp\.([a-zA-Z]|[0-9]|[$-_@.&+])+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_r'
),
]
|
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^u/(?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_u'
),
url(r'^r/(?P<token>(ezp\.[a-zA-Z]|[0-9]|[$-_@.&+])+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_r'
),
]
|
Make watch kicker load up using configured source path
|
// Runs the webpack dev server and respawns
// the server when pages,components, and tags
// are created or destroyed.
//
// This is required because the webpack
// static site generator plugin requires a
// static list of paths
const spawn = require('child_process').spawn;
const chokidar = require('chokidar');
const pkg = require('./package.json');
const script = pkg.scripts['watch-script'];
const debounce = require('lodash.debounce');
let parts = script.split(' ') ;
const cmd = parts.shift();
const options = parts;
let webpack;
const respawn = debounce(() => {
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
if (webpack) webpack.kill();
webpack = spawn(cmd, options, { stdio: 'inherit' });
}, 250);
const watcher =
chokidar
.watch(config.directories.source, { ignoreInitial: true })
.on('ready', () => respawn())
.on('addDir', () => respawn())
.on('unlinkDir', () => respawn());
|
// Runs the webpack dev server and respawns
// the server when pages,components, and tags
// are created or destroyed.
//
// This is required because the webpack
// static site generator plugin requires a
// static list of paths
const spawn = require('child_process').spawn;
const chokidar = require('chokidar');
const pkg = require('./package.json');
const script = pkg.scripts['watch-script'];
const debounce = require('lodash.debounce');
let parts = script.split(' ') ;
const cmd = parts.shift();
const options = parts;
let webpack;
const respawn = debounce(() => {
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
console.log('RESPAWN');
if (webpack) webpack.kill();
webpack = spawn(cmd, options, { stdio: 'inherit' });
}, 250);
const watcher =
chokidar
.watch('./source', { ignoreInitial: true })
.on('ready', () => respawn())
.on('addDir', () => respawn())
.on('unlinkDir', () => respawn());
|
Allow instantiation of the Barlesque object to be overridden.
|
<?php
/*
* Copyright 2012 Mo McRoberts.
*
* 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.
*/
require_once(dirname(__FILE__) . '/client.php');
class BarlesquePage extends Page
{
protected $blq;
protected $defaultSkin = 'barlesque';
public function __construct()
{
parent::__construct();
$this->blq = $this->barlesque();
}
protected function barlesque()
{
return new Barlesque();
}
protected function assignTemplate()
{
parent::assignTemplate();
$this->vars['blq'] = $this->blq;
}
}
|
<?php
/*
* Copyright 2012 Mo McRoberts.
*
* 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.
*/
require_once(dirname(__FILE__) . '/client.php');
class BarlesquePage extends Page
{
protected $blq;
protected $defaultSkin = 'barlesque';
public function __construct()
{
parent::__construct();
$this->blq = new Barlesque();
}
protected function assignTemplate()
{
parent::assignTemplate();
$this->vars['blq'] = $this->blq;
}
}
|
Fix migration for various situations
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes, to_str
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a PickleObjectField
"""
ServerConfig = apps.get_model("server", "ServerConfig")
for conf in ServerConfig.objects.all():
value = pickle.loads(to_bytes(conf.db_value))
conf.db_value2 = to_str(value)
conf.save(update_fields=["db_value2"])
class Migration(migrations.Migration):
dependencies = [
('server', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='serverconfig',
name='db_value2',
field=evennia.utils.picklefield.PickledObjectField(help_text='The data returned when the config value is accessed. Must be written as a Python literal if editing through the admin interface. Attribute values which are not Python literals cannot be edited through the admin interface.', null=True, verbose_name='value'),
),
# migrate data
migrations.RunPython(migrate_serverconf, migrations.RunPython.noop),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a PickleObjectField
"""
ServerConfig = apps.get_model("server", "ServerConfig")
for conf in ServerConfig.objects.all():
value = pickle.loads(to_bytes(conf.db_value))
conf.db_value2 = value
conf.save()
class Migration(migrations.Migration):
dependencies = [
('server', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='serverconfig',
name='db_value2',
field=evennia.utils.picklefield.PickledObjectField(help_text='The data returned when the config value is accessed. Must be written as a Python literal if editing through the admin interface. Attribute values which are not Python literals cannot be edited through the admin interface.', null=True, verbose_name='value'),
),
# migrate data
migrations.RunPython(migrate_serverconf, migrations.RunPython.noop),
]
|
Update the USDGBP exchange rate
|
// https://www.bloomberg.com/quote/USDGBP:CUR
const EXCHANGE_RATE_USD_TO_GBP = 0.7062
const EXCHANGE_RATE_GBP_TO_USD = parseFloat(
Number(1 / EXCHANGE_RATE_USD_TO_GBP).toFixed(4)
)
const DATE_LONG_FORMAT = 'd MMMM yyyy'
const DATE_DAY_LONG_FORMAT = 'E, dd MMM yyyy'
const DATE_MEDIUM_FORMAT = 'd mmm yyyy'
const DATE_TIME_MEDIUM_FORMAT = 'd MMM yyyy, h:mmaaa'
module.exports = {
EXCHANGE_RATE_USD_TO_GBP,
EXCHANGE_RATE_GBP_TO_USD,
DATE_DAY_LONG_FORMAT,
DATE_LONG_FORMAT,
DATE_MEDIUM_FORMAT,
DATE_TIME_MEDIUM_FORMAT,
}
|
// https://www.bloomberg.com/quote/USDGBP:CUR
const EXCHANGE_RATE_USD_TO_GBP = 0.7189
const EXCHANGE_RATE_GBP_TO_USD = parseFloat(
Number(1 / EXCHANGE_RATE_USD_TO_GBP).toFixed(4)
)
const DATE_LONG_FORMAT = 'd MMMM yyyy'
const DATE_DAY_LONG_FORMAT = 'E, dd MMM yyyy'
const DATE_MEDIUM_FORMAT = 'd mmm yyyy'
const DATE_TIME_MEDIUM_FORMAT = 'd MMM yyyy, h:mmaaa'
module.exports = {
EXCHANGE_RATE_USD_TO_GBP,
EXCHANGE_RATE_GBP_TO_USD,
DATE_DAY_LONG_FORMAT,
DATE_LONG_FORMAT,
DATE_MEDIUM_FORMAT,
DATE_TIME_MEDIUM_FORMAT,
}
|
Update team page header on load
|
function retrieveGetParameters(){
let parameters = {}
window.location.search
.substring(1) //Remove '?' at beginning
.split('&') //Split key-value pairs
.map((currentElement) => { //Fill parameters object with key-value pairs
const key = currentElement.split('=')[0];
const value = currentElement.split('=')[1];
parameters[key] = value;
})
return parameters;
}
function getTeamname(){
const parameters = retrieveGetParameters();
return parameters["teamname"];
}
function updateTeamname(){
$('h1')
.text(getTeamname())
}
window.addEventListener('load', () => {
updateTeamname()
})
|
function retrieveGetParameters(){
let parameters = {}
window.location.search
.substring(1) //Remove '?' at beginning
.split('&') //Split key-value pairs
.map((currentElement) => { //Fill parameters object with key-value pairs
const key = currentElement.split('=')[0];
const value = currentElement.split('=')[1];
parameters[key] = value;
})
return parameters;
}
function getTeamname(){
const parameters = retrieveGetParameters();
return parameters["teamname"];
}
|
Add children array to default component data
|
const fs = require('fs');
const path = require('path');
const overrideRequiredComponentStyle = {
position: 'absolute'
};
const defaultRequiredComponentStyle = {
width: '100px',
height: '100px'
};
const getComponentLibrary = (directory = path.join(__dirname, '/components/VisComponents')) => {
const componentList = fs
.readdirSync(directory)
.filter(file => path.extname(file) === '.jsx')
return componentList.map(file => {
const { style } = require(`./${file}`);
const name = file.split('.jsx')[0];
const finalStyle = {
...defaultRequiredComponentStyle,
...style,
...overrideRequiredComponentStyle
};
return {
name,
children: [],
props: { style: finalStyle },
events: {}
};
});
};
export default getComponentLibrary;
|
const fs = require('fs');
const path = require('path');
const overrideRequiredComponentStyle = {
position: 'absolute'
};
const defaultRequiredComponentStyle = {
width: '100px',
height: '100px'
};
const getComponentLibrary = (directory = path.join(__dirname, '/components/VisComponents')) => {
const componentList = fs
.readdirSync(directory)
.filter(file => path.extname(file) === '.jsx')
return componentList.map(file => {
const { style } = require(`./${file}`);
const name = file.split('.jsx')[0];
const finalStyle = {
...defaultRequiredComponentStyle,
...style,
...overrideRequiredComponentStyle
};
return {
name,
props: { style: finalStyle },
events: {}
};
});
};
export default getComponentLibrary;
|
Add coding for python 2.7 compatibility
|
# -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from wger.core.tests.base_testcase import WorkoutManagerTestCase
from wger.utils.helpers import smart_capitalize
class CapitalizerTestCase(WorkoutManagerTestCase):
'''
Tests the "intelligent" capitalizer
'''
def test_capitalizer(self):
'''
Tests different combinations of input strings
'''
self.assertEqual(smart_capitalize("some long words"), "Some Long Words")
self.assertEqual(smart_capitalize("Here a short one"), "Here a Short One")
self.assertEqual(smart_capitalize("meine gym AG"), "Meine Gym AG")
self.assertEqual(smart_capitalize("ßpecial case"), "ßpecial Case")
self.assertEqual(smart_capitalize("fIRST lettER only"), "FIRST LettER Only")
|
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from wger.core.tests.base_testcase import WorkoutManagerTestCase
from wger.utils.helpers import smart_capitalize
class CapitalizerTestCase(WorkoutManagerTestCase):
'''
Tests the "intelligent" capitalizer
'''
def test_capitalizer(self):
'''
Tests different combinations of input strings
'''
self.assertEqual(smart_capitalize("some long words"), "Some Long Words")
self.assertEqual(smart_capitalize("Here a short one"), "Here a Short One")
self.assertEqual(smart_capitalize("meine gym AG"), "Meine Gym AG")
self.assertEqual(smart_capitalize("ßpecial case"), "ßpecial Case")
self.assertEqual(smart_capitalize("fIRST lettER only"), "FIRST LettER Only")
|
Fix import path for blobstore gcs driver in project template
|
// +build appengine
package main
import (
"net/http"
"time"
_ "gnd.la/admin" // required for make-assets command
_ "gnd.la/cache/driver/memcache" // enable memcached cache driver
_ "gnd.la/orm/blobstore/gcs" // enable Google Could Storage blobstore driver
// Uncomment the following line to use Google Cloud SQL
//_ "gnd.la/orm/driver/mysql"
)
var (
wg sync.WaitGroup
)
func _app_engine_app_init() {
// Make sure App is initialized before the rest
// of this function runs.
for App == nil {
time.Sleep(5 * time.Millisecond)
}
if err := App.Prepare(); err != nil {
panic(err)
}
http.Handle("/", App)
wg.Done()
}
// Only executed on the development server. Required for
// precompiling assets.
func main() {
wg.Wait()
}
func init() {
wg.Add(1)
go _app_engine_app_init()
}
|
// +build appengine
package main
import (
"net/http"
"time"
_ "gnd.la/admin" // required for make-assets command
_ "gnd.la/cache/driver/memcache" // enable memcached cache driver
_ "gnd.la/orm/driver/gcs" // enable Google Could Storage blobstore driver
// Uncomment the following line to use Google Cloud SQL
//_ "gnd.la/orm/driver/mysql"
)
var (
wg sync.WaitGroup
)
func _app_engine_app_init() {
// Make sure App is initialized before the rest
// of this function runs.
for App == nil {
time.Sleep(5 * time.Millisecond)
}
if err := App.Prepare(); err != nil {
panic(err)
}
http.Handle("/", App)
wg.Done()
}
// Only executed on the development server. Required for
// precompiling assets.
func main() {
wg.Wait()
}
func init() {
wg.Add(1)
go _app_engine_app_init()
}
|
Remove useless imports from flask alchemy demo
|
import unittest
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.db = demoapp.db
self.db.create_all()
def tearDown(self):
self.db.drop_all()
def test_user_factory(self):
user = demoapp_factories.UserFactory()
self.db.session.commit()
self.assertIsNotNone(user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
def test_userlog_factory(self):
userlog = demoapp_factories.UserLogFactory()
self.db.session.commit()
self.assertIsNotNone(userlog.id)
self.assertIsNotNone(userlog.user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
self.assertEqual(1, len(demoapp.UserLog.query.all()))
|
import os
import unittest
import tempfile
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.db = demoapp.db
self.db.create_all()
def tearDown(self):
self.db.drop_all()
def test_user_factory(self):
user = demoapp_factories.UserFactory()
self.db.session.commit()
self.assertIsNotNone(user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
def test_userlog_factory(self):
userlog = demoapp_factories.UserLogFactory()
self.db.session.commit()
self.assertIsNotNone(userlog.id)
self.assertIsNotNone(userlog.user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
self.assertEqual(1, len(demoapp.UserLog.query.all()))
|
Fix build script on windows.
|
/*
Leaflet building, testing and linting scripts.
To use, install Node, then run the following commands in the project root:
npm install -g jake
npm install
To check the code for errors and build Leaflet from source, run "jake".
To run the tests, run "jake test".
For a custom build, open build/build.html in the browser and follow the instructions.
*/
var build = require('./build/build.js');
function hint(msg, paths) {
return function () {
console.log(msg);
jake.exec('node node_modules/jshint/bin/jshint -c ' + paths,
{printStdout: true}, function () {
console.log('\tCheck passed.\n');
complete();
});
}
}
desc('Check Leaflet source for errors with JSHint');
task('lint', {async: true}, hint('Checking for JS errors...', 'build/hintrc.js src'));
desc('Check Leaflet specs source for errors with JSHint');
task('lintspec', {async: true}, hint('Checking for specs JS errors...', 'spec/spec.hintrc.js spec/suites'));
desc('Combine and compress Leaflet source files');
task('build', build.build);
desc('Run PhantomJS tests');
task('test', ['lint', 'lintspec'], {async: true}, function () {
build.test(complete);
});
task('default', ['test', 'build']);
jake.addListener('complete', function () {
process.exit();
});
|
/*
Leaflet building, testing and linting scripts.
To use, install Node, then run the following commands in the project root:
npm install -g jake
npm install
To check the code for errors and build Leaflet from source, run "jake".
To run the tests, run "jake test".
For a custom build, open build/build.html in the browser and follow the instructions.
*/
var build = require('./build/build.js');
function hint(msg, paths) {
return function () {
console.log(msg);
jake.exec('./node_modules/jshint/bin/jshint -c ' + paths,
{printStdout: true}, function () {
console.log('\tCheck passed.\n');
complete();
});
}
}
desc('Check Leaflet source for errors with JSHint');
task('lint', {async: true}, hint('Checking for JS errors...', 'build/hintrc.js src'));
desc('Check Leaflet specs source for errors with JSHint');
task('lintspec', {async: true}, hint('Checking for specs JS errors...', 'spec/spec.hintrc.js spec/suites'));
desc('Combine and compress Leaflet source files');
task('build', build.build);
desc('Run PhantomJS tests');
task('test', ['lint', 'lintspec'], {async: true}, function () {
build.test(complete);
});
task('default', ['test', 'build']);
jake.addListener('complete', function () {
process.exit();
});
|
[Fix] Fix login with error login data redirect to / with no message
|
/**
* Created by Indexyz on 2017/4/10.
*/
"use strict";
/**
* Created by Indexyz on 2017/4/7.
*/
const db = require("mongoose");
const userSchema = require("../../Db/Schema/User");
const userService = require("../../Db/Service/userService");
let userModel = db.model(require('../../Define/Db').Db.USER_DB, userSchema);
module.exports.get = (req, res, next) => {
res.render("auth/login", {
"info": req.query.info
})
};
module.exports.post = (req, res, next) => {
let email = req.body.email,
password = req.body.password;
if (!email || !password) { res.render("auth/login", {"e": "请填写全部的信息"}); return }
userService.login(email, password, (err, doc) => {
if (!doc) { return res.render("auth/login", {"e": "用户名或密码错误"}); }
if (err) { return next(err); }
req.session.user = doc;
if (!req.query.redirect){
res.redirect("/")
} else {
res.redirect(req.query.redirect)
}
});
};
|
/**
* Created by Indexyz on 2017/4/10.
*/
"use strict";
/**
* Created by Indexyz on 2017/4/7.
*/
const db = require("mongoose");
const userSchema = require("../../Db/Schema/User");
const userService = require("../../Db/Service/userService");
let userModel = db.model(require('../../Define/Db').Db.USER_DB, userSchema);
module.exports.get = (req, res, next) => {
res.render("auth/login", {
"info": req.query.info
})
};
module.exports.post = (req, res, next) => {
let email = req.body.email,
password = req.body.password;
if (!email || !password) { res.render("auth/login", {"e": "请填写全部的信息"}); return }
userService.login(email, password, (err, doc) => {
if (err) { return next(err); }
req.session.user = doc;
if (!req.query.redirect){
res.redirect("/")
} else {
res.redirect(req.query.redirect)
}
});
};
|
Use spaces before the item name string in itemsets
|
# -*- coding: utf-8 -*-
"""
Item Sets
- ItemSet.dbc
"""
from .. import *
from ..globalstrings import *
class ItemSet(Model):
pass
class ItemSetTooltip(Tooltip):
def tooltip(self):
items = self.obj.getItems()
maxItems = len(items)
self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW)
for item in items:
self.append("item", " %s" % (item.getName()), color=GREY)
ret = self.values
self.values = []
return ret
class ItemSetProxy(object):
"""
WDBC proxy for item sets
"""
def __init__(self, cls):
from pywow import wdbc
self.__file = wdbc.get("ItemSet.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getItems(self, row):
from ..items import Item, ItemProxy
Item.initProxy(ItemProxy)
ret = []
for i in range(1, 11):
id = row._raw("item_%i" % (i))
if id:
ret.append(Item(id))
return ret
def getName(self, row):
return row.name_enus
|
# -*- coding: utf-8 -*-
"""
Item Sets
- ItemSet.dbc
"""
from .. import *
from ..globalstrings import *
class ItemSet(Model):
pass
class ItemSetTooltip(Tooltip):
def tooltip(self):
items = self.obj.getItems()
maxItems = len(items)
self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW)
for item in items:
self.append("item", item.getName(), color=GREY)
ret = self.values
self.values = []
return ret
class ItemSetProxy(object):
"""
WDBC proxy for item sets
"""
def __init__(self, cls):
from pywow import wdbc
self.__file = wdbc.get("ItemSet.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getItems(self, row):
from ..items import Item, ItemProxy
Item.initProxy(ItemProxy)
ret = []
for i in range(1, 11):
id = row._raw("item_%i" % (i))
if id:
ret.append(Item(id))
return ret
def getName(self, row):
return row.name_enus
|
Fix issue with displaying the correct options on array fields
|
<?php /** @var \Dms\Core\Form\IFieldOption[] $options */ ?>
<?php /** @var array $value */ ?>
@if (count($value) === 0)
@include('dms::components.field.null.value')
@else
<ul class="dms-display-list list-group">
@foreach ($options as $option)
<li class="list-group-item">
@if($urlCallback ?? false)
<a href="{{ $urlCallback($option->getValue()) }}">{{ $option->getLabel() }}</a>
@else
{{ $option->getLabel() }}
@endif
</li>
@endforeach
</ul>
@endif
|
<?php /** @var \Dms\Core\Form\IFieldOption[] $options */ ?>
<?php /** @var array $value */ ?>
@if (count($value) === 0)
@include('dms::components.field.null.value')
@else
<ul class="dms-display-list list-group">
@foreach ($value as $item)
@if(isset($options[$item]))
<li class="list-group-item">
@if($urlCallback ?? false)
<a href="{{ $urlCallback($options[$item]->getValue()) }}">{{ $options[$item]->getLabel() }}</a>
@else
{{ $options[$item]->getLabel() }}
@endif
</li>
@endif
@endforeach
</ul>
@endif
|
Add code example for Godoc.
|
package jump
import "testing"
func TestHashInBucketRange(t *testing.T) {
h := Hash(1, 1)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(42, 57)
if h != 43 {
t.Error("expected bucket to be 43, got", h)
}
h = Hash(0xDEAD10CC, 1)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(0xDEAD10CC, 666)
if h != 361 {
t.Error("expected bucket to be 361, got", h)
}
h = Hash(256, 1024)
if h != 520 {
t.Error("expected bucket to be 520, got", h)
}
}
func TestNegativeBucket(t *testing.T) {
h := Hash(0, -10)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(0xDEAD10CC, -666)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
}
func ExampleHash() {
Hash(256, 1024)
// Output: 520
}
|
package jump
import "testing"
func TestHashInBucketRange(t *testing.T) {
h := Hash(1, 1)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(42, 57)
if h != 43 {
t.Error("expected bucket to be 43, got", h)
}
h = Hash(0xDEAD10CC, 1)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(0xDEAD10CC, 666)
if h != 361 {
t.Error("expected bucket to be 361, got", h)
}
h = Hash(256, 1024)
if h != 520 {
t.Error("expected bucket to be 520, got", h)
}
}
func TestNegativeBucket(t *testing.T) {
h := Hash(0, -10)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
h = Hash(0xDEAD10CC, -666)
if h != 0 {
t.Error("expected bucket to be 0, got", h)
}
}
|
Fix webpack setup for production builds
|
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public', 'dist');
var APP_DIR = path.resolve(__dirname, 'src');
var API_BASE_URL = process.env.NODE_ENV === 'production' ? 'http://api.eachday.life' : 'http://localhost:5000'
var config = {
entry: APP_DIR + '/index.js',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test : /\.js?/,
include : APP_DIR,
loader : 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-2']
}
},
{
test: /\.css$/,
loader: [ 'style-loader', 'css-loader' ]
}
]
},
devServer: {
contentBase: path.join(__dirname, "public"),
publicPath: "/dist/",
port: 9000,
historyApiFallback: true
},
plugins:[
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `'${process.env.NODE_ENV}'`,
API_BASE_URL: `'${API_BASE_URL}'`
}
})
]
};
module.exports = config;
|
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public', 'dist');
var APP_DIR = path.resolve(__dirname, 'src');
var API_BASE_URL = process.env.NODE_ENV === 'production' ? 'http://api.eachday.life' : 'http://localhost:5000'
var config = {
entry: APP_DIR + '/index.js',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test : /\.js?/,
include : APP_DIR,
loader : 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-2']
}
},
{
test: /\.css$/,
loader: [ 'style-loader', 'css-loader' ]
}
]
},
devServer: {
contentBase: path.join(__dirname, "public"),
publicPath: "/dist/",
port: 9000,
historyApiFallback: true
},
plugins:[
new webpack.DefinePlugin({
'process.env.API_BASE_URL': `'${API_BASE_URL}'`,
'process.env.NODE_ENV': `'${process.env.NODE_ENV}'`
})
]
};
module.exports = config;
|
Make site url be http, not https
|
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.syndication.views import add_domain
from django.contrib.sites.models import get_current_site
def get_site_url(request, path):
"""Retrieve current site site
Always returns as http (never https)
"""
current_site = get_current_site(request)
site_url = add_domain(current_site.domain, path, request.is_secure())
return site_url.replace('https', 'http')
def do_paging(request, queryset):
paginator = Paginator(queryset, 25)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
objects = paginator.page(page)
except (EmptyPage, InvalidPage):
objects = paginator.page(paginator.num_pages)
return objects
|
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.syndication.views import add_domain
from django.contrib.sites.models import get_current_site
def get_site_url(request, path):
current_site = get_current_site(request)
return add_domain(current_site.domain, path, request.is_secure())
def do_paging(request, queryset):
paginator = Paginator(queryset, 25)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
objects = paginator.page(page)
except (EmptyPage, InvalidPage):
objects = paginator.page(paginator.num_pages)
return objects
|
Remove WKPB from geosearch - also change test
|
import unittest
from datapunt_geosearch import config
from datapunt_geosearch import datasource
class TestBAGDataset(unittest.TestCase):
def test_query(self):
x = 120993
y = 485919
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y)
self.assertEqual(len(results['features']), 7)
self.assertIn('distance', results['features'][0]['properties'])
def test_query_wgs84(self):
x = 52.36011
y = 4.88798
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y, rd=False)
self.assertEqual(len(results['features']), 6)
if __name__ == '__main__':
unittest.main()
|
import unittest
from datapunt_geosearch import config
from datapunt_geosearch import datasource
class TestBAGDataset(unittest.TestCase):
def test_query(self):
x = 120993
y = 485919
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y)
self.assertEqual(len(results['features']), 7)
self.assertIn('distance', results['features'][0]['properties'])
def test_query_wgs84(self):
x = 52.36011
y = 4.88798
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y, rd=False)
self.assertEqual(len(results['features']), 7)
if __name__ == '__main__':
unittest.main()
|
Add mime types to GCodeWriter plugin
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeWriter
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "mesh_writer",
"plugin": {
"name": "GCode Writer",
"author": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc("GCode Writer Plugin Description", "Writes GCode to a file")
},
"mesh_writer": {
"extension": "gcode",
"description": catalog.i18nc("GCode Writer File Description", "GCode File"),
"mime_types": [
"text/x-gcode"
]
}
}
def register(app):
return { "mesh_writer": GCodeWriter.GCodeWriter() }
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeWriter
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "mesh_writer",
"plugin": {
"name": "GCode Writer",
"author": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc("GCode Writer Plugin Description", "Writes GCode to a file")
},
"mesh_writer": {
"extension": "gcode",
"description": catalog.i18nc("GCode Writer File Description", "GCode File")
}
}
def register(app):
return { "mesh_writer": GCodeWriter.GCodeWriter() }
|
Save antibody-log at each time in temp directory
|
package shell
import (
"fmt"
"github.com/kardianos/osext"
)
const template = `#!/usr/bin/env zsh
ANTIBODY_BINARY="%s"
antibody() {
case "$1" in
bundle|update)
tmp_dir=$(mktemp -d)
while read -u 3 bundle; do
source "$bundle" 2&> ${temp_dir}/antibody-log
done 3< <( $ANTIBODY_BINARY $@ )
;;
*)
$ANTIBODY_BINARY $@
;;
esac
}
_antibody() {
IFS=' ' read -A reply <<< "$(echo "bundle update list help")"
}
compctl -K _antibody antibody
`
// Init returns the shell that should be loaded to antibody to work correctly.
func Init() string {
executable, _ := osext.Executable()
return fmt.Sprintf(template, executable)
}
|
package shell
import (
"fmt"
"github.com/kardianos/osext"
)
const template = `#!/usr/bin/env zsh
ANTIBODY_BINARY="%s"
antibody() {
case "$1" in
bundle|update)
while read -u 3 bundle; do
touch /tmp/antibody-log && chmod 777 /tmp/antibody-log
source "$bundle" 2&> /tmp/antibody-log
done 3< <( $ANTIBODY_BINARY $@ )
;;
*)
$ANTIBODY_BINARY $@
;;
esac
}
_antibody() {
IFS=' ' read -A reply <<< "$(echo "bundle update list help")"
}
compctl -K _antibody antibody
`
// Init returns the shell that should be loaded to antibody to work correctly.
func Init() string {
executable, _ := osext.Executable()
return fmt.Sprintf(template, executable)
}
|
Define the port variable for reconnection
|
import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor()
def execute(self, query):
try:
self._cursor.execute(query=query)
except (AttributeError, pymysql.OperationalError):
self.__reconnect__()
self._cursor.execute(query=query)
def fetchone(self):
return self._cursor.fetchone()
def commit(self):
return self._conn.commit()
def __reconnect__(self):
self._conn = pymysql.connect(host=self._host, port=self._port, user=self._user, passwd=self._password)
self._cursor = self._conn.cursor()
|
import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor()
def execute(self, query):
try:
self._cursor.execute(query=query)
except (AttributeError, pymysql.OperationalError):
self.__reconnect__()
self._cursor.execute(query=query)
def fetchone(self):
return self._cursor.fetchone()
def commit(self):
return self._conn.commit()
def __reconnect__(self):
self._conn = pymysql.connect(host=self._host, port=self._port, user=self._user, passwd=self._password)
self._cursor = self._conn.cursor()
|
Change default zerofill to 5
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddZerofillToSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('settings', function (Blueprint $table) {
$table->integer('zerofill_count')->default(5);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('settings', function ($table) {
$table->dropColumn('zerofill_count');
});
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddZerofillToSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('settings', function (Blueprint $table) {
$table->integer('zerofill_count')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('settings', function ($table) {
$table->dropColumn('zerofill_count');
});
}
}
|
Fix container list bug when missing image
|
def getContainerDetails(container):
ip = 'N/A'
if container.state().network != None and container.state().network.get('eth0') != None:
if len(container.state().network.get('eth0')['addresses']) > 0:
ip = container.state().network['eth0']['addresses'][0].get('address', 'N/A')
image = 'N/A'
if container.config.get('image.os') != None and container.config.get('image.release') != None and container.config.get('image.architecture') != None:
image = ''.join(container.config.get('image.os') + ' ' + container.config.get('image.release') + ' ' + container.config.get('image.architecture'))
return {
'name': container.name,
'status': container.status,
'ip': ip,
'ephemeral': container.ephemeral,
'image': image,
'created_at': container.created_at
}
|
def getContainerDetails(container):
ip = 'N/A'
if container.state().network != None and container.state().network.get('eth0') != None:
if len(container.state().network.get('eth0')['addresses']) > 0:
ip = container.state().network['eth0']['addresses'][0].get('address', 'N/A')
return {
'name': container.name,
'status': container.status,
'ip': ip,
'ephemeral': container.ephemeral,
'image': ''.join(container.config.get('image.os') + ' ' + container.config.get('image.release') + ' ' + container.config.get('image.architecture')),
'created_at': container.created_at
}
|
Fix space between title and version select
|
import theme from '../../theme'
export default {
mdContent: {},
content: {
position: 'relative',
},
markdown: {
display: 'block',
},
actions: {
float: 'right',
display: 'flex',
alignItems: 'center',
position: 'relative',
zIndex: 5,
marginLeft: 20
},
action: {
display: 'flex',
height: 30,
borderRight: [1, 'solid', theme.borderColor],
paddingRight: 20,
marginLeft: 20,
'&:last-child': {
isolate: false,
borderRight: 0,
paddingRight: 0
},
'&:first-child': {
marginLeft: 0
}
},
// Removes inlining with title.
[theme.media.md]: {
actions: {
float: 'none',
justifyContent: 'flex-end',
marginBottom: 20,
}
},
[theme.media.sm]: {
actions: {
justifyContent: 'center'
}
}
}
|
import theme from '../../theme'
export default {
mdContent: {},
content: {
position: 'relative',
},
markdown: {
display: 'block',
},
actions: {
float: 'right',
display: 'flex',
alignItems: 'center',
position: 'relative',
zIndex: 5
},
action: {
display: 'flex',
height: 30,
borderRight: [1, 'solid', theme.borderColor],
paddingRight: 20,
marginLeft: 20,
'&:last-child': {
isolate: false,
borderRight: 0,
paddingRight: 0
},
'&:first-child': {
marginLeft: 0
}
},
// Removes inlining with title.
[theme.media.md]: {
actions: {
float: 'none',
justifyContent: 'flex-end',
marginBottom: 20,
}
},
[theme.media.sm]: {
actions: {
justifyContent: 'center'
}
}
}
|
Add class name as argument.
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM;
/**
* Exception thrown when a Proxy fails to retrieve an Entity result.
*
* @author robo
* @since 2.0
*/
class EntityNotFoundException extends ORMException
{
/**
* Constructor.
*/
public function __construct($class)
{
parent::__construct("Entity of type '{$class}' was not found.");
}
}
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM;
/**
* Exception thrown when a Proxy fails to retrieve an Entity result.
*
* @author robo
* @since 2.0
*/
class EntityNotFoundException extends ORMException
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct('Entity was not found.');
}
}
|
Change the "user" variable to "doc"
|
Template.Users.events({
'click [name=add]': function(e, tmpl) {
Router.go('add');
}
});
Template.User.events({
'click .remove': function(e, tmpl) {
if (confirm('Are you sure to remove "' + this.fullName() + '"')) {
Meteor.call('/user/remove', this);
}
}
});
Template.Form.events({
'change input': function(e, tmpl) {
var doc = this;
var field = e.currentTarget;
doc.set(field.id, field.value);
doc.validate(field.id);
},
'click [name=save]': function(e, tmpl) {
var user = this;
if (user.validate()) {
Meteor.call('/user/save', user, function(err) {
if (!err) {
Router.go('users');
} else {
user.catchValidationException(err);
}
});
}
}
});
|
Template.Users.events({
'click [name=add]': function(e, tmpl) {
Router.go('add');
}
});
Template.User.events({
'click .remove': function(e, tmpl) {
if (confirm('Are you sure to remove "' + this.fullName() + '"')) {
Meteor.call('/user/remove', this);
}
}
});
Template.Form.events({
'change input': function(e, tmpl) {
var user = this;
var field = e.currentTarget;
user.set(field.id, field.value);
user.validate(field.id);
},
'click [name=save]': function(e, tmpl) {
var user = this;
if (user.validate()) {
Meteor.call('/user/save', user, function(err) {
if (!err) {
Router.go('users');
} else {
user.catchValidationException(err);
}
});
}
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.