text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add more greetings to the needs-multilining regex
|
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'Responds to greetings and such'
def GetResponse(self, message):
if message.Type != 'PRIVMSG':
return
match = re.search("^(?P<greeting>(wa+s+|')?so?u+p|hi(ya)?|hey|hello|'?lo|(good |g'?)?((mornin|evenin)[g']?|ni(ght|ni))|greetings|bonjour|salut|howdy|'?yo|o?hai|mojn|hej|dongs|ahoy( hoy)?|salutations|g'?day|hola|bye|herrow)( there)?,?[ ]%s([^a-zA-Z0-9_\|`\[\]\^-]|$)" % CurrentNick,
message.MessageString,
re.IGNORECASE)
if match:
return IRCResponse(ResponseType.Say,
'%s %s' % (match.group('greeting'), message.User.Name),
message.ReplyTo)
|
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'Responds to greetings and such'
def GetResponse(self, message):
if message.Type != 'PRIVMSG':
return
match = re.search("^(?P<greeting>(wa+s+|')?so?u+p|hi(ya)?|hey|hello|'?lo|mornin[g']?|greetings|bonjour|salut|howdy|'?yo|o?hai|mojn|hej|dongs|ahoy( hoy)?|salutations|g'?day|hola|bye|night|herrow)( there)?,?[ ]%s([^a-zA-Z0-9_\|`\[\]\^-]|$)" % CurrentNick,
message.MessageString,
re.IGNORECASE)
if match:
return IRCResponse(ResponseType.Say,
'%s %s' % (match.group('greeting'), message.User.Name),
message.ReplyTo)
|
Define const `OUTPUT_PANEL` for the panel name
|
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
panel_view = self.window.create_output_panel(PANEL_NAME, True)
panel_view.set_read_only(False)
panel_view.run_command('append', {'characters': msg})
panel_view.set_read_only(True)
panel_view.show(0)
self.window.run_command("show_panel", {"panel": OUTPUT_PANEL})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
|
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
panel_view = self.window.create_output_panel(PANEL_NAME, True)
panel_view.set_read_only(False)
panel_view.run_command('append', {'characters': msg})
panel_view.set_read_only(True)
panel_view.show(0)
self.window.run_command("show_panel", {"panel": "output.{}".format(PANEL_NAME)})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
|
Refactor controller to use promises
|
/**
* PlayersController
*
* @description :: Server-side logic for managing Players
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var Promise = require('bluebird');
module.exports = {
view: function(req, res) {
var playerPromise = Players.findOne(req.params.id).populate('team');
var statsPromise = playerPromise.then(function(playerRecord) {
if (typeof playerRecord === 'undefined' || playerRecord === null) {
res.notFound();
} else {
return Statistics.findOne({player: playerRecord.id, week: null, season: 1, team: null});
}
})
.catch(function(error) {
sails.log(error);
res.serverError();
});
Promise.all([playerPromise, statsPromise]).spread(function(playerRecord, statsRecord) {
res.view('players/view.jade', {player: playerRecord, stats: statsRecord});
})
.catch(function(error) {
sails.log(error);
res.serverError();
});
}
};
|
/**
* PlayersController
*
* @description :: Server-side logic for managing Players
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
view: function(req, res) {
Players.findOne(req.params.id)
.populate('team')
.exec(function(err, playerRecord) {
if (typeof playerRecord === 'undefined' || playerRecord === null) {
res.notFound();
} else {
Statistics.findOne({player: playerRecord.id, week: null, season: 1, team: null}).exec(function (err, statsRecord) {
res.view('players/view.jade', {player: playerRecord, stats: statsRecord});
});
}
});
}
};
|
Remove references to customer.io service class
|
<?php
namespace Northstar\Console\Commands;
use Northstar\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Northstar\Jobs\SendUserToCustomerIo;
class BackfillCustomerIo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'northstar:cio';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Re-export all profiles to Customer.io.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
// @TODO: Running this command will cause users to be sent to customer.io twice
$query = User::where('cio_full_backfill', '!=', true);
$progress = $this->output->createProgressBar($query->count());
$query->chunkById(200, function (Collection $users) use ($progress) {
$users->each(function (User $user) use ($progress) {
dispatch(new SendUserToCustomerIo($user));
$progress->advance();
});
});
$this->info(' Done!');
}
}
|
<?php
namespace Northstar\Console\Commands;
use Northstar\Models\User;
use Illuminate\Console\Command;
use Northstar\Services\CustomerIo;
use Illuminate\Support\Collection;
use Northstar\Jobs\SendUserToCustomerIo;
class BackfillCustomerIo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'northstar:cio';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Re-export all profiles to Customer.io.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(CustomerIo $customerIo)
{
// @TODO: Running this command will cause users to be sent to customer.io twice
$query = User::where('cio_full_backfill', '!=', true);
$progress = $this->output->createProgressBar($query->count());
$query->chunkById(200, function (Collection $users) use ($customerIo, $progress) {
$users->each(function (User $user) use ($customerIo, $progress) {
dispatch(new SendUserToCustomerIo($user));
$progress->advance();
});
});
$this->info(' Done!');
}
}
|
Improve context menu event handling
|
(function() {
var menu = chrome.contextMenus.create({
title: "Wicket Source",
contexts: [ "all" ],
enabled: false,
onclick: function() {}
});
chrome.extension.onRequest.addListener(function (request) {
if (request.hasOwnProperty('wicketsource')) {
var ws = request.wicketsource;
if (ws == null) {
chrome.contextMenus.update(menu, {
enabled: false,
title: "Wicket Source"
});
return;
}
var idx = ws.indexOf(':');
if (idx > -1) {
ws = ws.substring(idx + 1);
}
ws = ws.replace(/\.java:/, ':');
chrome.contextMenus.update(menu, {
enabled: true,
title: "Wicket Source - " + ws,
onclick: function () {
var ajax = new XMLHttpRequest();
var url = "http://localhost:9123/open?src=" + encodeURIComponent(request.wicketsource);
ajax.open("GET", url, true);
ajax.send();
}
});
}
});
})();
|
(function() {
var wicketsource, menu;
menu = chrome.contextMenus.create({
title: "Wicket Source",
contexts: ["all"],
onclick: function (info) {
if (wicketsource) {
var ajax = new XMLHttpRequest();
var url = "http://localhost:9123/open?src=" + encodeURIComponent(wicketsource);
ajax.open("GET", url, true);
ajax.send();
}
},
enabled: false
});
chrome.extension.onRequest.addListener(function (request) {
if (request.hasOwnProperty('wicketsource')) {
wicketsource = request.wicketsource;
if (wicketsource != null) {
var idx = wicketsource.indexOf(':');
if (idx > -1) {
wicketsource = wicketsource.substring(idx + 1);
}
wicketsource = wicketsource.replace(/\.java:/, ':');
chrome.contextMenus.update(menu, {
enabled: true,
title: "Wicket Source - " + wicketsource
});
} else {
chrome.contextMenus.update(menu, {
enabled: false,
title: "Wicket Source"
});
}
}
});
})();
|
Add missing switch closing brace
|
const BotModule = require('../BotModule');
module.exports = BotModule.extend({
initialize: function (dependencyGraph) {
this._super(dependencyGraph);
this.discordClient.on('message', message => {
switch(true) {
case message.content.replace(/\s/g,'').toLowerCase().match(/([s5s]+(h|h|\|\-\|n)+[ii1|]+[tt7]+|[kk]+[uu]+[ss5]+[oo0]+|クソ|クソ|シット|しっと)+(([bb8]|\|3)+[oo0]+[ww]+|弓|ボウ|ぼう)+/) !== null:
// General swear filters
case message.content.toLowerCase().match(/(?<!mi)[s\$5s]+(h|h|\|\-\|n)+[ii1|]+[tt7]+(?!(tah|tim|ake))/) !== null:
case message.content.toLowerCase().match(/[ff]+[uu]+[cc]+[kk]+/) !== null:
message.delete();
}
});
}
});
|
const BotModule = require('../BotModule');
module.exports = BotModule.extend({
initialize: function (dependencyGraph) {
this._super(dependencyGraph);
this.discordClient.on('message', message => {
switch(true) {
case message.content.replace(/\s/g,'').toLowerCase().match(/([s5s]+(h|h|\|\-\|n)+[ii1|]+[tt7]+|[kk]+[uu]+[ss5]+[oo0]+|クソ|クソ|シット|しっと)+(([bb8]|\|3)+[oo0]+[ww]+|弓|ボウ|ぼう)+/) !== null:
// General swear filters
case message.content.toLowerCase().match(/(?<!mi)[s\$5s]+(h|h|\|\-\|n)+[ii1|]+[tt7]+(?!(tah|tim|ake))/) !== null:
case message.content.toLowerCase().match(/[ff]+[uu]+[cc]+[kk]+/) !== null:
message.delete();
});
}
});
|
Package the tests so downstream extensions can use them
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
packages = ['streamz', 'streamz.dataframe']
tests = [p + '.tests' for p in packages]
setup(name='streamz',
version='0.3.0',
description='Streams',
url='http://github.com/mrocklin/streamz/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='streams',
packages=packages + tests,
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
install_requires=list(open('requirements.txt').read().strip().split('\n')),
zip_safe=False)
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='streamz',
version='0.3.0',
description='Streams',
url='http://github.com/mrocklin/streamz/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='streams',
packages=['streamz', 'streamz.dataframe',
# 'streamz.tests'
],
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
install_requires=list(open('requirements.txt').read().strip().split('\n')),
zip_safe=False)
|
Add comments, add method to get all property names.
|
package config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/**
* Extract configuration/properties from conf.properties
*/
public class ConfigExtractor {
private final String configFile = "../conf.properties";
private static Properties configProp;
private static ConfigExtractor configInstance = null;
private ConfigExtractor() {
InputStream in = getClass().getResourceAsStream(configFile);
configProp = new Properties();
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Read a property value from the config file
*
* @param property we want to find value for
* @return value of property
*/
public static String getProperty(String property) {
if (configInstance == null) {
configInstance = new ConfigExtractor();
}
return configProp.getProperty(property);
}
/**
* Retrieve a enumeration with all properties.
* @return properties
*/
public static Enumeration<String> getPropertyList() {
if (configInstance == null) {
configInstance = new ConfigExtractor();
}
return (Enumeration<String>)configProp.propertyNames();
}
}
|
package config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigExtractor {
private final String configFile = "../conf.properties";
private static Properties configProp;
private static ConfigExtractor configInstance = null;
private ConfigExtractor() {
InputStream in = getClass().getResourceAsStream(configFile);
configProp = new Properties();
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String property) {
if (configInstance == null) {
configInstance = new ConfigExtractor();
}
return configProp.getProperty(property);
}
}
|
Add build namespace to built image environment
|
package builder
import (
"fmt"
"strings"
"github.com/openshift/origin/pkg/build/api"
)
type Builder interface {
Build() error
}
// imageTag returns the tag to be used for the build. If a registry has been
// specified, it will prepend the registry to the name
func imageTag(build *api.Build) string {
tag := build.Parameters.Output.ImageTag
if !strings.HasPrefix(tag, build.Parameters.Output.Registry) {
tag = fmt.Sprintf("%s/%s", build.Parameters.Output.Registry, tag)
}
return tag
}
// getBuildEnvVars returns a map with the environment variables that should be added
// to the built image
func getBuildEnvVars(build *api.Build) map[string]string {
envVars := map[string]string{
"OPENSHIFT_BUILD_NAME": build.Name,
"OPENSHIFT_BUILD_NAMESPACE": build.Namespace,
"OPENSHIFT_BUILD_SOURCE": build.Parameters.Source.Git.URI,
}
if build.Parameters.Source.Git.Ref != "" {
envVars["OPENSHIFT_BUILD_REFERENCE"] = build.Parameters.Source.Git.Ref
}
if build.Parameters.Revision != nil &&
build.Parameters.Revision.Git != nil &&
build.Parameters.Revision.Git.Commit != "" {
envVars["OPENSHIFT_BUILD_COMMIT"] = build.Parameters.Revision.Git.Commit
}
return envVars
}
|
package builder
import (
"fmt"
"strings"
"github.com/openshift/origin/pkg/build/api"
)
type Builder interface {
Build() error
}
// imageTag returns the tag to be used for the build. If a registry has been
// specified, it will prepend the registry to the name
func imageTag(build *api.Build) string {
tag := build.Parameters.Output.ImageTag
if !strings.HasPrefix(tag, build.Parameters.Output.Registry) {
tag = fmt.Sprintf("%s/%s", build.Parameters.Output.Registry, tag)
}
return tag
}
// getBuildEnvVars returns a map with the environment variables that should be added
// to the built image
func getBuildEnvVars(build *api.Build) map[string]string {
envVars := map[string]string{
"OPENSHIFT_BUILD_NAME": build.Name,
"OPENSHIFT_BUILD_SOURCE": build.Parameters.Source.Git.URI,
}
if build.Parameters.Source.Git.Ref != "" {
envVars["OPENSHIFT_BUILD_REFERENCE"] = build.Parameters.Source.Git.Ref
}
if build.Parameters.Revision != nil &&
build.Parameters.Revision.Git != nil &&
build.Parameters.Revision.Git.Commit != "" {
envVars["OPENSHIFT_BUILD_COMMIT"] = build.Parameters.Revision.Git.Commit
}
return envVars
}
|
Add temporary workaround for monkey-patching bug
pyuv_cffi needs to be imported BEFORE monkey-patching the standard library in
order to successfully build the shared library. Need to find a workaround for
this. Once the library is built, subsequent imports will work fine even after
monkey-patching.
|
# FIXME: pyuv_cffi needs to build the library BEFORE the standard library is patched
import pyuv_cffi
print('pyuv_cffi imported', pyuv_cffi)
import guv
guv.monkey_patch()
import guv.server
import logging
import time
from util import create_example
import logger
if not hasattr(time, 'perf_counter'):
time.perf_counter = time.clock
logger.configure()
log = logging.getLogger()
response_times = []
def get_avg_time():
global response_times
times = response_times[-1000:]
avg = sum(times) / len(times)
if len(response_times) > 5000:
response_times = times
return avg
def handle(sock, addr):
# client connected
start_time = time.perf_counter()
sock.sendall(create_example())
sock.close()
total_time = time.perf_counter() - start_time
response_times.append(total_time)
if __name__ == '__main__':
pool = guv.GreenPool()
try:
log.debug('Start')
server_sock = guv.listen(('0.0.0.0', 8001))
server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
server.start()
except (SystemExit, KeyboardInterrupt):
log.debug('average response time: {}'.format(get_avg_time()))
log.debug('Bye!')
|
import guv
guv.monkey_patch()
import guv.server
import logging
import time
from util import create_example
import logger
if not hasattr(time, 'perf_counter'):
time.perf_counter = time.clock
logger.configure()
log = logging.getLogger()
response_times = []
def get_avg_time():
global response_times
times = response_times[-1000:]
avg = sum(times) / len(times)
if len(response_times) > 5000:
response_times = times
return avg
def handle(sock, addr):
# client connected
start_time = time.perf_counter()
sock.sendall(create_example())
sock.close()
total_time = time.perf_counter() - start_time
response_times.append(total_time)
if __name__ == '__main__':
pool = guv.GreenPool()
try:
log.debug('Start')
server_sock = guv.listen(('0.0.0.0', 8001))
server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
server.start()
except (SystemExit, KeyboardInterrupt):
log.debug('average response time: {}'.format(get_avg_time()))
log.debug('Bye!')
|
Fix to work on CI
|
package test.com.github.tmurakami.dexopener;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;
public class MyFragmentTest {
@Rule
public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class);
@Mock
MyService service;
private final MyFragment target = new MyFragment();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
target.service = service;
}
@Test
public void testOnCreate() {
Object o = new Object();
willReturn(o).given(service).doIt();
rule.getActivity().getSupportFragmentManager().beginTransaction().add(target, null).commit();
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
assertEquals(o, target.result);
}
}
|
package test.com.github.tmurakami.dexopener;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;
public class MyFragmentTest {
@Rule
public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class, false, false);
@Mock
MyService service;
private final MyFragment target = new MyFragment();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
target.service = service;
}
@Test
public void testOnCreate() {
Object o = new Object();
willReturn(o).given(service).doIt();
rule.launchActivity(null).getSupportFragmentManager().beginTransaction().add(target, null).commit();
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
assertEquals(o, target.result);
}
}
|
Add Access-Control headers to python
|
import json
import functools
from flask import Flask, Response
from foxgami.red import Story
app = Flask(__name__)
@app.after_response
def add_content_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
return response
def return_as_json(inner_f):
@functools.wraps(inner_f)
def new_f(*args, **kwargs):
result = inner_f(*args, **kwargs)
return Response(json.dumps(
result,
indent=4,
separators=(', ', ': ')
), mimetype='application/json')
return new_f
@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
return Story.find()
@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
return Story.get(story_id)
if __name__ == '__main__':
app.run(debug=True)
|
import json
import functools
from flask import Flask, Response
from foxgami.red import Story
app = Flask(__name__)
def return_as_json(inner_f):
@functools.wraps(inner_f)
def new_f(*args, **kwargs):
result = inner_f(*args, **kwargs)
return Response(json.dumps(
result,
indent=4,
separators=(', ', ': ')
), mimetype='application/json')
return new_f
@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
return Story.find()
@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
return Story.get(story_id)
if __name__ == '__main__':
app.run(debug=True)
|
Make sure triggering undo/redo properly updates overlays.
|
import { win, isIframe } from 'classes/helpers';
import { eventBus } from './eventbus';
import UndoStack from 'classes/UndoStack';
const trackedMutations = {
updateFieldValue: 'Update to block field',
addBlock: 'Added block to page',
reorderBlocks: 'Reordered blocks on page',
deleteBlock: 'Deleted block on page'
};
const undoStack = new UndoStack({ lock: true });
const undoRedo = store => {
if(isIframe) {
return;
}
undoStack.setUndoRedo(pageData => {
store.commit('setPage', JSON.parse(pageData));
eventBus.$emit('block:hideHoverOverlay');
eventBus.$emit('block:updateBlockOverlays');
});
undoStack.setCallback(({ canUndo, canRedo }) => {
store.commit('updateUndoRedo', { canUndo, canRedo });
});
store.subscribe((mutation, state) => {
if(!trackedMutations[mutation.type]) {
return;
}
undoStack.add(state.page.pageData);
});
};
export default undoRedo;
export const undoStackInstance = isIframe ?
win.top.astroUndoStack : (win.astroUndoStack = undoStack);
|
import { win, isIframe } from 'classes/helpers';
import { eventBus } from './eventbus';
import UndoStack from 'classes/UndoStack';
const trackedMutations = {
updateFieldValue: 'Update to block field',
addBlock: 'Added block to page',
reorderBlocks: 'Reordered blocks on page',
deleteBlock: 'Deleted block on page'
};
const undoStack = new UndoStack({ lock: true });
const undoRedo = store => {
if(isIframe) {
return;
}
undoStack.setUndoRedo(pageData => {
store.commit('setPage', JSON.parse(pageData));
eventBus.$emit('block:hideHoverOverlay', null);
eventBus.$emit('block:hideSelectedOverlay', null);
});
undoStack.setCallback(({ canUndo, canRedo }) => {
store.commit('updateUndoRedo', { canUndo, canRedo });
});
store.subscribe((mutation, state) => {
if(!trackedMutations[mutation.type]) {
return;
}
undoStack.add(state.page.pageData);
});
};
export default undoRedo;
export const undoStackInstance = isIframe ?
win.top.astroUndoStack : (win.astroUndoStack = undoStack);
|
Split MakeUnique function (to allow for more generic use, eg. commits as well)
|
/*
* Copyright 2016 Frank Wessels <fwessels@xs4all.nl>
*
* 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 s3git
import (
"errors"
)
// Get the full size unique hash for a given prefix.
// Return error in case none or multiple candidates are found
func (repo Repository) MakeUnique(prefix string) (string, error) {
list, errList := repo.List(prefix)
if errList != nil {
return "", errList
}
return getUnique(list)
}
func getUnique(list <-chan string) (string, error) {
err := errors.New("Not found (be less specific)")
hash := ""
for elem := range list {
if len(hash) == 0 {
hash, err = elem, nil
} else {
err = errors.New("More than one possiblity found (be more specific)")
}
}
return hash, err
}
|
/*
* Copyright 2016 Frank Wessels <fwessels@xs4all.nl>
*
* 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 s3git
import (
"errors"
)
// Get the full size unique hash for a given prefix.
// Return error in case none or multiple candidates are found
func (repo Repository) MakeUnique(prefix string) (string, error) {
list, errList := repo.List(prefix)
if errList != nil {
return "", errList
}
err := errors.New("Not found (be less specific)")
hash := ""
for elem := range list {
if len(hash) == 0 {
hash, err = elem, nil
} else {
err = errors.New("More than one possiblity found (be more specific)")
}
}
return hash, err
}
|
Set middleware classes to suppress warning on 1.7+
|
#!/usr/bin/env python
import os
import sys
from django.conf import settings
try:
from django import setup
except ImportError:
def setup():
pass
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=(
'selectable',
),
SITE_ID=1,
SECRET_KEY='super-secret',
ROOT_URLCONF='selectable.tests.urls',
)
from django.test.utils import get_runner
def runtests():
setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
args = sys.argv[1:] or ['selectable', ]
failures = test_runner.run_tests(args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
#!/usr/bin/env python
import os
import sys
from django.conf import settings
try:
from django import setup
except ImportError:
def setup():
pass
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'selectable',
),
SITE_ID=1,
SECRET_KEY='super-secret',
ROOT_URLCONF='selectable.tests.urls',
)
from django.test.utils import get_runner
def runtests():
setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
args = sys.argv[1:] or ['selectable', ]
failures = test_runner.run_tests(args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Expand simple test with another header.
|
// Copyright 2014, Kevin Ko <kevin@faveset.com>
package com.faveset.khttp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.nio.ByteBuffer;
@RunWith(JUnit4.class)
public class RequestHeaderHandlerTest {
@Test
public void testSimple() throws InvalidRequestException {
ByteBuffer buf = Helper.makeByteBuffer("hello: world\n");
HandlerState state = new HandlerState();
RequestHeaderHandler handler = new RequestHeaderHandler();
assertFalse(handler.handleState(null, buf, state));
assertEquals(1, state.getRequest().getHeader("hello").size());
assertEquals("world", state.getRequest().getHeaderFirst("hello"));
buf.clear();
buf.put(Helper.makeByteBuffer("foo: bar\r\n"));
buf.flip();
assertFalse(handler.handleState(null, buf, state));
assertEquals(1, state.getRequest().getHeader("foo").size());
assertEquals("bar", state.getRequest().getHeaderFirst("foo"));
buf.clear();
buf.put(Helper.makeByteBuffer("\n"));
buf.flip();
assertTrue(handler.handleState(null, buf, state));
}
}
|
// Copyright 2014, Kevin Ko <kevin@faveset.com>
package com.faveset.khttp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.nio.ByteBuffer;
@RunWith(JUnit4.class)
public class RequestHeaderHandlerTest {
@Test
public void testSimple() throws InvalidRequestException {
ByteBuffer buf = Helper.makeByteBuffer("hello: world\n");
HandlerState state = new HandlerState();
RequestHeaderHandler handler = new RequestHeaderHandler();
assertFalse(handler.handleState(null, buf, state));
assertEquals(1, state.getRequest().getHeader("hello").size());
assertEquals("world", state.getRequest().getHeaderFirst("hello"));
buf.clear();
buf.put(Helper.makeByteBuffer("\n"));
buf.flip();
assertTrue(handler.handleState(null, buf, state));
}
}
|
Make sure target destination has the right path separator.
Signed-off-by: David Calavera <b9b0c8e7f90ecf337f6797c4d2e0f1dd0dbc0324@gmail.com>
|
package target
import (
"io"
"path/filepath"
"github.com/spf13/hugo/helpers"
"github.com/spf13/hugo/hugofs"
)
type Publisher interface {
Publish(string, io.Reader) error
}
type Translator interface {
Translate(string) (string, error)
}
// TODO(bep) consider other ways to solve this.
type OptionalTranslator interface {
TranslateRelative(string) (string, error)
}
type Output interface {
Publisher
Translator
}
type Filesystem struct {
PublishDir string
}
func (fs *Filesystem) Publish(path string, r io.Reader) (err error) {
translated, err := fs.Translate(path)
if err != nil {
return
}
return helpers.WriteToDisk(translated, r, hugofs.DestinationFS)
}
func (fs *Filesystem) Translate(src string) (dest string, err error) {
return filepath.Join(fs.PublishDir, filepath.FromSlash(src)), nil
}
func (fs *Filesystem) extension(ext string) string {
return ext
}
func filename(f string) string {
ext := filepath.Ext(f)
if ext == "" {
return f
}
return f[:len(f)-len(ext)]
}
|
package target
import (
"io"
"path/filepath"
"github.com/spf13/hugo/helpers"
"github.com/spf13/hugo/hugofs"
)
type Publisher interface {
Publish(string, io.Reader) error
}
type Translator interface {
Translate(string) (string, error)
}
// TODO(bep) consider other ways to solve this.
type OptionalTranslator interface {
TranslateRelative(string) (string, error)
}
type Output interface {
Publisher
Translator
}
type Filesystem struct {
PublishDir string
}
func (fs *Filesystem) Publish(path string, r io.Reader) (err error) {
translated, err := fs.Translate(path)
if err != nil {
return
}
return helpers.WriteToDisk(translated, r, hugofs.DestinationFS)
}
func (fs *Filesystem) Translate(src string) (dest string, err error) {
return filepath.Join(fs.PublishDir, src), nil
}
func (fs *Filesystem) extension(ext string) string {
return ext
}
func filename(f string) string {
ext := filepath.Ext(f)
if ext == "" {
return f
}
return f[:len(f)-len(ext)]
}
|
Disable dev tools for now.
|
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
// Keep main window in scope so it isn't garbage collected
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({ width: 1000, height: 750 })
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
|
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
// Keep main window in scope so it isn't garbage collected
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({ width: 1000, height: 750 })
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
|
Fix tick, prepare for pending contracts
|
package main
import (
"fmt"
"io"
"net/http"
)
type agent struct {
name string
value int
}
var tick int
var agents []*agent
var broadcastGroup []chan bool
func broadcastTick(cs []chan bool) {
for _, c := range cs {
c <- true
}
}
func hello(w http.ResponseWriter, r *http.Request) {
broadcastTick(broadcastGroup)
tick++
for _, a := range agents {
io.WriteString(w,
fmt.Sprintf("Agent: %v, Val:%v\n", a.name, a.value))
}
io.WriteString(w, "\n___________\n")
io.WriteString(w, "Stuff\n")
io.WriteString(w, "\n___________\n")
io.WriteString(w, fmt.Sprintf("Tick: %v", tick))
io.WriteString(w, "\n___________\n")
}
func addAgent(name string, v int) {
agent := &agent{name, v}
agents = append(agents, agent)
tick := make(chan bool, 1)
broadcastGroup = append(broadcastGroup, tick)
go func() {
for {
<-tick // Wait for tick.
agent.value++
}
}()
}
func main() {
addAgent("a", 0)
addAgent("b", 1)
addAgent("bank", 50)
http.HandleFunc("/view", hello)
http.ListenAndServe(":8080", nil)
}
|
package main
import (
"fmt"
"io"
"net/http"
)
type agent struct {
name string
value int
}
var agents []*agent
var broadcastGroup []chan bool
func broadcastTick(cs []chan bool) {
for _, c := range cs {
c <- true
}
}
func hello(w http.ResponseWriter, r *http.Request) {
broadcastTick(broadcastGroup)
for _, a := range agents {
io.WriteString(w,
fmt.Sprintf("Agent: %v, Val:%v\n", a.name, a.value))
}
}
func addAgent(name string, v int) {
go func() {
agent := &agent{name, v}
agents = append(agents, agent)
tick := make(chan bool, 1)
broadcastGroup = append(broadcastGroup, tick)
for {
<-tick // Wait for tick.
agent.value++
}
}()
}
func main() {
addAgent("a", 0)
addAgent("b", 1)
addAgent("bank", 50)
http.HandleFunc("/", hello)
http.ListenAndServe(":8080", nil)
}
|
Fix deprecation warning of router
ember-router.router renamed to ember-router._routerMicrolib in ember 2.13
https://emberjs.com/deprecations/v2.x/#toc_ember-router-router-renamed-to-ember-router-_routermicrolib
|
import Ember from 'ember';
const { get, set, guidFor, merge, getOwner } = Ember;
function updateTitle(tokens) {
set(this, 'title', tokens.toString());
}
export default Ember.Helper.extend({
pageTitleList: Ember.inject.service(),
headData: Ember.inject.service(),
init() {
this._super();
let tokens = get(this, 'pageTitleList');
tokens.push({ id: guidFor(this) });
},
compute(params, _hash) {
let tokens = get(this, 'pageTitleList');
let hash = merge({}, _hash);
hash.id = guidFor(this);
hash.title = params.join('');
tokens.push(hash);
Ember.run.scheduleOnce('afterRender', get(this, 'headData'), updateTitle, tokens);
return '';
},
destroy() {
let tokens = get(this, 'pageTitleList');
let id = guidFor(this);
tokens.remove(id);
let router = getOwner(this).lookup('router:main');
let routes = router._routerMicrolib || router.router;
let { activeTransition } = routes;
let headData = get(this, 'headData');
if (activeTransition) {
activeTransition.promise.finally(function () {
if (headData.isDestroyed) { return; }
Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens);
});
} else {
Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens);
}
}
});
|
import Ember from 'ember';
const { get, set, guidFor, merge, getOwner } = Ember;
function updateTitle(tokens) {
set(this, 'title', tokens.toString());
}
export default Ember.Helper.extend({
pageTitleList: Ember.inject.service(),
headData: Ember.inject.service(),
init() {
this._super();
let tokens = get(this, 'pageTitleList');
tokens.push({ id: guidFor(this) });
},
compute(params, _hash) {
let tokens = get(this, 'pageTitleList');
let hash = merge({}, _hash);
hash.id = guidFor(this);
hash.title = params.join('');
tokens.push(hash);
Ember.run.scheduleOnce('afterRender', get(this, 'headData'), updateTitle, tokens);
return '';
},
destroy() {
let tokens = get(this, 'pageTitleList');
let id = guidFor(this);
tokens.remove(id);
let activeTransition = getOwner(this).lookup('router:main').get('router.activeTransition');
let headData = get(this, 'headData');
if (activeTransition) {
activeTransition.promise.finally(function () {
if (headData.isDestroyed) { return; }
Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens);
});
} else {
Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens);
}
}
});
|
Add script to fix mobile menu JS not functioning.
|
<?php include 'templates/header.php'; ?>
<div class="col-sm-12 row">
<div class="col-sm-12">
<h2>
User Options
</h2>
<p>
Modify your options to your preferences.
</p>
<p>
<b>
Email:
</b>
<?php echo $_SESSION['user']; ?>
</p>
<?php include 'templates/color-select.html'; ?>
<?php include 'templates/sections.html'; ?>
<?php include 'templates/password.php'; ?>
</div>
</div>
<?php echo '<script>var userId = "' . $_SESSION['userId'] . '"; </script>'; // use this to echo the session user ID for the JS to use ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/user-script.js"></script>
<?php include 'templates/footer.html'; ?>
|
<?php include 'templates/header.php'; ?>
<div class="col-sm-12 row">
<div class="col-sm-12">
<h2>
User Options
</h2>
<p>
Modify your options to your preferences.
</p>
<p>
<b>
Email:
</b>
<?php echo $_SESSION['user']; ?>
</p>
<?php include 'templates/color-select.html'; ?>
<?php include 'templates/sections.html'; ?>
<?php include 'templates/password.php'; ?>
</div>
</div>
<?php echo '<script>var userId = "' . $_SESSION['userId'] . '"; </script>'; // use this to echo the session user ID for the JS to use ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="js/user-script.js"></script>
<?php include 'templates/footer.html'; ?>
|
Add missing methods to NN class
|
## FIX use ffnet for now, use sklearn in future
from ffnet import ffnet,mlgraph,tmlgraph
import numpy as np
from scipy.stats import linregress
class neuralnetwork:
def __init__(self, shape, loadnet=None, full_conn=True, biases=False):
"""
shape: shape of a NN given as a tuple
"""
if loadnet:
self.model = ffnet()
self.model.load(loadnet)
else:
if full_conn:
conec = tmlgraph(shape, biases)
else:
conec = mlgraph(shapebiases)
self.model = ffnet(conec)
def fit(self, input_descriptors, target_values, train_alg='tnc'):
getattr(self.model, 'train_'+train_alg)(input_descriptors, target_values, maxfun=10000)
def predict(self, input_descriptors):
return np.array(self.model.call(input_descriptors))
def score(X, y):
return linregress(self.predict(X), y)[2]**2
|
## FIX use ffnet for now, use sklearn in future
from ffnet import ffnet,mlgraph,tmlgraph
import numpy as np
class neuralnetwork:
def __init__(self, shape, loadnet=None, full_conn=True, biases=False):
"""
shape: shape of a NN given as a tuple
"""
if loadnet:
self.model = ffnet()
self.model.load(loadnet)
else:
if full_conn:
conec = tmlgraph(shape, biases)
else:
conec = mlgraph(shapebiases)
self.model = ffnet(conec)
def fit(self, input_descriptors, target_values, train_alg='tnc'):
getattr(self.model, 'train_'+train_alg)(input_descriptors, target_values, maxfun=10000)
def predict(self, input_descriptors):
return np.array(self.model.call(input_descriptors)).flatten()
|
Fix - send JSON to the API, not raw data
|
"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
"""Post data into the REST API endpoint for user-intent."""
url = "/api/v1/user-intent"
if payload is not None:
context.response = requests.post(context.coreapi_url + url,
headers=authorization(context),
json=payload)
else:
context.response = requests.post(context.coreapi_url + url,
headers=authorization(context))
@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
"""Post no payload into the REST API endpoint for user-intent."""
post_data_to_user_intent_endpoint(context)
@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
"""Post empty into the REST API endpoint for user-intent."""
payload = {}
post_data_to_user_intent_endpoint(context, payload)
|
"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
"""Post data into the REST API endpoint for user-intent."""
url = "/api/v1/user-intent"
if payload is not None:
context.response = requests.post(context.coreapi_url + url,
headers=authorization(context),
data=payload)
else:
context.response = requests.post(context.coreapi_url + url,
headers=authorization(context))
@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
"""Post no payload into the REST API endpoint for user-intent."""
post_data_to_user_intent_endpoint(context)
@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
"""Post empty into the REST API endpoint for user-intent."""
payload = {}
post_data_to_user_intent_endpoint(context, payload)
|
Fix Slides & Quotes for home
|
from bluebottle.slides.models import Slide
from bluebottle.projects import get_project_model
from bluebottle.quotes.models import Quote
PROJECT_MODEL = get_project_model()
class HomePage(object):
def get(self, language):
# FIXME: Hack to make sure quotes and slides load.
if language == 'en-us':
language = 'en_US'
self.id = 1
self.quotes = Quote.objects.published().filter(language=language)
self.slides = Slide.objects.published().filter(language=language)
projects = PROJECT_MODEL.objects.filter(status__viewable=True).order_by('?')
if len(projects) > 4:
self.projects = projects[0:4]
elif len(projects) > 0:
self.projects = projects[0:len(projects)]
else:
self.projects = None
return self
|
from bluebottle.slides.models import Slide
from bluebottle.projects import get_project_model
from bluebottle.quotes.models import Quote
PROJECT_MODEL = get_project_model()
class HomePage(object):
def get(self, language):
self.id = 1
self.quotes = Quote.objects.published().filter(language=language)
self.slides = Slide.objects.published().filter(language=language)
projects = PROJECT_MODEL.objects.filter(status__viewable=True, favorite=True).order_by('?')
if len(projects) > 4:
self.projects = projects[0:4]
elif len(projects) > 0:
self.projects = projects[0:len(projects)]
else:
self.projects = None
return self
|
Add missing loading movie details call to presenter
|
package com.tobi.movies.posterdetails;
public class MovieDetailsPresenter implements MovieDetailsMVP.Presenter {
private final MovieDetailsUseCase movieDetailsUseCase;
public MovieDetailsPresenter(MovieDetailsUseCase movieDetailsUseCase) {
this.movieDetailsUseCase = movieDetailsUseCase;
}
@Override
public void startPresenting(final MovieDetailsMVP.View movieDetailsView, long movieId) {
MovieDetails movieDetails = movieDetailsUseCase.getMovieDetails();
if (movieDetails != null) {
movieDetailsView.display(movieDetails);
} else {
movieDetailsUseCase.setListener(new MovieDetailsUseCase.Listener() {
@Override
public void onMovieDetails(MovieDetails movieDetails) {
movieDetailsView.display(movieDetails);
}
@Override
public void onError(Throwable throwable) {
movieDetailsView.showError();
}
});
movieDetailsUseCase.loadMovieDetails(movieId);
}
}
@Override
public void stopPresenting() {
movieDetailsUseCase.setListener(null);
}
}
|
package com.tobi.movies.posterdetails;
public class MovieDetailsPresenter implements MovieDetailsMVP.Presenter {
private final MovieDetailsUseCase movieDetailsUseCase;
public MovieDetailsPresenter(MovieDetailsUseCase movieDetailsUseCase) {
this.movieDetailsUseCase = movieDetailsUseCase;
}
@Override
public void startPresenting(final MovieDetailsMVP.View movieDetailsView, long movieId) {
MovieDetails movieDetails = movieDetailsUseCase.getMovieDetails();
if (movieDetails != null) {
movieDetailsView.display(movieDetails);
} else {
movieDetailsUseCase.setListener(new MovieDetailsUseCase.Listener() {
@Override
public void onMovieDetails(MovieDetails movieDetails) {
movieDetailsView.display(movieDetails);
}
@Override
public void onError(Throwable throwable) {
movieDetailsView.showError();
}
});
}
}
@Override
public void stopPresenting() {
movieDetailsUseCase.setListener(null);
}
}
|
Fix spaces in error message
|
package service
import "fmt"
//Builder is a simple implementation of ContainerBuilder
type Builder struct {
definitions []Definition
}
//Insert a new definition into the Builder
func (b *Builder) Insert(def Definition) {
b.definitions = append(b.definitions, def)
}
//Build builds the container once all definitions have been place in it
//dependencies need to be inserted in order for now
func (b *Builder) Build() (Container, error) {
numDefs := len(b.definitions)
servs := make(map[string]interface{}, numDefs)
for _, def := range b.definitions {
numDeps := len(def.Dependencies)
deps := make(map[string]interface{}, numDeps)
for _, name := range def.Dependencies {
dep, ok := servs[name]
if !ok {
return nil, fmt.Errorf("service: Could not find "+
"dependency %q for service %q. Please make "+
"sure to insert them in order", name, def.Name)
}
deps[name] = dep
}
service, err := def.Initializer.Init(deps, def.Configuration)
if err != nil {
return nil, err
}
servs[def.Name] = service
}
return SimpleContainer{
services: servs,
}, nil
}
|
package service
import "fmt"
//Builder is a simple implementation of ContainerBuilder
type Builder struct {
definitions []Definition
}
//Insert a new definition into the Builder
func (b *Builder) Insert(def Definition) {
b.definitions = append(b.definitions, def)
}
//Build builds the container once all definitions have been place in it
//dependencies need to be inserted in order for now
func (b *Builder) Build() (Container, error) {
numDefs := len(b.definitions)
servs := make(map[string]interface{}, numDefs)
for _, def := range b.definitions {
numDeps := len(def.Dependencies)
deps := make(map[string]interface{}, numDeps)
for _, name := range def.Dependencies {
dep, ok := servs[name]
if !ok {
return nil, fmt.Errorf("service: Could not find"+
"dependency %q for service %q. Please make"+
"sure to insert them in order", name, def.Name)
}
deps[name] = dep
}
service, err := def.Initializer.Init(deps, def.Configuration)
if err != nil {
return nil, err
}
servs[def.Name] = service
}
return SimpleContainer{
services: servs,
}, nil
}
|
Clean the local NVD dir using homedir.Expand
|
package main
import (
"log"
"github.com/docopt/docopt-go"
"github.com/mitchellh/go-homedir"
)
func main() {
usage := `Usage: nvd-search [-c CVE | -k KEY] [-v VENDOR] [-p PRODUCT] [-n NVD]
Options:
-h --help show this
-c CVE --cve CVE CVE-ID of the vulnerability [default: ]
-k KEY --key KEY keyword search [default: ]
-v VENDOR --vendor VENDOR CPE vendor name [default: ]
-p PRODUCT --product PRODUCT CPE product name [default: ]
-n NVD --nvd NVD Location of the local NVD [default: ~/.config/nvd-cli/db]
`
args, _ := docopt.Parse(usage, nil, true, "nvd-cli 0.1", false)
path, err := homedir.Expand(args["--nvd"].(string))
if err != nil {
log.Fatal(err)
}
log.Println(path)
}
|
package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
usage := `Usage: nvd-search [-c CVE | -k KEY] [-v VENDOR] [-p PRODUCT] [-n NVD]
Options:
-h --help show this
-c CVE --cve CVE CVE-ID of the vulnerability [default: ]
-k KEY --key KEY keyword search [default: ]
-v VENDOR --vendor VENDOR CPE vendor name [default: ]
-p PRODUCT --product PRODUCT CPE product name [default: ]
-n NVD --nvd NVD Location of the local NVD [default: ~/.config/nvd-cli/db]
`
args, _ := docopt.Parse(usage, nil, true, "nvd-cli 0.1", false)
fmt.Println(args)
}
|
Add dummy cb when none given
|
const getModel = require( './model.js' );
module.exports = function ( modelName, item, cb ) {
if (cb === undefined) cb = ()=>{};
return new Promise( ( resolve ) => {
getModel( modelName )
.then( ( model, b ) => {
if ( ! item.id && item.id !== 0 )
return resolve( model.create( item, cb ) );
model.findOrCreate( {
id: item.id
}, () => {
resolve( model.update( {
id: item.id
}, item, cb ) );
} );
} );
} );
};
|
const getModel = require( './model.js' );
module.exports = function ( modelName, item, cb ) {
return new Promise( ( resolve ) => {
getModel( modelName )
.then( ( model, b ) => {
if ( ! item.id && item.id !== 0 )
return resolve( model.create( item, cb ) );
model.findOrCreate( {
id: item.id
}, () => {
resolve( model.update( {
id: item.id
}, item, cb ) );
} );
} );
} );
};
|
Simplify retrieval of literal for insertion recovery messages
|
package org.spoofax.jsglr2.recovery;
import org.metaborg.parsetable.productions.IProduction;
import org.metaborg.parsetable.symbols.ILiteralSymbol;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;
public class RecoveryMessages {
public static Message get(IProduction production, Position start, Position end) {
SourceRegion region = new SourceRegion(start, end);
String message;
if("WATER".equals(production.constructor()))
message = "Not expected";
else if("INSERTION".equals(production.constructor())) {
String insertion;
if (production.isLiteral())
insertion = ((ILiteralSymbol) production.lhs()).literal();
else
insertion = "Token";
message = insertion + " expected";
} else
message = "Invalid syntax";
return Message.error(message, region);
}
}
|
package org.spoofax.jsglr2.recovery;
import org.metaborg.parsetable.productions.IProduction;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;
public class RecoveryMessages {
public static Message get(IProduction production, Position start, Position end) {
SourceRegion region = new SourceRegion(start, end);
String message;
if("WATER".equals(production.constructor()))
message = "Not expected";
else if("INSERTION".equals(production.constructor())) {
String insertion;
if (production.isLiteral())
insertion = production.lhs().descriptor().replaceAll("^\"|\"$", "");
else
insertion = "Token";
message = insertion + " expected";
} else
message = "Invalid syntax";
return Message.error(message, region);
}
}
|
Add classifier for Python 3.3
|
#!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine Pitrou',
author_email='solipsis@pitrou.net',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Filesystems',
],
download_url='https://pypi.python.org/pypi/pathlib/',
url='http://readthedocs.org/docs/pathlib/',
)
|
#!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine Pitrou',
author_email='solipsis@pitrou.net',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Filesystems',
],
download_url='https://pypi.python.org/pypi/pathlib/',
url='http://readthedocs.org/docs/pathlib/',
)
|
Test coverage for DEL_SERIES action
|
import assert from 'assert';
import series from './series';
import * as TYPES from '../../actions/types';
describe('A series reducer for redux state', () => {
//Test states
const seriesDefaultState = {};
const seriesWithTicker = { GOOGL: [] };
//Test actions
const testAddSeries = {
type: TYPES.ADD_SERIES,
ticker: 'GOOGL',
data: [],
}
const testDelSeries = {
type: TYPES.DEL_SERIES,
ticker: 'GOOGL',
}
const testInvalidAction = {
type: 'INVALID_ACTION',
}
it('should return a default state when no arguments are supplied', () => {
assert.deepEqual(series(), seriesDefaultState );
})
it('should add an empty series attribute if it is missing from the supplied state', () => {
assert.deepEqual(series({}), seriesDefaultState);
})
it('should return an unchanged state when no actions are supplied', () => {
assert.deepEqual(series(seriesDefaultState), seriesDefaultState);
})
it('should return an unchanged state when an invalid action is supplied', () => {
assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState);
})
it('should return a new state based on a ADD_SERIES action', () => {
assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker);
})
it('should return a new state based on a DEL_SERIES action', () => {
assert.deepEqual(series(seriesDefaultState, testDelSeries), seriesDefaultState);
})
it('should return a new object', () => {
assert(series({}) !== {});
})
})
|
import assert from 'assert';
import series from './series';
import * as TYPES from '../../actions/types';
describe('A series reducer for redux state', () => {
//Test states
const seriesDefaultState = {};
const seriesWithTicker = { GOOGL: [] };
//Test actions
const testAddSeries = {
type: TYPES.ADD_SERIES,
ticker: 'GOOGL',
data: [],
}
const testInvalidAction = {
type: 'INVALID_ACTION',
}
it('should return a default state when no arguments are supplied', () => {
assert.deepEqual(series(), seriesDefaultState );
})
it('should add an empty series attribute if it is missing from the supplied state', () => {
assert.deepEqual(series({}), seriesDefaultState);
})
it('should return an unchanged state when no actions are supplied', () => {
assert.deepEqual(series(seriesDefaultState), seriesDefaultState);
})
it('should return an unchanged state when an invalid action is supplied', () => {
assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState);
})
it('should return a new state based on a passed action', () => {
assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker);
})
it('should return a new object', () => {
assert(series({}) !== {});
})
})
|
Add documentation url and update version number
|
<?php
namespace Craft;
class AssetRevPlugin extends BasePlugin
{
/**
* @return string
*/
public function getName()
{
return 'Asset Rev';
}
/**
* Returns the plugin’s version number.
*
* @return string The plugin’s version number.
*/
public function getVersion()
{
return '3.0.0';
}
/**
* Returns the plugin developer’s name.
*
* @return string The plugin developer’s name.
*/
public function getDeveloper()
{
return 'Club Studio Ltd';
}
/**
* Returns the plugin developer’s URL.
*
* @return string The plugin developer’s URL.
*/
public function getDeveloperUrl()
{
return 'https://clubstudio.co.uk';
}
/**
* @return string
*/
public function getDocumentationUrl()
{
return 'https://github.com/clubstudioltd/craft-asset-rev';
}
/**
* Add Twig Extension
*
* @return AssetRevTwigExtension
* @throws \Exception
*/
public function addTwigExtension()
{
Craft::import('plugins.assetrev.twigextensions.AssetRevTwigExtension');
return new AssetRevTwigExtension();
}
}
|
<?php
namespace Craft;
class AssetRevPlugin extends BasePlugin
{
/**
* @return string
*/
public function getName()
{
return 'Asset Rev';
}
/**
* Returns the plugin’s version number.
*
* @return string The plugin’s version number.
*/
public function getVersion()
{
return '2.0.1';
}
/**
* Returns the plugin developer’s name.
*
* @return string The plugin developer’s name.
*/
public function getDeveloper()
{
return 'Club Studio Ltd';
}
/**
* Returns the plugin developer’s URL.
*
* @return string The plugin developer’s URL.
*/
public function getDeveloperUrl()
{
return 'https://clubstudio.co.uk';
}
/**
* Add Twig Extension
*
* @return AssetRevTwigExtension
* @throws \Exception
*/
public function addTwigExtension()
{
Craft::import('plugins.assetrev.twigextensions.AssetRevTwigExtension');
return new AssetRevTwigExtension();
}
/**
* Define plugin settings
*
* @return array
*/
protected function defineSettings()
{
return array(
'manifestPath' => array(AttributeType::String, 'required' => true),
);
}
/**
* Get settings html
*
* @return string
*/
public function getSettingsHtml()
{
return craft()->templates->render('assetrev/_settings', array(
'settings' => $this->getSettings(),
'basePath' => CRAFT_BASE_PATH,
));
}
}
|
Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'.
|
from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
|
from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
|
Add dates to dummy data.
|
$(function() {
yourCollection = new Models.ItemListings();
friendCollection = new Models.ItemListings();
featuredCollection = new Models.ItemListings();
publicCollection = new Models.ItemListings();
yourView = new Views.ListingView({
collection: yourCollection,
el: $('#you-listing')[0]
});
friendView = new Views.ListingView({
collection: friendCollection,
el: $('#friend-listing')[0]
});
featuredView = new Views.ListingView({
collection: featuredCollection,
el: $('#featured-listing')[0]
});
publicView = new Views.ListingView({
collection: publicCollection,
el: $('#public-listing')[0]
});
yourCollection.add({
id: 0,
name: "Test Item",
price: "5.00 (USD)",
location: "Singapore",
buyers: [0],
owner: 0,
imageUrl: 'http://placehold.it/96x96',
dateStart: new Date(2013, 8, 23),
dateEnd: new Date(2013, 9, 22)
});
friendCollection.add({
id: 1,
name: "Another Item",
price: "25.00 (USD)",
location: "Singapore",
buyers: [0, 1, 2],
owner: 1,
imageUrl: 'http://placehold.it/96x96',
dateStart: new Date(2013, 8, 22),
dateEnd: new Date(2013, 9, 16)
});
});
|
$(function() {
yourCollection = new Models.ItemListings();
friendCollection = new Models.ItemListings();
featuredCollection = new Models.ItemListings();
publicCollection = new Models.ItemListings();
yourView = new Views.ListingView({
collection: yourCollection,
el: $('#you-listing')[0]
});
friendView = new Views.ListingView({
collection: friendCollection,
el: $('#friend-listing')[0]
});
featuredView = new Views.ListingView({
collection: featuredCollection,
el: $('#featured-listing')[0]
});
publicView = new Views.ListingView({
collection: publicCollection,
el: $('#public-listing')[0]
});
yourCollection.add({
id: 0,
name: "Test Item",
price: "5.00 (USD)",
location: "Singapore",
buyers: [0],
owner: 0,
imageUrl: 'http://placehold.it/96x96'
});
friendCollection.add({
id: 1,
name: "Another Item",
price: "25.00 (USD)",
location: "Singapore",
buyers: [0, 1, 2],
owner: 1,
imageUrl: 'http://placehold.it/96x96'
});
});
|
Remove geolocation in wait for https
|
const html = require('choo/html');
const map = require('./map');
const { loader } = require('../icons');
const { __ } = require('../../locale');
module.exports = function (state, emit) {
let center;
const { cooperatives, user, geoip } = state;
if (user.isAuthenticated) {
const home = cooperatives.find(item => item._id === user.cooperative);
center = home && { longitude: home.lng, latitude: home.lat };
}
if ((!center || geoip.precission === 'exact') && geoip.longitude) {
center = {
longitude: geoip.longitude,
latitude: geoip.latitude,
isLoading: geoip.isLoading,
precission: geoip.precission
};
}
if (typeof window !== 'undefined' && !center) {
emit('geoip:fetch');
}
return html`
<div class="Map u-sizeFill u-flex u-flexCol u-flexJustifyCenter">
${ center ? map(state.cooperatives.slice(), center) : html`
<div class="u-colorSky u-flex u-flexJustifyCenter">
${ loader() }
</div>
` }
</div>
`;
};
|
const html = require('choo/html');
const map = require('./map');
const { loader } = require('../icons');
const { __ } = require('../../locale');
module.exports = function (state, emit) {
let center;
const { cooperatives, user, geoip } = state;
if (user.isAuthenticated) {
const home = cooperatives.find(item => item._id === user.cooperative);
center = home && { longitude: home.lng, latitude: home.lat };
}
if ((!center || geoip.precission === 'exact') && geoip.longitude) {
center = {
longitude: geoip.longitude,
latitude: geoip.latitude,
isLoading: geoip.isLoading,
precission: geoip.precission
};
}
if (typeof window !== 'undefined' && !center) {
emit('geoip:fetch');
}
return html`
<div class="Map u-sizeFill u-flex u-flexCol u-flexJustifyCenter">
${ center ? map(state.cooperatives.slice(), center) : html`
<div class="u-colorSky u-flex u-flexJustifyCenter">
${ loader() }
</div>
` }
<div class="Map-locate">
<button class="Button Button--round u-textS" onclick=${ () => emit('geoip:getPosition') } disabled=${ !!geoip.isLoading }>
${ __('Find me') }
</button>
</div>
</div>
`;
};
|
Fix typo: `dimentional` -> `dimensional`
|
from __future__ import unicode_literals
from itertools import product
from collections import defaultdict
__all__ = (
'MouseHandlers',
)
class MouseHandlers(object):
"""
Two dimensional raster of callbacks for mouse events.
"""
def __init__(self):
def dummy_callback(mouse_event):
"""
:param mouse_event: `MouseEvent` instance.
"""
# Map (x,y) tuples to handlers.
self.mouse_handlers = defaultdict(lambda: dummy_callback)
def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x, y] = handler
|
from __future__ import unicode_literals
from itertools import product
from collections import defaultdict
__all__ = (
'MouseHandlers',
)
class MouseHandlers(object):
"""
Two dimentional raster of callbacks for mouse events.
"""
def __init__(self):
def dummy_callback(mouse_event):
"""
:param mouse_event: `MouseEvent` instance.
"""
# Map (x,y) tuples to handlers.
self.mouse_handlers = defaultdict(lambda: dummy_callback)
def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x, y] = handler
|
:new: Enable the new confirmation dialog in latest package-deps
|
/* @flow */
import LinterUI from './main'
import type Intentions from './intentions'
const linterUiDefault = {
instances: new Set(),
signalRegistry: null,
statusBarRegistry: null,
activate() {
if (!atom.inSpecMode()) {
// eslint-disable-next-line global-require
require('atom-package-deps').install('linter-ui-default', true)
}
},
deactivate() {
for (const entry of this.instances) {
entry.dispose()
}
this.instances.clear()
},
provideUI(): LinterUI {
const instance = new LinterUI()
this.instances.add(instance)
if (this.signalRegistry) {
instance.signal.attach(this.signalRegistry)
}
return instance
},
provideIntentions(): Array<Intentions> {
return Array.from(this.instances).map(entry => entry.intentions)
},
consumeSignal(signalRegistry: Object) {
this.signalRegistry = signalRegistry
this.instances.forEach(function(instance) {
instance.signal.attach(signalRegistry)
})
},
consumeStatusBar(statusBarRegistry: Object) {
this.statusBarRegistry = statusBarRegistry
this.instances.forEach(function(instance) {
instance.statusBar.attach(statusBarRegistry)
})
}
}
module.exports = linterUiDefault
|
/* @flow */
import LinterUI from './main'
import type Intentions from './intentions'
const linterUiDefault = {
instances: new Set(),
signalRegistry: null,
statusBarRegistry: null,
activate() {
if (!atom.inSpecMode()) {
// eslint-disable-next-line global-require
require('atom-package-deps').install('linter-ui-default')
}
},
deactivate() {
for (const entry of this.instances) {
entry.dispose()
}
this.instances.clear()
},
provideUI(): LinterUI {
const instance = new LinterUI()
this.instances.add(instance)
if (this.signalRegistry) {
instance.signal.attach(this.signalRegistry)
}
return instance
},
provideIntentions(): Array<Intentions> {
return Array.from(this.instances).map(entry => entry.intentions)
},
consumeSignal(signalRegistry: Object) {
this.signalRegistry = signalRegistry
this.instances.forEach(function(instance) {
instance.signal.attach(signalRegistry)
})
},
consumeStatusBar(statusBarRegistry: Object) {
this.statusBarRegistry = statusBarRegistry
this.instances.forEach(function(instance) {
instance.statusBar.attach(statusBarRegistry)
})
}
}
module.exports = linterUiDefault
|
Remove moot empty file check
Closes #153
Closes #152
|
'use strict';
const dargs = require('dargs');
const execa = require('execa');
const gutil = require('gulp-util');
const through = require('through2');
module.exports = opts => {
opts = Object.assign({
colors: true,
suppress: false
}, opts);
if (Array.isArray(opts.globals)) {
// `globals` option should end up as a comma-separated list
opts.globals = opts.globals.join(',');
}
const args = dargs(opts, {
excludes: ['suppress'],
ignoreFalse: true
});
const files = [];
function aggregate(file, encoding, done) {
if (file.isStream()) {
done(new gutil.PluginError('gulp-mocha', 'Streaming not supported'));
return;
}
files.push(file.path);
done();
}
function flush(done) {
execa('mocha', files.concat(args))
.then(result => {
if (!opts.suppress) {
process.stdout.write(result.stdout);
}
// For testing
this.emit('_result', result);
done();
})
.catch(err => {
this.emit('error', new gutil.PluginError('gulp-mocha', err));
done();
});
}
return through.obj(aggregate, flush);
};
|
'use strict';
const dargs = require('dargs');
const execa = require('execa');
const gutil = require('gulp-util');
const through = require('through2');
module.exports = opts => {
opts = Object.assign({
colors: true,
suppress: false
}, opts);
if (Array.isArray(opts.globals)) {
// `globals` option should end up as a comma-separated list
opts.globals = opts.globals.join(',');
}
const args = dargs(opts, {
excludes: ['suppress'],
ignoreFalse: true
});
const files = [];
function aggregate(file, encoding, done) {
if (file.isNull()) {
done(null, file);
return;
}
if (file.isStream()) {
done(new gutil.PluginError('gulp-mocha', 'Streaming not supported'));
return;
}
files.push(file.path);
done();
}
function flush(done) {
execa('mocha', files.concat(args))
.then(result => {
if (!opts.suppress) {
process.stdout.write(result.stdout);
}
// For testing
this.emit('_result', result);
done();
})
.catch(err => {
this.emit('error', new gutil.PluginError('gulp-mocha', err));
done();
});
}
return through.obj(aggregate, flush);
};
|
Add .get() method to AuthenticationBase
|
import json
import requests
from ..exceptions import Auth0Error
class AuthenticationBase(object):
def post(self, url, data={}, headers={}):
response = requests.post(url=url, data=json.dumps(data),
headers=headers)
return self._process_response(response)
def get(self, url, params={}, headers={}):
return requests.get(url=url, params=params, headers=headers).text
def _process_response(self, response):
text = json.loads(response.text) if response.text else {}
if 'error' in text:
raise Auth0Error(status_code=text['error'],
error_code=text['error'],
message=text['error_description'])
return text
|
import json
import requests
from ..exceptions import Auth0Error
class AuthenticationBase(object):
def post(self, url, data={}, headers={}):
response = requests.post(url=url, data=json.dumps(data),
headers=headers)
return self._process_response(response)
def _process_response(self, response):
text = json.loads(response.text) if response.text else {}
if 'error' in text:
raise Auth0Error(status_code=text['error'],
error_code=text['error'],
message=text['error_description'])
return text
|
fix(extensions): Add label to the title component.
|
import React from "react";
import classnames from 'classnames';
import styles from './custom-title.scss';
const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => (
<div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')}
onClick={onClick}
style={style}
>
{icon ? (
<span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/>
) : null}
<div className={styles["custom-title-label-container"]}>
<span
className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])}
style={labelStyle}
title={label}
>
{label}
</span>
{children}
</div>
</div>
);
export default Title;
|
import React from "react";
import classnames from 'classnames';
import styles from './custom-title.scss';
const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => (
<div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')}
onClick={onClick}
style={style}
>
{icon ? (
<span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/>
) : null}
<div className={styles["custom-title-label-container"]}>
<span
className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])}
style={labelStyle}
>
{label}
</span>
{children}
</div>
</div>
);
export default Title;
|
Make it compile on windows
|
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
import sys
# To compile and install locally run "python setup.py build_ext --inplace"
# To install library to Python site-packages run "python setup.py build_ext install"
extra_compile_args = ['-Wno-cpp', '-Wno-unused-function', '-std=c99']
if sys.platform == 'win32':
extra_compile_args = []
ext_modules = [
Extension(
'pycocotools._mask',
sources=['./pycocotools/headers/maskApi.c', 'pycocotools/_mask.pyx'],
include_dirs = [np.get_include(), './pycocotools/headers'],
extra_compile_args=extra_compile_args,
)
]
setup(name='pycocotools',
packages=['pycocotools'],
package_dir = {'pycocotools': 'pycocotools'},
version='2.0',
ext_modules=
cythonize(ext_modules)
)
|
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
# To compile and install locally run "python setup.py build_ext --inplace"
# To install library to Python site-packages run "python setup.py build_ext install"
ext_modules = [
Extension(
'pycocotools._mask',
sources=['./pycocotools/headers/maskApi.c', 'pycocotools/_mask.pyx'],
include_dirs = [np.get_include(), './pycocotools/headers'],
extra_compile_args=['-Wno-cpp', '-Wno-unused-function', '-std=c99'],
)
]
setup(name='pycocotools',
packages=['pycocotools'],
package_dir = {'pycocotools': 'pycocotools'},
version='2.0',
ext_modules=
cythonize(ext_modules)
)
|
Revert "fix UnicodeDecodeError for long_description", Py3 only workaround
This reverts commit 417bf8df61dba0fa2e924008c4dbe204a609d4f2.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'coinmarketcap',
packages = ['coinmarketcap'],
version = '5.0.1',
description = 'Python wrapper around the coinmarketcap.com API.',
author = 'Martin Simon',
author_email = 'me@martinsimon.me',
url = 'https://github.com/barnumbirr/coinmarketcap',
license = 'Apache v2.0 License',
install_requires=['requests==2.18.4', 'requests_cache==0.4.13'],
keywords = ['cryptocurrency', 'API', 'coinmarketcap','BTC', 'Bitcoin', 'LTC', 'Litecoin', 'XRP', 'Ripple', 'ETH', 'Ethereum '],
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
long_description = open('README.md','r').read(),
long_description_content_type='text/markdown',
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'coinmarketcap',
packages = ['coinmarketcap'],
version = '5.0.2',
description = 'Python wrapper around the coinmarketcap.com API.',
author = 'Martin Simon',
author_email = 'me@martinsimon.me',
url = 'https://github.com/barnumbirr/coinmarketcap',
license = 'Apache v2.0 License',
install_requires=['requests==2.18.4', 'requests_cache==0.4.13'],
keywords = ['cryptocurrency', 'API', 'coinmarketcap','BTC', 'Bitcoin', 'LTC', 'Litecoin', 'XRP', 'Ripple', 'ETH', 'Ethereum '],
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
long_description = open('README.md','r', encoding='utf8').read(),
long_description_content_type='text/markdown',
)
|
Add all possibilities to Babylon parser
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
const babylon = require('babylon');
const options = {
sourceType: 'module',
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
plugins: [
'flow',
'flowComments',
'jsx',
'typescript',
'asyncGenerators',
'bigInt',
'classProperties',
'classPrivateProperties',
'classPrivateMethods',
'decorators',
'doExpressions',
'dynamicImport',
'exportDefaultFrom',
'exportNamespaceFrom',
'functionBind',
'functionSent',
'importMeta',
'logicalAssignment',
'nullishCoalescingOperator',
'numericSeparator',
'objectRestSpread',
'optionalCatchBinding',
'optionalChaining',
'pipelineOperator',
'throwExpressions',
],
};
/**
* Wrapper to set default options
*/
exports.parse = function parse (code) {
return babylon.parse(code, options);
};
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
const babylon = require('babylon');
const options = {
sourceType: 'module',
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
plugins: [
'jsx',
'flow',
'asyncFunctions',
'classConstructorCall',
'doExpressions',
'trailingFunctionCommas',
'objectRestSpread',
'decorators',
'classProperties',
'exportExtensions',
'exponentiationOperator',
'asyncGenerators',
'functionBind',
'functionSent',
'dynamicImport',
'nullishCoalescingOperator',
'optionalChaining',
'numericSeparator',
],
};
/**
* Wrapper to set default options
*/
exports.parse = function parse (code) {
return babylon.parse(code, options);
};
|
Fix PHPDoc wrong type annotation
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Writer\Midi;
use PhpTabs\Music\Note;
class MidiNoteHelper
{
/**
* @var \PhpTabs\Writer\Midi\MidiMeasureHelper
*/
private $measure;
/**
* @var \PhpTabs\Music\Note
*/
private $note;
/**
* @param \PhpTabs\Writer\Midi\MidiMeasureHelper $measure
* @param \PhpTabs\Music\Note $note
*/
public function __construct(MidiMeasureHelper $measure, Note $note)
{
$this->measure = $measure;
$this->note = $note;
}
/**
* @return \PhpTabs\Writer\Midi\MidiMeasureHelper $measure
*/
public function getMeasure()
{
return $this->measure;
}
/**
* @return \PhpTabs\Music\Note
*/
public function getNote()
{
return $this->note;
}
}
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Writer\Midi;
use PhpTabs\Music\Note;
class MidiNoteHelper
{
private $measure;
private $note;
/**
* @param \PhpTabs\Writer\Midi\MidiMeasureHelper $measure
* @param \PhpTabs\Writer\Midi\Note $note $measure
*/
public function __construct(MidiMeasureHelper $measure, Note $note)
{
$this->measure = $measure;
$this->note = $note;
}
/**
* @return \PhpTabs\Writer\Midi\MidiMeasureHelper $measure
*/
public function getMeasure()
{
return $this->measure;
}
/**
* @return \PhpTabs\Writer\Midi\Note $note
*/
public function getNote()
{
return $this->note;
}
}
|
Fix for Uncaught TypeError: Cannot read property 'match' of undefined
If no content type provided with function to match request parameters it will fail with specified error
`
let nockRequest = nock('https:/...')
.replyContentLength()
.post('/httppost', function(body){
return true;
}).reply(401, "");
`
|
'use strict';
var deepEqual = require('deep-equal');
var qs = require('querystring');
module.exports =
function matchBody(spec, body) {
if (typeof spec === 'undefined') {
return true;
}
var options = this || {};
if (Buffer.isBuffer(body)) {
body = body.toString();
}
//strip line endings from both so that we get a match no matter what OS we are running on
body = body.replace(/\r?\n|\r/g, '');
if (spec instanceof RegExp) {
return body.match(spec);
}
if (typeof spec === "string") {
spec = spec.replace(/\r?\n|\r/g, '');
}
// try to transform body to json
var json;
if (typeof spec === 'object' || typeof spec === 'function') {
try { json = JSON.parse(body);} catch(err) {}
if (json !== undefined) {
body = json;
}
else
if (options.headers) {
var contentType = options.headers['Content-Type'] ||
options.headers['content-type'];
if (contentType && contentType.match(/application\/x-www-form-urlencoded/)) {
body = qs.parse(body);
}
}
}
if (typeof spec === "function") {
return spec.call(this, body);
}
return deepEqual(spec, body, { strict: true });
};
|
'use strict';
var deepEqual = require('deep-equal');
var qs = require('querystring');
module.exports =
function matchBody(spec, body) {
if (typeof spec === 'undefined') {
return true;
}
var options = this || {};
if (Buffer.isBuffer(body)) {
body = body.toString();
}
//strip line endings from both so that we get a match no matter what OS we are running on
body = body.replace(/\r?\n|\r/g, '');
if (spec instanceof RegExp) {
return body.match(spec);
}
if (typeof spec === "string") {
spec = spec.replace(/\r?\n|\r/g, '');
}
// try to transform body to json
var json;
if (typeof spec === 'object' || typeof spec === 'function') {
try { json = JSON.parse(body);} catch(err) {}
if (json !== undefined) {
body = json;
}
else
if (options.headers) {
var contentType = options.headers['Content-Type'] ||
options.headers['content-type'];
if (contentType.match(/application\/x-www-form-urlencoded/)) {
body = qs.parse(body);
}
}
}
if (typeof spec === "function") {
return spec.call(this, body);
}
return deepEqual(spec, body, { strict: true });
};
|
Fix tests on python 2.6
|
import unittest
import subprocess
import random
# copied from python 2.7 for python 2.6
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
class DomainsTest(unittest.TestCase):
def _cmd(self, cmd, *args):
pargs = ('scripts/cli53', cmd) + args
return check_output(pargs, stderr=subprocess.STDOUT)
def _unique_name(self):
return 'temp%d.com' % random.randint(0, 65535)
def test_usage(self):
assert 'usage' in self._cmd('-h')
def test_create_delete(self):
name = self._unique_name()
self._cmd('create', name)
assert name in self._cmd('list')
self._cmd('delete', name)
assert name not in self._cmd('list')
|
import unittest
import subprocess
import random
class DomainsTest(unittest.TestCase):
def _cmd(self, cmd, *args):
pargs = ('scripts/cli53', cmd) + args
return subprocess.check_output(pargs, stderr=subprocess.STDOUT)
def _unique_name(self):
return 'temp%d.com' % random.randint(0, 65535)
def test_usage(self):
assert 'usage' in self._cmd('-h')
def test_create_delete(self):
name = self._unique_name()
self._cmd('create', name)
assert name in self._cmd('list')
self._cmd('delete', name)
assert name not in self._cmd('list')
|
Add javadoc to random port method
|
package zero.downtime.soa.api;
import org.apache.camel.builder.RouteBuilder;
import org.eclipse.jetty.server.Server;
/**
* @author magonzal
* @version 1.0.0
*/
public class HelloServiceApi extends RouteBuilder {
@Override
public void configure() throws Exception {
//@formatter:off
restConfiguration().component("jetty")
.host("localhost")
.port(getRandomServerPort())
.contextPath("hello-service-api/rest");
rest("/{user}").description("Say hello to User")
.get().route().to("direct-vm:hello");
//@formatter:on
}
/**
* Looks up an available port number on the host
* by creating a dummy Jetty Server.
*
* TODO: there's probably a better way to do this
*
* @return a port number available for use
* @throws Exception
*/
protected int getRandomServerPort() throws Exception {
Server server = new Server(0);
server.start();
int port = server.getConnectors()[0].getLocalPort();
server.stop();
return port;
}
}
|
package zero.downtime.soa.api;
import org.apache.camel.builder.RouteBuilder;
import org.eclipse.jetty.server.Server;
/**
* @author magonzal
* @version 1.0.0
*/
public class HelloServiceApi extends RouteBuilder {
@Override
public void configure() throws Exception {
//@formatter:off
restConfiguration().component("jetty")
.host("localhost")
.port(getRandomServerPort())
.contextPath("hello-service-api/rest");
rest("/{user}").description("Say hello to User")
.get().route().to("direct-vm:hello");
//@formatter:on
}
private int getRandomServerPort() throws Exception {
Server server = new Server(0);
server.start();
int port = server.getConnectors()[0].getLocalPort();
server.stop();
return port;
}
}
|
Allow NULL scheme rank conversions.
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.language.identifier;
import com.opengamma.language.convert.AbstractMappedConverter;
import com.opengamma.language.convert.TypeMap;
import com.opengamma.language.definition.JavaTypeInfo;
/**
* Converts ExternalSchemeRank to/from an array of strings.
*/
public class ExternalSchemeRankConverter extends AbstractMappedConverter {
private static final JavaTypeInfo<String[]> STRING_ARRAY = JavaTypeInfo.builder(String[].class).allowNull().get();
private static final JavaTypeInfo<ExternalSchemeRank> EXTERNAL_SCHEME_RANK = JavaTypeInfo.builder(ExternalSchemeRank.class).allowNull().get();
/**
* Default instance.
*/
public static final ExternalSchemeRankConverter INSTANCE = new ExternalSchemeRankConverter();
protected ExternalSchemeRankConverter() {
conversion(TypeMap.ZERO_LOSS, STRING_ARRAY, EXTERNAL_SCHEME_RANK, new Action<String[], ExternalSchemeRank>() {
@Override
protected ExternalSchemeRank convert(final String[] value) {
return ExternalSchemeRank.ofStrings(value);
}
});
conversion(TypeMap.MINOR_LOSS, EXTERNAL_SCHEME_RANK, STRING_ARRAY, new Action<ExternalSchemeRank, String[]>() {
@Override
protected String[] convert(final ExternalSchemeRank value) {
return value.asStrings();
}
});
}
}
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.language.identifier;
import com.opengamma.language.convert.AbstractMappedConverter;
import com.opengamma.language.convert.TypeMap;
import com.opengamma.language.definition.JavaTypeInfo;
/**
* Converts ExternalSchemeRank to/from an array of strings.
*/
public class ExternalSchemeRankConverter extends AbstractMappedConverter {
private static final JavaTypeInfo<String[]> STRING_ARRAY = JavaTypeInfo.builder(String[].class).get();
private static final JavaTypeInfo<ExternalSchemeRank> EXTERNAL_SCHEME_RANK = JavaTypeInfo.builder(ExternalSchemeRank.class).get();
/**
* Default instance.
*/
public static final ExternalSchemeRankConverter INSTANCE = new ExternalSchemeRankConverter();
protected ExternalSchemeRankConverter() {
conversion(TypeMap.ZERO_LOSS, STRING_ARRAY, EXTERNAL_SCHEME_RANK, new Action<String[], ExternalSchemeRank>() {
@Override
protected ExternalSchemeRank convert(final String[] value) {
return ExternalSchemeRank.ofStrings(value);
}
});
conversion(TypeMap.MINOR_LOSS, EXTERNAL_SCHEME_RANK, STRING_ARRAY, new Action<ExternalSchemeRank, String[]>() {
@Override
protected String[] convert(final ExternalSchemeRank value) {
return value.asStrings();
}
});
}
}
|
Use getBody() method instead of body property directly
|
<?php
namespace ElasticSearcher\Traits;
use ArrayHelpers\Arr;
/**
* A body can be an entire query or just a chunk of query (fragment).
* Any entity (query, fragment, index, ...) that builds request body's should
* use this trait.
*
* @package ElasticSearcher\Traits
*/
trait BodyTrait
{
/**
* Body of the query to execute.
*
* @var array
*/
public $body = [];
/**
* @param array $body
*/
public function setBody(array $body)
{
$this->body = $body;
}
/**
* @return array
*/
public function getBody()
{
return $this->body;
}
/**
* Set a value in the body using the dotted notation.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function set($key, $value)
{
Arr::set($this->body, $key, $value);
return $this;
}
/**
* Get a value in the body using the dotted notation.
*
* @param string $key
* @param mixed $default
*
* @return $this
*/
public function get($key, $default = null)
{
return Arr::get($this->getBody(), $key, $default);
}
}
|
<?php
namespace ElasticSearcher\Traits;
use ArrayHelpers\Arr;
/**
* A body can be an entire query or just a chunk of query (fragment).
* Any entity (query, fragment, index, ...) that builds request body's should
* use this trait.
*
* @package ElasticSearcher\Traits
*/
trait BodyTrait
{
/**
* Body of the query to execute.
*
* @var array
*/
public $body = [];
/**
* @param array $body
*/
public function setBody(array $body)
{
$this->body = $body;
}
/**
* @return array
*/
public function getBody()
{
return $this->body;
}
/**
* Set a value in the body using the dotted notation.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function set($key, $value)
{
Arr::set($this->body, $key, $value);
return $this;
}
/**
* Get a value in the body using the dotted notation.
*
* @param string $key
* @param mixed $default
*
* @return $this
*/
public function get($key, $default = null)
{
return Arr::get($this->body, $key, $default);
}
}
|
Add argument for launching client
Before, client would launch automatically on port you specify as a
positional argument.
This means you can't just not to launch the client.
Now, there are 2 options:
1) -c to launch client on the port defined in settings
2) --client to specify the port explicitly
So, if you want to launch just the server without client, there
will be an option for that, just say what to launch.
|
import argparse
from settings import HONEYPORT
"""
Here we define command line arguments.
`port` stands for port, to listen on.
`-v` to increase verbose of the server
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that`s how you`d detect a sneaky chinese bot.',
prog='mfh.py',
)
client_group = parser.add_mutually_exclusive_group()
client_group.add_argument(
'-c',
action='store_true',
help='launch client with on port defined in settings',
)
client_group.add_argument(
'--client',
help='port to start a client on',
metavar='PORT',
nargs='?',
type=int,
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help='increase output verbosity',
)
return parser.parse_args()
|
import argparse
from settings import HONEYPORT
"""
Here we define command line arguments.
`port` stands for port, to listen on.
`-v` to increase verbose of the server
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that`s how you`d detect a sneaky chinese bot.',
prog='runme.py',
)
parser.add_argument(
'port',
default=HONEYPORT,
help='port to start a listener on (default: %(default)s, %(type)s)',
nargs='?',
type=int,
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help='increase output verbosity',
)
return parser.parse_args()
|
Fix for failing test on node 0.10
After merging #593, tests against node 0.10 started failing with
```
util.js:556
ctor.prototype = Object.create(superCtor.prototype, {
^
TypeError: Object prototype may only be an Object or null
```
|
/*jshint node:true, laxcomma:true */
var fs = require('fs')
, util = require('util');
var Configurator = function (file) {
var self = this;
var config = {};
var oldConfig = {};
this.updateConfig = function () {
util.log('[' + process.pid + '] reading config file: ' + file);
fs.readFile(file, function (err, data) {
if (err) { throw err; }
old_config = self.config;
self.config = eval('config = ' + data);
self.emit('configChanged', self.config);
});
};
this.updateConfig();
fs.watch(file, function (event, filename) {
if (event == 'change' && self.config.automaticConfigReload != false) {
self.updateConfig();
}
});
};
util.inherits(Configurator, require('events').EventEmitter);
exports.Configurator = Configurator;
exports.configFile = function(file, callbackFunc) {
var config = new Configurator(file);
config.on('configChanged', function() {
callbackFunc(config.config, config.oldConfig);
});
};
|
/*jshint node:true, laxcomma:true */
var fs = require('fs')
, util = require('util');
var Configurator = function (file) {
var self = this;
var config = {};
var oldConfig = {};
this.updateConfig = function () {
util.log('[' + process.pid + '] reading config file: ' + file);
fs.readFile(file, function (err, data) {
if (err) { throw err; }
old_config = self.config;
self.config = eval('config = ' + data);
self.emit('configChanged', self.config);
});
};
this.updateConfig();
fs.watch(file, function (event, filename) {
if (event == 'change' && self.config.automaticConfigReload != false) {
self.updateConfig();
}
});
};
util.inherits(Configurator, require('events'));
exports.Configurator = Configurator;
exports.configFile = function(file, callbackFunc) {
var config = new Configurator(file);
config.on('configChanged', function() {
callbackFunc(config.config, config.oldConfig);
});
};
|
Add textContent for cross-browser compatibility.
Firefox doesn't appear to like `innerText`.
|
'use strict';
dragula([$('left1'), $('right1')]);
dragula([$('left2'), $('right2')], { copy: true });
dragula([$('left3'), $('right3')]).on('drag', function (el) {
el.className = el.className.replace(' ex-moved', '');
}).on('drop', function (el) {
setTimeout(function () {
el.className += ' ex-moved';
}, 0);
});
dragula([$('left4'), $('right4')], { revertOnSpill: true });
dragula([$('left5'), $('right5')], {
moves: function (el, container, handle) {
return handle.className === 'handle';
}
});
var single2 = $('single2');
dragula([$('single1')], { removeOnSpill: true });
dragula({ containers: [single2], delay: 200 });
if (single2.addEventListener) {
single2.addEventListener('click', clickHandler, false);
} else {
single2.attachEvent('onclick', clickHandler);
}
function clickHandler (e) {
if (e.target === this) {
return;
}
var target = e.target || e.srcElement;
var text = ('innerText' in target)? 'innerText' : 'textContent';
target[text] += ' [click!]';
setTimeout(function () {
target[text] = target[text].replace(/ \[click!\]/g, '');
}, 500);
}
function $ (id) {
return document.getElementById(id);
}
|
'use strict';
dragula([$('left1'), $('right1')]);
dragula([$('left2'), $('right2')], { copy: true });
dragula([$('left3'), $('right3')]).on('drag', function (el) {
el.className = el.className.replace(' ex-moved', '');
}).on('drop', function (el) {
setTimeout(function () {
el.className += ' ex-moved';
}, 0);
});
dragula([$('left4'), $('right4')], { revertOnSpill: true });
dragula([$('left5'), $('right5')], {
moves: function (el, container, handle) {
return handle.className === 'handle';
}
});
var single2 = $('single2');
dragula([$('single1')], { removeOnSpill: true });
dragula({ containers: [single2], delay: 200 });
if (single2.addEventListener) {
single2.addEventListener('click', clickHandler, false);
} else {
single2.attachEvent('onclick', clickHandler);
}
function clickHandler (e) {
if (e.target === this) {
return;
}
var target = e.target || e.srcElement;
target.innerText += ' [click!]';
setTimeout(function () {
target.innerText = target.innerText.replace(/ \[click!\]/g, '');
}, 500);
}
function $ (id) {
return document.getElementById(id);
}
|
[Discord] Use constant for SteamID64 base for Steam Account converter
|
from discord.ext import commands
class Maptype(commands.Converter):
'''
For Google Maps Static API parameter
https://developers.google.com/maps/documentation/maps-static/dev-guide
'''
async def convert(self, ctx, argument):
if argument not in ("roadmap", "satellite", "hybrid", "terrain"):
raise commands.BadArgument("Invalid map type")
return argument
# https://developer.valvesoftware.com/wiki/SteamID
STEAM_ID_64_BASE = int("0x110000100000000", 16) # Assuming Public Individual user account
# TODO: Use for steam gamecount command?
class SteamAccount(commands.Converter):
async def convert(self, ctx, argument):
try:
return int(argument) - STEAM_ID_64_BASE
except ValueError:
url = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/"
params = {"key": ctx.bot.STEAM_WEB_API_KEY, "vanityurl": argument}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
# TODO: Handle 429?
data = await resp.json()
if data["response"]["success"] == 42: # NoMatch, https://partner.steamgames.com/doc/api/steam_api#EResult
raise commands.BadArgument("Account not found")
return int(data['response']['steamid']) - STEAM_ID_64_BASE
|
from discord.ext import commands
class Maptype(commands.Converter):
'''
For Google Maps Static API parameter
https://developers.google.com/maps/documentation/maps-static/dev-guide
'''
async def convert(self, ctx, argument):
if argument not in ("roadmap", "satellite", "hybrid", "terrain"):
raise commands.BadArgument("Invalid map type")
return argument
# TODO: Use for steam gamecount command?
class SteamAccount(commands.Converter):
async def convert(self, ctx, argument):
try:
return int(argument) - 76561197960265728
except ValueError:
url = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/"
params = {"key": ctx.bot.STEAM_WEB_API_KEY, "vanityurl": argument}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
# TODO: Handle 429?
data = await resp.json()
if data["response"]["success"] == 42: # NoMatch, https://partner.steamgames.com/doc/api/steam_api#EResult
raise commands.BadArgument("Account not found")
return int(data['response']['steamid']) - 76561197960265728
|
Update guard to ensure enabledFeatures isArray.
|
/**
* Feature Flags hook.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import FeaturesContext from '../components/FeaturesProvider/FeaturesContext';
/**
* Returns the enabled state of a feature flag.
*
* @since n.e.x.t
*
* @param {string} feature The feature flag name to check enabled state for.
* @return {boolean} `true` if the feature is enabled, `false` otherwise.
*/
export const useFeature = ( feature ) => {
const enabledFeatures = useContext( FeaturesContext );
if ( ! Array.isArray( enabledFeatures ) ) {
return false;
}
return enabledFeatures.includes( feature );
};
|
/**
* Feature Flags hook.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import FeaturesContext from '../components/FeaturesProvider/FeaturesContext';
/**
* Returns the enabled state of a feature flag.
*
* @since n.e.x.t
*
* @param {string} feature The feature flag name to check enabled state for.
* @return {boolean} `true` if the feature is enabled, `false` otherwise.
*/
export const useFeature = ( feature ) => {
const enabledFeatures = useContext( FeaturesContext );
if ( ! enabledFeatures ) {
return false;
}
return enabledFeatures.includes( feature );
};
|
Fix contact form recipient email address
Since Celery is configured differently now we can't reach in and
grab config values outside of Celery.
|
from flask import current_app
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail message
:type user_id: str
:return: None
"""
ctx = {'email': email, 'message': message}
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
recipients=[current_app.config['MAIL_USERNAME']],
reply_to=email,
template='contact/mail/index', ctx=ctx)
return None
|
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail message
:type user_id: str
:return: None
"""
ctx = {'email': email, 'message': message}
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
recipients=[celery.conf.get('MAIL_USERNAME')],
reply_to=email,
template='contact/mail/index', ctx=ctx)
return None
|
Allow eslint config options overrides
|
const path = require('path');
const { getLoader } = require('react-app-rewired');
// this is the path of eslint-loader `index.js`
const ESLINT_PATH = `eslint-loader${path.sep}index.js`;
function getEslintOptions(rules) {
const matcher = (rule) => rule.loader
&& typeof rule.loader === 'string'
&& rule.loader.endsWith(ESLINT_PATH);
return getLoader(rules, matcher).options;
}
function rewireEslint(config, env, override = f => f) {
// if `react-scripts` version < 1.0.0
// **eslint options** is in `config`
const oldOptions = config.eslint;
// else `react-scripts` >= 1.0.0
// **eslint options** is in `config.module.rules`
const newOptions = getEslintOptions(config.module.rules);
// Thx @Guria, with no break change.
const options = oldOptions || newOptions;
options.useEslintrc = true;
options.ignore = true;
override(options);
return config;
}
module.exports = rewireEslint;
|
const path = require('path');
const { getLoader } = require('react-app-rewired');
// this is the path of eslint-loader `index.js`
const ESLINT_PATH = `eslint-loader${path.sep}index.js`;
function getEslintOptions(rules) {
const matcher = (rule) => rule.loader
&& typeof rule.loader === 'string'
&& rule.loader.endsWith(ESLINT_PATH);
return getLoader(rules, matcher).options;
}
function rewireEslint(config, env) {
// if `react-scripts` version < 1.0.0
// **eslint options** is in `config`
const oldOptions = config.eslint;
// else `react-scripts` >= 1.0.0
// **eslint options** is in `config.module.rules`
const newOptions = getEslintOptions(config.module.rules);
// Thx @Guria, with no break change.
const options = oldOptions || newOptions;
options.useEslintrc = true;
options.ignore = true;
return config;
}
module.exports = rewireEslint;
|
Replace obsolete references to "gwt" with "j2cl"
PiperOrigin-RevId: 432275111
|
/*
* Copyright 2016 The Closure Compiler 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.
*/
/**
* @fileoverview
* Tests identifier names.
*/
goog.require('goog.testing.jsunit');
// Test Scanner.java workaround to prevent J2CL-compiled compiler from choking
// on a special character used by Angular in some names.
// Note that the non-J2CL compiler allows all legal JS identifier names, but
// due to J2CL lack for Unicode support for Java's Character.is* methods, the
// J2CL-compiled compiler does not.
function testUnicodeInVariableName() {
var ɵ = true;
// Note: a failure of this test actually manifests as
// No tests found in given test case: identifier_test
assertTrue(ɵ);
}
|
/*
* Copyright 2016 The Closure Compiler 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.
*/
/**
* @fileoverview
* Tests identifier names.
*/
goog.require('goog.testing.jsunit');
// Test Scanner.java workaround to prevent GWT-compiled compiler from choking
// on a special character used by Angular in some names.
// Note that the non-GWT compiler allows all legal JS identifier names, but
// due to GWT lack for Unicode support for Java's Character.is* methods, the
// GWT-compiled compiler does not.
function testUnicodeInVariableName() {
var ɵ = true;
// Note: a failure of this test actually manifests as
// No tests found in given test case: identifier_test
assertTrue(ɵ);
}
|
Use chromedriver instead of phantomjs
|
exports.config = {
params: {
baseUrl: {
osio: 'https://openshift.io/',
username: 'testuser@redhat.com'
}
},
useAllAngular2AppRoots: true,
getPageTimeout: 30000,
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['src/tests/**/*.spec.js'],
exclude: ['src/tests/**/EE/*.spec.js'],
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 60000
},
troubleshoot: true,
capabilities: {
'browserName': 'chrome',
'maxInstances': 2,
'shardTestFiles': true,
'loggingPrefs': {
'driver': 'WARNING',
'server': 'WARNING',
'browser': 'INFO'
},
'chromeOptions': {
'args': [ '--no-sandbox', '--window-workspace=1']
}
}
};
|
exports.config = {
params: {
baseUrl: {
osio: 'https://openshift.io/',
username: 'testuser@redhat.com'
}
},
useAllAngular2AppRoots: true,
getPageTimeout: 30000,
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['src/tests/**/*.spec.js'],
exclude: ['src/tests/**/EE/*.spec.js'],
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
},
capabilities: {
'browserName': 'phantomjs',
'phantomjs.binary.path': require('phantomjs-prebuilt').path,
'phantomjs.cli.args': ['--webdriver-loglevel=ERROR', '--local-storage-path=/tmp/phantom_' + Math.random()]
}
};
|
Adjust media scaling in narrow window
|
import Immutable from 'immutable';
import { COLUMN_MEDIA_RESIZE } from '../actions/column_media';
const initialState = Immutable.Map({
scale: null,
single: null,
wide: null,
});
function resize(state, { columnCount, defaultPage, single: givenSingle, window: givenWindow }) {
const single = state.get('single') || givenSingle;
let scale;
let wide;
if (single) {
wide = givenWindow.innerWidth - 30 < givenWindow.innerHeight / 2;
if (wide) {
scale = 'calc(100vw - 100px)';
} else {
scale = 'calc(50vh - 70px)';
}
} else {
const widthCandidate = (givenWindow.innerWidth - 300) / columnCount;
const width = Math.max(widthCandidate, 330);
wide = !defaultPage || Math.min(width, 400) < givenWindow.innerHeight;
if (!defaultPage || widthCandidate < 330) {
scale = '230px';
} else if (!wide) {
scale = '50vh';
} else if (width > 500) {
scale = '400px';
} else {
scale = `calc((100vw - 300px)/${columnCount} - 100px)`;
}
}
return state.merge({ scale, single, wide });
}
export default function columnMedia(state = initialState, action) {
switch (action.type) {
case COLUMN_MEDIA_RESIZE:
return resize(state, action);
default:
return state;
}
}
|
import Immutable from 'immutable';
import { COLUMN_MEDIA_RESIZE } from '../actions/column_media';
const initialState = Immutable.Map({
scale: null,
single: null,
wide: null,
});
function resize(state, { columnCount, defaultPage, single: givenSingle, window: givenWindow }) {
const single = state.get('single') || givenSingle;
const widthCandidate = (givenWindow.innerWidth - 300) / columnCount;
const width = single ? givenWindow.innerWidth : Math.max(widthCandidate, 330);
const wide = !defaultPage || Math.min(width, 400) < givenWindow.innerHeight;
let scale;
if (!defaultPage || (!single && widthCandidate < 330)) {
scale = '230px';
} else if (!wide) {
scale = '50vh';
} else if (single) {
scale = 'calc(50vw - 100px)';
} else if (width > 500) {
scale = '400px';
} else {
scale = `calc((100vw - 300px)/${columnCount} - 100px)`;
}
return state.merge({ scale, single, wide });
}
export default function columnMedia(state = initialState, action) {
switch (action.type) {
case COLUMN_MEDIA_RESIZE:
return resize(state, action);
default:
return state;
}
}
|
Remove o required do gender para modelo de usuário.
|
var mongoose, Schema, UserSchema;
mongoose = require('mongoose');
// criando um schema para o banco de dados
// ==========
Schema = mongoose.Schema;
UserSchema = new Schema ({
name: {
type: String,
default: '',
required: true
},
email: {
type: String,
default: '',
required: true,
unique: true
},
gender: {
type: String,
default: ''
},
social: {
type: String,
default: ''
},
social_id: {
type: String,
default: ''
},
picture: {
type: String,
default: ''
},
created_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', UserSchema);
|
var mongoose, Schema, UserSchema;
mongoose = require('mongoose');
// criando um schema para o banco de dados
// ==========
Schema = mongoose.Schema;
UserSchema = new Schema ({
name: {
type: String,
default: '',
required: true
},
email: {
type: String,
default: '',
required: true,
uniq: true
},
gender: {
type: String,
default: '',
required: true
},
social: {
type: String,
default: ''
},
social_id: {
type: String,
default: ''
},
picture: {
type: String,
default: ''
},
created_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', UserSchema);
|
gst1: Send in an argument to Gst.init
As of gst-python 1.5.2, the init call requires one argument. The
argument is a list of the command line options. I don't think we need to
send any.
This relates to #1432.
|
from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init([])
REQUIRED_GST_VERSION = (1, 2, 3)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
|
from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
REQUIRED_GST_VERSION = (1, 2, 3)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
|
Create after checked source directory
|
<?php
/* (c) Anton Medvedev <anton@medv.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer;
desc('Copy directories');
task('deploy:copy_dirs', function () {
$dirs = get('copy_dirs');
$releases = get('releases_list');
if (isset($releases[0])) {
foreach ($dirs as $dir) {
$path = "{{deploy_path}}/releases/{$releases[0]}/$dir";
// Copy if dir exists.
if (test("[ -d $path ]")) {
// Create destination dir(needed for nested dirs)
run("mkdir -p {{release_path}}/$dir");
run("rsync -av $path/ {{release_path}}/$dir");
}
}
}
});
|
<?php
/* (c) Anton Medvedev <anton@medv.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer;
desc('Copy directories');
task('deploy:copy_dirs', function () {
$dirs = get('copy_dirs');
$releases = get('releases_list');
if (isset($releases[0])) {
foreach ($dirs as $dir) {
$path = "{{deploy_path}}/releases/{$releases[0]}/$dir";
// Create destination dir(needed for nested dirs)
run("mkdir -p {{release_path}}/$dir");
// Copy if dir exists.
if (test("[ -d $path ]")) {
run("rsync -av $path/ {{release_path}}/$dir");
}
}
}
});
|
Support for web url widget creator
|
package uk.ac.edukapp.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.routines.UrlValidator;
public class ServletUtils {
public static String getCookieValue(Cookie[] cookies, String cookieName,
String defaultValue) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return (cookie.getValue());
}
return (defaultValue);
}
public static String getServletRootURL ( HttpServletRequest request ) {
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String protocol;
if (request.isSecure()){
protocol = "https";
}
else {
protocol = "http";
}
String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";
return root;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
public static boolean checkURL ( String url ) {
String schemes[] = {"http", "https"};
UrlValidator urlValidator = new UrlValidator(schemes);
return urlValidator.isValid(url);
}
}
|
package uk.ac.edukapp.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class ServletUtils {
public static String getCookieValue(Cookie[] cookies, String cookieName,
String defaultValue) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return (cookie.getValue());
}
return (defaultValue);
}
public static String getServletRootURL ( HttpServletRequest request ) {
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String protocol;
if (request.isSecure()){
protocol = "https";
}
else {
protocol = "http";
}
String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";
return root;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
}
|
[BUGFIX] Fix functional test by explicitly naming sequence
The auto-generated name of a sequence exceeds the maximum length, is
truncated and thus duplicates an already existing name in the schema.
This is solved by manually giving a name to the sequence.
This bug affects only PostgreSQL and is triggered by a functional test
fixture.
|
<?php
namespace TYPO3\Flow\Tests\Functional\Persistence\Fixtures;
/*
* This file is part of the TYPO3.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use TYPO3\Flow\Annotations as Flow;
use Doctrine\ORM\Mapping as ORM;
/**
* A sample entity that has a property with a Id annotation
*
* @Flow\Entity
*/
class AnnotatedIdEntity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\SequenceGenerator(sequenceName="annotatedidentity_seq")
* @var string
*/
protected $id;
/**
* @var string
*/
protected $title;
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
|
<?php
namespace TYPO3\Flow\Tests\Functional\Persistence\Fixtures;
/*
* This file is part of the TYPO3.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use TYPO3\Flow\Annotations as Flow;
use Doctrine\ORM\Mapping as ORM;
/**
* A sample entity that has a property with a Id annotation
*
* @Flow\Entity
*/
class AnnotatedIdEntity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @var string
*/
protected $id;
/**
* @var string
*/
protected $title;
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
|
Add recovery and improve errType
|
package gobreak
import "time"
type runFunc func() error
type fallbackFunc func(error) error
const (
Success = "success"
ErrReject = "reject"
ErrFallBack = "fallback"
ErrFail = "fail"
ErrPanic = "panic"
)
// Do runs your function in a synchronous manner, blocking until either your function succeeds
// or an error is returned, including circuit errors
func Do(name string, run runFunc, fall fallbackFunc) error {
errorType := Success
// obtain circuit by name
c := getCircuit(name)
// ask circuit allow run or not
done, err := c.Allow()
if err != nil {
errorType = ErrReject
if fall != nil {
errorType = ErrFallBack
err = fall(err)
}
requests.WithLabelValues(name, errorType).Inc()
return err
}
now := time.Now()
// process run function
err = run()
// try recover when run function panics
defer func() {
e := recover()
if e != nil {
done(false)
requests.WithLabelValues(name, ErrPanic).Inc()
panic(e)
}
}()
elapsed := time.Now().Sub(now).Seconds()
requestLatencyHistogram.WithLabelValues(name).Observe(elapsed)
// report run results to circuit
done(err == nil)
if err != nil {
errorType = ErrFail
if fall != nil {
errorType = ErrFallBack
err = fall(err)
}
}
requests.WithLabelValues(name, errorType).Inc()
return err
}
|
package gobreak
import "time"
type runFunc func() error
type fallbackFunc func(error) error
const (
Success = "success"
ErrReject = "reject"
ErrFail = "fail"
)
// Do runs your function in a synchronous manner, blocking until either your function succeeds
// or an error is returned, including circuit errors
func Do(name string, run runFunc, fall fallbackFunc) error {
c := getCircuit(name)
done, err := c.Allow()
if err != nil {
requests.WithLabelValues(name, ErrReject).Inc()
if fall != nil {
err = fall(err)
}
return err
}
now := time.Now()
err = run()
elapsed := time.Now().Sub(now).Seconds()
requestLatencyHistogram.WithLabelValues(name).Observe(elapsed)
if err != nil {
done(false)
requests.WithLabelValues(name, ErrFail).Inc()
if fall != nil {
err = fall(err)
}
return err
}
done(true)
requests.WithLabelValues(name, Success).Inc()
return nil
}
|
Change script order to load Jquery first
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bootstrap.min.css" type="text/css" >
<link rel="stylesheet" href="base.css" type="text/css" >
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href='dist/css/bootstrap-material-design.min.css' rel='stylesheet' type='text/css'>
<link href='dist/css/ripples.min.css' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coupley</title>
</head>
<body>
<div id="content"></div>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="bundle.js"></script>
<script src="dist/js/material.min.js"></script>
<script src="dist/js/ripples.min.js"></script>
<script>
$.material.init();
</script>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bootstrap.min.css" type="text/css" >
<link rel="stylesheet" href="base.css" type="text/css" >
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href='dist/css/bootstrap-material-design.min.css' rel='stylesheet' type='text/css'>
<link href='dist/css/ripples.min.css' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coupley</title>
</head>
<body>
<div id="content"></div>
<script src="bundle.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="dist/js/material.min.js"></script>
<script src="dist/js/ripples.min.js"></script>
<script>
$.material.init();
</script>
</body>
</html>
|
Fix service provider not giving `Stopper` to the worker
|
<?php
namespace MaxBrokman\SafeQueue;
use Illuminate\Support\ServiceProvider;
use MaxBrokman\SafeQueue\Console\WorkCommand;
/
class DoctrineQueueProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerWorker();
}
/**
* @return void
*/
protected function registerWorker()
{
$this->registerWorkCommand();
$this->app->singleton('safeQueue.worker', function ($app) {
return new Worker($app['queue'], $app['queue.failer'], $app['events'], $app['em'], new Stopper());
});
}
/**
* @return void
*/
protected function registerWorkCommand()
{
$this->app->singleton('command.safeQueue.work', function ($app) {
return new WorkCommand($app['safeQueue.worker']);
});
$this->commands('command.safeQueue.work');
}
}
|
<?php
namespace MaxBrokman\SafeQueue;
use Illuminate\Support\ServiceProvider;
use MaxBrokman\SafeQueue\Console\WorkCommand;
class DoctrineQueueProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerWorker();
}
/**
* @return void
*/
protected function registerWorker()
{
$this->registerWorkCommand();
$this->app->singleton('safeQueue.worker', function ($app) {
return new Worker($app['queue'], $app['queue.failer'], $app['events'], $app['em']);
});
}
/**
* @return void
*/
protected function registerWorkCommand()
{
$this->app->singleton('command.safeQueue.work', function ($app) {
return new WorkCommand($app['safeQueue.worker']);
});
$this->commands('command.safeQueue.work');
}
}
|
Remove tracker field from ParsedBug. Add _tracker_name
|
import scrapy.item
class ParsedBug(scrapy.item.Item):
# Fields beginning with an underscore are not really part of a
# bug, but extra information that can be exported.
_project_name = scrapy.item.Field()
_tracker_name = scrapy.item.Field()
# These fields correspond to bug data
title = scrapy.item.Field()
description = scrapy.item.Field()
status = scrapy.item.Field()
importance = scrapy.item.Field()
people_involved = scrapy.item.Field()
date_reported = scrapy.item.Field()
last_touched = scrapy.item.Field()
submitter_username = scrapy.item.Field()
submitter_realname = scrapy.item.Field()
canonical_bug_link = scrapy.item.Field()
looks_closed = scrapy.item.Field()
last_polled = scrapy.item.Field()
as_appears_in_distribution = scrapy.item.Field()
good_for_newcomers = scrapy.item.Field()
concerns_just_documentation = scrapy.item.Field()
|
import scrapy.item
class ParsedBug(scrapy.item.Item):
# Fields beginning with an underscore are not really part of a
# bug, but extra information that can be exported.
_project_name = scrapy.item.Field()
# These fields correspond to bug data
title = scrapy.item.Field()
description = scrapy.item.Field()
status = scrapy.item.Field()
importance = scrapy.item.Field()
people_involved = scrapy.item.Field()
date_reported = scrapy.item.Field()
last_touched = scrapy.item.Field()
submitter_username = scrapy.item.Field()
submitter_realname = scrapy.item.Field()
canonical_bug_link = scrapy.item.Field()
looks_closed = scrapy.item.Field()
last_polled = scrapy.item.Field()
as_appears_in_distribution = scrapy.item.Field()
good_for_newcomers = scrapy.item.Field()
concerns_just_documentation = scrapy.item.Field()
tracker = scrapy.item.Field()
|
Fix Twig table extension runtime
|
<?php
/*
* This file is part of TableBundle.
*
* (c) David Coudrier <david.coudrier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nours\TableBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class TwigExtensionPass
*
* @author David Coudrier <david.coudrier@gmail.com>
*/
class TwigExtensionPass implements CompilerPassInterface
{
/**
* Adds runtime loader for symfony 2.8 (without twig.runtime tag support)
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('twig.runtime_loader')) {
$container
->getDefinition('twig')
->addMethodCall('addRuntimeLoader', array(new Reference('nours_table.twig.runtime_loader')))
;
}
}
}
|
<?php
/*
* This file is part of TableBundle.
*
* (c) David Coudrier <david.coudrier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nours\TableBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class TwigExtensionPass
*
* @author David Coudrier <david.coudrier@gmail.com>
*/
class TwigExtensionPass implements CompilerPassInterface
{
/**
* Adds runtime loader for symfony 2.8 (without twig.runtime tag support)
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('twig.runtime_loader')) {
// $container
// ->getDefinition('twig')
// ->addMethodCall('addRuntimeLoader', array(new Reference('nours_table.twig.runtime_loader')))
// ;
}
}
}
|
[util] Remove useless check from default urlhandler
|
import { flashURLHandler } from './urlhandlers/flash_url_handler';
import { nodeURLHandler } from './urlhandlers/mock_node_url_handler';
import { XHRURLHandler } from './urlhandlers/xhr_url_handler';
function get(url, options, cb) {
// Allow skip of the options param
if (!cb) {
if (typeof options === 'function') {
cb = options;
}
options = {};
}
if (typeof window === 'undefined' || window === null) {
return nodeURLHandler.get(url, options, cb);
} else if (XHRURLHandler.supported()) {
return XHRURLHandler.get(url, options, cb);
} else if (flashURLHandler.supported()) {
return flashURLHandler.get(url, options, cb);
} else {
return cb(
new Error(
'Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler'
)
);
}
}
export const urlHandler = {
get
};
|
import { flashURLHandler } from './urlhandlers/flash_url_handler';
import { nodeURLHandler } from './urlhandlers/mock_node_url_handler';
import { XHRURLHandler } from './urlhandlers/xhr_url_handler';
function get(url, options, cb) {
// Allow skip of the options param
if (!cb) {
if (typeof options === 'function') {
cb = options;
}
options = {};
}
if (options.urlhandler && options.urlhandler.supported()) {
// explicitly supply your own URLHandler object
return options.urlhandler.get(url, options, cb);
} else if (typeof window === 'undefined' || window === null) {
return nodeURLHandler.get(url, options, cb);
} else if (XHRURLHandler.supported()) {
return XHRURLHandler.get(url, options, cb);
} else if (flashURLHandler.supported()) {
return flashURLHandler.get(url, options, cb);
} else {
return cb(
new Error(
'Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler'
)
);
}
}
export const urlHandler = {
get
};
|
Use environment to detect gecko in mouse wheel
|
(function() {
var bound = false;
var target = document.body;
var synthesizer = function(e) {
var delta;
if (e.wheelDelta) {
delta = e.wheelDelta / 120;
} else if (e.detail) {
delta = -e.detail / 3;
}
lowland.bom.Events.dispatch(e.target, "hook_mousewheel", false, { wheelDelta: delta });
e.preventDefault();
};
var startListen = function() {
if (core.Env.getValue("engine") == "gecko") {
lowland.bom.Events.set(target, "DOMMouseScroll", synthesizer, false);
} else {
lowland.bom.Events.set(target, "mousewheel", synthesizer, false);
}
};
core.Module("lowland.bom.event.MouseWheel", {
listen : function(element, type, handler, capture) {
if (!bound) {
bound=true;
startListen();
}
lowland.bom.Events.listen(element, "hook_"+type, handler ,capture);
},
unlisten : function(element, type, handler, capture) {
lowland.bom.Events.unlisten(element, "hook_"+type, handler ,capture);
}
});
lowland.bom.Events.registerHook("mousewheel", lowland.bom.event.MouseWheel);
})();
|
(function() {
var bound = false;
var target = document.body;
var synthesizer = function(e) {
var delta;
if (e.wheelDelta) {
delta = e.wheelDelta / 120;
} else if (e.detail) {
delta = -e.detail / 3;
}
lowland.bom.Events.dispatch(e.target, "hook_mousewheel", false, { wheelDelta: delta });
e.preventDefault();
};
var startListen = function() {
if (core.detect.Engine.VALUE === 'gecko') {
lowland.bom.Events.set(target, "DOMMouseScroll", synthesizer, false);
} else {
lowland.bom.Events.set(target, "mousewheel", synthesizer, false);
}
};
core.Module("lowland.bom.event.MouseWheel", {
listen : function(element, type, handler, capture) {
if (!bound) {
bound=true;
startListen();
}
lowland.bom.Events.listen(element, "hook_"+type, handler ,capture);
},
unlisten : function(element, type, handler, capture) {
lowland.bom.Events.unlisten(element, "hook_"+type, handler ,capture);
}
});
lowland.bom.Events.registerHook("mousewheel", lowland.bom.event.MouseWheel);
})();
|
Fix mock of request for block rendering
|
import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumnLayoutBlock, self).setUp()
self.user = factories.UserFactory.build()
self.request = mock.Mock()
self.request.META = {}
self.request_context = RequestContext(self.request, {})
self.request_context['user'] = self.user
def test_generates_two_empty_containers_when_rendered(self):
container = Container.objects.create(name='test-container')
block = TwoColumnLayoutBlock.objects.create(container=container)
self.assertEquals(block.containers.count(), 0)
renderer = block.get_renderer_class()(block, self.request_context)
renderer.render()
self.assertEquals(block.containers.count(), 2)
|
import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumnLayoutBlock, self).setUp()
self.user = factories.UserFactory.build()
self.request_context = RequestContext(mock.MagicMock())
self.request_context['user'] = self.user
def test_generates_two_empty_containers_when_rendered(self):
container = Container.objects.create(name='test-container')
block = TwoColumnLayoutBlock.objects.create(container=container)
self.assertEquals(block.containers.count(), 0)
renderer = block.get_renderer_class()(block, self.request_context)
block_html = renderer.render()
self.assertEquals(block.containers.count(), 2)
|
Fix regex for template files
The regex wasn't matching dotfiles with no file extension so modify it to also include .tpl files with no additional extension.
|
'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl(\.|$)/)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
|
'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl\./)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
|
Set the large screen dimensions to 400x500
|
define([], function () {
'use strict';
return {
'oauthConsumerKey': 'wPfXjdZViPvrRWSlenSWBsAWhYKarmOkOKk5WS4U',
'oauthSecret': 'kaBZXTHZHKSk2jvBUr8vzk7JRI1cryFI08ubv7Du',
// 'overpassServer': 'http://overpass-api.de/api/',
'overpassServer': 'http://overpass.osm.rambler.ru/cgi/',
// 'overpassServer': 'http://api.openstreetmap.fr/oapi/',
'overpassTimeout': 30 * 1000, // Milliseconds
'defaultAvatar': 'img/default_avatar.png',
'apiPath': 'api/',
'largeScreenMinWidth': 400,
'largeScreenMinHeight': 500,
'shareIframeWidth': 100,
'shareIframeWidthUnit': '%',
'shareIframeHeight': 400,
'shareIframeHeightUnit': 'px',
};
});
|
define([], function () {
'use strict';
return {
'oauthConsumerKey': 'wPfXjdZViPvrRWSlenSWBsAWhYKarmOkOKk5WS4U',
'oauthSecret': 'kaBZXTHZHKSk2jvBUr8vzk7JRI1cryFI08ubv7Du',
// 'overpassServer': 'http://overpass-api.de/api/',
'overpassServer': 'http://overpass.osm.rambler.ru/cgi/',
// 'overpassServer': 'http://api.openstreetmap.fr/oapi/',
'overpassTimeout': 30 * 1000, // Milliseconds
'defaultAvatar': 'img/default_avatar.png',
'apiPath': 'api/',
'largeScreenMinWidth': 800,
'largeScreenMinHeight': 600,
'shareIframeWidth': 100,
'shareIframeWidthUnit': '%',
'shareIframeHeight': 400,
'shareIframeHeightUnit': 'px',
};
});
|
Improve Javadoc (was: typo and typo 2)
git-svn-id: 6d6ade8e88b1292e17cba3559b7335a947e495e0@513709 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* 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.
*/
package wicket.markup;
import wicket.MarkupContainer;
/**
* To be implemented by MarkupContainers that wish to implement their own
* algorithms for the markup cache key.
*
* @author Juergen Donnerstag
*/
public interface IMarkupCacheKeyProvider
{
/**
* Provide the markup cache key for the associated Markup resource stream.
*
* @see IMarkupResourceStreamProvider
*
* @param container
* The MarkupContainer object requesting the markup cache key
* @param containerClass
* The container the markup should be associated with
* @return A IResourceStream if the resource was found
*/
CharSequence getCacheKey(final MarkupContainer container, Class containerClass);
}
|
/*
* 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.
*/
package wicket.markup;
import wicket.MarkupContainer;
/**
* To be implemented by MarkupContainers which wish to implement their own
* algorithms for the markup cache key.
*
* @author Juergen Donnerstag
*/
public interface IMarkupCacheKeyProvider
{
/**
* Provide the markup cache key for the associated Markup resource stream.
*
* @see IMarkupResourceStreamProvider
*
* @param container
* The MarkupContainer object requesting the markup cache key
* @param containerClass
* The container the markup should be associated with
* @return A IResourceStream if the resource was found
*/
CharSequence getCacheKey(final MarkupContainer container, Class containerClass);
}
|
Add HTMLParser to viewless mdoels.
|
/**
* @license
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var files = [
'stdlib',
'io',
'writer',
'socket',
'hash',
'base64',
'encodings',
'utf8',
'parse',
'event',
'JSONUtil',
'XMLUtil',
'HTMLParser',
'context',
'FOAM',
'JSONParser',
'TemplateUtil',
'FObject',
'BootstrapModel',
'mm1Model',
'mm2Property',
'mm3Types',
'mm4Method',
'mm5Misc',
'mm6Protobuf',
'mlang',
'QueryParser',
'search',
'async',
'visitor',
'messaging',
'dao',
'arrayDAO',
'ClientDAO',
'diff',
'SplitDAO',
'index',
'experimental/protobufparser',
'experimental/protobuf',
'models',
'oauth'
];
|
/**
* @license
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var files = [
'stdlib',
'io',
'writer',
'socket',
'hash',
'base64',
'encodings',
'utf8',
'parse',
'event',
'JSONUtil',
'XMLUtil',
'context',
'FOAM',
'JSONParser',
'TemplateUtil',
'FObject',
'BootstrapModel',
'mm1Model',
'mm2Property',
'mm3Types',
'mm4Method',
'mm5Misc',
'mm6Protobuf',
'mlang',
'QueryParser',
'search',
'async',
'visitor',
'messaging',
'dao',
'arrayDAO',
'ClientDAO',
'diff',
'SplitDAO',
'index',
'experimental/protobufparser',
'experimental/protobuf',
'models',
'oauth'
];
|
Set availabilityResult for backward compatibility
|
/*
* This file is part of Bitsquare.
*
* Bitsquare 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.
*
* Bitsquare 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.trade.protocol.availability.messages;
import io.bitsquare.app.Version;
import io.bitsquare.trade.protocol.availability.AvailabilityResult;
public final class OfferAvailabilityResponse extends OfferMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
public final AvailabilityResult availabilityResult;
// TODO keep for backward compatibility. Can be removed once everyone is on v0.4.9
public boolean isAvailable;
public OfferAvailabilityResponse(String offerId, AvailabilityResult availabilityResult) {
super(offerId);
this.availabilityResult = availabilityResult;
isAvailable = availabilityResult == AvailabilityResult.AVAILABLE;
}
@Override
public String toString() {
return "OfferAvailabilityResponse{" +
"availabilityResult=" + availabilityResult +
"} " + super.toString();
}
}
|
/*
* This file is part of Bitsquare.
*
* Bitsquare 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.
*
* Bitsquare 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.trade.protocol.availability.messages;
import io.bitsquare.app.Version;
import io.bitsquare.trade.protocol.availability.AvailabilityResult;
public final class OfferAvailabilityResponse extends OfferMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
public final AvailabilityResult availabilityResult;
// TODO keep for backward compatibility. Can be removed once everyone is on v0.4.9
public boolean isAvailable;
public OfferAvailabilityResponse(String offerId, AvailabilityResult availabilityResult) {
super(offerId);
this.availabilityResult = availabilityResult;
}
@Override
public String toString() {
return "OfferAvailabilityResponse{" +
"availabilityResult=" + availabilityResult +
"} " + super.toString();
}
}
|
SO-4282: Store the message of the causing Exception as an additional...
...info key in ReasonerApiException
|
/*
* Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.reasoner.exceptions;
import java.util.Map;
import com.b2international.commons.exceptions.ApiException;
import com.google.common.collect.ImmutableMap;
/**
* @since 7.0
*/
public final class ReasonerApiException extends ApiException {
public ReasonerApiException(final String template, final Object... args) {
super(template, args);
}
@Override
protected Map<String, Object> getAdditionalInfo() {
final ImmutableMap.Builder<String, Object> additionalInfoBuilder = ImmutableMap.<String, Object>builder()
.putAll(super.getAdditionalInfo());
if (getCause() != null) {
additionalInfoBuilder.put("cause", getCause().getMessage());
}
return additionalInfoBuilder.build();
}
@Override
protected Integer getStatus() {
return 500;
}
}
|
/*
* Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.reasoner.exceptions;
import com.b2international.commons.exceptions.ApiException;
/**
* @since 7.0
*/
public final class ReasonerApiException extends ApiException {
public ReasonerApiException(final String template, final Object... args) {
super(template, args);
}
@Override
protected Integer getStatus() {
return 500;
}
}
|
Fix test signature value type for task
|
#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
from stoq.plugins import ArchiverPlugin
from stoq.data_classes import ArchiverResponse, Payload, RequestMeta
class DummyArchiver(ArchiverPlugin):
def archive(
self, payload: Payload, request_meta: RequestMeta
) -> Optional[ArchiverResponse]:
return None
def get(self, task: ArchiverResponse) -> Optional[Payload]:
return None
|
#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
from stoq.data_classes import ArchiverResponse, Payload, RequestMeta
from stoq.plugins import ArchiverPlugin
class DummyArchiver(ArchiverPlugin):
def archive(
self, payload: Payload, request_meta: RequestMeta
) -> Optional[ArchiverResponse]:
return None
def get(self, task: str) -> Optional[Payload]:
return None
|
Fix NPE when benchmark result is null
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.benchmark.impl.ranking;
import java.io.Serializable;
import java.util.Comparator;
import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult;
public class SubSingleBenchmarkRankBasedComparator implements Comparator<SubSingleBenchmarkResult>, Serializable {
private static final Comparator<SubSingleBenchmarkResult> COMPARATOR =
Comparator.nullsLast(Comparator
// Reverse, less is better (redundant: failed benchmarks don't get ranked at all)
.comparing(SubSingleBenchmarkResult::hasAnyFailure, Comparator.reverseOrder())
.thenComparing(SubSingleBenchmarkResult::getRanking, Comparator.naturalOrder()));
@Override
public int compare(SubSingleBenchmarkResult a, SubSingleBenchmarkResult b) {
return COMPARATOR.compare(a, b);
}
}
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.benchmark.impl.ranking;
import java.io.Serializable;
import java.util.Comparator;
import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult;
public class SubSingleBenchmarkRankBasedComparator implements Comparator<SubSingleBenchmarkResult>, Serializable {
@Override
public int compare(SubSingleBenchmarkResult a, SubSingleBenchmarkResult b) {
return Comparator
// Reverse, less is better (redundant: failed benchmarks don't get ranked at all)
.comparing(SubSingleBenchmarkResult::hasAnyFailure, Comparator.reverseOrder())
.thenComparing(SubSingleBenchmarkResult::getRanking, Comparator.naturalOrder())
.compare(a, b);
}
}
|
Simplify region check if a default value needs to be set.
|
'use strict';
const preconditions = require('conditional');
const promisify = require('./../utils/promisify');
const checkNotEmpty = preconditions.checkNotEmpty;
const AWS = require('aws-sdk');
/**
* Provider for KMS encrypted secrets
*/
class KMSProvider {
/**
* Create a new instance of the `KMSProvider`.
*
* @param {Object} secret
*/
constructor(secret) {
checkNotEmpty(secret, 'secret is required');
checkNotEmpty(secret.ciphertext, 'secret.ciphertext is required');
this._parameters = {
CiphertextBlob: Buffer.from(secret.ciphertext, 'base64')
};
}
/**
* Initialize the credentials
* @returns {Promise}
*/
initialize() {
return this._decrypt();
}
/**
* Retrieve and decrypt data from KMS
* @return {Promise}
* @private
*/
_decrypt() {
let region = Config.get('kms:region');
if (!region) {
region = 'us-east-1';
}
return promisify((done) => new AWS.KMS({region}).decrypt(this._parameters, done))
.then((data) => ({data}));
}
/**
* Removes cached data
*
* This is stubbed to conform to the Provider interface
*/
invalidate() { }
}
module.exports = KMSProvider;
|
'use strict';
const preconditions = require('conditional');
const promisify = require('./../utils/promisify');
const checkNotEmpty = preconditions.checkNotEmpty;
const AWS = require('aws-sdk');
/**
* Provider for KMS encrypted secrets
*/
class KMSProvider {
/**
* Create a new instance of the `KMSProvider`.
*
* @param {Object} secret
*/
constructor(secret) {
checkNotEmpty(secret, 'secret is required');
checkNotEmpty(secret.ciphertext, 'secret.ciphertext is required');
this._parameters = {
CiphertextBlob: Buffer.from(secret.ciphertext, 'base64')
};
}
/**
* Initialize the credentials
* @returns {Promise}
*/
initialize() {
return this._decrypt();
}
/**
* Retrieve and decrypt data from KMS
* @return {Promise}
* @private
*/
_decrypt() {
let region = Config.get('kms:region');
region = (typeof region === 'undefined') ? 'us-east-1' : region;
return promisify((done) => new AWS.KMS({region}).decrypt(this._parameters, done))
.then((data) => ({data}));
}
/**
* Removes cached data
*
* This is stubbed to conform to the Provider interface
*/
invalidate() { }
}
module.exports = KMSProvider;
|
Use more precise React.createClass call regex to avoid matching own code
|
var path = require('path');
module.exports = function (source) {
if (this.cacheable) {
this.cacheable();
}
var matches = 0,
processedSource;
processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) {
matches++;
return '__hotUpdateAPI.createClass({';
});
if (!matches) {
return source;
}
return [
'var __hotUpdateAPI = (function () {',
' var React = require("react");',
' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');',
' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);',
'})();',
processedSource,
'if (module.hot) {',
' module.hot.accept();',
' module.hot.dispose(function () {',
' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');',
' nextTick(__hotUpdateAPI.updateMountedInstances);',
' });',
'}'
].join('\n');
};
|
var path = require('path');
module.exports = function (source) {
if (this.cacheable) {
this.cacheable();
}
var matches = 0,
processedSource;
processedSource = source.replace(/React\.createClass/g, function (match) {
matches++;
return '__hotUpdateAPI.createClass';
});
if (!matches) {
return source;
}
return [
'var __hotUpdateAPI = (function () {',
' var React = require("react");',
' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');',
' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);',
'})();',
processedSource,
'if (module.hot) {',
' module.hot.accept();',
' module.hot.dispose(function () {',
' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');',
' nextTick(__hotUpdateAPI.updateMountedInstances);',
' });',
'}'
].join('\n');
};
|
Add a banner ad here too.
git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3612 46e82423-29d8-e211-989e-002590a4cdd4
|
<?php if ( !defined( "_COMMON_PHP" ) ) return; ?>
<?php
#
# $Id: header.php,v 1.1.2.5 2006-07-02 20:53:36 dan Exp $
#
# Copyright (c) 1998-2005 DVL Software Limited
#
require($_SERVER['DOCUMENT_ROOT'] . "/include/common.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/freshports.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/databaselogin.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/getvalues.php");
freshports_Start('', '', '', 1);
function custom_BannerForum($ForumName, $article_id) {
$TableWidth = "100%";
echo '<TABLE WIDTH="' . $TableWidth . '" ALIGN="center" cellspacing="0">';
echo "
<TR>
<TD>
<div class=\"section\">$ForumName</div>
</TD>
</TR>
";
echo '</TABLE>';
}
if ($BannerAd) {
echo "</td></tr>\n<tr><td>\n<CENTER>\n";
echo Ad_728x90();
echo "</CENTER>\n\n";
}
?>
<TABLE ALIGN="center" WIDTH="<? echo $TableWidth; ?>" CELLPADDING="<? echo $BannerCellPadding; ?>" CELLSPACING="<? echo $BannerCellSpacing; ?>" BORDER="0">
<TR>
<!-- first column in body -->
<TD WIDTH="100%" VALIGN="top" ALIGN="center">
|
<?php if ( !defined( "_COMMON_PHP" ) ) return; ?>
<?php
#
# $Id: header.php,v 1.1.2.4 2005-03-31 04:29:24 dan Exp $
#
# Copyright (c) 1998-2005 DVL Software Limited
#
require($_SERVER['DOCUMENT_ROOT'] . "/include/common.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/freshports.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/databaselogin.php");
require($_SERVER['DOCUMENT_ROOT'] . "/include/getvalues.php");
freshports_Start('', '', '', 1);
function custom_BannerForum($ForumName, $article_id) {
$TableWidth = "100%";
echo '<TABLE WIDTH="' . $TableWidth . '" ALIGN="center" cellspacing="0">';
echo "
<TR>
<TD>
<div class=\"section\">$ForumName</div>
</TD>
</TR>
";
echo '</TABLE>';
}
?>
<TABLE ALIGN="center" WIDTH="<? echo $TableWidth; ?>" CELLPADDING="<? echo $BannerCellPadding; ?>" CELLSPACING="<? echo $BannerCellSpacing; ?>" BORDER="0">
<TR>
<!-- first column in body -->
<TD WIDTH="100%" VALIGN="top" ALIGN="center">
|
Change the signature of getMessagesHeardBy
This makes the exercise "Add a new scenario" easier, as for those steps
to work, you need to know the identity of the shouter.
|
package shouty;
import java.util.*;
public class Shouty {
private final int MESSAGE_RANGE = 1000;
private Map<String, Coordinate> locations = new HashMap<String, Coordinate>();
private Map<String, String> messages = new HashMap<String, String>();
public void setLocation(String person, Coordinate location) {
locations.put(person, location);
}
public void shout(String person, String message) {
messages.put(person, message);
}
public Map<String, String> getMessagesHeardBy(String listener) {
HashMap<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry: messages.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
|
package shouty;
import java.util.*;
public class Shouty {
private final int MESSAGE_RANGE = 1000;
private Map<String, Coordinate> locations = new HashMap<String, Coordinate>();
private Map<String, String> messages = new HashMap<String, String>();
public void setLocation(String person, Coordinate location) {
locations.put(person, location);
}
public void shout(String person, String message) {
messages.put(person, message);
}
public List<String> getMessagesHeardBy(String listener) {
List<String> messagesHeard = new ArrayList<String>();
for (Map.Entry<String, String> entry : messages.entrySet()) {
messagesHeard.add(entry.getValue());
}
return messagesHeard;
}
}
|
Copy minlength change over from Struts. Now minlength passes if all whitespace is entered.
git-svn-id: c96248f4ce6931c9674b921fd55ab67490fa1adf@140031 13f79535-47bb-0310-9956-ffa450edef68
|
function validateMinLength(form) {
var isValid = true;
var focusField = null;
var i = 0;
var fields = new Array();
oMinLength = new minlength();
for (x in oMinLength) {
var field = form[oMinLength[x][0]];
if (field.type == 'text' ||
field.type == 'textarea') {
var iMin = parseInt(oMinLength[x][2]("minlength"));
if ((trim(field.value).length > 0) && (field.value.length < iMin)) {
if (i == 0) {
focusField = field;
}
fields[i++] = oMinLength[x][1];
isValid = false;
}
}
}
if (fields.length > 0) {
focusField.focus();
alert(fields.join('\n'));
}
return isValid;
}
|
function validateMinLength(form) {
var isValid = true;
var focusField = null;
var i = 0;
var fields = new Array();
oMinLength = new minlength();
for (x in oMinLength) {
var field = form[oMinLength[x][0]];
if (field.type == 'text' ||
field.type == 'textarea') {
var iMin = parseInt(oMinLength[x][2]("minlength"));
if ((field.value.length > 0) && (field.value.length < iMin)) {
if (i == 0) {
focusField = field;
}
fields[i++] = oMinLength[x][1];
isValid = false;
}
}
}
if (fields.length > 0) {
focusField.focus();
alert(fields.join('\n'));
}
return isValid;
}
|
Remove unnecessary default of state.required to false
|
import syntax from '@babel/plugin-syntax-jsx'
import pureAnnotation from './visitors/pure'
import minify from './visitors/minify'
import displayNameAndId from './visitors/displayNameAndId'
import templateLiterals from './visitors/templateLiterals'
import assignStyledRequired from './visitors/assignStyledRequired'
import transpileCssProp from './visitors/transpileCssProp'
export default function({ types: t }) {
return {
inherits: syntax,
visitor: {
JSXAttribute(path, state) {
transpileCssProp(t)(path, state)
},
CallExpression(path, state) {
displayNameAndId(t)(path, state)
pureAnnotation(t)(path, state)
},
TaggedTemplateExpression(path, state) {
minify(t)(path, state)
displayNameAndId(t)(path, state)
templateLiterals(t)(path, state)
pureAnnotation(t)(path, state)
},
VariableDeclarator(path, state) {
assignStyledRequired(t)(path, state)
},
},
}
}
|
import syntax from '@babel/plugin-syntax-jsx'
import pureAnnotation from './visitors/pure'
import minify from './visitors/minify'
import displayNameAndId from './visitors/displayNameAndId'
import templateLiterals from './visitors/templateLiterals'
import assignStyledRequired from './visitors/assignStyledRequired'
import transpileCssProp from './visitors/transpileCssProp'
export default function({ types: t }) {
return {
inherits: syntax,
visitor: {
// These visitors insert newly generated code and missing import/require statements
Program: {
enter(path, state) {
state.required = false
},
},
JSXAttribute(path, state) {
transpileCssProp(t)(path, state)
},
CallExpression(path, state) {
displayNameAndId(t)(path, state)
pureAnnotation(t)(path, state)
},
TaggedTemplateExpression(path, state) {
minify(t)(path, state)
displayNameAndId(t)(path, state)
templateLiterals(t)(path, state)
pureAnnotation(t)(path, state)
},
VariableDeclarator(path, state) {
assignStyledRequired(t)(path, state)
},
},
}
}
|
Improve readability of hard-coded number
|
define([
'extensions/collections/matrix'
],
function (MatrixCollection) {
var VisitorsRealtimeCollection = MatrixCollection.extend({
apiName: "realtime",
queryParams: function () {
return {
sort_by: "_timestamp:descending",
limit: this.options.numTwoMinPeriodsToQuery || (((60/2) * 24) + 2)
};
},
updateInterval: 120 * 1000,
initialize: function (models, options) {
MatrixCollection.prototype.initialize.apply(this, arguments);
if (isClient) {
clearInterval(this.timer);
this.timer = setInterval(
_.bind(this.fetch, this), this.updateInterval
);
}
},
parse: function (response) {
return {
id: 'realtime',
title: 'Realtime',
values: response.data.reverse()
};
},
fetch: function (options) {
options = _.extend({
headers: {
"cache-control": "max-age=120"
}
}, options);
MatrixCollection.prototype.fetch.call(this, options);
}
});
return VisitorsRealtimeCollection;
});
|
define([
'extensions/collections/matrix'
],
function (MatrixCollection) {
var VisitorsRealtimeCollection = MatrixCollection.extend({
apiName: "realtime",
queryParams: function () {
return {
sort_by: "_timestamp:descending",
limit: this.options.numTwoMinPeriodsToQuery || 722
};
},
updateInterval: 120 * 1000,
initialize: function (models, options) {
MatrixCollection.prototype.initialize.apply(this, arguments);
if (isClient) {
clearInterval(this.timer);
this.timer = setInterval(
_.bind(this.fetch, this), this.updateInterval
);
}
},
parse: function (response) {
return {
id: 'realtime',
title: 'Realtime',
values: response.data.reverse()
};
},
fetch: function (options) {
options = _.extend({
headers: {
"cache-control": "max-age=120"
}
}, options);
MatrixCollection.prototype.fetch.call(this, options);
}
});
return VisitorsRealtimeCollection;
});
|
Update use of fsnotify in example
|
package lrserver_test
import (
"github.com/jaschaephraim/lrserver"
"golang.org/x/exp/fsnotify"
"log"
"net/http"
)
// html includes the client JavaScript
const html = `<!doctype html>
<html>
<head>
<title>Example</title>
</head>
<body>
<script src="http://localhost:35729/livereload.js"></script>
</body>
</html>`
func Example() {
// Create file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalln(err)
}
defer watcher.Close()
// Watch dir
err = watcher.Watch("/path/to/watched/dir")
if err != nil {
log.Fatalln(err)
}
// Start LiveReload server
go lrserver.ListenAndServe()
// Start goroutine that requests reload upon watcher event
go func() {
for {
event := <-watcher.Event
lrserver.Reload(event.Name)
}
}()
// Start serving html
http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(html))
})
http.ListenAndServe(":3000", nil)
}
|
package lrserver_test
import (
"github.com/jaschaephraim/lrserver"
"golang.org/x/exp/fsnotify"
"log"
"net/http"
)
// html includes the client JavaScript
const html = `<!doctype html>
<html>
<head>
<title>Example</title>
<body>
<script src="http://localhost:35729/livereload.js"></script>
</body>
</html>`
func Example() {
// Create file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalln(err)
}
defer watcher.Close()
// Add dir to watcher
err = watcher.Add("/path/to/watched/dir")
if err != nil {
log.Fatalln(err)
}
// Start LiveReload server
go lrserver.ListenAndServe()
// Start goroutine that requests reload upon watcher event
go func() {
for {
event := <-watcher.Events
lrserver.Reload(event.Name)
}
}()
// Start serving html
http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(html))
})
http.ListenAndServe(":3000", nil)
}
|
Remove the specification of thread from the bus
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.padlock.model.event;
import android.support.annotation.NonNull;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
public abstract class RxBus<T> {
@NonNull private final Subject<T, T> bus = new SerializedSubject<>(PublishSubject.create());
public void post(@NonNull T event) {
if (bus.hasObservers()) {
bus.onNext(event);
}
}
@NonNull public Observable<T> register() {
return bus.filter(confirmationEvent -> confirmationEvent != null);
}
}
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.padlock.model.event;
import android.support.annotation.NonNull;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
public abstract class RxBus<T> {
@NonNull private final Subject<T, T> bus = new SerializedSubject<>(PublishSubject.create());
public void post(@NonNull T event) {
if (bus.hasObservers()) {
bus.onNext(event);
}
}
@NonNull public Observable<T> register() {
return bus.filter(confirmationEvent -> confirmationEvent != null)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
}
|
Use a List<String> rather than hard-coding newlines
|
package uk.ac.ic.wlgitbridge.snapshot.base;
import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class MissingRepositoryException extends SnapshotAPIException {
public static final List<String> GENERIC_REASON = Arrays.asList(
"This Overleaf project currently has no git access.",
"",
"If this problem persists, please contact us."
);
public static final List<String> EXPORTED_TO_V2 = Arrays.asList(
"This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.",
"",
"See https://www.overleaf.com/help/342 for more information."
);
private List<String> descriptionLines;
public MissingRepositoryException() {
descriptionLines = new ArrayList<String>();
}
public MissingRepositoryException(String message) {
this.descriptionLines = Arrays.asList(message);
}
public MissingRepositoryException(List<String> descriptionLines) {
this.descriptionLines = descriptionLines;
}
@Override
public void fromJSON(JsonElement json) {}
@Override
public String getMessage() {
return String.join("\n", this.descriptionLines);
}
@Override
public List<String> getDescriptionLines() {
return this.descriptionLines;
}
}
|
package uk.ac.ic.wlgitbridge.snapshot.base;
import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;
import java.util.Arrays;
import java.util.List;
public class MissingRepositoryException extends SnapshotAPIException {
public static final String GENERIC_REASON =
"This Overleaf project currently has no git access.\n" +
"\n" +
"If this problem persists, please contact us.";
public static final String EXPORTED_TO_V2 =
"This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
"\n" +
"See https://www.overleaf.com/help/342 for more information.";
private String message = "";
public MissingRepositoryException() {
}
public MissingRepositoryException(String message) {
this.message = message;
}
@Override
public void fromJSON(JsonElement json) {}
@Override
public String getMessage() {
return message;
}
@Override
public List<String> getDescriptionLines() {
return Arrays.asList(getMessage());
}
}
|
Fix a bug that caused the "facebook_authorization_required" decorator to be incompatible
with Django libraries that modify the order of arguments given to views.
|
from functools import wraps
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.handlers.wsgi import WSGIRequest
from django.conf import settings
from utils import redirect_to_facebook_authorization
def facebook_authorization_required(redirect_uri=False):
"""
Redirect Facebook canvas views to authorization if required.
Arguments:
redirect_uri -- A string describing an URI to redirect to after authorization is complete.
Defaults to current URI in Facebook canvas (ex. http://apps.facebook.com/myapp/path/).
"""
def decorator(function):
@wraps(function)
def wrapper(*args, **kwargs):
request = [arg for arg in args if arg.__class__ is WSGIRequest][0]
if not request.facebook or not request.facebook.user:
return redirect_to_facebook_authorization(
redirect_uri = redirect_uri or settings.FACEBOOK_APPLICATION_URL + request.get_full_path()
)
return function(*args, **kwargs)
return wrapper
return decorator
|
from functools import wraps
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from utils import redirect_to_facebook_authorization
def facebook_authorization_required(redirect_uri=False):
"""
Redirect Facebook canvas views to authorization if required.
Arguments:
redirect_uri -- A string describing an URI to redirect to after authorization is complete.
Defaults to current URI in Facebook canvas (ex. http://apps.facebook.com/myapp/path/).
"""
def decorator(function):
@wraps(function)
def wrapper(request, *args, **kwargs):
if not request.facebook or not request.facebook.user:
return redirect_to_facebook_authorization(
redirect_uri = redirect_uri or settings.FACEBOOK_APPLICATION_URL + request.get_full_path()
)
return function(request, *args, **kwargs)
return wrapper
return decorator
|
Print a list of aliases, if any exist.
git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@921 c76caeb1-94fd-44dd-870f-0c9d92034fc1
|
import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
Name [] aliases = lookup.getAliases();
if (aliases.length > 0) {
System.out.print("# aliases: ");
for (int i = 0; i < aliases.length; i++) {
System.out.print(aliases[i]);
if (i < aliases.length - 1)
System.out.print(" ");
}
System.out.println();
}
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up.
Reviewed By: stevegury, vitaut
Differential Revision: D14814205
fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.github_project_workdir('krb5/krb5', 'src'),
builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
Fix that will hopefully include all the contents (files and directories) of htdocs/js/
|
from setuptools import setup, find_packages
PACKAGE = 'AdaptiveArtifacts'
VERSION = '0.2'
setup(name=PACKAGE,
version=VERSION,
author='Filipe Correia',
author_email='filipe dot correia at fe dot up dot pt',
long_description="""
This Trac plugin allows to create information following an arbitrary structure, that can emerge during a project's lifetime, rather than having to be established at installation/configuration time.
""",
packages=find_packages(exclude=['*.tests']),
entry_points={
'trac.plugins': [
'%s = AdaptiveArtifacts' % PACKAGE,
'%s.setup = AdaptiveArtifacts.persistence.db' % PACKAGE,
]
},
package_data={'AdaptiveArtifacts': ['htdocs/css/*.css',
'htdocs/js/*',
'htdocs/images/*.jpg',
'templates/*.html']},
)
|
from setuptools import setup, find_packages
PACKAGE = 'AdaptiveArtifacts'
VERSION = '0.2'
setup(name=PACKAGE,
version=VERSION,
author='Filipe Correia',
author_email='filipe dot correia at fe dot up dot pt',
long_description="""
This Trac plugin allows to create information following an arbitrary structure, that can emerge during a project's lifetime, rather than having to be established at installation/configuration time.
""",
packages=find_packages(exclude=['*.tests']),
entry_points={
'trac.plugins': [
'%s = AdaptiveArtifacts' % PACKAGE,
'%s.setup = AdaptiveArtifacts.persistence.db' % PACKAGE,
]
},
package_data={'AdaptiveArtifacts': ['htdocs/css/*.css',
'htdocs/js/*.js',
'htdocs/images/*.jpg',
'templates/*.html']},
)
|
Allow to set empty settings.ext with null value
|
'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
module.exports = function (options, settings) {
settings = settings || {};
options = options || {};
settings.ext = typeof settings.ext === "undefined" ? ".html" : settings.ext;
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit(
'error',
new gutil.PluginError('gulp-ejs', 'Streaming not supported')
);
}
options.filename = options.filename || file.path;
try {
file.contents = new Buffer(ejs.render(file.contents.toString(), options));
file.path = gutil.replaceExtension(file.path, settings.ext);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-ejs', err.toString()));
}
this.push(file);
cb();
});
};
|
'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
module.exports = function (options, settings) {
settings = settings || {};
options = options || {};
settings.ext = settings.ext || '.html';
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit(
'error',
new gutil.PluginError('gulp-ejs', 'Streaming not supported')
);
}
options.filename = options.filename || file.path;
try {
file.contents = new Buffer(ejs.render(file.contents.toString(), options));
file.path = gutil.replaceExtension(file.path, settings.ext);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-ejs', err.toString()));
}
this.push(file);
cb();
});
};
|
Check for the actual warning description
|
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test;
use PHPUnit\Framework\TestCase;
use Composer\Factory;
class FactoryTest extends TestCase
{
/**
* @group TLS
*/
public function testDefaultValuesAreAsExpected()
{
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->once())
->method("writeError")
->with($this->equalTo('<warning>You are running Composer with SSL/TLS protection disabled.</warning>'));
$config = $this
->getMockBuilder('Composer\Config')
->getMock();
$config->method('get')
->with($this->equalTo('disable-tls'))
->will($this->returnValue(true));
Factory::createRemoteFilesystem($ioMock, $config);
}
}
|
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test;
use PHPUnit\Framework\TestCase;
use Composer\Factory;
class FactoryTest extends TestCase
{
/**
* @group TLS
*/
public function testDefaultValuesAreAsExpected()
{
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->once())
->method("writeError");
$config = $this
->getMockBuilder('Composer\Config')
->getMock();
$config->method('get')
->with($this->equalTo('disable-tls'))
->will($this->returnValue(true));
Factory::createRemoteFilesystem($ioMock, $config);
}
}
|
Check if we are running in headless environment
|
package me.coley.recaf.command.impl;
import me.coley.recaf.Recaf;
import me.coley.recaf.control.Controller;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.control.headless.HeadlessController;
import picocli.CommandLine;
import java.awt.*;
import java.io.File;
/**
* Command line initializer for Recaf, invoked from the main method.
*
* @author Matt
*/
@CommandLine.Command(
name = "Recaf",
version = Recaf.VERSION,
description = "Recaf: A modern java bytecode editor.",
mixinStandardHelpOptions = true)
public class Initializer implements Runnable {
/**
* Workspace file to import.
*/
@CommandLine.Option(names = {"--input" }, description = "The input file to load. " +
"Supported types are: class, jar, json")
public File input;
@CommandLine.Option(names = {"--script" }, description = "Script file to load for cli usage")
public File script;
@CommandLine.Option(names = { "--cli" }, description = "Run Recaf via CLI")
public boolean cli;
@Override
public void run() {
Controller controller;
if (cli || script != null || GraphicsEnvironment.isHeadless())
controller = new HeadlessController(input, script);
else
controller = new GuiController(input);
controller.setup();
controller.run();
}
}
|
package me.coley.recaf.command.impl;
import me.coley.recaf.Recaf;
import me.coley.recaf.control.Controller;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.control.headless.HeadlessController;
import picocli.CommandLine;
import java.io.File;
/**
* Command line initializer for Recaf, invoked from the main method.
*
* @author Matt
*/
@CommandLine.Command(
name = "Recaf",
version = Recaf.VERSION,
description = "Recaf: A modern java bytecode editor.",
mixinStandardHelpOptions = true)
public class Initializer implements Runnable {
/**
* Workspace file to import.
*/
@CommandLine.Option(names = {"--input" }, description = "The input file to load. " +
"Supported types are: class, jar, json")
public File input;
@CommandLine.Option(names = {"--script" }, description = "Script file to load for cli usage")
public File script;
@CommandLine.Option(names = { "--cli" }, description = "Run Recaf via CLI")
public boolean cli;
@Override
public void run() {
Controller controller;
if (cli || script != null)
controller = new HeadlessController(input, script);
else
controller = new GuiController(input);
controller.setup();
controller.run();
}
}
|
Remove error test from IE8
|
// Get base config
var karmaConfig = require('./karma-base.js');
// Get platform/browser/version from passed args
var platform = process.argv[4];
var browser = process.argv[5];
var version = process.argv[6];
// Set custom launcher object
var customLaunchers = {
'SL_Browser': {
base: 'SauceLabs',
browserName: browser,
platform: platform
}
};
// Add version number if set
if (version) {
customLaunchers.SL_Browser.version = version;
};
module.exports = function(config) {
// Don't run error test in IE8 as we know it will fail due to limitation of broswer
karmaConfig.files = [
'../stan-loader.min.js',
'test-load-ok.js'
];
// Set sauce labs object
karmaConfig.sauceLabs = {
public: 'public',
testName: 'STAN Loader Tests',
};
// Set reporters
karmaConfig.reporters = ['saucelabs', 'spec'];
// Set custom launchers
karmaConfig.customLaunchers = customLaunchers;
// Set browser info from custom launchers
karmaConfig.browsers = Object.keys(customLaunchers);
// Set loglevel
karmaConfig.logLevel = config.LOG_INFO;
// Set config
config.set(karmaConfig);
};
|
// Get base config
var karmaConfig = require('./karma-base.js');
// Get platform/browser/version from passed args
var platform = process.argv[4];
var browser = process.argv[5];
var version = process.argv[6];
// Set custom launcher object
var customLaunchers = {
'SL_Browser': {
base: 'SauceLabs',
browserName: browser,
platform: platform
}
};
// Add version number if set
if (version) {
customLaunchers.SL_Browser.version = version;
};
module.exports = function(config) {
// Don't run error test in IE8 as we know it will fail due to limitation of broswer
karmaConfig.files = [
'../stan-loader.min.js',
'test-load-ok.js',
'test-load-error.js'
];
// Set sauce labs object
karmaConfig.sauceLabs = {
public: 'public',
testName: 'STAN Loader Tests',
};
// Set reporters
karmaConfig.reporters = ['saucelabs', 'spec'];
// Set custom launchers
karmaConfig.customLaunchers = customLaunchers;
// Set browser info from custom launchers
karmaConfig.browsers = Object.keys(customLaunchers);
// Set loglevel
karmaConfig.logLevel = config.LOG_INFO;
// Set config
config.set(karmaConfig);
};
|
Add translation for android app links text
|
<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
"Connectivity Checks" => "Vérifications des connections",
"No problems found" => "Aucun problème trouvé",
"Please double check the <a href=\'%s\'>installation guides</a>." => "Merci de bien vérifier les <a href=\'%s\'>guides d'installation</a>.",
"Paid client app" => "Client payant",
"Free client app" => "Client gratuit",
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
|
<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
"Connectivity Checks" => "Vérifications des connections",
"No problems found" => "Aucun problème trouvé",
"Please double check the <a href=\'%s\'>installation guides</a>." => "Merci de bien vérifier les <a href=\'%s\'>guides d'installation</a>."
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
|
Change build listings to sort by -time_queue instead of -id so that
rebuilds show up higher in the listing
|
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.paginator import Paginator
from mrbelvedereci.build.models import Build
def paginate(build_list, request):
page = request.GET.get('page')
per_page = request.GET.get('per_page', '25')
paginator = Paginator(build_list, int(per_page))
try:
builds = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
builds = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
builds = paginator.page(paginator.num_pages)
return builds
def view_queryset(request, query=None):
if not query:
query = {}
if not request.user.is_staff:
query['plan__public'] = True
builds = Build.objects.all()
if query:
builds = builds.filter(**query)
order_by = request.GET.get('order_by', '-time_queue')
order_by = order_by.split(',')
builds = builds.order_by(*order_by)
builds = paginate(builds, request)
return builds
|
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.paginator import Paginator
from mrbelvedereci.build.models import Build
def paginate(build_list, request):
page = request.GET.get('page')
per_page = request.GET.get('per_page', '25')
paginator = Paginator(build_list, int(per_page))
try:
builds = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
builds = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
builds = paginator.page(paginator.num_pages)
return builds
def view_queryset(request, query=None):
if not query:
query = {}
if not request.user.is_staff:
query['plan__public'] = True
builds = Build.objects.all()
if query:
builds = builds.filter(**query)
builds = paginate(builds, request)
return builds
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.