text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add method to get the right block type from a module extra
|
<?php
namespace Backend\Modules\Pages\Domain\ModuleExtra;
use Backend\Modules\Pages\Domain\PageBlock\Type;
use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;
final class ModuleExtraType implements JsonSerializable
{
private const BLOCK = 'block';
private const WIDGET = 'widget';
public const POSSIBLE_TYPES = [
self::BLOCK,
self::WIDGET,
];
/** @var string */
private $type;
/**
* @param string $type
*
* @throws InvalidModuleExtraType
*/
public function __construct(string $type)
{
if (!in_array($type, self::POSSIBLE_TYPES, true)) {
throw InvalidModuleExtraType::withType($type);
}
$this->type = $type;
}
public static function block(): self
{
return new self(self::BLOCK);
}
public static function widget(): self
{
return new self(self::WIDGET);
}
public function __toString(): string
{
return $this->type;
}
public function getPageBlockType(): Type
{
return new Type($this->type);
}
public function jsonSerialize(): string
{
return (string) $this;
}
}
|
<?php
namespace Backend\Modules\Pages\Domain\ModuleExtra;
use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;
final class ModuleExtraType implements JsonSerializable
{
private const BLOCK = 'block';
private const WIDGET = 'widget';
public const POSSIBLE_TYPES = [
self::BLOCK,
self::WIDGET,
];
/** @var string */
private $type;
/**
* @param string $type
*
* @throws InvalidModuleExtraType
*/
public function __construct(string $type)
{
if (!in_array($type, self::POSSIBLE_TYPES, true)) {
throw InvalidModuleExtraType::withType($type);
}
$this->type = $type;
}
public static function block(): self
{
return new self(self::BLOCK);
}
public static function widget(): self
{
return new self(self::WIDGET);
}
public function __toString(): string
{
return $this->type;
}
public function jsonSerialize(): string
{
return (string) $this;
}
}
|
Fix bad encoding in boilerplate
|
# Copyright 2015 IBM Corp. 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
#
# 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.
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def Welcome():
return app.send_static_file('index.html')
@app.route('/myapp')
def WelcomeToMyapp():
return 'Welcome again to my app running on Bluemix!'
port = os.getenv('VCAP_APP_PORT', '5000')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(port))
|
# Copyright 2015 IBM Corp. 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
#
# 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.
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def Welcome():
return app.send_static_file('index.html')
@app.route('/myapp')
def WelcomeToMyapp():
return 'Welcome again to my app running on Bluemix!'
port = os.getenv('VCAP_APP_PORT', '5000')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(port))
|
Fix Django version check for 1.10
|
# -*- encoding: utf-8 -*-
import django
from django.test import TestCase
from django.core.management import call_command
if django.VERSION >= (1, 7):
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear_app_cache = apps.clear_cache
else:
from django.test.utils import override_settings
from django.db.models import loading
initial_data_fixture = 'initial_data_legacy'
def clear_app_cache():
loading.cache.loaded = False
@override_settings(INSTALLED_APPS=[
'datatableview',
'datatableview.tests.test_app',
'datatableview.tests.example_project.example_project.example_app',
])
class DatatableViewTestCase(TestCase):
def _pre_setup(self):
"""
Asks the management script to re-sync the database. Having test-only models is a pain.
"""
clear_app_cache()
call_command('syncdb', interactive=False, verbosity=0)
call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0)
super(DatatableViewTestCase, self)._pre_setup()
|
# -*- encoding: utf-8 -*-
from django import get_version
from django.test import TestCase
from django.core.management import call_command
if get_version().split('.') >= ['1', '7']:
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear_app_cache = apps.clear_cache
else:
from django.test.utils import override_settings
from django.db.models import loading
initial_data_fixture = 'initial_data_legacy'
def clear_app_cache():
loading.cache.loaded = False
@override_settings(INSTALLED_APPS=[
'datatableview',
'datatableview.tests.test_app',
'datatableview.tests.example_project.example_project.example_app',
])
class DatatableViewTestCase(TestCase):
def _pre_setup(self):
"""
Asks the management script to re-sync the database. Having test-only models is a pain.
"""
clear_app_cache()
call_command('syncdb', interactive=False, verbosity=0)
call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0)
super(DatatableViewTestCase, self)._pre_setup()
|
Remove unused variables and fields
|
package io.tracee.contextlogger.jaxws.container;
import io.tracee.Tracee;
import io.tracee.TraceeBackend;
import io.tracee.TraceeLogger;
import io.tracee.jaxws.container.TraceeServerHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/**
* JaxWs client side handler that detects uncaught exceptions and outputs contextual information.
*/
public class TraceeClientErrorLoggingHandler extends AbstractTraceeErrorLoggingHandler {
TraceeClientErrorLoggingHandler(TraceeBackend traceeBackend) {
super(traceeBackend);
}
public TraceeClientErrorLoggingHandler() {
this(Tracee.getBackend());
}
@Override
protected final void handleIncoming(SOAPMessageContext context) {
// Do nothing
}
@Override
protected final void handleOutgoing(SOAPMessageContext context) {
storeMessageInThreadLocal(context);
}
}
|
package io.tracee.contextlogger.jaxws.container;
import io.tracee.Tracee;
import io.tracee.TraceeBackend;
import io.tracee.TraceeLogger;
import io.tracee.jaxws.container.TraceeServerHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/**
* JaxWs client side handler that detects uncaught exceptions and outputs contextual information.
*/
public class TraceeClientErrorLoggingHandler extends AbstractTraceeErrorLoggingHandler {
private final TraceeLogger traceeLogger = this.getTraceeBackend().getLoggerFactory().getLogger(
TraceeServerHandler.class);
TraceeClientErrorLoggingHandler(TraceeBackend traceeBackend) {
super(traceeBackend);
}
public TraceeClientErrorLoggingHandler() {
this(Tracee.getBackend());
}
@Override
protected final void handleIncoming(SOAPMessageContext context) {
// Do nothing
}
@Override
protected final void handleOutgoing(SOAPMessageContext context) {
storeMessageInThreadLocal(context);
}
}
|
Update Fasttext pretrained vectors location
|
import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
|
import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
|
Fix bug of ssm parameter ls when name is empty
|
package myaws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/pkg/errors"
)
// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
Name string
}
// SSMParameterLs get values from SSM parameter store with KMS decryption.
func (client *Client) SSMParameterLs(options SSMParameterLsOptions) error {
var filter *ssm.ParametersFilter
if len(options.Name) > 0 {
filter = &ssm.ParametersFilter{
Key: aws.String("Name"),
Values: []*string{
aws.String(options.Name),
},
}
}
filters := []*ssm.ParametersFilter{filter}
params := &ssm.DescribeParametersInput{
Filters: filters,
}
response, err := client.SSM.DescribeParameters(params)
if err != nil {
return errors.Wrap(err, "DescribeParameters failed:")
}
for _, parameter := range response.Parameters {
fmt.Fprintln(client.stdout, *parameter.Name)
}
return nil
}
|
package myaws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/pkg/errors"
)
// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
Name string
}
// SSMParameterLs get values from SSM parameter store with KMS decryption.
func (client *Client) SSMParameterLs(options SSMParameterLsOptions) error {
filter := &ssm.ParametersFilter{
Key: aws.String("Name"),
Values: []*string{
aws.String(options.Name),
},
}
filters := []*ssm.ParametersFilter{filter}
params := &ssm.DescribeParametersInput{
Filters: filters,
}
response, err := client.SSM.DescribeParameters(params)
if err != nil {
return errors.Wrap(err, "DescribeParameters failed:")
}
for _, parameter := range response.Parameters {
fmt.Fprintln(client.stdout, *parameter.Name)
}
return nil
}
|
Add mapping for age covariate.
|
'use strict';
const { DEFAULT_LAMBDA } = require('../src/constants.js');
const path = require('path');
module.exports = {
/**
* This property is used to pass computation input values from the
* declaration into the computation.
*
* @todo Don't require `covariates` computation input
*
* {@link https://github.com/MRN-Code/coinstac/issues/161}
*/
__ACTIVE_COMPUTATION_INPUTS__: [[
['TotalGrayVol'], // FreeSurfer region of interest
DEFAULT_LAMBDA, // Lambda
[{
name: 'Is Control',
type: 'boolean',
}, {
name: 'Age',
type: 'number',
}],
]],
computationPath: path.resolve(__dirname, '../src/index.js'),
local: [{
metaFilePath: path.join(__dirname, 'mocks/metadata-1.csv'),
metaCovariateMapping: {
1: 0,
2: 1,
},
}, {
metaFilePath: path.join(__dirname, 'mocks/metadata-2.csv'),
metaCovariateMapping: {
1: 0,
2: 1,
},
}],
verbose: true,
};
|
'use strict';
const { DEFAULT_LAMBDA } = require('../src/constants.js');
const path = require('path');
module.exports = {
/**
* This property is used to pass computation input values from the
* declaration into the computation.
*
* @todo Don't require `covariates` computation input
*
* {@link https://github.com/MRN-Code/coinstac/issues/161}
*/
__ACTIVE_COMPUTATION_INPUTS__: [[
['TotalGrayVol'], // FreeSurfer region of interest
DEFAULT_LAMBDA, // Lambda
[{
name: 'Is Control',
type: 'boolean',
}, {
name: 'Age',
type: 'number',
}],
]],
computationPath: path.resolve(__dirname, '../src/index.js'),
local: [{
metaFilePath: path.join(__dirname, 'mocks/metadata-1.csv'),
metaCovariateMapping: {
1: 0,
},
}, {
metaFilePath: path.join(__dirname, 'mocks/metadata-2.csv'),
metaCovariateMapping: {
1: 0,
},
}],
verbose: true,
};
|
Update post-back script for Braintree
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wireup.db(wireup.env())
inp = csv.reader(open('refunds.completed.csv'))
note = 'refund of advance payment; see https://medium.com/gratipay-blog/18cacf779bee'
total = N = 0
for ts, id, amount, username, route_id, success, ref in inp:
print('posting {} back for {}'.format(amount, username))
assert success == 'True'
total += D(amount)
N += 1
amount = D('-' + amount)
route = ExchangeRoute.from_id(route_id)
# Such a hack. :(
rp = route.participant
participant = Participant.from_id(rp) if type(rp) is long else rp
route.set_attributes(participant=participant)
exchange_id = record_exchange(db, route, amount, 0, participant, 'pending', note)
db.run("update exchanges set ref=%s where id=%s", (ref, exchange_id))
print('posted {} back for {}'.format(total, N))
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wireup.db(wireup.env())
inp = csv.reader(open('balanced/refund/refunds.completed.csv'))
note = 'refund of advance payment; see https://medium.com/gratipay-blog/charging-in-arrears-18cacf779bee'
for ts, id, amount, username, route_id, status_code, content in inp:
if status_code != '201': continue
amount = '-' + amount[:-2] + '.' + amount[-2:]
print('posting {} back for {}'.format(amount, username))
route = ExchangeRoute.from_id(route_id)
rp = route.participant
participant = Participant.from_id(rp) if type(rp) is long else rp # Such a hack. :(
route.set_attributes(participant=participant)
record_exchange(db, route, amount, 0, participant, 'pending', note)
|
Fix evaluation query on report
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
Print a warning if your king is checked
|
package main
import (
"board"
"color"
"fmt"
"point"
)
func scanMove() (*point.Move, error) {
var file byte
var rank int
_, err := fmt.Scanf("%c%d", &file, &rank)
return point.NewMove(file, rank), err
}
func main() {
chessboard := board.NewBoard()
finish := false
now := color.White
for finish == false {
success := false
chessboard.Print()
if chessboard.IsChecked(now) {
fmt.Println("Your king is checked")
}
for success == false {
from, err := scanMove()
if err != nil {
finish = true
break
}
to, err := scanMove()
if err != nil {
finish = true
break
}
err = chessboard.Move(from.ToPoint(), to.ToPoint(), now)
success = err == nil
if success == false {
fmt.Println(err)
}
}
fmt.Println()
now = now.Enemy()
}
}
|
package main
import (
"board"
"color"
"fmt"
"point"
)
func scanMove() (*point.Move, error) {
var file byte
var rank int
_, err := fmt.Scanf("%c%d", &file, &rank)
return point.NewMove(file, rank), err
}
func main() {
chessboard := board.NewBoard()
finish := false
now := color.White
for finish == false {
success := false
chessboard.Print()
for success == false {
from, err := scanMove()
if err != nil {
finish = true
break
}
to, err := scanMove()
if err != nil {
finish = true
break
}
err = chessboard.Move(from.ToPoint(), to.ToPoint(), now)
success = err == nil
if success == false {
fmt.Println(err)
}
}
fmt.Println()
now = now.Enemy()
}
}
|
Fix picked color sometimes undefined
|
var squares = document.querySelectorAll(".square");
var colors = [];
for (var i = squares.length - 1; i >= 0; i--) {
colors.push(getRandomRGB());
}
var pickedColor = colors[getRandomInt(0, colors.length)];
var h1 = document.querySelector('h1');
var t = document.createTextNode(' ' + pickedColor);
h1.appendChild(t);
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandomRGB() {
var red = getRandomInt(0, 256);
var green = getRandomInt(0, 256);
var blue = getRandomInt(0, 256);
var rgb = "rgb(" + red + ", " +
green + ", " +
blue + ")";
return rgb;
}
var colorCounter = 0;
squares.forEach(function(square) {
square.style.backgroundColor = colors[colorCounter];
colorCounter++;
square.addEventListener('click', function() {
if (square.style.backgroundColor === pickedColor) {
alert("You're right!!")
} else {
square.style.backgroundColor = '#232323';
}
})
});
|
var squares = document.querySelectorAll(".square");
var colors = [];
for (var i = squares.length - 1; i >= 0; i--) {
colors.push(getRandomRGB());
}
var pickedColor = colors[getRandomInt(0, colors.length + 1)];
var h1 = document.querySelector('h1');
var t = document.createTextNode(' ' + pickedColor);
h1.appendChild(t);
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandomRGB() {
var red = getRandomInt(0, 256);
var green = getRandomInt(0, 256);
var blue = getRandomInt(0, 256);
var rgb = "rgb(" + red + ", " +
green + ", " +
blue + ")";
return rgb;
}
var colorCounter = 0;
squares.forEach(function(square) {
square.style.backgroundColor = colors[colorCounter];
colorCounter++;
square.addEventListener('click', function() {
if (square.style.backgroundColor === pickedColor) {
alert("You're right!!")
} else {
alert("WRONG!")
square.style.backgroundColor = '#232323';
}
})
});
|
Check before calling a function
|
module.exports = {
add: add,
get: get,
isSupported: isSupported
};
var rules = {};
// Functions should return the string to be appended to a key to find the pluralized
// form for the count given.
function add(lng, fn) {
fn.memo = [];
rules[lng] = function(count) {
return fn.memo[count] || (fn.memo[count] = fn(count));
}
}
function get(lng, count) {
return rules[lng] && rules[lng](count);
}
function isSupported(lng) {
return !!rules[lng];
}
// English and Japanese are added as demonstrations, but you can add your own rules.
// Find more rules at http://translate.sourceforge.net/wiki/l10n/pluralforms
add("en", function(n) { return n != 1 ? "_plural" : ""; });
add("ja", function(n) { return ""; });
|
module.exports = {
add: add,
get: get,
isSupported: isSupported
};
var rules = {};
// Functions should return the string to be appended to a key to find the pluralized
// form for the count given.
function add(lng, fn) {
fn.memo = [];
rules[lng] = function(count) {
return fn.memo[count] || (fn.memo[count] = fn(count));
}
}
function get(lng, count) {
return rules[lng](count);
}
function isSupported(lng) {
return !!rules[lng];
}
// English and Japanese are added as demonstrations, but you can add your own rules.
// Find more rules at http://translate.sourceforge.net/wiki/l10n/pluralforms
add("en", function(n) { return n != 1 ? "_plural" : ""; });
add("ja", function(n) { return ""; });
|
Raise TypeError instead of returning
|
#!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.types = types
self.position = 0
if 'position' in kwargs:
self.position = int(kwargs['position']) - 1
def __call__(self, f):
def wrapped_f(*args, **kwargs):
if type(args[self.position]) not in self.types:
raise TypeError("Invalid argument type '%s' at position %d. " +
"Expected one of (%s)" % (
type(args[self.position]).__name__, self.position,
", ".join([t.__name__ for t in self.types])))
return f(*args, **kwargs)
return wrapped_f
|
#!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.types = types
self.position = 0
self.returnvalue = False
if 'position' in kwargs:
self.position = int(kwargs['position']) - 1
if 'returnvalue' in kwargs:
self.returnvalue = kwargs['returnvalue']
def __call__(self, f):
def wrapped_f(*args, **kwargs):
if type(args[self.position]) not in self.types:
return self.returnvalue
return f(*args, **kwargs)
return wrapped_f
|
Remove Fork cms copyright comment
|
<?php
namespace Frontend\Modules\Instagram\Engine;
use Frontend\Core\Engine\Model as FrontendModel;
/**
* The frontend Instagram Model
*
* @author Jesse Dobbelaere <jesse@dobbelae.re>
*/
class Model
{
/**
* Fetches a certain item
*
* @param string $id
* @return array
*/
public static function get($id)
{
$item = (array) FrontendModel::get('database')->getRecord(
'SELECT i.*
FROM instagram_users AS i
WHERE i.id = ? AND i.hidden = ?',
array((int) $id, 'N')
);
// no results?
if (empty($item)) {
return array();
}
return $item;
}
public static function getRecentMedia($userId, $count = 10)
{
$recentData = Helper::getUserMedia($userId, $count);
return isset($recentData) ? $recentData->data : null;
}
}
|
<?php
namespace Frontend\Modules\Instagram\Engine;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Frontend\Core\Engine\Model as FrontendModel;
/**
* The frontend Instagram Model
*
* @author Jesse Dobbelaere <jesse@dobbelae.re>
*/
class Model
{
/**
* Fetches a certain item
*
* @param string $id
* @return array
*/
public static function get($id)
{
$item = (array) FrontendModel::get('database')->getRecord(
'SELECT i.*
FROM instagram_users AS i
WHERE i.id = ? AND i.hidden = ?',
array((int) $id, 'N')
);
// no results?
if (empty($item)) {
return array();
}
return $item;
}
public static function getRecentMedia($userId, $count = 10)
{
$recentData = Helper::getUserMedia($userId, $count);
return isset($recentData) ? $recentData->data : null;
}
}
|
Tidy up info a little for the PluginModule popup edit form
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40384 b456876b-0849-0410-b77d-98878d47e9d5
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_last_image_galleries_info()
{
return array(
'name' => tra('Last-Modified Image Galleries'),
'description' => tra('Displays the specified number of image galleries, starting from the most recently modified.'),
'prefs' => array("feature_galleries"),
'params' => array(),
'common_params' => array('nonums', 'rows')
);
}
function module_last_image_galleries($mod_reference, $module_params)
{
global $smarty, $user;
global $imagegallib; include_once 'lib/imagegals/imagegallib.php';
$ranking = $imagegallib->list_visible_galleries(0, $mod_reference["rows"], 'lastModif_desc', $user, '');
$smarty->assign('modLastGalleries', $ranking["data"]);
}
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_last_image_galleries_info()
{
return array(
'name' => tra('Last-modified Image Galleries'),
'description' => tra('Displays the specified number of image galleries, starting from the most recently modified.'),
'prefs' => array("feature_galleries"),
'params' => array(),
'common_params' => array('nonums', 'rows')
);
}
function module_last_image_galleries($mod_reference, $module_params)
{
global $smarty, $user;
global $imagegallib; include_once 'lib/imagegals/imagegallib.php';
$ranking = $imagegallib->list_visible_galleries(0, $mod_reference["rows"], 'lastModif_desc', $user, '');
$smarty->assign('modLastGalleries', $ranking["data"]);
}
|
Change logging to use standard logging library.
|
__author__ = 'Matt Stibbs'
__version__ = '1.27.00'
target_schema_version = '1.25.00'
from flask import Flask
import logging
logger = logging.getLogger(__name__)
app = Flask(__name__)
import blockbuster.bb_auditlogger as audit
def startup():
import blockbuster.bb_dbconnector_factory
blockbuster.app.debug = blockbuster.config.debug_mode
print(str.format("Application Startup - BlockBuster v{0} Schema v{1}",
blockbuster.__version__, target_schema_version))
time_setting = "Application Setting - Time Restriction Disabled" \
if not blockbuster.config.timerestriction \
else "Application Setting - Time Restriction Enabled"
print(time_setting)
if blockbuster.config.debug_mode:
print("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
try:
if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check():
import blockbuster.bb_routes
print("Running...")
else:
raise RuntimeError(str.format("Incorrect database schema version. Wanted {0}", target_schema_version))
except RuntimeError, e:
logger.exception(e)
audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', str(e))
raise
startup()
|
__author__ = 'Matt Stibbs'
__version__ = '1.27.00'
target_schema_version = '1.25.00'
from flask import Flask
app = Flask(__name__)
def startup():
import blockbuster.bb_dbconnector_factory
import blockbuster.bb_logging as log
import blockbuster.bb_auditlogger as audit
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info(str.format("Application Startup - BlockBuster v{0} Schema v{1}",
blockbuster.__version__, target_schema_version))
time_setting = "Application Setting - Time Restriction Disabled" if not blockbuster.config.timerestriction else "Application Setting - Time Restriction Enabled"
print(time_setting)
if blockbuster.config.debug_mode:
print("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
try:
if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check():
import blockbuster.bb_routes
print("Running...")
else:
raise RuntimeError("Incorrect database schema version. Wanted ")
except RuntimeError, e:
log.logger.exception(e)
audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', str(e))
startup()
|
Set code push install mode to immediate
|
// @flow
import CodePush from 'react-native-code-push';
import { AppRegistry, YellowBox } from 'react-native';
import {
SingleHotelStandalonePackage,
NewHotelsStandAlonePackage,
} from '@kiwicom/react-native-app-hotels';
// TODO: please check if it's still needed
YellowBox.ignoreWarnings([
// react-native-share warnings. Should be gone with the version 1.1.3
'Class GenericShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class WhatsAppShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class GooglePlusShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class InstagramShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
]);
// Hotels
AppRegistry.registerComponent(
'NewKiwiHotels',
() => NewHotelsStandAlonePackage,
);
AppRegistry.registerComponent(
'SingleHotel',
() => SingleHotelStandalonePackage,
);
// This file is only used for native integration and we use CodePush there
CodePush.sync({
installMode: CodePush.InstallMode.IMMEDIATE,
});
|
// @flow
import CodePush from 'react-native-code-push';
import { AppRegistry, YellowBox } from 'react-native';
import {
SingleHotelStandalonePackage,
NewHotelsStandAlonePackage,
} from '@kiwicom/react-native-app-hotels';
// TODO: please check if it's still needed
YellowBox.ignoreWarnings([
// react-native-share warnings. Should be gone with the version 1.1.3
'Class GenericShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class WhatsAppShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class GooglePlusShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
'Class InstagramShare was not exported. Did you forget to use RCT_EXPORT_MODULE()',
]);
// Hotels
AppRegistry.registerComponent(
'NewKiwiHotels',
() => NewHotelsStandAlonePackage,
);
AppRegistry.registerComponent(
'SingleHotel',
() => SingleHotelStandalonePackage,
);
// This file is only used for native integration and we use CodePush there
CodePush.sync();
|
Use tempdir to ensure there will always be a directory which can be accessed.
|
'''
Tests for the file state
'''
# Import python libs
# Import salt libs
import integration
import tempfile
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
cmd.run
'''
ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir())
result = ret[next(iter(ret))]['result']
self.assertTrue(result)
def test_test_run(self):
'''
cmd.run test interface
'''
ret = self.run_state('cmd.run', name='ls',
cwd=tempfile.gettempdir(), test=True)
result = ret[next(iter(ret))]['result']
self.assertIsNone(result)
|
'''
Tests for the file state
'''
# Import python libs
import os
#
# Import salt libs
from saltunittest import TestLoader, TextTestRunner
import integration
from integration import TestDaemon
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
cmd.run
'''
ret = self.run_state('cmd.run', name='ls', cwd='/')
result = ret[next(iter(ret))]['result']
self.assertTrue(result)
def test_test_run(self):
'''
cmd.run test interface
'''
ret = self.run_state('cmd.run', name='ls', test=True)
result = ret[next(iter(ret))]['result']
self.assertIsNone(result)
|
Make version format PEP 440 compatible
|
import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'c': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
(Elasticsearch,)
|
import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
(Elasticsearch,)
|
Increment version for memory stores
|
from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
setup(
name="pconf",
version="0.3.0",
author="Andras Maroy",
author_email="andras@maroy.hu",
description=("Hierarchical python configuration with files, environment variables, command-line arguments."),
license="MIT",
keywords="configuration hierarchical",
url="https://github.com/andrasmaroy/pconf",
packages=['pconf', 'tests'],
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
extras_require={
'test': ['pytest', 'mock'],
},
)
|
from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
setup(
name="pconf",
version="0.2.1",
author="Andras Maroy",
author_email="andras@maroy.hu",
description=("Hierarchical python configuration with files, environment variables, command-line arguments."),
license="MIT",
keywords="configuration hierarchical",
url="https://github.com/andrasmaroy/pconf",
packages=['pconf', 'tests'],
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
extras_require={
'test': ['pytest', 'mock'],
},
)
|
Add specific Resource bundle management
|
package woko.actions;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class WokoResourceBundle extends ResourceBundle {
private static final String WOKO_RESOURCES_BUNDLE = "WokoResources";
private static final String APP_RESOURCES_BUNDLE = "ApplicationResources";
private Locale locale;
public WokoResourceBundle(Locale locale) {
this.locale = locale;
}
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
protected Object handleGetObject(String fullKey) {
// First, try to get resources from app specific bundle
String result = getResult(locale, APP_RESOURCES_BUNDLE, fullKey);
if (result == null)
result = getResult(locale, WOKO_RESOURCES_BUNDLE, fullKey);
return result;
}
// Just returns null if the bundle or the key is not found,
// instead of throwing an exception.
private String getResult(Locale loc, String name, String key) {
String result = null;
ResourceBundle bundle = ResourceBundle.getBundle(name, loc);
if (bundle != null) {
try { result = bundle.getString(key); }
catch (MissingResourceException exc) { }
}
return result;
}
}
|
package woko.actions;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class WokoResourceBundle extends ResourceBundle {
private Locale locale;
public WokoResourceBundle(Locale locale) {
this.locale = locale;
}
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
protected Object handleGetObject(String fullKey) {
return getResult(locale, "WokoResources", fullKey);
}
// Just returns null if the bundle or the key is not found,
// instead of throwing an exception.
private String getResult(Locale loc, String name, String key) {
String result = null;
ResourceBundle bundle = ResourceBundle.getBundle(name, loc);
if (bundle != null) {
try { result = bundle.getString(key); }
catch (MissingResourceException exc) { }
}
return result;
}
}
|
Use the proper temp dir
closes #964
|
package steps
import (
"log"
"os"
"path"
"regexp"
"github.com/Originate/git-town/src/git"
)
// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
CreateAbortStep() Step
CreateContinueStep() Step
CreateUndoStepBeforeRun() Step
CreateUndoStepAfterRun() Step
GetAutomaticAbortErrorMessage() string
Run() error
ShouldAutomaticallyAbortOnError() bool
}
// SerializedStep is used to store Steps as JSON.
type SerializedStep struct {
Data []byte
Type string
}
// SerializedRunState is used to store RunStates as JSON.
type SerializedRunState struct {
AbortStep SerializedStep
RunSteps []SerializedStep
UndoSteps []SerializedStep
}
func getRunResultFilename(command string) string {
replaceCharacterRegexp, err := regexp.Compile("[[:^alnum:]]")
if err != nil {
log.Fatal("Error compiling replace character expression: ", err)
}
directory := replaceCharacterRegexp.ReplaceAllString(git.GetRootDirectory(), "-")
return path.Join(os.TempDir(), command+"_"+directory)
}
|
package steps
import (
"fmt"
"log"
"regexp"
"github.com/Originate/git-town/src/git"
)
// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
CreateAbortStep() Step
CreateContinueStep() Step
CreateUndoStepBeforeRun() Step
CreateUndoStepAfterRun() Step
GetAutomaticAbortErrorMessage() string
Run() error
ShouldAutomaticallyAbortOnError() bool
}
// SerializedStep is used to store Steps as JSON.
type SerializedStep struct {
Data []byte
Type string
}
// SerializedRunState is used to store RunStates as JSON.
type SerializedRunState struct {
AbortStep SerializedStep
RunSteps []SerializedStep
UndoSteps []SerializedStep
}
func getRunResultFilename(command string) string {
replaceCharacterRegexp, err := regexp.Compile("[[:^alnum:]]")
if err != nil {
log.Fatal("Error compiling replace character expression: ", err)
}
directory := replaceCharacterRegexp.ReplaceAllString(git.GetRootDirectory(), "-")
return fmt.Sprintf("/tmp/%s_%s", command, directory)
}
|
Add complexity in tilde notation.
|
package com.jeffreydiaz.search;
/**
* Implementation of the classic Linear Search algorithm.
* Complexity: ~N
* @author Jeffrey Diaz
*/
public class LinearSearch {
/**
* Linearly search for item elem in array items.
* @param items an array of Item objects who've implemented the equals method.
* @param elem item to search array items for.
* @return true if elem is found within items.
*/
public static <Item> boolean search(Item[] items, Item elem)
{
for (int i = 0; i < items.length; ++i) {
if (items[i].equals(elem)){
return true;
}
}
return false;
}
/**
* Linearly search for elem in Iterable items.
* @param items Collection implementing the Iterable interface.
* @param elem Item to search collection for.
* @return true if elem is found within items.
*/
public static <Item> boolean search(Iterable<Item> items, Item elem)
{
for (Item item : items) {
if (item.equals(elem)) {
return true;
}
}
return false;
}
}
|
package com.jeffreydiaz.search;
/**
* Implementation of the classic Linear Search algorithm.
* @author Jeffrey Diaz
*/
public class LinearSearch {
/**
* Linearly search for item elem in array items.
* @param items an array of Item objects who've implemented the equals method.
* @param elem item to search array items for.
* @return true if elem is found within items.
*/
public static <Item> boolean search(Item[] items, Item elem)
{
for (int i = 0; i < items.length; ++i) {
if (items[i].equals(elem)){
return true;
}
}
return false;
}
/**
* Linearly search for elem in Iterable items.
* @param items Collection implementing the Iterable interface.
* @param elem Item to search collection for.
* @return true if elem is found within items.
*/
public static <Item> boolean search(Iterable<Item> items, Item elem)
{
for (Item item : items) {
if (item.equals(elem)) {
return true;
}
}
return false;
}
}
|
[Telemetry] Fix profile generation after r275633.
TBR=dtu@chromium.org
NOTRY=True
BUG=
Review URL: https://codereview.chromium.org/323703003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@275689 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import profile_creator
import page_sets
class SmallProfileCreator(profile_creator.ProfileCreator):
"""
Runs a browser through a series of operations to fill in a small test profile.
"""
def __init__(self):
super(SmallProfileCreator, self).__init__()
self._page_set = page_sets.Typical25PageSet()
# Open all links in the same tab save for the last _NUM_TABS links which
# are each opened in a new tab.
self._NUM_TABS = 5
def TabForPage(self, page, browser):
idx = page.page_set.pages.index(page)
# The last _NUM_TABS pages open a new tab.
if idx <= (len(page.page_set.pages) - self._NUM_TABS):
return browser.tabs[0]
else:
return browser.tabs.New()
def MeasurePage(self, _, tab, results):
tab.WaitForDocumentReadyStateToBeComplete()
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import profile_creator
import page_sets
class SmallProfileCreator(profile_creator.ProfileCreator):
"""
Runs a browser through a series of operations to fill in a small test profile.
"""
def __init__(self):
super(SmallProfileCreator, self).__init__()
self._page_set = page_sets.Typical25()
# Open all links in the same tab save for the last _NUM_TABS links which
# are each opened in a new tab.
self._NUM_TABS = 5
def TabForPage(self, page, browser):
idx = page.page_set.pages.index(page)
# The last _NUM_TABS pages open a new tab.
if idx <= (len(page.page_set.pages) - self._NUM_TABS):
return browser.tabs[0]
else:
return browser.tabs.New()
def MeasurePage(self, _, tab, results):
tab.WaitForDocumentReadyStateToBeComplete()
|
Make the website nav header's hysteresis a bit more robust
In particular, this prevents the nav header from reappearing all the
time while scrolling down on Firefox.
|
//- ----------------------------------
//- 💫 MAIN JAVASCRIPT
//- ----------------------------------
'use strict'
{
const nav = document.querySelector('.js-nav')
const fixedClass = 'is-fixed'
let vh, scrollY = 0, scrollUp = false
const updateVh = () => Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
const updateNav = () => {
const vh = updateVh()
const newScrollY = (window.pageYOffset || document.scrollTop) - (document.clientTop || 0)
if (newScrollY != scrollY) scrollUp = newScrollY <= scrollY
scrollY = newScrollY
if(scrollUp && !(isNaN(scrollY) || scrollY <= vh)) nav.classList.add(fixedClass)
else if(!scrollUp || (isNaN(scrollY) || scrollY <= vh/2)) nav.classList.remove(fixedClass)
}
window.addEventListener('scroll', () => requestAnimationFrame(updateNav))
}
|
//- ----------------------------------
//- 💫 MAIN JAVASCRIPT
//- ----------------------------------
'use strict'
{
const nav = document.querySelector('.js-nav')
const fixedClass = 'is-fixed'
let vh, scrollY = 0, scrollUp = false
const updateVh = () => Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
const updateNav = () => {
const vh = updateVh()
const newScrollY = (window.pageYOffset || document.scrollTop) - (document.clientTop || 0)
scrollUp = newScrollY <= scrollY
scrollY = newScrollY
if(scrollUp && !(isNaN(scrollY) || scrollY <= vh)) nav.classList.add(fixedClass)
else if(!scrollUp || (isNaN(scrollY) || scrollY <= vh/2)) nav.classList.remove(fixedClass)
}
window.addEventListener('scroll', () => requestAnimationFrame(updateNav))
}
|
FIX typo error on comments
|
package villa;
// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int
// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int
// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int
// ComplexCmpFunc is the function compares two complex128 elements.
type ComplexCmpFunc func(complex128, complex128) int
// IntValueCompare compares the input int values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natural IntCmpFunc.
func IntValueCompare(a, b int) int {
if a < b {
return -1
} else if a > b {
return 1
} // else if
return 0
}
// FloatValueCompare compares the input float64 values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natural FloatCmpFunc.
func FloatValueCompare(a, b float64) int {
if a < b {
return -1
} else if a > b {
return 1
} // else if
return 0
}
|
package villa;
// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int
// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int
// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int
// ComplexCmpFunc is the function compares two complex128 elements.
type ComplexCmpFunc func(complex128, complex128) int
// IntValueCompare compares the input int values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natual IntCmpFunc.
func IntValueCompare(a, b int) int {
if a < b {
return -1
} else if a > b {
return 1
} // else if
return 0
}
// FloatValueCompare compares the input float64 values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natual FloatCmpFunc.
func FloatValueCompare(a, b float64) int {
if a < b {
return -1
} else if a > b {
return 1
} // else if
return 0
}
|
Change to avoid "DeprecationWarning: invalid escape sequence"
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._base import VarNameSanitizer
class ElasticsearchIndexNameSanitizer(VarNameSanitizer):
__RE_INVALID_INDEX_NAME = re.compile("[" + re.escape('\\/*?"<>|,"') + r"\s]+")
__RE_INVALID_INDEX_NAME_HEAD = re.compile("^[_]+")
@property
def reserved_keywords(self):
return []
@property
def _invalid_var_name_head_re(self):
return self.__RE_INVALID_INDEX_NAME_HEAD
@property
def _invalid_var_name_re(self):
return self.__RE_INVALID_INDEX_NAME
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._base import VarNameSanitizer
class ElasticsearchIndexNameSanitizer(VarNameSanitizer):
__RE_INVALID_INDEX_NAME = re.compile("[" + re.escape('\\/*?"<>|,"') + "\s]+")
__RE_INVALID_INDEX_NAME_HEAD = re.compile("^[_]+")
@property
def reserved_keywords(self):
return []
@property
def _invalid_var_name_head_re(self):
return self.__RE_INVALID_INDEX_NAME_HEAD
@property
def _invalid_var_name_re(self):
return self.__RE_INVALID_INDEX_NAME
|
Update Group API
- ADD type hints
- Remove unused imports
|
# stdlib
from typing import Any
from typing import Callable
# syft relative
from ...messages.group_messages import CreateGroupMessage
from ...messages.group_messages import DeleteGroupMessage
from ...messages.group_messages import GetGroupMessage
from ...messages.group_messages import GetGroupsMessage
from ...messages.group_messages import UpdateGroupMessage
from .request_api import GridRequestAPI
class GroupRequestAPI(GridRequestAPI):
response_key = "group"
def __init__(self, send: Callable):
super().__init__(
create_msg=CreateGroupMessage,
get_msg=GetGroupMessage,
get_all_msg=GetGroupsMessage,
update_msg=UpdateGroupMessage,
delete_msg=DeleteGroupMessage,
send=send,
response_key=GroupRequestAPI.response_key,
)
def __getitem__(self, key: int) -> Any:
return self.get(group_id=key)
def __delitem__(self, key: int) -> Any:
self.delete(group_id=key)
|
# stdlib
from typing import Any
from typing import Dict
# third party
from pandas import DataFrame
# syft relative
from ...messages.group_messages import CreateGroupMessage
from ...messages.group_messages import DeleteGroupMessage
from ...messages.group_messages import GetGroupMessage
from ...messages.group_messages import GetGroupsMessage
from ...messages.group_messages import UpdateGroupMessage
from .request_api import GridRequestAPI
class GroupRequestAPI(GridRequestAPI):
response_key = "group"
def __init__(self, send):
super().__init__(
create_msg=CreateGroupMessage,
get_msg=GetGroupMessage,
get_all_msg=GetGroupsMessage,
update_msg=UpdateGroupMessage,
delete_msg=DeleteGroupMessage,
send=send,
response_key=GroupRequestAPI.response_key,
)
def __getitem__(self, key):
return self.get(group_id=key)
def __delitem__(self, key):
self.delete(group_id=key)
|
Fix number going outside of level issue
|
function LevelController(onComplete, level) {
this.onComplete = onComplete;
this.level = level;
};
LevelController.prototype.left = function() {
if(this.level.index === 0) {
return;
}
this.level.index -= 1;
};
LevelController.prototype.right = function() {
if(this.level.index === this.level.puzzle.board.columns - 1) {
return;
}
this.level.index += 1;
};
LevelController.prototype.down = function() {
if(!this.level.puzzle.isComplete()) {
this.level.puzzle.playIndex(this.level.index);
}
if(this.level.puzzle.isComplete() && typeof this.onComplete === 'function') {
this.onComplete(this.level);
}
};
LevelController.prototype.up = function() {
this.level.puzzle.reset();
};
LevelController.prototype.onComplete = function() {};
|
function LevelController(onComplete, level) {
this.onComplete = onComplete;
this.level = level;
};
LevelController.prototype.left = function() {
if( this.index === 0 ) {
return;
}
this.level.index -= 1;
};
LevelController.prototype.right = function() {
if(this.index === this.level.puzzle.board.columns - 1) {
return;
}
this.level.index += 1;
};
LevelController.prototype.down = function() {
if(!this.level.puzzle.isComplete()) {
this.level.puzzle.playIndex(this.level.index);
}
if(this.level.puzzle.isComplete() && typeof this.onComplete === 'function') {
this.onComplete(this.level);
}
};
LevelController.prototype.up = function() {
this.level.puzzle.reset();
};
LevelController.prototype.onComplete = function() {};
|
Set ptm return pointer to nil if it is closed.
|
// © 2012 Jay Weisskopf
package pty
// #include <stdlib.h>
// #include <fcntl.h>
import "C"
import "os"
func Open() (ptm *os.File, ptsName string, err error) {
ptmFd, err := C.posix_openpt(C.O_RDWR | C.O_NOCTTY)
if err != nil {
return nil, "", err
}
ptm = os.NewFile(uintptr(ptmFd), "")
defer func() {
if err != nil && ptm != nil {
ptm.Close()
ptm = nil
}
}()
_, err = C.grantpt(ptmFd)
if err != nil {
return nil, "", err
}
_, err = C.unlockpt(ptmFd)
if err != nil {
return nil, "", err
}
ptsNameCstr, err := C.ptsname(ptmFd)
if err != nil {
return nil, "", err
}
ptsName = C.GoString(ptsNameCstr)
return ptm, ptsName, nil
}
|
// © 2012 Jay Weisskopf
package pty
// #include <stdlib.h>
// #include <fcntl.h>
import "C"
import "os"
func Open() (ptm *os.File, ptsName string, err error) {
ptmFd, err := C.posix_openpt(C.O_RDWR | C.O_NOCTTY)
if err != nil {
return nil, "", err
}
ptm = os.NewFile(uintptr(ptmFd), "")
defer func() {
if err != nil && ptm != nil {
ptm.Close()
}
}()
_, err = C.grantpt(ptmFd)
if err != nil {
return nil, "", err
}
_, err = C.unlockpt(ptmFd)
if err != nil {
return nil, "", err
}
ptsNameCstr, err := C.ptsname(ptmFd)
if err != nil {
return nil, "", err
}
ptsName = C.GoString(ptsNameCstr)
return ptm, ptsName, nil
}
|
Fix for tests breaking on keep-alive
|
package android.net;
import io.reon.test.support.LocalWire;
import java.io.*;
public class LocalSocket {
private InputStream inputStream;
private OutputStream outputStream;
public LocalSocket() {
this(null, null);
}
public LocalSocket(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public OutputStream getOutputStream() throws IOException {
return outputStream;
}
public InputStream getInputStream() throws IOException {
return inputStream;
}
public FileDescriptor getFileDescriptor() {
return new FileDescriptor();
}
public void shutdownOutput() throws IOException {
}
public void close() throws IOException {
inputStream.close();
outputStream.close();
}
public int getSendBufferSize() throws IOException {
return 1111;
}
public void connect(LocalSocketAddress localSocketAddress) throws IOException {
LocalWire.ClientsSideStreams clientsSideStreams = LocalWire.getInstance().connect();
inputStream = clientsSideStreams.getInputStream();
outputStream = clientsSideStreams.getOutputStream();
}
}
|
package android.net;
import io.reon.test.support.LocalWire;
import java.io.*;
public class LocalSocket {
private InputStream inputStream;
private OutputStream outputStream;
public LocalSocket() {
this(null, null);
}
public LocalSocket(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public OutputStream getOutputStream() throws IOException {
return outputStream;
}
public InputStream getInputStream() throws IOException {
return inputStream;
}
public FileDescriptor getFileDescriptor() {
return new FileDescriptor();
}
public void shutdownOutput() throws IOException {
}
public void close() throws IOException {
}
public int getSendBufferSize() throws IOException {
return 1111;
}
public void connect(LocalSocketAddress localSocketAddress) throws IOException {
LocalWire.ClientsSideStreams clientsSideStreams = LocalWire.getInstance().connect();
inputStream = clientsSideStreams.getInputStream();
outputStream = clientsSideStreams.getOutputStream();
}
}
|
Work around slack message limits
|
'use strict';
var
bole = require('bole'),
restify = require('restify')
;
var slackClient;
var logger = bole('slack');
exports.createClient = function createClient(opts)
{
slackClient = restify.createJSONClient({ url: opts.slack });
logger.info('Slack client created')
};
exports.report = function report(message, options)
{
if (!slackClient) return;
var body = options || {};
var text = message;
// because slack has message limits
if (message.length > 499){
text = message.substr(0, 499)
exports.report(message.substr(499))
}
body.text = text;
slackClient.post('', body, function(err, req, res, obj)
{
if (err)
logger.error({error: err, message: message}, 'error posting to webhook');
else if (res.statusCode === 200)
{
logger.info('report posted to Slack');
}
});
};
|
'use strict';
var
bole = require('bole'),
restify = require('restify')
;
var slackClient;
var logger = bole('slack');
exports.createClient = function createClient(opts)
{
slackClient = restify.createJSONClient({ url: opts.slack });
logger.info('Slack client created')
};
exports.report = function report(message, options)
{
if (!slackClient) return;
var body = options || {};
body.text = message;
slackClient.post('', body, function(err, req, res, obj)
{
if (err)
logger.error({error: err, message: message}, 'error posting to webhook');
else if (res.statusCode === 200)
{
logger.info('report posted to Slack');
}
});
};
|
Switch order (again) of legend for example
|
"""
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import discretize
import matplotlib.pyplot as plt
def run(plotIt=True):
M = discretize.TreeMesh([8, 8])
def refine(cell):
xyz = cell.center
dist = ((xyz - [0.25, 0.25]) ** 2).sum() ** 0.5
if dist < 0.25:
return 3
return 2
M.refine(refine)
if plotIt:
M.plotGrid(nodes=True, centers=True, faces_x=True)
plt.legend(
(
"Nodes",
"Hanging Nodes",
"Cell Centers",
"X faces",
"Hanging X faces",
"Grid",
)
)
if __name__ == "__main__":
run()
plt.show()
|
"""
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import discretize
import matplotlib.pyplot as plt
def run(plotIt=True):
M = discretize.TreeMesh([8, 8])
def refine(cell):
xyz = cell.center
dist = ((xyz - [0.25, 0.25]) ** 2).sum() ** 0.5
if dist < 0.25:
return 3
return 2
M.refine(refine)
if plotIt:
M.plotGrid(nodes=True, centers=True, faces_x=True)
plt.legend(
(
"Grid",
"Cell Centers",
"Nodes",
"Hanging Nodes",
"X faces",
"Hanging X faces",
)
)
if __name__ == "__main__":
run()
plt.show()
|
Add setting of undefined rather than an empty string
|
import React from 'react';
import PropTypes from 'prop-types';
import { TextInput, StyleSheet } from 'react-native';
import { DARKER_GREY, LIGHT_GREY } from '../../../globalStyles/colors';
import { APP_FONT_FAMILY } from '../../../globalStyles/fonts';
import { useJSONFormOptions } from '../JSONFormContext';
export const Text = ({ autofocus, disabled, placeholder, value, onChange }) => {
const { focusController } = useJSONFormOptions();
const ref = focusController.useRegisteredRef();
return (
<TextInput
ref={ref}
style={styles.textInputStyle}
value={value}
placeholderTextColor={LIGHT_GREY}
underlineColorAndroid={DARKER_GREY}
placeholder={placeholder}
selectTextOnFocus
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
onChangeText={newVal => onChange(newVal || undefined)}
onSubmitEditing={() => focusController.next(ref)}
editable={!disabled}
blurOnSubmit={false}
autoFocus={autofocus}
/>
);
};
const styles = StyleSheet.create({
textInputStyle: { flex: 1, fontFamily: APP_FONT_FAMILY },
});
Text.propTypes = {
autofocus: PropTypes.bool,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
};
Text.defaultProps = {
autofocus: false,
disabled: false,
placeholder: '',
value: '',
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { TextInput, StyleSheet } from 'react-native';
import { DARKER_GREY, LIGHT_GREY } from '../../../globalStyles/colors';
import { APP_FONT_FAMILY } from '../../../globalStyles/fonts';
import { useJSONFormOptions } from '../JSONFormContext';
export const Text = ({ autofocus, disabled, placeholder, value, onChange }) => {
const { focusController } = useJSONFormOptions();
const ref = focusController.useRegisteredRef();
return (
<TextInput
ref={ref}
style={styles.textInputStyle}
value={value}
placeholderTextColor={LIGHT_GREY}
underlineColorAndroid={DARKER_GREY}
placeholder={placeholder}
selectTextOnFocus
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
onChangeText={onChange}
onSubmitEditing={() => focusController.next(ref)}
editable={!disabled}
blurOnSubmit={false}
autoFocus={autofocus}
/>
);
};
const styles = StyleSheet.create({
textInputStyle: { flex: 1, fontFamily: APP_FONT_FAMILY },
});
Text.propTypes = {
autofocus: PropTypes.bool,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
};
Text.defaultProps = {
autofocus: false,
disabled: false,
placeholder: '',
value: '',
};
|
Use reflect to test time access methods on Document
|
package asciidocgo
import (
"fmt"
"reflect"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var dm = new(Document).Monitor()
var dnm = new(Document)
var notMonitoredError = &NotMonitoredError{"test"}
var monitorFNames = [1]string{"ReadTime"}
func TestDocumentMonitor(t *testing.T) {
Convey("A Document can be monitored", t, func() {
Convey("By default, a Document is not monitored", func() {
So(dnm.IsMonitored(), ShouldBeFalse)
})
Convey("A monitored Document is monitored", func() {
So(dm.IsMonitored(), ShouldBeTrue)
})
})
Convey("A non-monitored Document should return error when accessing times", t, func() {
_, err := dnm.ReadTime()
So(err, ShouldNotBeNil)
So(err, ShouldHaveSameTypeAs, notMonitoredError)
So(err.Error(), ShouldContainSubstring, "not monitored")
})
Convey("A monitored empty Document should return 0 when accessing times", t, func() {
dtype := reflect.ValueOf(dm)
for _, fname := range monitorFNames {
dfunc := dtype.MethodByName(fname)
ret := dfunc.Call([]reflect.Value{})
So(ret[1], shouldBeNilReflectValue)
So(ret[0].Int(), ShouldBeZeroValue)
}
})
}
func shouldBeNilReflectValue(actual interface{}, expected ...interface{}) string {
if actual.(reflect.Value).IsNil() {
return ""
}
return "Value " + fmt.Sprintf("%v", actual) + " should be nil"
}
|
package asciidocgo
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var dm = new(Document).Monitor()
var dnm = new(Document)
var notMonitoredError = &NotMonitoredError{"test"}
func TestDocumentMonitor(t *testing.T) {
Convey("A Document can be monitored", t, func() {
Convey("By default, a Document is not monitored", func() {
So(dnm.IsMonitored(), ShouldBeFalse)
})
Convey("A monitored Document is monitored", func() {
So(dm.IsMonitored(), ShouldBeTrue)
})
})
Convey("A non-monitored Document should return error when accessing times", t, func() {
_, err := dnm.ReadTime()
So(err, ShouldNotBeNil)
So(err, ShouldHaveSameTypeAs, notMonitoredError)
So(err.Error(), ShouldContainSubstring, "not monitored")
})
Convey("A monitored empty Document should return 0 when accessing times", t, func() {
readTime, err := dm.ReadTime()
So(err, ShouldBeNil)
So(readTime, ShouldBeZeroValue)
})
}
|
sdack-1: Add classes for simplified building of process UIs
|
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.process.ui.container;
import de.esoco.lib.property.Layout;
import de.esoco.lib.property.Orientation;
import de.esoco.process.ui.Container;
import de.esoco.process.ui.LayoutContainer;
import static de.esoco.lib.property.StyleProperties.VERTICAL;
/********************************************************************
* A panel that layouts components on the edges of it's center area.
*
* @author eso
*/
public class DockPanel extends LayoutContainer<DockPanel>
{
//~ Constructors -----------------------------------------------------------
/***************************************
* Creates a new instance.
*
* @param rParent The parent container
* @param eOrientation bVertical TRUE for vertical orientation
*/
public DockPanel(Container<?> rParent, Orientation eOrientation)
{
super(rParent, Layout.DOCK);
if (eOrientation == Orientation.VERTICAL)
{
set(VERTICAL);
}
}
}
|
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.process.ui.container;
import de.esoco.lib.property.Layout;
import de.esoco.process.ui.Container;
import de.esoco.process.ui.LayoutContainer;
/********************************************************************
* A panel that layouts components on the four edges around it's center area.
*
* @author eso
*/
public class DockPanel extends LayoutContainer<DockPanel>
{
//~ Constructors -----------------------------------------------------------
/***************************************
* Creates a new instance.
*
* @param rParent The parent container
*/
public DockPanel(Container<?> rParent)
{
super(rParent, Layout.DOCK);
}
}
|
Move webui optional config file to the same directory DNSCheck Lib uses.
|
<?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');
define('PAGER_SIZE', 10);
define('GUI_TIMEOUT', 300);
$sourceIdentifiers = array(
'standard' => 'webgui',
'undelegated' => 'webgui-undelegated'
);
define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());
/* Provide a place where settings can be overridden, to make Debian packaging easier. */
if (is_readable('/etc/dnscheck/webui_config.php')) {
require_once('/etc/dnscheck/webui_config.php');
}
?>
|
<?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');
define('PAGER_SIZE', 10);
define('GUI_TIMEOUT', 300);
$sourceIdentifiers = array(
'standard' => 'webgui',
'undelegated' => 'webgui-undelegated'
);
define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());
/* Provide a place where settings can be overridden, to make Debian packaging easier. */
if (is_readable('/etc/dnscheck.php')) {
require_once('/etc/dnscheck.php');
}
?>
|
Update the PyPI version to 0.2.5.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.5',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.4',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Add directory (auto-populates if running in a sub-directory) to assets path in main template
|
<?php
namespace CRD\Core;
$resources = $template->resources;
$html = $template->html;
$app = $template->view->app;
$router = $app->router;
?><!doctype html>
<html lang="<?= $html->entities($resources->locale) ?>">
<head>
<meta charset="utf-8">
<title><?= $html->entities(((!empty($template->title))? $template->title . ' — ' : '') . $app->name) ?></title>
<!-- Handheld support -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS includes -->
<link rel="stylesheet" href="<?= $router->directory ?>/assets/css/engine.css?cache=<?= urlencode($app->version) ?>">
<!-- Initialise advanced UI -->
<script>document.documentElement.className = 'advanced';</script>
</head>
<body class="<?= $html->entities($template->page) ?>">
<div id="container">
<?= $template->content('main') ?>
<?= $template->content('footer') ?>
</div>
</body>
</html>
|
<?php
namespace CRD\Core;
$resources = $template->resources;
$html = $template->html;
$app = $template->view->app;
?><!doctype html>
<html lang="<?= $html->entities($resources->locale) ?>">
<head>
<meta charset="utf-8">
<title><?= $html->entities(((!empty($template->title))? $template->title . ' — ' : '') . $app->name) ?></title>
<!-- Handheld support -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS includes -->
<link rel="stylesheet" href="/assets/css/engine.css?cache=<?= urlencode($app->version) ?>">
<!-- Initialise advanced UI -->
<script>document.documentElement.className = 'advanced';</script>
</head>
<body class="<?= $html->entities($template->page) ?>">
<div id="container">
<?= $template->content('main') ?>
<?= $template->content('footer') ?>
</div>
</body>
</html>
|
Add hostname to avahi_pub advertisement method
|
var os = require('os'),
hostname = os.hostname(),
serviceName = 'radiodan-http';
if(process.platform === 'linux') {
var avahi = require('avahi_pub');
module.exports.advertise = function(radiodan, port) {
radiodan.create().player.discover().then(function(players) {
var txtRecord = { players: JSON.stringify(players) },
service = {
name: hostname, type: '_'+serviceName+'._tcp',
port: port, data: txtRecord
};
avahi.publish(service);
});
};
} else {
var mdns = require('mdns'),
serviceType = mdns.makeServiceType({
name: serviceName, protocol: 'tcp'
});
console.log('serviceType', process.platform, serviceType.toString());
module.exports.advertise = function(radiodan, port) {
var utils = radiodan.utils,
logger = utils.logger(__filename),
txtRecord,
mdnsAd;
radiodan.create().player.discover().then(function(players) {
txtRecord = {
players: JSON.stringify(players)
};
mdnsAd = mdns.createAdvertisement(
serviceType.toString(), port, {txtRecord: txtRecord}
);
mdnsAd.start();
}).then(null, utils.failedPromiseHandler(logger));
};
}
|
var serviceName = 'radiodan-http';
if(process.platform === 'linux') {
var avahi = require('avahi_pub');
module.exports.advertise = function(radiodan, port) {
radiodan.create().player.discover().then(function(players) {
var txtRecord = { players: JSON.stringify(players) },
service = {
name: serviceName, type: '_radiodan-http._tcp',
port: port, data: txtRecord
};
avahi.publish(service);
});
};
} else {
var mdns = require('mdns'),
serviceType = mdns.makeServiceType({
name: serviceName, protocol: 'tcp', subtypes: ['radiodanv1']
});
console.log('serviceType', process.platform, serviceType.toString());
module.exports.advertise = function(radiodan, port) {
var utils = radiodan.utils,
logger = utils.logger(__filename),
txtRecord,
mdnsAd;
radiodan.create().player.discover().then(function(players) {
txtRecord = {
players: JSON.stringify(players)
};
mdnsAd = mdns.createAdvertisement(
serviceType.toString(), port, {txtRecord: txtRecord}
);
mdnsAd.start();
}).then(null, utils.failedPromiseHandler(logger));
};
}
|
Fix destination at create account
|
var baseUrl = "http://marihachi.php.xdomain.jp/crystal-resonance";
$(function() {
// ログイン処理
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/login", {
type: 'post',
data: $('#login-form').serialize(),
dataType: 'json',
}).done(function() {
location.reload();
}).fail(function() {
$('#log-message').text("ログインに失敗しました");
});
});
// ログアウト処理
$('#logout-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/logout", {
type: 'get',
dataType: 'json',
}).done(function() {
location.reload();
}).fail(function() {
$('#log-message').text("ログアウトに失敗しました");
});
});
$('#signup-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/create", {
type: 'post',
data: $(this).serialize(),
dataType: 'json',
}).done(function() {
location.href = baseUrl;
}).fail(function() {
$('#log-message').text("サインアップに失敗しました");
});
});
});
|
var baseUrl = "http://marihachi.php.xdomain.jp/crystal-resonance";
$(function() {
// ログイン処理
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/login", {
type: 'post',
data: $('#login-form').serialize(),
dataType: 'json',
}).done(function() {
location.reload();
}).fail(function() {
$('#log-message').text("ログインに失敗しました");
});
});
// ログアウト処理
$('#logout-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/logout", {
type: 'get',
dataType: 'json',
}).done(function() {
location.reload();
}).fail(function() {
$('#log-message').text("ログアウトに失敗しました");
});
});
$('#signup-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/create", {
type: 'post',
data: $(this).serialize(),
dataType: 'json',
}).done(function() {
location.href = "../";
}).fail(function() {
$('#log-message').text("サインアップに失敗しました");
});
});
});
|
Add class to footer widget headings.
|
<?php
/**
* Register widget areas
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
if ( ! function_exists( 'foundationpress_sidebar_widgets' ) ) :
function foundationpress_sidebar_widgets() {
register_sidebar(array(
'id' => 'sidebar-widgets',
'name' => __( 'Sidebar widgets', 'foundationpress' ),
'description' => __( 'Drag widgets to this sidebar container.', 'foundationpress' ),
'before_widget' => '<article id="%1$s" class="widget %2$s">',
'after_widget' => '</article>',
'before_title' => '<h6 class="widget__heading">',
'after_title' => '</h6>',
));
register_sidebar(array(
'id' => 'footer-widgets',
'name' => __( 'Footer widgets', 'foundationpress' ),
'description' => __( 'Drag widgets to this footer container', 'foundationpress' ),
'before_widget' => '<article id="%1$s" class="large-4 columns widget %2$s">',
'after_widget' => '</article>',
'before_title' => '<h6 class="widget__heading">',
'after_title' => '</h6>',
));
}
add_action( 'widgets_init', 'foundationpress_sidebar_widgets' );
endif;
|
<?php
/**
* Register widget areas
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
if ( ! function_exists( 'foundationpress_sidebar_widgets' ) ) :
function foundationpress_sidebar_widgets() {
register_sidebar(array(
'id' => 'sidebar-widgets',
'name' => __( 'Sidebar widgets', 'foundationpress' ),
'description' => __( 'Drag widgets to this sidebar container.', 'foundationpress' ),
'before_widget' => '<article id="%1$s" class="widget %2$s">',
'after_widget' => '</article>',
'before_title' => '<h6>',
'after_title' => '</h6>',
));
register_sidebar(array(
'id' => 'footer-widgets',
'name' => __( 'Footer widgets', 'foundationpress' ),
'description' => __( 'Drag widgets to this footer container', 'foundationpress' ),
'before_widget' => '<article id="%1$s" class="large-4 columns widget %2$s">',
'after_widget' => '</article>',
'before_title' => '<h6>',
'after_title' => '</h6>',
));
}
add_action( 'widgets_init', 'foundationpress_sidebar_widgets' );
endif;
|
Return ok for favicon requests
|
package main
import (
"log"
"net/http"
"os"
)
type Config struct {
port string
allowedContentTypes string // uncompiled regex
}
func envOrDefault(key string, default_value string) string {
env := os.Getenv(key)
if env != "" {
return env
} else {
return default_value
}
}
func main() {
config := Config{
port: os.Getenv("PORT"),
allowedContentTypes: envOrDefault("ALLOWED_CONTENT_TYPE_REGEX", "^image/"),
}
proxy := newProxy(config)
// Simply ok favicon requests
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("/", proxy.handler)
log.Println("Listening as front on port " + config.port + "...")
err := http.ListenAndServe(":"+config.port, nil)
if err != nil {
log.Panic(err)
}
}
|
package main
import (
"log"
"net/http"
"os"
)
type Config struct {
port string
allowedContentTypes string // uncompiled regex
}
func envOrDefault(key string, default_value string) string {
env := os.Getenv(key)
if env != "" {
return env
} else {
return default_value
}
}
func main() {
config := Config{
port: os.Getenv("PORT"),
allowedContentTypes: envOrDefault("ALLOWED_CONTENT_TYPE_REGEX", "^image/"),
}
proxy := newProxy(config)
http.HandleFunc("/", proxy.handler)
log.Println("Listening as front on port " + config.port + "...")
err := http.ListenAndServe(":"+config.port, nil)
if err != nil {
log.Panic(err)
}
}
|
Use customElement in chatOutput component
|
"use strict";
let element = require("../../lib/customElement");
let ChatOutput = element.define("chat-output", {
style: require("./chatOutput.styl"),
template: require("./chatOutput.mustache"),
scope: {
log: [],
debug: false
},
helpers: {
renderEntryGroup: renderEntryGroup
}
});
let entryTemplates = {
system: require("./entries/system.mustache"),
dialogue: require("./entries/dialogue.mustache"),
action: require("./entries/action.mustache"),
slug: require("./entries/slug.mustache"),
heading: require("./entries/heading.mustache"),
ooc: require("./entries/ooc.mustache")
};
function renderEntryGroup(opts) {
let group = opts.context;
return (entryTemplates[group.firstEntry.entryType] || entryWarn)(group);
}
function entryWarn(ctx) {
console.warn("No template for entry type: ", ctx.entryType);
}
/*
* Exports
*/
module.exports.install = function(tag) {
element.install(ChatOutput, tag);
};
|
"use strict";
let can = require("../../shims/can");
let style = require("../../lib/ensureStyle"),
viewCss = require("./chatOutput.styl");
let chatTemplate = require("./chatOutput.mustache");
let entryTemplates = {
system: require("./entries/system.mustache"),
dialogue: require("./entries/dialogue.mustache"),
action: require("./entries/action.mustache"),
slug: require("./entries/slug.mustache"),
heading: require("./entries/heading.mustache"),
ooc: require("./entries/ooc.mustache")
};
function renderEntryGroup(opts) {
let group = opts.context;
return (entryTemplates[group.firstEntry.entryType] || entryWarn)(group);
}
function entryWarn(ctx) {
console.warn("No template for entry type: ", ctx.entryType);
}
function install(tag) {
tag = tag || "chat-output";
style(viewCss);
can.Component.extend({
tag: "chat-output",
template: chatTemplate,
scope: {
log: [],
debug: false
},
helpers: {
renderEntryGroup: renderEntryGroup
}
});
}
/*
* Exports
*/
module.exports.install = install;
|
Test case for Mapper injection (fail)
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.cdi;
import javax.inject.Inject;
@Transactional
public class FooService {
private @Inject @Mapper UserMapper userMapper;
private @Inject @Mapper UserMapper userMapper2;
public User doSomeBusinessStuff(int userId) {
User dummy = userMapper2.getUser(userId);
return this.userMapper.getUser(userId);
}
}
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.cdi;
import javax.inject.Inject;
@Transactional
public class FooService {
private @Inject @Mapper UserMapper userMapper;
public User doSomeBusinessStuff(int userId) {
return this.userMapper.getUser(userId);
}
}
|
Check if deletedDocument are same than the original document
|
'use strict';
var async = require('async');
var crypto = require('crypto');
var Anyfetch = require('anyfetch');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} original document
* @param {object} changes object provided by anyFetch's API. Update this object to send document's modification to anyFetch's API.
* @param {function} cb Callback, first parameter is the error if any, then the processed data
*/
module.exports = function(path, document, changes, cb) {
var anyfetch = new Anyfetch(document.access_token);
anyfetch.setApiUrl(cb.apiUrl);
async.waterfall([
function generateHash(cb) {
var shasum = crypto.createHash('sha1');
shasum.update(JSON.stringify(document.metadata));
cb(null, shasum.digest('hex'));
},
function getDocumentsWithSameHash(hash, cb) {
changes.hash = hash;
anyfetch.getDocuments({hash: hash}, cb);
},
function deleteOldDocuments(res, cb) {
var documents = res.body.data;
async.each(documents, function(deletedDocument, cb) {
if (deletedDocument.id !== document.id) {
console.log("DELETE", deletedDocument.identifier);
anyfetch.deleteDocumentById(deletedDocument.id, cb);
}
}, cb);
}
], function(err) {
cb(err, changes);
});
};
|
'use strict';
var async = require('async');
var crypto = require('crypto');
var Anyfetch = require('anyfetch');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} original document
* @param {object} changes object provided by anyFetch's API. Update this object to send document's modification to anyFetch's API.
* @param {function} cb Callback, first parameter is the error if any, then the processed data
*/
module.exports = function(path, document, changes, cb) {
var anyfetch = new Anyfetch(document.access_token);
anyfetch.setApiUrl(cb.apiUrl);
async.waterfall([
function generateHash(cb) {
var shasum = crypto.createHash('sha1');
shasum.update(JSON.stringify(document.metadata));
cb(null, shasum.digest('hex'));
},
function getDocumentsWithSameHash(hash, cb) {
changes.hash = hash;
anyfetch.getDocuments({hash: hash}, cb);
},
function deleteOldDocuments(res, cb) {
var documents = res.body.data;
async.each(documents, function(document, cb) {
console.log("DELETE", document.identifier);
anyfetch.deleteDocumentById(document.id, cb);
}, cb);
}
], function(err) {
cb(err, changes);
});
};
|
Add support for new(er) smartCampaigns endpoints.
|
var _ = require('lodash'),
Promise = require('bluebird'),
util = require('../util'),
log = util.logger();
function Campaign(marketo, connection) {
this._marketo = marketo;
this._connection = connection;
}
Campaign.prototype = {
request: function(campaignId, leads, tokens, options) {
if (!_.isArray(leads)) {
var msg = 'leads needs to be an Array';
log.error(msg);
return Promise.reject(msg);
}
options = _.extend({}, options, {
input: { leads: leads, tokens: tokens },
_method: 'POST'
});
options = util.formatOptions(options);
return this._connection.post(util.createPath('campaigns',campaignId,'trigger.json'),
{data: JSON.stringify(options), headers: {'Content-Type': 'application/json'}});
},
getCampaigns: function(options) {
var path = util.createPath( 'campaigns.json' );
options = _.extend({}, options, {
_method: 'GET'
});
return this._connection.get(path, {data: options});
},
getSmartCampaigns: function(options) {
var path = util.createAssetPath( 'smartCampaigns.json' );
options = _.extend({}, options, {
_method: 'GET'
});
return this._connection.get(path, {query: options});
},
};
module.exports = Campaign;
|
var _ = require('lodash'),
Promise = require('bluebird'),
util = require('../util'),
log = util.logger();
function Campaign(marketo, connection) {
this._marketo = marketo;
this._connection = connection;
}
Campaign.prototype = {
request: function(campaignId, leads, tokens, options) {
if (!_.isArray(leads)) {
var msg = 'leads needs to be an Array';
log.error(msg);
return Promise.reject(msg);
}
options = _.extend({}, options, {
input: { leads: leads, tokens: tokens },
_method: 'POST'
});
options = util.formatOptions(options);
return this._connection.post(util.createPath('campaigns',campaignId,'trigger.json'),
{data: JSON.stringify(options), headers: {'Content-Type': 'application/json'}});
},
getCampaigns: function(options) {
var path = util.createPath( 'campaigns.json' );
options = _.extend({}, options, {
_method: 'GET'
});
return this._connection.get(path, {data: options});
},
};
module.exports = Campaign;
|
Add try-catch as safeguard against potentionally misbehaving parser
|
/*
* Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.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.
*/
var Transform = require('stream').Transform;
function ToSignalK(options) {
Transform.call(this, {
objectMode: true
});
this.parser = new(require('nmea0183-signalk').Parser)(options);
var that = this;
this.parser.on('delta', function(delta) {
that.push(delta);
});
}
require('util').inherits(ToSignalK, Transform);
ToSignalK.prototype._transform = function(chunk, encoding, done) {
try {
this.parser.write(chunk + '\n');
} catch (ex) {
console.error(ex);
}
done();
}
module.exports = ToSignalK;
|
/*
* Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.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.
*/
var Transform = require('stream').Transform;
function ToSignalK(options) {
Transform.call(this, {
objectMode: true
});
this.parser = new(require('nmea0183-signalk').Parser)(options);
var that = this;
this.parser.on('delta', function(delta) {
that.push(delta);
});
}
require('util').inherits(ToSignalK, Transform);
ToSignalK.prototype._transform = function(chunk, encoding, done) {
this.parser.write(chunk + '\n');
done()
}
module.exports = ToSignalK;
|
Add a 'b()' utility for forcing encoding to bytes.
In Python2, the 'bytes()' builtin doesn't take an encoding argument.
|
try:
TEXT = unicode
except NameError: #pragma NO COVER Py3k
TEXT = str
STRING_TYPES = (str, bytes)
def b(x, encoding='ascii'):
return bytes(x, encoding)
else: #pragma NO COVER Python2
STRING_TYPES = (unicode, bytes)
def b(x, encoding='ascii'):
if isinstance(x, unicode):
x = x.encode(encoding)
return x
def u(x, encoding='ascii'):
if isinstance(x, TEXT): #pragma NO COVER
return x
try:
return x.decode(encoding)
except AttributeError: #pragma NO COVER
raise ValueError('WTF: %s' % x)
try:
import urlparse
except ImportError: #pragma NO COVER Py3k
from urllib.parse import parse_qs
from urllib.parse import parse_qsl
from urllib.parse import quote
from urllib.parse import unquote
from urllib.parse import unquote_to_bytes
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.parse import urlunparse
else: #pragma NO COVER Python2
from urlparse import parse_qs
from urlparse import parse_qsl
from urllib import quote
from urllib import unquote
from urllib import urlencode
from urlparse import urlparse
from urlparse import urlunparse
unquote_to_bytes = unquote
|
try:
TEXT = unicode
except NameError: #pragma NO COVER Py3k
TEXT = str
STRING_TYPES = (str, bytes)
else: #pragma NO COVER Python2
STRING_TYPES = (unicode, bytes)
def u(x, encoding='ascii'):
if isinstance(x, TEXT): #pragma NO COVER
return x
try:
return x.decode(encoding)
except AttributeError: #pragma NO COVER
raise ValueError('WTF: %s' % x)
try:
import urlparse
except ImportError: #pragma NO COVER Py3k
from urllib.parse import parse_qs
from urllib.parse import parse_qsl
from urllib.parse import quote
from urllib.parse import unquote
from urllib.parse import unquote_to_bytes
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.parse import urlunparse
else: #pragma NO COVER Python2
from urlparse import parse_qs
from urlparse import parse_qsl
from urllib import quote
from urllib import unquote
from urllib import urlencode
from urlparse import urlparse
from urlparse import urlunparse
unquote_to_bytes = unquote
|
Update test files to remove in teardown script
Drops HDF5 files that are no longer generated during routine testing
from teardown. Also adds Dask's workspace directory for cleanup.
|
#!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"data.tif",
"data.h5",
"data_traces.h5",
"data_rois.h5",
"data.zarr",
"data_trim.zarr",
"data_dn.zarr",
"data_reg.zarr",
"data_sub.zarr",
"data_f_f0.zarr",
"data_wt.zarr",
"data_norm.zarr",
"data_dict.zarr",
"data_post.zarr",
"data_traces.zarr",
"data_rois.zarr",
"data_proj.zarr",
"data_proj.html",
"dask-worker-space"]:
if os.path.isfile(each):
os.remove(each)
elif os.path.isdir(each):
shutil.rmtree(each)
|
#!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"data.tif",
"data.h5",
"data_trim.h5",
"data_dn.h5",
"data_reg.h5",
"data_sub.h5",
"data_f_f0.h5",
"data_wt.h5",
"data_norm.h5",
"data_dict.h5",
"data_post.h5",
"data_traces.h5",
"data_rois.h5",
"data_proj.h5",
"data.zarr",
"data_trim.zarr",
"data_dn.zarr",
"data_reg.zarr",
"data_sub.zarr",
"data_f_f0.zarr",
"data_wt.zarr",
"data_norm.zarr",
"data_dict.zarr",
"data_post.zarr",
"data_traces.zarr",
"data_rois.zarr",
"data_proj.zarr",
"data_proj.html"]:
if os.path.isfile(each):
os.remove(each)
elif os.path.isdir(each):
shutil.rmtree(each)
|
Add Search form for mobile devices
|
<?php get_header(); ?>
<head><title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title></head>
<div class="container">
<div class="col-md-9">
<div class = "hidden-lg hidden-md"> <?php get_search_form(); ?> </div>
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="row shadow-box">
<a href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "text-center"><?php the_title();?></h3></a>
<h6 class = "text-muted text-center">Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?></h6>
<center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?></center>
<p class = "content"><?php the_excerpt(); ?></p>
</div>
<?php endwhile; else : ?>
<div class = "row shadow-box"><h5><?php _e("We can't find what you are looking for."); ?></h5></div>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>
|
<?php get_header(); ?>
<head><title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title></head>
<div class="container">
<div class="col-md-9">
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="row shadow-box">
<a href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "text-center"><?php the_title();?></h3></a>
<h6 class = "text-muted text-center">Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?></h6>
<center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?></center>
<p class = "content"><?php the_excerpt(); ?></p>
</div>
<?php endwhile; else : ?>
<div class = "row shadow-box"><h5><?php _e("We can't find what you are looking for."); ?></h5></div>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>
|
Allow active element selection for REST routing.
|
$(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse');
}
height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
});
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
});
|
$(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse');
}
height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
});
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
});
|
HTCONDOR-1028: Allow Jira tickets over 1000
This used to double check between GitTrac and Jira ticket numbers.
I was tempted to remove the check altogether. However, it would
guard against and unfortunate key bounce. The change is going into
stable, so adding a digit to the number is a minimal change.
|
import os
import sys
from docutils import nodes
from docutils.parsers.rst import Directive
def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a JIRA ticket.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issue, changeset, etc.)
:param slug: ID of the ticket to link to
:param options: Options dictionary passed to role func.
"""
base = "https://opensciencegrid.atlassian.net/browse/HTCONDOR-"
ref = base + slug
# set_classes(options)
node = nodes.reference(rawtext, "(HTCONDOR-" + slug + ")", refuri=ref, **options)
return node
def ticket_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
try:
ticket_id = int(text)
if ticket_id > 10000:
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'HTCondor ticket number must be a number less than or equal to 10000; '
'"%s" is invalid.' % text, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
node = make_link_node(rawtext, app, 'issue', str(ticket_id), options)
return [node], []
def setup(app):
app.add_role("jira", ticket_role)
|
import os
import sys
from docutils import nodes
from docutils.parsers.rst import Directive
def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a JIRA ticket.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issue, changeset, etc.)
:param slug: ID of the ticket to link to
:param options: Options dictionary passed to role func.
"""
base = "https://opensciencegrid.atlassian.net/browse/HTCONDOR-"
ref = base + slug
# set_classes(options)
node = nodes.reference(rawtext, "(HTCONDOR-" + slug + ")", refuri=ref, **options)
return node
def ticket_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
try:
ticket_id = int(text)
if ticket_id > 1000:
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'HTCondor ticket number must be a number less than or equal to 1000; '
'"%s" is invalid.' % text, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
node = make_link_node(rawtext, app, 'issue', str(ticket_id), options)
return [node], []
def setup(app):
app.add_role("jira", ticket_role)
|
Fix py3 x64 crash thread related
Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd
|
# Copyright 2012 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
import pythoncom
sys.coinit_flags = pythoncom.COINIT_MULTITHREADED
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
from oslo_config import cfg
from oslo_log import log as oslo_logging
from cloudbaseinit import init
from cloudbaseinit.utils import log as logging
CONF = cfg.CONF
LOG = oslo_logging.getLogger(__name__)
def main():
CONF(sys.argv[1:])
logging.setup('cloudbaseinit')
try:
init.InitManager().configure_host()
except Exception as exc:
LOG.exception(exc)
raise
if __name__ == "__main__":
main()
|
# Copyright 2012 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
from oslo_config import cfg
from oslo_log import log as oslo_logging
from cloudbaseinit import init
from cloudbaseinit.utils import log as logging
CONF = cfg.CONF
LOG = oslo_logging.getLogger(__name__)
def main():
CONF(sys.argv[1:])
logging.setup('cloudbaseinit')
try:
init.InitManager().configure_host()
except Exception as exc:
LOG.exception(exc)
raise
if __name__ == "__main__":
main()
|
Add CORS headers to js files for local dev
|
"""
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers import render_to_response
def static_media(request, **kwargs):
"""
Serve static files below a given point in the directory structure.
"""
from django.contrib.staticfiles.views import serve
module = kwargs.get('module')
path = kwargs.get('path', '')
if module:
path = '%s/%s' % (module, path)
response = serve(request, path, insecure=True)
# We need CORS for font files
if path.endswith(('.eot', '.ttf', '.woff', '.js')):
response['Access-Control-Allow-Origin'] = '*'
return response
class TemplateView(BaseTemplateView):
def render_to_response(self, context, **response_kwargs):
return render_to_response(
request=self.request,
template=self.get_template_names(),
context=context,
**response_kwargs
)
|
"""
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers import render_to_response
def static_media(request, **kwargs):
"""
Serve static files below a given point in the directory structure.
"""
from django.contrib.staticfiles.views import serve
module = kwargs.get('module')
path = kwargs.get('path', '')
if module:
path = '%s/%s' % (module, path)
response = serve(request, path, insecure=True)
# We need CORS for font files
if path.endswith(('.eot', '.ttf', '.woff')):
response['Access-Control-Allow-Origin'] = '*'
return response
class TemplateView(BaseTemplateView):
def render_to_response(self, context, **response_kwargs):
return render_to_response(
request=self.request,
template=self.get_template_names(),
context=context,
**response_kwargs
)
|
Correct demo so it actually works
|
/*
Examples
Author: Addy Osmani
See: http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders
for more information on the module loader proposal
*/
//Module: Define a new module
var module = new Module({test:'hello'});
console.log(module);
//System (pre-configured Loader)
System.import('js/test1', function(test1){
console.log('test1.js loaded', test1);
test1.tester();
});
// Loader: Define a new module loader instance
var baseURL = document.URL.substring(0, document.URL.lastIndexOf('\/') + 1);
var loader = new Loader({global: window,
strict: false,
resolve: function (name, options) {
return baseURL + name;
}
});
console.log(loader);
//Usage:
loader.import('js/test2.js',
function(test) {
console.log('test2.js loaded', test);
test.foobar();
}, function(err){
console.log(err);
});
loader.import('js/libs/jquery-1.7.1.js',
function() {
console.log('jQuery loaded', loader.global.jQuery);
loader.global.$('body').css({'background':'blue'});
}, function(err){
console.log(err);
});
|
/*
Examples
Author: Addy Osmani
See: http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders
for more information on the module loader proposal
*/
//Module: Define a new module
var module = new Module({test:'hello'});
console.log(module);
//System (pre-configured Loader)
System.import('js/test1.js', function(test1){
console.log('test1.js loaded', test1);
test1.tester();
});
// Loader: Define a new module loader instance
var baseURL = document.URL.substring(0, document.URL.lastIndexOf('\/') + 1);
var loader = new Loader({global: window,
strict: false,
resolve: function (name, options) {
return baseURL + name;
}
});
console.log(loader);
//Usage:
loader.import('js/test2.js',
function(test) {
console.log('test2.js loaded', test);
test.foobar();
}, function(err){
console.log(err);
});
loader.import('js/libs/jquery-1.7.1.js',
function() {
console.log('jQuery loaded', loader.global.jQuery);
loader.global.$('body').css({'background':'blue'});
}, function(err){
console.log(err);
});
|
Copy the node options too.
|
'use strict'
const common = require('./webpack.common')
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const config = {
devtool: 'cheap-module-source-map',
entry: common.entry,
output: common.output,
plugins: [
...common.plugins,
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.DefinePlugin({
__DEV__: false
})
],
module: common.module,
resolve: common.resolve,
target: common.target,
externals: common.externals,
node: common.node
}
// This will cause the compiled CSS to be output to a
// styles.css and a <link rel="stylesheet"> tag to be
// appended to the index.html HEAD at compile time
config.module.loaders.push({
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
})
// Necessary to be able to use ExtractTextPlugin as a loader.
config.plugins.push(new ExtractTextPlugin('styles.css'))
config.target = webpackTargetElectronRenderer(config)
module.exports = config
|
'use strict'
const common = require('./webpack.common')
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const config = {
devtool: 'cheap-module-source-map',
entry: common.entry,
output: common.output,
plugins: [
...common.plugins,
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.DefinePlugin({
__DEV__: false
})
],
module: common.module,
resolve: common.resolve,
target: common.target,
externals: common.externals
}
// This will cause the compiled CSS to be output to a
// styles.css and a <link rel="stylesheet"> tag to be
// appended to the index.html HEAD at compile time
config.module.loaders.push({
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
})
// Necessary to be able to use ExtractTextPlugin as a loader.
config.plugins.push(new ExtractTextPlugin('styles.css'))
config.target = webpackTargetElectronRenderer(config)
module.exports = config
|
Fix class name in test file
|
from robot.conf import Language
class Custom(Language):
setting_headers = {'H 1'}
variable_headers = {'H 2'}
test_case_headers = {'H 3'}
task_headers = {'H 4'}
keyword_headers = {'H 5'}
comment_headers = {'H 6'}
library = 'L'
resource = 'R'
variables = 'V'
documentation = 'S 1'
metadata = 'S 2'
suite_setup = 'S 3'
suite_teardown = 'S 4'
test_setup = 'S 5'
test_teardown = 'S 6'
test_template = 'S 7'
force_tags = 'S 8'
default_tags = 'S 9'
test_timeout = 'S 10'
setup = 'S 11'
teardown = 'S 12'
template = 'S 13'
tags = 'S 14'
timeout = 'S 15'
arguments = 'S 16'
return_ = 'S 17'
bdd_prefixes = {}
|
from robot.conf import Language
class Fi(Language):
setting_headers = {'H 1'}
variable_headers = {'H 2'}
test_case_headers = {'H 3'}
task_headers = {'H 4'}
keyword_headers = {'H 5'}
comment_headers = {'H 6'}
library = 'L'
resource = 'R'
variables = 'V'
documentation = 'S 1'
metadata = 'S 2'
suite_setup = 'S 3'
suite_teardown = 'S 4'
test_setup = 'S 5'
test_teardown = 'S 6'
test_template = 'S 7'
force_tags = 'S 8'
default_tags = 'S 9'
test_timeout = 'S 10'
setup = 'S 11'
teardown = 'S 12'
template = 'S 13'
tags = 'S 14'
timeout = 'S 15'
arguments = 'S 16'
return_ = 'S 17'
bdd_prefixes = {}
|
Add fix for period syncing
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Methods to create internal records from a requested
* sync/external record. Used primarily by
* createOrUpdateRecord in incomingSyncUtils.
*/
import { parseBoolean, parseDate } from './incomingSyncUtils';
export const createPeriodInternalRecord = (record, database) => ({
id: record.ID,
startDate: record.startDate ? parseDate(record.startDate) : new Date(),
endDate: record.endDate ? parseDate(record.endDate) : new Date(),
name: record.name,
periodSchedule: database.getOrCreate('PeriodSchedule', record.periodScheduleID),
});
export const createOptionsInternalRecord = record => ({
id: record.ID,
title: record.title,
type: record.type,
isActive: parseBoolean(record.isActive),
});
export const createPeriodScheduleInternalRecord = record => ({
id: record.ID,
name: record.name,
});
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Methods to create internal records from a requested
* sync/external record. Used primarily by
* createOrUpdateRecord in incomingSyncUtils.
*/
import { parseBoolean, parseDate } from './incomingSyncUtils';
export const createPeriodInternalRecord = (record, database) => ({
id: record.ID,
startDate: record.startDate ? parseDate(record.startDate) : new Date(),
endDate: record.endDate ? parseDate(record.startDate) : new Date(),
name: record.name,
periodSchedule: database.getOrCreate('PeriodSchedule', record.periodScheduleID),
});
export const createOptionsInternalRecord = record => ({
id: record.ID,
title: record.title,
type: record.type,
isActive: parseBoolean(record.isActive),
});
export const createPeriodScheduleInternalRecord = record => ({
id: record.ID,
name: record.name,
});
|
Add more databases for transaction thingy
|
<?php
/**
* Copyright 2015-2017 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
use DatabaseTransactions;
protected $connectionsToTransact = [
'mysql',
'mysql-chat',
'mysql-mp',
'mysql-store',
'mysql-updates',
];
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
return $app;
}
}
|
<?php
/**
* Copyright 2015-2017 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
use DatabaseTransactions;
protected $connectionsToTransact = [
'mysql',
'mysql-store',
];
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
return $app;
}
}
|
CC-5781: Upgrade script for new storage quota implementation
|
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
Copy arguments only when necessary
|
import _isArray from './_isArray.js';
import _isTransformer from './_isTransformer.js';
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with one of the given method names, it will
* execute that function (functor case). Otherwise, if it is a transformer,
* uses transducer [xf] to return a new transformer (transducer case).
* Otherwise, it will default to executing [fn].
*
* @private
* @param {Array} methodNames properties to check for a custom implementation
* @param {Function} xf transducer to initialize if object is transformer
* @param {Function} fn default ramda implementation
* @return {Function} A function that dispatches on object in list position
*/
export default function _dispatchable(methodNames, xf, fn) {
return function() {
if (arguments.length === 0) {
return fn();
}
var obj = arguments[arguments.length - 1];
if (!_isArray(obj)) {
var idx = 0;
while (idx < methodNames.length) {
if (typeof obj[methodNames[idx]] === 'function') {
return obj[methodNames[idx]].apply(obj, Array.prototype.slice.call(arguments, 0, -1));
}
idx += 1;
}
if (_isTransformer(obj)) {
var transducer = xf.apply(null, Array.prototype.slice.call(arguments, 0, -1));
return transducer(obj);
}
}
return fn.apply(this, arguments);
};
}
|
import _isArray from './_isArray.js';
import _isTransformer from './_isTransformer.js';
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with one of the given method names, it will
* execute that function (functor case). Otherwise, if it is a transformer,
* uses transducer [xf] to return a new transformer (transducer case).
* Otherwise, it will default to executing [fn].
*
* @private
* @param {Array} methodNames properties to check for a custom implementation
* @param {Function} xf transducer to initialize if object is transformer
* @param {Function} fn default ramda implementation
* @return {Function} A function that dispatches on object in list position
*/
export default function _dispatchable(methodNames, xf, fn) {
return function() {
if (arguments.length === 0) {
return fn();
}
var args = Array.prototype.slice.call(arguments, 0);
var obj = args.pop();
if (!_isArray(obj)) {
var idx = 0;
while (idx < methodNames.length) {
if (typeof obj[methodNames[idx]] === 'function') {
return obj[methodNames[idx]].apply(obj, args);
}
idx += 1;
}
if (_isTransformer(obj)) {
var transducer = xf.apply(null, args);
return transducer(obj);
}
}
return fn.apply(this, arguments);
};
}
|
Add lazy loading also to pills
|
/**
* Lazy-loaded tabs
*/
jQuery(function() {
$('.nav.nav-tabs, .nav.nav-pills').on('click', '[data-url]', function(event) {
var loader = $(this);
if (loader.data('loaded'))
return;
var target = $(loader.attr('href')); // It's an #anchor
$.ajax({
url: loader.data('url'),
beforeSend: function() {
loader.trigger('stradivari:tab:loading');
}
})
.done(function(html) {
loader.data('loaded', true);
target.html(html);
loader.trigger('stradivari:tab:loaded');
})
.fail(function() {
alert('Aw, snap! Something went wrong');
target.html('');
loader.trigger('stradivari:tab:failed');
});
})
});
|
/**
* Lazy-loaded tabs
*/
jQuery(function() {
$('.nav.nav-tabs').on('click', '[data-url]', function(event) {
var loader = $(this);
if (loader.data('loaded'))
return;
var target = $(loader.attr('href')); // It's an #anchor
$.ajax({
url: loader.data('url'),
beforeSend: function() {
loader.trigger('stradivari:tab:loading');
}
})
.done(function(html) {
loader.data('loaded', true);
target.html(html);
loader.trigger('stradivari:tab:loaded');
})
.fail(function() {
alert('Aw, snap! Something went wrong');
target.html('');
loader.trigger('stradivari:tab:failed');
});
})
});
|
Add error message for "
|
'use strict';
var kmp = require('kmp-matcher').kmp;
module.exports = function (query) {
if (!query.length) {
return [];
}
if (query.indexOf('"') >= 0) {
throw new Error('Unimplemented: can\'t match "');
}
var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
document, null, XPathResult.ANY_TYPE, null);
var result = [];
var node;
while (node = xpathResult.iterateNext()) {
kmp(node.textContent, query)
.forEach(function (start) {
var range = document.createRange();
range.setStart(node, start);
range.setEnd(node, start + query.length);
result.push(range);
});
}
return result;
};
|
'use strict';
var kmp = require('kmp-matcher').kmp;
module.exports = function (query) {
if (!query.length) {
return [];
}
var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
document, null, XPathResult.ANY_TYPE, null);
var result = [];
var node;
while (node = xpathResult.iterateNext()) {
kmp(node.textContent, query)
.forEach(function (start) {
var range = document.createRange();
range.setStart(node, start);
range.setEnd(node, start + query.length);
result.push(range);
});
}
return result;
};
|
Add method to get AttributeReader for specific attribute as well as ability to determine namespaces for a given prefix
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@888 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
|
package org.codehaus.xfire.aegis;
import javax.xml.namespace.QName;
/**
* A MessageReader. You must call getNextChildReader() until hasMoreChildReaders()
* returns false.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public interface MessageReader
{
public String getValue();
public int getValueAsInt();
public long getValueAsLong();
public double getValueAsDouble();
public float getValueAsFloat();
public boolean getValueAsBoolean();
public MessageReader getAttributeReader( QName qName );
public boolean hasMoreAttributeReaders();
public MessageReader getNextAttributeReader();
public boolean hasMoreElementReaders();
public MessageReader getNextElementReader();
public QName getName();
/**
* Get the local name of the element this reader represents.
* @return Local Name
*/
public String getLocalName();
/**
* @return Namespace
*/
public String getNamespace();
public String getNamespaceForPrefix( String prefix );
}
|
package org.codehaus.xfire.aegis;
import javax.xml.namespace.QName;
/**
* A MessageReader. You must call getNextChildReader() until hasMoreChildReaders()
* returns false.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public interface MessageReader
{
public String getValue();
public int getValueAsInt();
public long getValueAsLong();
public double getValueAsDouble();
public float getValueAsFloat();
public boolean getValueAsBoolean();
public boolean hasMoreAttributeReaders();
public MessageReader getNextAttributeReader();
public boolean hasMoreElementReaders();
public MessageReader getNextElementReader();
public QName getName();
/**
* Get the local name of the element this reader represents.
* @return
*/
public String getLocalName();
/**
* @return
*/
public String getNamespace();
}
|
Make it work with VIM
|
// Native
const fs = require('fs')
const path = require('path')
const styles = fs.readFileSync(path.join(__dirname, 'styles.css'), 'utf8')
const colors = {
yellow: '#afaf00',
lightGreen: '#30de04'
}
exports.decorateConfig = config => Object.assign({}, config, {
padding: '7px 7px',
backgroundColor: '#fff',
foregroundColor: '#000',
css: (config.css || '') + styles,
colors
})
exports.decorateBrowserOptions = defaults => Object.assign({}, defaults, {
titleBarStyle: 'default',
transparent: false
})
exports.getTabsProps = (parentProps, props) => {
const bodyClasses = document.body.classList
if (props.tabs.length <= 1) {
bodyClasses.add('closed-tabs')
} else {
bodyClasses.remove('closed-tabs')
}
return Object.assign({}, parentProps, props)
}
|
// Native
const fs = require('fs')
const path = require('path')
const styles = fs.readFileSync(path.join(__dirname, 'styles.css'), 'utf8')
const colors = {
yellow: '#afaf00',
lightGreen: '#30de04'
}
exports.decorateConfig = config => Object.assign({}, config, {
padding: '7px 7px',
backgroundColor: '#fff',
foregroundColor: '#000',
cursorColor: '#000',
cursorShape: 'BEAM',
css: (config.css || '') + styles,
colors
})
exports.decorateBrowserOptions = defaults => Object.assign({}, defaults, {
titleBarStyle: 'default',
transparent: false
})
exports.getTabsProps = (parentProps, props) => {
const bodyClasses = document.body.classList
if (props.tabs.length <= 1) {
bodyClasses.add('closed-tabs')
} else {
bodyClasses.remove('closed-tabs')
}
return Object.assign({}, parentProps, props)
}
|
Make GPU mem split optional
|
#!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
user_input = raw_input("Want to change the GPU memory split? (Y/N): ")
if user_input == 'Y':
gpu_mem = 0
while gpu_mem == 0:
mem_split = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
if is_valid_gpu_mem(mem_split):
gpu_mem = mem_split
else:
print("Acceptable memory values are: 16/32/64/128/256")
update_file('/boot/config.txt', gpu_mem)
else:
print("Skipping GPU memory split...")
def update_file(path, gpu_mem):
data = {
'gpu_mem': gpu_mem
}
template_name = path.split('/')[-1]
new_file_data = file_templates.build(template_name, data)
with open(path, 'w') as f:
f.write(new_file_data)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
gpu_mem = 0
while gpu_mem == 0:
user_input = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
if is_valid_gpu_mem(user_input):
gpu_mem = user_input
else:
print("Acceptable memory values are: 16/32/64/128/256")
update_file('/boot/config.txt', gpu_mem)
def update_file(path, gpu_mem):
data = {
'gpu_mem': gpu_mem
}
template_name = path.split('/')[-1]
new_file_data = file_templates.build(template_name, data)
with open(path, 'w') as f:
f.write(new_file_data)
if __name__ == '__main__':
main()
|
Use new-password as autocomplete on share auth page
Fixes #6821
This makes sure that (supported) browsers will not prefill the password
field if a user has a password saved for that nextcloud.
Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>
|
<?php
/** @var $_ array */
/** @var $l \OCP\IL10N */
style('files_sharing', 'authenticate');
script('files_sharing', 'authenticate');
?>
<form method="post">
<fieldset class="warning">
<?php if (!isset($_['wrongpw'])): ?>
<div class="warning-info"><?php p($l->t('This share is password-protected')); ?></div>
<?php endif; ?>
<?php if (isset($_['wrongpw'])): ?>
<div class="warning"><?php p($l->t('The password is wrong. Try again.')); ?></div>
<?php endif; ?>
<p>
<label for="password" class="infield"><?php p($l->t('Password')); ?></label>
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
<input type="password" name="password" id="password"
placeholder="<?php p($l->t('Password')); ?>" value=""
autocomplete="new-password" autocapitalize="off" autocorrect="off"
autofocus />
<input type="submit" id="password-submit"
class="svg icon-confirm input-button-inline" value="" disabled="disabled" />
</p>
</fieldset>
</form>
|
<?php
/** @var $_ array */
/** @var $l \OCP\IL10N */
style('files_sharing', 'authenticate');
script('files_sharing', 'authenticate');
?>
<form method="post">
<fieldset class="warning">
<?php if (!isset($_['wrongpw'])): ?>
<div class="warning-info"><?php p($l->t('This share is password-protected')); ?></div>
<?php endif; ?>
<?php if (isset($_['wrongpw'])): ?>
<div class="warning"><?php p($l->t('The password is wrong. Try again.')); ?></div>
<?php endif; ?>
<p>
<label for="password" class="infield"><?php p($l->t('Password')); ?></label>
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
<input type="password" name="password" id="password"
placeholder="<?php p($l->t('Password')); ?>" value=""
autocomplete="off" autocapitalize="off" autocorrect="off"
autofocus />
<input type="submit" id="password-submit"
class="svg icon-confirm input-button-inline" value="" disabled="disabled" />
</p>
</fieldset>
</form>
|
Added: Support for the GitHub Updater.
|
<?php
/**
* Plugin Name: Geo Query
* Description: Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
* Plugin URI: https://github.com/birgire/geo-query
* GitHub Plugin URI: https://github.com/birgire/geo-query.git
* Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
* Licence: MIT
*/
namespace Birgir\Geo;
/**
* Autoload
*/
\add_action( 'plugins_loaded', function()
{
require __DIR__ . '/vendor/autoload.php';
});
/**
* Init
*/
\add_action( 'init', function()
{
if( class_exists( __NAMESPACE__ . '\\GeoQueryContext' ) )
{
$o = new GeoQueryContext();
$o->setup( $GLOBALS['wpdb'] )->activate();
}
});
|
<?php
/**
* Plugin Name: Geo Query
* Description: Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
* Plugin URI: https://github.com/birgire/geo-query
* Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
* Licence: MIT
*/
namespace Birgir\Geo;
/**
* Autoload
*/
\add_action( 'plugins_loaded', function()
{
require __DIR__ . '/vendor/autoload.php';
});
/**
* Init
*/
\add_action( 'init', function()
{
if( class_exists( __NAMESPACE__ . '\\GeoQueryContext' ) )
{
$o = new GeoQueryContext();
$o->setup( $GLOBALS['wpdb'] )->activate();
}
});
|
Make fastboot transform actually work
|
/* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');
const filesToImport = [
'dependencyLibs/inputmask.dependencyLib.js',
'inputmask.js',
'inputmask.extensions.js',
'inputmask.date.extensions.js',
'inputmask.numeric.extensions.js',
'inputmask.phone.extensions.js'
];
module.exports = {
name: 'ember-inputmask',
options: {
nodeAssets: {
inputmask: () => ({
vendor: {
include: filesToImport.map(file => `dist/inputmask/${file}`),
processTree: input => fastbootTransform(input)
}
})
}
},
included() {
this._super.included.apply(this, arguments);
filesToImport.forEach(file => {
this.import(`vendor/inputmask/dist/inputmask/${file}`);
});
}
};
|
/* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');
const filesToImport = [
'dependencyLibs/inputmask.dependencyLib.js',
'inputmask.js',
'inputmask.extensions.js',
'inputmask.date.extensions.js',
'inputmask.numeric.extensions.js',
'inputmask.phone.extensions.js'
];
module.exports = {
name: 'ember-inputmask',
options: {
nodeAssets: {
inputmask: () => ({
vendor: filesToImport.map(file => `dist/inputmask/${file}`),
processTree: input => fastbootTransform(input)
})
}
},
included() {
this._super.included.apply(this, arguments);
filesToImport.forEach(file => {
this.import(`vendor/inputmask/dist/inputmask/${file}`);
});
}
};
|
Print a nicer error messages on startup
|
package main
import (
"log"
"os"
"github.com/arachnist/gorepost/bot"
"github.com/arachnist/gorepost/config"
"github.com/arachnist/gorepost/irc"
)
func main() {
var exit chan struct{}
if len(os.Args) < 2 {
log.Fatalln("Usage:", os.Args[0], "<config-file.json>")
}
config, err := config.ReadConfig(os.Args[1])
if err != nil {
log.Fatalln("Error reading configuration from", os.Args[1], "error:", err.Error())
}
logfile, err := os.OpenFile(config.Logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalln("Error opening", config.Logpath, "for writing, error:", err.Error())
}
log.SetOutput(logfile)
connections := make([]irc.Connection, len(config.Networks))
for i, _ := range connections {
network := config.Networks[i]
connections[i].Setup(bot.Dispatcher, network, config.Servers[network], config.Nick, config.User, config.RealName)
}
<-exit
}
|
package main
import (
"fmt"
"log"
"os"
"github.com/arachnist/gorepost/bot"
"github.com/arachnist/gorepost/config"
"github.com/arachnist/gorepost/irc"
)
func main() {
var exit chan struct{}
config, err := config.ReadConfig(os.Args[1])
if err != nil {
fmt.Println("Error reading configuration from", os.Args[1], "error:", err.Error())
os.Exit(1)
}
logfile, err := os.OpenFile(config.Logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Println("Error opening", config.Logpath, "for writing, error:", err.Error())
os.Exit(1)
}
log.SetOutput(logfile)
connections := make([]irc.Connection, len(config.Networks))
for i, _ := range connections {
network := config.Networks[i]
connections[i].Setup(bot.Dispatcher, network, config.Servers[network], config.Nick, config.User, config.RealName)
}
<-exit
}
|
Switch from render to hydrate on the client side
|
import React from 'react';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
} from 'react-apollo';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import initStore from '../shared/store';
import Routes from './routes';
require('offline-plugin/runtime').install();
const store = initStore(window.APOLLO_STATE);
const webClient = new ApolloClient({
initialState: { apollo: window.APOLLO_STATE.apollo },
networkInterface: createNetworkInterface({
uri: '/graphql',
}),
});
const render = (Component) => {
ReactDOM.hydrate(
(
<ApolloProvider client={webClient} store={store}>
<BrowserRouter>
<Component />
</BrowserRouter>
</ApolloProvider>
),
document.querySelector('#app'),
);
};
render(Routes);
if (module.hot) {
// eslint-disable-next-line global-require
module.hot.accept('./routes', () => render(require('./routes').default));
}
|
import React from 'react';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
} from 'react-apollo';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import initStore from '../shared/store';
import Routes from './routes';
require('offline-plugin/runtime').install();
const store = initStore(window.APOLLO_STATE);
const webClient = new ApolloClient({
initialState: { apollo: window.APOLLO_STATE.apollo },
networkInterface: createNetworkInterface({
uri: '/graphql',
}),
});
const render = (Component) => {
ReactDOM.render(
(
<ApolloProvider client={webClient} store={store}>
<BrowserRouter>
<Component />
</BrowserRouter>
</ApolloProvider>
),
document.querySelector('#app'),
);
};
render(Routes);
if (module.hot) {
// eslint-disable-next-line global-require
module.hot.accept('./routes', () => render(require('./routes').default));
}
|
Fix object subkeys, make tests pass
|
/**
* Filters out all duplicate items from an array by checking the specified key
* @param [key] {string} the name of the attribute of each object to compare for uniqueness
if the key is empty, the entire object will be compared
if the key === false then no filtering will be performed
* @return {array}
*/
angular.module('ui.unique',[]).filter('unique', ['$parse', function ($parse) {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [],
get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item };
var extractValueToCompare = function (item) {
return angular.isObject(item) ? get(item) : item;
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
}]);
|
/**
* Filters out all duplicate items from an array by checking the specified key
* @param [key] {string} the name of the attribute of each object to compare for uniqueness
if the key is empty, the entire object will be compared
if the key === false then no filtering will be performed
* @return {array}
*/
angular.module('ui.unique',[]).filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
|
Call _super in beforeModel hook
|
import Ember from 'ember';
const {
Route,
inject: {
service
}
} = Ember;
export default Route.extend({
logger: service(),
smt: service(),
beforeModel() {
this._super(...arguments);
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.get('logger').addToLogs('message');
// this.get('logger').removeFromLogs('join');
},
model() {
this.get('smt').loadFixtures();
},
actions: {
menu(which, what) {
let menuProp = `show${which.capitalize()}Menu`;
switch(what) {
case 'show':
this.controller.set(menuProp, true);
break;
case 'hide':
this.controller.set(menuProp, false);
break;
case 'toggle':
this.controller.toggleProperty(menuProp);
break;
}
},
}
});
|
import Ember from 'ember';
const {
Route,
inject: {
service
}
} = Ember;
export default Route.extend({
logger: service(),
smt: service(),
beforeModel() {
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.get('logger').addToLogs('message');
// this.get('logger').removeFromLogs('join');
},
model() {
this.get('smt').loadFixtures();
},
actions: {
menu(which, what) {
let menuProp = `show${which.capitalize()}Menu`;
switch(what) {
case 'show':
this.controller.set(menuProp, true);
break;
case 'hide':
this.controller.set(menuProp, false);
break;
case 'toggle':
this.controller.toggleProperty(menuProp);
break;
}
},
}
});
|
Remove space from blank line for unit-tests
|
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
|
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
|
Set default default number of items to 0 (ignore)
|
public function getPaginationCustomPageSize()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_custom_page_size']) ? $this->config['get']['pagination_custom_page_size'] : false) ?>;
<?php unset($this->config['get']['pagination_custom_page_size']) ?>
}
public function getPaginationEnabled()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_enabled']) ? $this->config['get']['pagination_enabled'] : false) ?>;
<?php unset($this->config['get']['pagination_enabled']) ?>
}
public function getPaginationPageSize()
{
return <?php echo isset($this->config['get']['pagination_page_size']) ? (integer) $this->config['get']['pagination_page_size'] : 0 ?>;
<?php unset($this->config['get']['pagination_page_size']) ?>
}
|
public function getPaginationCustomPageSize()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_custom_page_size']) ? $this->config['get']['pagination_custom_page_size'] : false) ?>;
<?php unset($this->config['get']['pagination_custom_page_size']) ?>
}
public function getPaginationEnabled()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_enabled']) ? $this->config['get']['pagination_enabled'] : false) ?>;
<?php unset($this->config['get']['pagination_enabled']) ?>
}
public function getPaginationPageSize()
{
return <?php echo isset($this->config['get']['pagination_page_size']) ? (integer) $this->config['get']['pagination_page_size'] : 100 ?>;
<?php unset($this->config['get']['pagination_page_size']) ?>
}
|
Make proud topbar id unique
|
<?php if ( $topbar_logo || $topbar_title ): ?>
<ul class="logo-menu list-unstyled clearfix">
<?php if ( $topbar_logo ): ?>
<li class="h3">
<a href="<?php echo get_logo_link_url(); ?>" title="Home" rel="home" id="header-logo-topbar" class="nav-logo same-window">
<?php echo $topbar_logo ?>
</a>
</li>
<?php endif; ?>
<?php if ( $topbar_title ): ?>
<li class="h3">
<a href="<?php echo get_site_name_link_url(); ?>" title="Home" rel="home" class="navbar-brand nav-text topbar-title">
<strong><?php echo $topbar_title ?></strong>
</a>
</li>
<?php endif; ?>
</ul>
<?php endif; ?>
|
<?php if ( $topbar_logo || $topbar_title ): ?>
<ul class="logo-menu list-unstyled clearfix">
<?php if ( $topbar_logo ): ?>
<li class="h3">
<a href="<?php echo get_logo_link_url(); ?>" title="Home" rel="home" id="header-logo" class="nav-logo same-window">
<?php echo $topbar_logo ?>
</a>
</li>
<?php endif; ?>
<?php if ( $topbar_title ): ?>
<li class="h3">
<a href="<?php echo get_site_name_link_url(); ?>" title="Home" rel="home" class="navbar-brand nav-text topbar-title">
<strong><?php echo $topbar_title ?></strong>
</a>
</li>
<?php endif; ?>
</ul>
<?php endif; ?>
|
Include a nonce in the reply address.
We'll probably want to use just hashes here instead of nonces. Actually, come to think of it, we don't need time-based hashes at all, since email is presumed secure and we're not preventing CSRF.
I'll change this. :)
|
<?php
class bbSubscriptions_Handler_Lamson implements bbSubscriptions_Handler {
public function __construct() {
}
public static function send_mail($user, $subject, $content, $headers, $attrs) {
extract($attrs);
// For some stupid reason, a lot of plugins override 'From:'
// without checking if it's the default, so we need to
// filter instead of using $headers
$mailer_filter = function (&$phpmailer) use ($topic_id, $reply_author_name, $user) {
$phpmailer->From = sprintf('me+bbsub-%s-%s@ryanmccue.info', $topic_id, wp_create_nonce('bbsub_reply_by_email-' . $user->ID));
$phpmailer->FromName = $reply_author_name;
$phpmailer->AddReplyTo($phpmailer->From, $phpmailer->FromName);
};
// Register
add_filter('phpmailer_init', $mailer_filter, 9999);
// Send notification email
wp_mail( $user->user_email, $subject, $content, $headers );
// And unregister
remove_filter('phpmailer_init', $mailer_filter, 9999);
}
/**
* Check the inbox for replies
*
* With Lamson, we don't have to worry about this, as we get instant
* notifications instead.
*/
public static function check_inbox() {
// no-op
}
}
|
<?php
class bbSubscriptions_Handler_Lamson implements bbSubscriptions_Handler {
public function __construct() {
}
public static function send_mail($user, $subject, $content, $headers, $attrs) {
extract($attrs);
// For some stupid reason, a lot of plugins override 'From:'
// without checking if it's the default, so we need to
// filter instead of using $headers
$mailer_filter = function (&$phpmailer) use ($topic_id, $reply_author_name) {
$phpmailer->From = sprintf('me+bbsub-%s@ryanmccue.info', $topic_id);
$phpmailer->FromName = $reply_author_name;
$phpmailer->AddReplyTo($phpmailer->From, $phpmailer->FromName);
};
// Register
add_filter('phpmailer_init', $mailer_filter, 9999);
// Send notification email
wp_mail( $user->user_email, $subject, $content, $headers );
// And unregister
remove_filter('phpmailer_init', $mailer_filter, 9999);
}
/**
* Check the inbox for replies
*
* With Lamson, we don't have to worry about this, as we get instant
* notifications instead.
*/
public static function check_inbox() {
// no-op
}
}
|
Fix the examples and use the same names
Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com>
|
var express = require("express");
var app = express();
const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();
app.use((req, res, next) => {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
app.post('/', function (req, res) {
console.log(req.headers);
console.log(req.body);
unmarshaller.unmarshall(req.body, req.headers)
.then(cloudevent => {
// pretty print
console.log("Accepted event:");
console.log(JSON.stringify(cloudevent.format(), null, 2));
res.status(201)
.send("Event Accepted");
})
.catch(err => {
console.error(err);
res.status(400)
.header("Content-Type", "application/json")
.send(JSON.stringify(err));
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
|
var express = require("express");
var app = express();
const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();
app.use((req, res, next) => {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
app.post('/', function (req, res) {
console.log(req.headers);
console.log(req.body);
unmarshaller.unmarshall(req.body, req.headers)
.then(event => {
// pretty print
console.log("Accepted event:");
console.log(JSON.stringify(event.format(), null, 2));
res.status(201)
.send("Event Accepted");
})
.catch(err => {
console.error(err);
res.status(400)
.header("Content-Type", "application/json")
.send(JSON.stringify(err));
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
|
Use authorize instead of enforce for policies
After fully implementing policies in code, the authorize method
can be safely used and its a safeguard against introducing
policies for some API which are not properly defined in the code.
Change-Id: I499f13c34027b217bf1de905f829f36ef919e3b8
|
#
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Policy Engine For Sahara"""
import functools
from oslo_config import cfg
from oslo_policy import policy
from sahara.common import policies
from sahara import context
from sahara import exceptions
ENFORCER = None
def setup_policy():
global ENFORCER
ENFORCER = policy.Enforcer(cfg.CONF)
ENFORCER.register_defaults(policies.list_rules())
def enforce(rule):
def decorator(func):
@functools.wraps(func)
def handler(*args, **kwargs):
ctx = context.ctx()
ENFORCER.authorize(rule, {}, ctx.to_dict(), do_raise=True,
exc=exceptions.Forbidden)
return func(*args, **kwargs)
return handler
return decorator
|
#
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Policy Engine For Sahara"""
import functools
from oslo_config import cfg
from oslo_policy import policy
from sahara.common import policies
from sahara import context
from sahara import exceptions
ENFORCER = None
def setup_policy():
global ENFORCER
ENFORCER = policy.Enforcer(cfg.CONF)
ENFORCER.register_defaults(policies.list_rules())
def enforce(rule):
def decorator(func):
@functools.wraps(func)
def handler(*args, **kwargs):
ctx = context.ctx()
ENFORCER.enforce(rule, {}, ctx.to_dict(), do_raise=True,
exc=exceptions.Forbidden)
return func(*args, **kwargs)
return handler
return decorator
|
Normalize emiited peerjs id's with a plus sign
|
'use strict';
import { log, LOG_TYPES } from './log';
import config from './config';
import { io, EVENT_TYPES } from './socketIO';
let peerJSOptions = config.peerJSOptions;
export default function (server, app) {
let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions);
ExpressPeerServer.on('connection', (id) => {
log('PeerJS Connection from: ' + id);
//TODO: Proper way of doing online contacts, not this!
io.emit(EVENT_TYPES.CONTACT_ONLINE, { peerJSId: '+' + id });
});
ExpressPeerServer.on('disconnect', (id) => {
log('PeerJS Disconnection from: ' + id, LOG_TYPES.WARN);
io.emit(EVENT_TYPES.CONTACT_OFFLINE, { peerJSId: '+' + id });
});
app.use('/peerjs', ExpressPeerServer);
}
|
'use strict';
import { log, LOG_TYPES } from './log';
import config from './config';
import { io, EVENT_TYPES } from './socketIO';
let peerJSOptions = config.peerJSOptions;
export default function (server, app) {
let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions);
ExpressPeerServer.on('connection', (id) => {
log('PeerJS Connection from: ' + id);
//TODO: Proper way of doing online contacts, not this!
io.emit(EVENT_TYPES.CONTACT_ONLINE, { peerJSId: id });
});
ExpressPeerServer.on('disconnect', (id) => {
log('PeerJS Disconnection from: ' + id, LOG_TYPES.WARN);
io.emit(EVENT_TYPES.CONTACT_OFFLINE, { peerJSId: id });
});
app.use('/peerjs', ExpressPeerServer);
}
|
Revert "increasing result queue TTL"
This reverts commit 488a377b9702090275a33a335ceb90a89e6ed6f5.
|
package xing
// Constants
const (
// Type
Command = "command"
Event = "event"
Result = "result"
// Event
Register = "Register"
// Exchanges
RPCExchange = "xing.rpc"
EventExchange = "xing.event"
// Client Types
ProducerClient = "producer"
ServiceClient = "service"
EventHandlerClient = "event_handler"
StreamHandlerClient = "stream_handler"
// Defaults
RPCTTL = int64(1)
EVTTTL = int64(15 * 60 * 1000) // 15 minutes
STRMTTL = int64(60 * 1000) // 1 minutes
ResultQueueTTL = int64(10 * 60 * 1000) // 10 minutes
QueueTTL = int64(3 * 60 * 60 * 1000) // 3 hours
// Threshold
MinHeatbeat = 3
// Threading
PoolSize = 1000
NWorker = 5
)
|
package xing
// Constants
const (
// Type
Command = "command"
Event = "event"
Result = "result"
// Event
Register = "Register"
// Exchanges
RPCExchange = "xing.rpc"
EventExchange = "xing.event"
// Client Types
ProducerClient = "producer"
ServiceClient = "service"
EventHandlerClient = "event_handler"
StreamHandlerClient = "stream_handler"
// Defaults
RPCTTL = int64(1)
EVTTTL = int64(15 * 60 * 1000) // 15 minutes
STRMTTL = int64(60 * 1000) // 1 minutes
ResultQueueTTL = int64(3 * 60 * 60 * 1000) // 10 minutes
QueueTTL = int64(3 * 60 * 60 * 1000) // 3 hours
// Threshold
MinHeatbeat = 3
// Threading
PoolSize = 1000
NWorker = 5
)
|
Allow use of a custom environment for tests.
|
# -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self, env='test'):
self.app = create_app(env, initialize=False)
self.db = db
db.app = self.app
db.drop_all()
db.create_all()
self.create_brand_and_party()
self.client = self.app.test_client()
def create_brand_and_party(self):
self.brand = Brand(id='acme', title='ACME')
db.session.add(self.brand)
self.party = Party(id='acme-2014', brand=self.brand, title='ACME 2014')
db.session.add(self.party)
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()
|
# -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('test', initialize=False)
self.db = db
db.app = self.app
db.drop_all()
db.create_all()
self.create_brand_and_party()
self.client = self.app.test_client()
def create_brand_and_party(self):
self.brand = Brand(id='acme', title='ACME')
db.session.add(self.brand)
self.party = Party(id='acme-2014', brand=self.brand, title='ACME 2014')
db.session.add(self.party)
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()
|
Rename function for generating query string.
|
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function queryStringFromArgs(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
searchString = searchString.concat('+language:' + args.language);
}
return searchString;
}
function performQuery(config, request, args) {
api.search(request, queryStringFromArgs(args), function(error, result) {
if (error) {
console.log('Something unexpected has happended..');
return;
}
/* jshint camelcase: false */
var res = result.total_count || 0;
console.log('Showing %d out of %d repositories ' +
'that match your search query',
Math.min(res, 30), res);
_.forEach(result.items, function(repo) {
console.log(repo.full_name);
});
/* jshint camelcase: true */
});
}
function help() {
console.log(fs.readFileSync(
path.resolve(__dirname, '../templates/help-search.txt'), 'utf8'));
}
module.exports = function(config, request, args) {
if (args.help) {
help();
} else {
performQuery(config, request, args);
}
};
|
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function arrayToQueryString(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
searchString = searchString.concat('+language:' + args.language);
}
return searchString;
}
function performQuery(config, request, args) {
api.search(request, arrayToQueryString(args), function(error, result) {
if (error) {
console.log('Something unexpected has happended..');
return;
}
/* jshint camelcase: false */
var res = result.total_count || 0;
console.log('Showing %d out of %d repositories ' +
'that match your search query',
Math.min(res, 30), res);
_.forEach(result.items, function(repo) {
console.log(repo.full_name);
});
/* jshint camelcase: true */
});
}
function help() {
console.log(fs.readFileSync(
path.resolve(__dirname, '../templates/help-search.txt'), 'utf8'));
}
module.exports = function(config, request, args) {
if (args.help) {
help();
} else {
performQuery(config, request, args);
}
};
|
Include arch in dependency cache key
|
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const CONFIG = require('../config')
const FINGERPRINT_PATH = path.join(CONFIG.repositoryRootPath, 'node_modules', '.dependencies-fingerprint')
module.exports = {
write: function () {
const fingerprint = this.compute()
fs.writeFileSync(FINGERPRINT_PATH, fingerprint)
console.log('Wrote Dependencies Fingerprint:', FINGERPRINT_PATH, fingerprint)
},
read: function () {
return fs.existsSync(FINGERPRINT_PATH) ? fs.readFileSync(FINGERPRINT_PATH, 'utf8') : null
},
isOutdated: function () {
const fingerprint = this.read()
return fingerprint ? fingerprint !== this.compute() : false
},
compute: function () {
// Include the electron minor version in the fingerprint since that changing requires a re-install
const electronVersion = CONFIG.appMetadata.electronVersion.replace(/\.\d+$/, '')
const apmVersion = CONFIG.apmMetadata.dependencies['atom-package-manager']
const body = electronVersion + apmVersion + process.platform + process.version + process.arch
return crypto.createHash('sha1').update(body).digest('hex')
}
}
|
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const CONFIG = require('../config')
const FINGERPRINT_PATH = path.join(CONFIG.repositoryRootPath, 'node_modules', '.dependencies-fingerprint')
module.exports = {
write: function () {
const fingerprint = this.compute()
fs.writeFileSync(FINGERPRINT_PATH, fingerprint)
console.log('Wrote Dependencies Fingerprint:', FINGERPRINT_PATH, fingerprint)
},
read: function () {
return fs.existsSync(FINGERPRINT_PATH) ? fs.readFileSync(FINGERPRINT_PATH, 'utf8') : null
},
isOutdated: function () {
const fingerprint = this.read()
return fingerprint ? fingerprint !== this.compute() : false
},
compute: function () {
// Include the electron minor version in the fingerprint since that changing requires a re-install
const electronVersion = CONFIG.appMetadata.electronVersion.replace(/\.\d+$/, '')
const apmVersion = CONFIG.apmMetadata.dependencies['atom-package-manager']
const body = electronVersion + apmVersion + process.platform + process.version
return crypto.createHash('sha1').update(body).digest('hex')
}
}
|
Set q2 field as disabled when invisible
|
$(function() {
$("#class-table tr td:first-child").each(function() {
var t = this.textContent;
if (t.length > 30) {
var elipsized = t.substring(0, 16) + "..." + t.substring(t.length - 13, t.length);
$(this).html($("<span/>").attr({"title": t}).html(elipsized));
}
});
changeQueryType();
});
function changeQueryType() {
var transition = {
"classes": ["Class name:"],
"manifests": ["Header:", "Value:"]
}[$("#qtype")[0].value];
$("#q2").css("display", transition[1]? "inline": "none").prop("disabled", !transition[1]);
$("label[for='q']").text(transition[0]);
$("label[for='q2']").text(transition[1] || "");
}
|
$(function() {
$("#class-table tr td:first-child").each(function() {
var t = this.textContent;
if (t.length > 30) {
var elipsized = t.substring(0, 16) + "..." + t.substring(t.length - 13, t.length);
$(this).html($("<span/>").attr({"title": t}).html(elipsized));
}
});
changeQueryType();
});
function changeQueryType() {
var transition = {
"classes": ["Class name:"],
"manifests": ["Header:", "Value:"]
}[$("#qtype")[0].value];
$("#q2").css("display", transition[1]? "inline": "none");
$("label[for='q']").text(transition[0]);
$("label[for='q2']").text(transition[1] || "");
}
|
Add isRoleOfGuild service, add null check to getRole
|
const RedisRole = require('../../structs/db/Redis/Role.js')
/**
* @param {string} roleID
*/
async function getRole (roleID) {
const role = await RedisRole.fetch(roleID)
return role ? role.toJSON() : null
}
/**
* @param {Object<string, any>} roleData
*/
async function formatRole (roleData) {
return {
...roleData,
hexColor: roleData.hexColor === '#000000' ? '' : roleData.hexColor
}
}
/**
* @param {string[]} roleIDs
*/
async function getRoles (roleIDs) {
const promises = []
for (const id of roleIDs) {
promises.push(getRole(id))
}
const resolved = await Promise.all(promises)
return resolved.map(formatRole)
.sort((a, b) => b.position - a.position)
}
/**
* @param {string} roleID
* @param {string} guildID
*/
async function isManagerOfGuild (roleID, guildID) {
return RedisRole.utils.isManagerOfGuild(roleID, guildID)
}
/**
* @param {string} roleID
* @param {string} guildID
*/
async function isRoleOfGuild (roleID, guildID) {
const role = await getRole(roleID)
if (!role) {
return false
}
return role.guildID === guildID
}
module.exports = {
getRole,
getRoles,
formatRole,
isManagerOfGuild,
isRoleOfGuild
}
|
const RedisRole = require('../../structs/db/Redis/Role.js')
async function getRole (roleID) {
const role = await RedisRole.fetch(roleID)
return role.toJSON()
}
async function formatRole (roleData) {
return {
...roleData,
hexColor: roleData.hexColor === '#000000' ? '' : roleData.hexColor
}
}
/**
* @param {string[]} roleIDs
*/
async function getRoles (roleIDs) {
const promises = []
for (const id of roleIDs) {
promises.push(getRole(id))
}
const resolved = await Promise.all(promises)
return resolved.map(formatRole)
.sort((a, b) => b.position - a.position)
}
async function isManagerOfGuild (roleID, guildID) {
return RedisRole.utils.isManagerOfGuild(roleID, guildID)
}
module.exports = {
getRole,
getRoles,
formatRole,
isManagerOfGuild
}
|
Check that `document` is defined
Check that document is defined before determining browser
capabilities. Otherwise this fails inside a web worker context.
FIX: The package can now be loaded in a web worker context (where
`navigator` is defined but `document` isn't) without crashing.
|
const result = {}
export default result
if (typeof navigator != "undefined" && typeof document != "undefined") {
const ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent)
const ie_upto10 = /MSIE \d/.test(navigator.userAgent)
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent)
result.mac = /Mac/.test(navigator.platform)
let ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge)
result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null
result.gecko = !ie && /gecko\/(\d+)/i.test(navigator.userAgent)
result.gecko_version = result.gecko && +(/Firefox\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]
let chrome = !ie && /Chrome\/(\d+)/.exec(navigator.userAgent)
result.chrome = !!chrome
result.chrome_version = chrome && +chrome[1]
result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
result.webkit = !ie && 'WebkitAppearance' in document.documentElement.style
result.safari = /Apple Computer/.test(navigator.vendor)
}
|
const result = {}
export default result
if (typeof navigator != "undefined") {
const ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent)
const ie_upto10 = /MSIE \d/.test(navigator.userAgent)
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent)
result.mac = /Mac/.test(navigator.platform)
let ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge)
result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null
result.gecko = !ie && /gecko\/(\d+)/i.test(navigator.userAgent)
result.gecko_version = result.gecko && +(/Firefox\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]
let chrome = !ie && /Chrome\/(\d+)/.exec(navigator.userAgent)
result.chrome = !!chrome
result.chrome_version = chrome && +chrome[1]
result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
result.webkit = !ie && 'WebkitAppearance' in document.documentElement.style
result.safari = /Apple Computer/.test(navigator.vendor)
}
|
Fix HardwareDevice constructor to provide 'description' argument
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU)
>>> cpu.desc = "800MHz OMAP3 Processor"
>>> cpu.attributes['machine'] = 'arm'
>>> cpu.attributes['mhz'] = 800
>>> cpu.attributes['vendor'] = 'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'desc', 'attributes')
def __init__(self, device_type, description, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU)
>>> cpu.desc = "800MHz OMAP3 Processor"
>>> cpu.attributes['machine'] = 'arm'
>>> cpu.attributes['mhz'] = 800
>>> cpu.attributes['vendor'] = 'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'desc', 'attributes')
def __init__(self, device_type, desc, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
Revert "flush and close writer"
This reverts commit f3db49d08480fa1b5d3a493469c8990b04b0a524.
|
package com.pengyifan.pubtator.io;
import com.google.common.base.Joiner;
import com.pengyifan.pubtator.PubTatorDocument;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
public class PubTatorIO {
public static List<PubTatorDocument> readBioCFormat(Reader reader)
throws XMLStreamException, IOException {
return new BioCLoader().load(reader);
}
public static List<PubTatorDocument> readPubTatorFormat(Reader reader)
throws IOException {
return new PubTatorLoader().load(reader);
}
public static String toPubTatorString(List<PubTatorDocument> documentList) {
return Joiner.on("\n\n").join(documentList);
}
public static void write(Writer writer, List<PubTatorDocument> documentList)
throws IOException {
writer.write(Joiner.on("\n\n").join(documentList));
writer.flush();
}
}
|
package com.pengyifan.pubtator.io;
import com.google.common.base.Joiner;
import com.pengyifan.pubtator.PubTatorDocument;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
public class PubTatorIO {
public static List<PubTatorDocument> readBioCFormat(Reader reader)
throws XMLStreamException, IOException {
return new BioCLoader().load(reader);
}
public static List<PubTatorDocument> readPubTatorFormat(Reader reader)
throws IOException {
return new PubTatorLoader().load(reader);
}
public static String toPubTatorString(List<PubTatorDocument> documentList) {
return Joiner.on("\n\n").join(documentList);
}
public static void write(Writer writer, List<PubTatorDocument> documentList)
throws IOException {
writer.write(Joiner.on("\n\n").join(documentList));
writer.flush();
writer.close();
}
}
|
Add pretty printing for API
|
from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_grid(request):
"""Display the restaurants in a grid. Main page."""
if 'sort' in request.GET:
if request.GET['sort'] == 'location':
# Display the grid by location (instead of listing alphabetically)
pass # Not implemented yet
return render_to_response('restaurant_grid.html',
context_instance=RequestContext(request))
def gen_etag(request):
return hashlib.sha1(str(OpenTime.objects.all())).hexdigest()
def gen_last_modified(request):
return BaseModel.objects.all().order_by('-last_modified')[0].last_modified
@condition(etag_func=gen_etag, last_modified_func=gen_last_modified)
def ajax_schedule_data(request):
# Wrapping up in an object to avoid possible CSRF attack on top-level
# arrays in JSON objects
return HttpResponse(json.dumps({'data': export_data()}, indent=4),
content_type="application/json")
|
from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_grid(request):
"""Display the restaurants in a grid. Main page."""
if 'sort' in request.GET:
if request.GET['sort'] == 'location':
# Display the grid by location (instead of listing alphabetically)
pass # Not implemented yet
return render_to_response('restaurant_grid.html',
context_instance=RequestContext(request))
def gen_etag(request):
return hashlib.sha1(str(OpenTime.objects.all())).hexdigest()
def gen_last_modified(request):
return BaseModel.objects.all().order_by('-last_modified')[0].last_modified
@condition(etag_func=gen_etag, last_modified_func=gen_last_modified)
def ajax_schedule_data(request):
# Wrapping up in an object to avoid possible CSRF attack on top-level
# arrays in JSON objects
return HttpResponse(json.dumps({'data': export_data()}),
content_type="application/json")
|
Tidy up whitespace and line-endings
|
$(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
return $(el).attr('href').split('#').pop();
});
$defaultTab = $('input[name=tab]');
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
|
$(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
return $(el).attr('href').split('#').pop();
}),
$defaultTab = $('input[name=tab]'),
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
|
Introduce an active prop for filters
|
import React, { Component } from 'react';
import classnames from 'classnames';
class Filter extends Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
};
static defaultProps = {
active: false,
};
constructor(props) {
super(props);
const { active } = this.props;
this.state = {
active,
};
}
onFilterChange = () => {
const { onChange } = this.props;
const { active } = this.state;
const nextActive = !active;
this.setState({ active: nextActive });
onChange(nextActive);
}
render() {
const { title } = this.props;
const { active } = this.state;
return (
<div className={classnames('ui-filter')} onClick={this.onFilterChange}>
<input
type="checkbox"
checked={active}
/> {title}
</div>
);
}
}
export default Filter;
|
import React, { Component } from 'react';
import classnames from 'classnames';
class Filter extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
};
}
render() {
return (
<div
className={classnames('ui-filter')}
onClick={() => {
this.setState({
active: !this.state.active,
}, () => this.props.onChange(this.state.active));
}}
>
<input
type="checkbox"
checked={this.state.active}
/> {this.props.title}
</div>
);
}
}
Filter.propTypes = {
title: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
};
export default Filter;
|
Use typeof to test for function
|
var hasOwn = Object.prototype.hasOwnProperty;
module.exports = function forEach (obj, fn, ctx) {
if (typeof obj !== 'object' || obj === null) {
throw new TypeError('can only iterate over objects or arrays');
}
if (typeof fn !== 'function') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
|
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (typeof obj !== 'object' || obj === null) {
throw new TypeError('can only iterate over objects or arrays');
}
if (toStr.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
|
Throw an error if we attempt to modify a different version of Leaflet.
|
// Make sure we're modifying the correct version of Leaflet
if (L.version !== '0.7.2') {
throw new Error('Attempting to patch Leaflet ' + L.version + '. Only 0.7.2 is supported');
}
// Modify Draggable to ignore shift key.
L.Draggable.prototype._onDown = function(e) {
this._moved = false;
if ((e.which !== 1) && (e.button !== 1) && !e.touches) { return; }
L.DomEvent.stopPropagation(e);
if (L.Draggable._disabled) { return; }
L.DomUtil.disableImageDrag();
L.DomUtil.disableTextSelection();
if (this._moving) { return; }
var first = e.touches ? e.touches[0] : e;
this._startPoint = new L.Point(first.clientX, first.clientY);
this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
L.DomEvent
.on(document, L.Draggable.MOVE[e.type], this._onMove, this)
.on(document, L.Draggable.END[e.type], this._onUp, this);
};
|
// Modify Draggable to ignore shift key.
L.Draggable.prototype._onDown = function(e) {
this._moved = false;
if ((e.which !== 1) && (e.button !== 1) && !e.touches) { return; }
L.DomEvent.stopPropagation(e);
if (L.Draggable._disabled) { return; }
L.DomUtil.disableImageDrag();
L.DomUtil.disableTextSelection();
if (this._moving) { return; }
var first = e.touches ? e.touches[0] : e;
this._startPoint = new L.Point(first.clientX, first.clientY);
this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
L.DomEvent
.on(document, L.Draggable.MOVE[e.type], this._onMove, this)
.on(document, L.Draggable.END[e.type], this._onUp, this);
};
|
Add an option to also return intermediate example norms
|
import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
plane_vectors = a - b
return plane_vectors
def simhash(plane_vectors, data):
output = np.zeros((len(data), len(plane_vectors)), dtype=np.uint8)
flattened = data.reshape((len(data), -1))
x = np.dot(plane_vectors, flattened.T).T
output[np.where(x > 0)] = 1
return output
def example_wise_unit_norm(x, return_norms=False):
original_shape = x.shape
# flatten all dimensions of x, treating the first axis as examples and all
# other axes as features
x = x.reshape((len(x), -1))
norms = np.linalg.norm(x, axis=-1, keepdims=True)
normed = np.divide(x, norms, where=norms != 0)
normed = normed.reshape(original_shape)
if return_norms:
return normed, norms
else:
return normed
|
import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
plane_vectors = a - b
return plane_vectors
def simhash(plane_vectors, data):
output = np.zeros((len(data), len(plane_vectors)), dtype=np.uint8)
flattened = data.reshape((len(data), -1))
x = np.dot(plane_vectors, flattened.T).T
output[np.where(x > 0)] = 1
return output
def example_wise_unit_norm(x):
original_shape = x.shape
x = x.reshape((len(x), -1))
norms = np.linalg.norm(x, axis=-1, keepdims=True)
normed = np.divide(x, norms, where=norms != 0)
return normed.reshape(original_shape)
|
Make transformations apply correctly to the matrix
|
/**
* @depends App.js
* @depends BasicRenderer.js
* @depends Framebuffer.js
*/
var FramebufferRenderer = new Class({
Extends: BasicRenderer,
initialize: function(width, height, vertexShader, fragmentShader,
options) {
this.parent(vertexShader, fragmentShader, options);
this.framebuffer = new Framebuffer(width, height);
},
renderMesh: function(mesh, camera) {
camera.modelview.pushMatrix();
mesh.applyTransformations(camera.modelview.matrix);
camera.setUniforms(this.shaderProgram);
camera.modelview.popMatrix();
mesh.associate(this.shaderProgram);
this.framebuffer.begin();
mesh.render();
this.framebuffer.end();
}
});
|
/**
* @depends App.js
* @depends BasicRenderer.js
* @depends Framebuffer.js
*/
var FramebufferRenderer = new Class({
Extends: BasicRenderer,
initialize: function(width, height, vertexShader, fragmentShader,
options) {
this.parent(vertexShader, fragmentShader, options);
this.framebuffer = new Framebuffer(width, height);
},
renderMesh: function(mesh, camera) {
camera.modelview.pushMatrix();
mesh.applyTransformations(camera);
camera.setUniforms(this.shaderProgram);
camera.modelview.popMatrix();
mesh.associate(this.shaderProgram);
this.framebuffer.begin();
mesh.render();
this.framebuffer.end();
}
});
|
Add support for 2020 ECMAScript version
|
'use strict';
module.exports = {
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module'
},
plugins: ['import'],
rules: {
'prefer-object-spread': 1,
'prefer-named-capture-group': 1,
// "import" and "require"
'import/no-absolute-path': 2,
'import/no-dynamic-require': 2,
'import/no-webpack-loader-syntax': 2,
'import/no-self-import': 2,
'import/export': 2,
'import/no-mutable-exports': 2,
'import/no-commonjs': 1,
'import/no-amd': 1,
'import/exports-last': 2,
'import/no-namespace': 1,
'import/order': [1, { 'newlines-between': 'never' }],
'import/prefer-default-export': 1,
'import/no-unassigned-import': 1,
'import/group-exports': 1,
'import/dynamic-import-chunkname': 2
}
};
|
'use strict';
module.exports = {
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
plugins: ['import'],
rules: {
'prefer-object-spread': 1,
'prefer-named-capture-group': 1,
// "import" and "require"
'import/no-absolute-path': 2,
'import/no-dynamic-require': 2,
'import/no-webpack-loader-syntax': 2,
'import/no-self-import': 2,
'import/export': 2,
'import/no-mutable-exports': 2,
'import/no-commonjs': 1,
'import/no-amd': 1,
'import/exports-last': 2,
'import/no-namespace': 1,
'import/order': [1, { 'newlines-between': 'never' }],
'import/prefer-default-export': 1,
'import/no-unassigned-import': 1,
'import/group-exports': 1,
'import/dynamic-import-chunkname': 2
}
};
|
Update again to cause purge hopefully
|
importScripts('/importme.mjs');
const CACHE_NAME = 'ROOT_CACHE';
async function cacheAllThings() {
const cache = await caches.open(CACHE_NAME);
cache.addAll([
'./index.html',
'./app.js',
'./app.css',
]);
}
self.addEventListener('install', async (event) => {
consoleTheLogs('ROOT DONE', event);
event.waitUntil(cacheAllThings());
});
self.addEventListener('fetch', (event) => {
if ('storage' in navigator && 'estimate' in navigator.storage) {
navigator.storage.estimate()
.then(function(estimate){
consoleTheLogs(`Using ${estimate.usage} out of ${estimate.quota} bytes.`);
});
}
event.respondWith(
fetch(event.request)
.then(response => {
consoleTheLogs('sw-root fetch interception');
return response;
})
)
});
|
importScripts('/importme.mjs');
const CACHE_NAME = 'ROOT_CACHE';
async function cacheAllThings() {
const cache = await caches.open(CACHE_NAME);
cache.addAll([
'./index.html',
'./app.js',
'./app.css',
]);
}
self.addEventListener('install', async (event) => {
consoleTheLogs('ROOT DONE', event);
event.waitUntil(cacheAllThings());
});
self.addEventListener('fetch', (event) => {
if ('storage' in navigator && 'estimate' in navigator.storage) {
navigator.storage.estimate()
.then(function(estimate){
consoleTheLogs(`Using ${estimate.usage} out of ${estimate.quota} bytes.`);
});
}
event.respondWith(
fetch(event.request)
.then(response => {
consoleTheLogs('sw-root fetch interception');
return response;
})
)
});
|
Add functions to add shapes and iterate over each shape to render.
|
#Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
#Create a function to add a shape
def addshape(self, s):
self.shapes.append(s)
#Create a function to render the shapes
def render(self):
#For each of the shapes, check the type and render it
for s in shapes:
#If the shape is a cube, call the rendercube method
if s.type == Shape.CUBE:
rendercube(s)
|
#Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.