text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Implement set_current_user for CapturingAuthentication (NC-529)
|
from __future__ import unicode_literals
import threading
_locals = threading.local()
def get_event_context():
return getattr(_locals, 'context', None)
def set_event_context(context):
_locals.context = context
def reset_event_context():
if hasattr(_locals, 'context'):
del _locals.context
def set_current_user(user):
set_event_context(user._get_log_context('user'))
def get_ip_address(request):
"""
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
else:
return request.META['REMOTE_ADDR']
class CaptureEventContextMiddleware(object):
def process_request(self, request):
context = {'ip_address': get_ip_address(request)}
user = getattr(request, 'user', None)
if user and not user.is_anonymous():
context.update(user._get_log_context('user'))
set_event_context(context)
def process_response(self, request, response):
reset_event_context()
return response
|
from __future__ import unicode_literals
import threading
_locals = threading.local()
def get_event_context():
return getattr(_locals, 'context', None)
def set_event_context(context):
_locals.context = context
def reset_event_context():
if hasattr(_locals, 'context'):
del _locals.context
def get_ip_address(request):
"""
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
else:
return request.META['REMOTE_ADDR']
class CaptureEventContextMiddleware(object):
def process_request(self, request):
context = {'ip_address': get_ip_address(request)}
user = getattr(request, 'user', None)
if user and not user.is_anonymous():
context.update(user._get_log_context('user'))
set_event_context(context)
def process_response(self, request, response):
reset_event_context()
return response
|
Remove max-length on links control
The `max-length` attribute was inadvertently added.
[Finishes: #119027729](https://www.pivotaltracker.com/story/show/119027729)
[#119014219](https://www.pivotaltracker.com/story/show/119014219)
|
import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
/* eslint-disable react/prefer-stateless-function */
class LinksControl extends Component {
static propTypes = {
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
}
static defaultProps = {
className: 'LinksControl',
id: 'external_links',
label: 'Links',
name: 'user[links]',
placeholder: 'Links (optional)',
}
getLinks() {
const { text } = this.props
const links = text || ''
if (typeof links === 'string') {
return links
}
return links.map((link) => link.text).join(', ')
}
render() {
return (
<FormControl
{ ...this.props }
autoCapitalize="off"
autoCorrect="off"
text={ this.getLinks() }
type="text"
/>
)
}
}
export default LinksControl
|
import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
/* eslint-disable react/prefer-stateless-function */
class LinksControl extends Component {
static propTypes = {
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
}
static defaultProps = {
className: 'LinksControl',
id: 'external_links',
label: 'Links',
name: 'user[links]',
placeholder: 'Links (optional)',
}
getLinks() {
const { text } = this.props
const links = text || ''
if (typeof links === 'string') {
return links
}
return links.map((link) => link.text).join(', ')
}
render() {
return (
<FormControl
{ ...this.props }
autoCapitalize="off"
autoCorrect="off"
maxLength="50"
text={ this.getLinks() }
type="text"
/>
)
}
}
export default LinksControl
|
Add reformatted (EN) verse references to dump
|
#!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/en');
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
ref.reformat = formatter('niv-long', match.osis);
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
|
#!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
|
Reduce the time we keep expired remotes sessions and fix comment
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import java.time.Duration;
/**
* Removes inactive sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
// Start this maintainer immediately. It frees disk space, so if disk goes full and config server
// restarts this makes sure that cleanup will happen as early as possible
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
// Expired remote sessions are sessions that belong to an application that have external deployments that
// are no longer active
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(7);
applicationRepository.deleteExpiredRemoteSessions(expiryTime);
}
}
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import java.time.Duration;
/**
* Removes inactive sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
// Start this maintainer immediately. It frees disk space, so if disk goes full and config server
// restarts this makes sure that cleanup will happen as early as possible
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
// Expired remote sessions are not expected to exist, they should have been deleted when
// a deployment happened or when the application was deleted. We still see them from time to time,
// probably due to some race or another bug
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(30);
applicationRepository.deleteExpiredRemoteSessions(expiryTime);
}
}
}
|
Add default value to intro
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddProfileToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->text('intro')->default('');
$table->string('avatar')->default('https://loverecorder-1251779005.picsh.myqcloud.com/user/avatar/avatar-default.png');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('intro');
$table->dropColumn('avatar');
});
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddProfileToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->text('intro');
$table->string('avatar')->default('https://loverecorder-1251779005.picsh.myqcloud.com/user/avatar/avatar-default.png');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('intro');
$table->dropColumn('avatar');
});
}
}
|
Rewrite residual block as class rather than method
|
from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from eva.layers.masked_convolution2d import MaskedConvolution2D
class ResidualBlock(object):
def __init__(self, filters):
self.filters = filters
def __call__(self, model):
# 2h -> h
block = PReLU()(model)
block = MaskedConvolution2D(self.filters//2, 1, 1)(block)
# h 3x3 -> h
block = PReLU()(block)
block = MaskedConvolution2D(self.filters//2, 3, 3, border_mode='same')(block)
# h -> 2h
block = PReLU()(block)
block = MaskedConvolution2D(self.filters, 1, 1)(block)
return Merge(mode='sum')([model, block])
class ResidualBlockList(object):
def __init__(self, filters, length):
self.filters = filters
self.length = length
def __call__(self, model):
for _ in range(self.length):
model = ResidualBlock(self.filters)(model)
return model
|
from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from eva.layers.masked_convolution2d import MaskedConvolution2D
def ResidualBlock(model, filters):
# 2h -> h
block = PReLU()(model)
block = MaskedConvolution2D(filters//2, 1, 1)(block)
# h 3x3 -> h
block = PReLU()(block)
block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block)
# h -> 2h
block = PReLU()(block)
block = MaskedConvolution2D(filters, 1, 1)(block)
return Merge(mode='sum')([model, block])
def ResidualBlockList(model, filters, length):
for _ in range(length):
model = ResidualBlock(model, filters)
return model
|
Fix the output file name for solution
|
# -*- coding: utf-8 -*-
"""
nbtutor - a small utility to indicate which cells should be cleared (exercises).
"""
import os
try:
from nbconvert.preprocessors.base import Preprocessor
except ImportError:
from IPython.nbconvert.preprocessors.base import Preprocessor
class ClearExercisePreprocessor(Preprocessor):
def preprocess_cell(self, cell, resources, index):
if 'clear_cell' in cell.metadata and cell.metadata.clear_cell:
fname = os.path.join(
'_solutions', resources['metadata']['name'] + str(cell['execution_count']) + '.py')
with open(fname, 'w') as f:
f.write(cell['source'])
cell['source'] = ["# %load {0}".format(fname)]
cell['outputs'] = []
# cell['source'] = []
return cell, resources
|
# -*- coding: utf-8 -*-
"""
nbtutor - a small utility to indicate which cells should be cleared (exercises).
"""
try:
from nbconvert.preprocessors.base import Preprocessor
except ImportError:
from IPython.nbconvert.preprocessors.base import Preprocessor
class ClearExercisePreprocessor(Preprocessor):
def preprocess_cell(self, cell, resources, index):
if 'clear_cell' in cell.metadata and cell.metadata.clear_cell:
fname = 'snippets/' + resources['unique_key'] + str(cell['execution_count']) + '.py'
with open(fname, 'w') as f:
f.write(cell['source'])
cell['source'] = ["# %load {0}".format(fname)]
#cell['source'] = []
cell['execution_count'] = None
cell['outputs'] = []
return cell, resources
|
Fix case on start function
|
<?php
/**
* Welcome to the PHP.Gt WebEngine!
*
* This file is the entry point to the WebEngine. The whole request-response lifecycle is
* documented at https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
*/
/**
* Before any code is executed, return false here if a static file is requested. When running the
* PHP inbuilt server, this will output the static file. Other webservers should not get to this
* point, but it's safe to prevent unnecessary execution.
*/
$uri = urldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
if(is_file($_SERVER["DOCUMENT_ROOT"] . $uri)) {
return false;
}
/**
* Require the Composer autoloader, so the rest of the script can locate classes by their namespace,
* rather than having to know where on disk the files exist.
* @see https://getcomposer.org/doc/00-intro.md
*/
require(__DIR__ . "/vendor/autoload.php");
/**
* That's all we need to start the request-response lifecycle. Buckle up and enjoy the ride!
* @see https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
*/
Gt\WebEngine\Lifecycle::start();
|
<?php
/**
* Welcome to the PHP.Gt WebEngine!
*
* This file is the entry point to the WebEngine. The whole request-response lifecycle is
* documented at https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
*/
/**
* Before any code is executed, return false here if a static file is requested. When running the
* PHP inbuilt server, this will output the static file. Other webservers should not get to this
* point, but it's safe to prevent unnecessary execution.
*/
$uri = urldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
if(is_file($_SERVER["DOCUMENT_ROOT"] . $uri)) {
return false;
}
/**
* Require the Composer autoloader, so the rest of the script can locate classes by their namespace,
* rather than having to know where on disk the files exist.
* @see https://getcomposer.org/doc/00-intro.md
*/
require(__DIR__ . "/vendor/autoload.php");
/**
* That's all we need to start the request-response lifecycle. Buckle up and enjoy the ride!
* @see https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
*/
Gt\WebEngine\Lifecycle::Start();
|
JceSecurityCleanupTest: Move exceptions in one catch expression
|
package se.jiderhamn.classloader.leak.prevention.cleanup;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
/**
* Test that the leak caused by {@link javax.crypto.JceSecurity} is cleared.
* Thanks to Paul Kiman for the report.
* @author Mattias Jiderhamn
*/
public class JceSecurityCleanUpTest extends ClassLoaderPreMortemCleanUpTestBase<JceSecurityCleanUp> {
@Override
protected void triggerLeak() throws Exception {
try {
// Alternative classes: KeyAgreement, KeyGenerator, ExemptionMechanism
MyProvider myProvider = new MyProvider("foo", 1.0, "bar");
javax.crypto.Mac.getInstance("baz", myProvider);
}
catch (SecurityException | NoSuchAlgorithmException e) { // CS:IGNORE
// Leak is triggered despite an exception being thrown
}
}
/** Custom {@link Provider}, to be put in {@link javax.crypto.JceSecurity} caches */
public static class MyProvider extends Provider {
public MyProvider(String name, double version, String info) {
super(name, version, info);
}
@Override
public synchronized Service getService(String type, String algorithm) {
return new Service(this, "type", "algorithm", "className", null, null);
}
}
}
|
package se.jiderhamn.classloader.leak.prevention.cleanup;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
/**
* Test that the leak caused by {@link javax.crypto.JceSecurity} is cleared.
* Thanks to Paul Kiman for the report.
* @author Mattias Jiderhamn
*/
public class JceSecurityCleanUpTest extends ClassLoaderPreMortemCleanUpTestBase<JceSecurityCleanUp> {
@Override
protected void triggerLeak() throws Exception {
try {
// Alternative classes: KeyAgreement, KeyGenerator, ExemptionMechanism
MyProvider myProvider = new MyProvider("foo", 1.0, "bar");
javax.crypto.Mac.getInstance("baz", myProvider);
}
catch (SecurityException e) { // CS:IGNORE
}
catch (NoSuchAlgorithmException e) {
// Custom providers seem to work different in Java 11, this still triggers the leak, even if we get this exception
}
}
/** Custom {@link Provider}, to be put in {@link javax.crypto.JceSecurity} caches */
public static class MyProvider extends Provider {
public MyProvider(String name, double version, String info) {
super(name, version, info);
}
@Override
public synchronized Service getService(String type, String algorithm) {
return new Service(this, "type", "algorithm", "className", null, null);
}
}
}
|
Remove local vars path & path_form
|
<?php
/**
* @file
* Containt Drupal\AppConsole\Generator\FormGenerator.
*/
namespace Drupal\AppConsole\Generator;
use Drupal\AppConsole\Utils\Utils;
class FormGenerator extends Generator
{
/**
* @param $module
* @param $class_name
* @param $services
* @param $inputs
* @param $update_routing
*/
public function generate($module, $class_name, $services, $inputs, $update_routing)
{
$parameters = array(
'class_name' => $class_name,
'services' => $services,
'inputs' => $inputs,
'module_name' => $module,
'form_id' => Utils::camelCaseToMachineName($class_name),
);
$this->renderFile(
'module/module.form.php.twig',
$path_form . '/'. $class_name .'.php',
$parameters
);
if ($update_routing) {
$this->renderFile('module/form-routing.yml.twig', $path .'/'. $module.'.routing.yml', $parameters, FILE_APPEND);
}
}
}
|
<?php
/**
* @file
* Containt Drupal\AppConsole\Generator\FormGenerator.
*/
namespace Drupal\AppConsole\Generator;
use Drupal\AppConsole\Utils\Utils;
class FormGenerator extends Generator
{
/**
* @param $module
* @param $class_name
* @param $services
* @param $inputs
* @param $update_routing
*/
public function generate($module, $class_name, $services, $inputs, $update_routing)
{
$path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module);
$path_form = $path . '/src/Form';
$parameters = array(
'class_name' => $class_name,
'services' => $services,
'inputs' => $inputs,
'module_name' => $module,
'form_id' => Utils::camelCaseToMachineName($class_name),
);
$this->renderFile(
'module/module.form.php.twig',
$path_form . '/'. $class_name .'.php',
$parameters
);
if ($update_routing) {
$this->renderFile('module/form-routing.yml.twig', $path .'/'. $module.'.routing.yml', $parameters, FILE_APPEND);
}
}
}
|
Apply change to all Android 13 devices
|
export default {
// Android emits composition events when moving the cursor through existing text
// Introduced in Chrome 65: https://bugs.chromium.org/p/chromium/issues/detail?id=764439#c9
composesExistingText: /Android.*Chrome/.test(navigator.userAgent),
// On Android 13 Samsung keyboards emit a composition event when moving the cursor
composesOnCursorMove: (function() {
const androidVersionMatch = navigator.userAgent.match(/android\s([0-9]+.*Chrome)/i)
return androidVersionMatch && parseInt(androidVersionMatch[1]) > 12
})(),
// IE 11 activates resizing handles on editable elements that have "layout"
forcesObjectResizing: /Trident.*rv:11/.test(navigator.userAgent),
// https://www.w3.org/TR/input-events-1/ + https://www.w3.org/TR/input-events-2/
supportsInputEvents: (function() {
if (typeof InputEvent === "undefined") {
return false
}
for (const property of [ "data", "getTargetRanges", "inputType" ]) {
if (!(property in InputEvent.prototype)) {
return false
}
}
return true
})(),
}
|
export default {
// Android emits composition events when moving the cursor through existing text
// Introduced in Chrome 65: https://bugs.chromium.org/p/chromium/issues/detail?id=764439#c9
composesExistingText: /Android.*Chrome/.test(navigator.userAgent),
// On Android 13 Samsung keyboards emit a composition event when moving the cursor
composesOnCursorMove: (function() {
const samsungAndroid = /Android.*SM-.*Chrome/.test(navigator.userAgent)
const androidVersionMatch = navigator.userAgent.match(/android\s([0-9]+)/i)
return samsungAndroid && androidVersionMatch && parseInt(androidVersionMatch[1]) > 12
})(),
// IE 11 activates resizing handles on editable elements that have "layout"
forcesObjectResizing: /Trident.*rv:11/.test(navigator.userAgent),
// https://www.w3.org/TR/input-events-1/ + https://www.w3.org/TR/input-events-2/
supportsInputEvents: (function() {
if (typeof InputEvent === "undefined") {
return false
}
for (const property of [ "data", "getTargetRanges", "inputType" ]) {
if (!(property in InputEvent.prototype)) {
return false
}
}
return true
})(),
}
|
Fix false bug flag by allowing empty lines
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
Mark conference and language as required
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code', required=True)
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code', required=True)
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data.get('conference')
if conference and not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code')
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code')
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data['conference']
if not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
Add ReferenceScreen to references tab in WorkerProfileScreen
|
import React, { Component } from 'react';
import { Container, Tab, Tabs } from 'native-base';
import WorkerInfoScreen from '../worker-info-screen';
import ReferenceScreen from '../reference-screen';
import I18n from '../../../i18n';
// @TODO Replace temporary data with data from Redux/API
const NAME = 'John Doe';
export default class WorkerProfileScreen extends Component {
static navigationOptions = {
title: I18n.t('screen_titles.worker_profile', { name: NAME }),
};
// TODO Replace placeholder data in WorkerInfoScreen and ReferenceScreen
render() {
return (
<Container>
<Tabs>
<Tab heading={I18n.t('account.profile_info')} >
<WorkerInfoScreen />
</Tab>
<Tab heading={I18n.t('account.references')}>
<ReferenceScreen />
</Tab>
</Tabs>
</Container>
);
}
}
|
import React, { Component } from 'react';
import { Container, Tab, Tabs, Text } from 'native-base';
import WorkerInfoScreen from '../worker-info-screen';
import I18n from '../../../i18n';
// @TODO Replace temporary data with data from Redux/API
const NAME = 'John Doe';
export default class WorkerProfileScreen extends Component {
static navigationOptions = {
title: I18n.t('screen_titles.worker_profile', { name: NAME }),
};
// TODO Replace reference placeholder text with reference screen.
render() {
return (
<Container>
<Tabs>
<Tab heading={I18n.t('account.profile_info')} >
<WorkerInfoScreen />
</Tab>
<Tab heading={I18n.t('account.references')}>
<Text>References screen goes here</Text>
</Tab>
</Tabs>
</Container>
);
}
}
|
Add the process command and the addCommand
|
/**
* Created with JetBrains WebStorm.
* User: vincent.peybernes
* Date: 25/06/13
* Time: 16:31
* To change this template use File | Settings | File Templates.
*/
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
// Get the stream input node console
var stdin = process.stdin;
// Flush the stream input buffer
stdin.resume();
// Set encoding for the input stream to UTF8
stdin.setEncoding('UTF-8');
// Listen the new command pass through console on the enter pressed key
stdin.on('data', function(key){
// Parse the command line
var params = parseCommand(key);
// Process the command
processCommand(params);
});
var parseCommand = function(key){
// Remove the carryage return character
key = key.replace("\n", "");
// Split the command line to get the command key and the arguments
var split = key.split(" ");
return split;
}
var processCommand = function(params){
// Get the command key
var command = params.shift();
// Create an emitter and broadcast the command
emitter.emit(command, params);
}
var addCommand = function(name, action){
// Listen the command
emitter.on(name, function(){
// Call the callback with the global context and the arguments array
action.apply(global, arguments);
});
}
module.exports = {
addCommand: addCommand
};
|
/**
* Created with JetBrains WebStorm.
* User: vincent.peybernes
* Date: 25/06/13
* Time: 16:31
* To change this template use File | Settings | File Templates.
*/
// Get the stream input node console
var stdin = process.stdin;
// Flush the stream input buffer
stdin.resume();
// Set encoding for the input stream to UTF8
stdin.setEncoding('UTF-8');
// Listen the new command pass through console on the enter pressed key
stdin.on('data', function(key){
// Parse the command line
parseCommand(key);
});
var parseCommand = function(key){
// Remove the carryage return character
key.replace("\n", "");
// Split the command line to get the command key and the arguments
var split = key.split(" ");
// Get the command key and remove it from the split array. So the split array are the arguments
var command = split.shift();
}
|
Change how/where to save the file
|
from GamTools import corr
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('npz_frequencies_file', help='An npz file containing co-segregation frequencies to convert to correlations')
args = parser.parse_args()
correlation_file = args.npz_frequencies_file.split('.')
correlation_file[correlation_file.index('chrom')] = "corr"
correlation_file = '.'.join(correlation_file)
freqs = np.load(args.npz_frequencies_file)['freqs']
def flatten_freqs(freqs):
freqs_shape = freqs.shape
flat_shape = ( freqs_shape[0] * freqs_shape[1], freqs_shape[2], freqs_shape[3])
return freqs.reshape(flat_shape)
distances = np.array(map(corr, flatten_freqs(freqs))).reshape(freqs.shape[:2])
np.savez_compressed(correlation_file, corr=distances)
|
from GamTools import corr
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('npz_frequencies_file', help='An npz file containing co-segregation frequencies to convert to correlations')
args = parser.parse_args()
correlation_file = args.npz_frequencies_file.split('.')
correlation_file = correlation_file[0] + '.correlations.npz'
freqs = np.load(args.npz_frequencies_file)['freqs']
def flatten_freqs(freqs):
freqs_shape = freqs.shape
flat_shape = ( freqs_shape[0] * freqs_shape[1], freqs_shape[2], freqs_shape[3])
return freqs.reshape(flat_shape)
distances = np.array(map(corr, flatten_freqs(freqs))).reshape(freqs.shape[:2])
np.save_compressed(correlation_file, corr=distances)
|
Fix the console.tron call in a saga when running via ava.
|
import { put, select } from 'redux-saga/effects'
import TemperatureActions from '../Redux/TemperatureRedux'
import { is } from 'ramda'
// exported to make available for tests
export const selectTemperature = (state) => state.temperature.temperature
// process STARTUP actions
export function * startup (action) {
if (__DEV__ && console.tron) {
// straight-up string logging
console.tron.log('Hello, I\'m an example of how to log via Reactotron.')
// logging an object for better clarity
console.tron.log({
message: 'pass objects for better logging',
someGeneratorFunction: selectTemperature
})
// fully customized!
const subObject = { a: 1, b: [1, 2, 3], c: true }
subObject.circularDependency = subObject // osnap!
console.tron.display({
name: '🔥 IGNITE 🔥',
preview: 'You should totally expand this',
value: {
'💃': 'Welcome to the future!',
subObject,
someInlineFunction: () => true,
someGeneratorFunction: startup,
someNormalFunction: selectTemperature
}
})
}
const temp = yield select(selectTemperature)
// only fetch new temps when we don't have one yet
if (!is(Number, temp)) {
yield put(TemperatureActions.temperatureRequest('San Francisco'))
}
}
|
import { put, select } from 'redux-saga/effects'
import TemperatureActions from '../Redux/TemperatureRedux'
import { is } from 'ramda'
// exported to make available for tests
export const selectTemperature = (state) => state.temperature.temperature
// process STARTUP actions
export function * startup (action) {
if (__DEV__) {
// straight-up string logging
console.tron.log('Hello, I\'m an example of how to log via Reactotron.')
// logging an object for better clarity
console.tron.log({
message: 'pass objects for better logging',
someGeneratorFunction: selectTemperature
})
// fully customized!
const subObject = { a: 1, b: [1, 2, 3], c: true }
subObject.circularDependency = subObject // osnap!
console.tron.display({
name: '🔥 IGNITE 🔥',
preview: 'You should totally expand this',
value: {
'💃': 'Welcome to the future!',
subObject,
someInlineFunction: () => true,
someGeneratorFunction: startup,
someNormalFunction: selectTemperature
}
})
}
const temp = yield select(selectTemperature)
// only fetch new temps when we don't have one yet
if (!is(Number, temp)) {
yield put(TemperatureActions.temperatureRequest('San Francisco'))
}
}
|
Add endtime class to endtime element
|
import Remarkable from 'remarkable';
const markdown = (text) => {
var md = new Remarkable();
return {
__html: md.render(text)
};
};
const Event = ({ title, start_time, end_time, content, eventClickHandler, index, active }) => {
const classes = (index === active) ? 'cal-event-content-active' : '';
return (
<a href={`#event-${index}`} onClick={ () => { eventClickHandler(index); } } className="cal-event" id={`event-${index}`}>
<div className="cal-event-indicator"></div>
<div className="cal-event-header">
<p className="cal-event-dateString">{start_time.toTimeString().substr(0, 5)}</p>
<h3 className="cal-title">{title}</h3>
</div>
<p className={`cal-event-content ${ classes }`} dangerouslySetInnerHTML={markdown(content)}/>
<p className={`cal-event-content ${ classes } cal-event-endtime`}>Antatt sluttidspunkt: {end_time.toTimeString().substr(0, 5)}</p>
</a>
);
};
export default Event;
|
import Remarkable from 'remarkable';
const markdown = (text) => {
var md = new Remarkable();
return {
__html: md.render(text)
};
};
const Event = ({ title, start_time, end_time, content, eventClickHandler, index, active }) => {
const classes = (index === active) ? 'cal-event-content-active' : '';
return (
<a href={`#event-${index}`} onClick={ () => { eventClickHandler(index); } } className="cal-event" id={`event-${index}`}>
<div className="cal-event-indicator"></div>
<div className="cal-event-header">
<p className="cal-event-dateString">{start_time.toTimeString().substr(0, 5)}</p>
<h3 className="cal-title">{title}</h3>
</div>
<p className={`cal-event-content ${ classes }`} dangerouslySetInnerHTML={markdown(content)}/>
<p className={`cal-event-content ${ classes }`}>Antatt sluttidspunkt: {end_time.toTimeString().substr(0, 5)}</p>
</a>
);
};
export default Event;
|
Remove unneeded map for collection model
|
/**
* Main entrypoint for banknote.
*
* Copyright 2015 Ethan Smith
*/
var Backbone = require('backbone'),
Marionette = require('backbone.marionette'),
$ = require('jquery'),
_ = require('underscore'),
MainLayout = require('./src/view/MainLayout'),
RegionModal = require('./src/common/modal/RegionModal.js'),
CategorizedController = require('./src/controller/CategorizedController');
require('./src/common/library/CurrencyInputStyler');
var Banknote = new Marionette.Application();
Banknote.addRegions({
central: '#app',
modal: RegionModal
});
Banknote.addInitializer(function(options) {
$.getJSON('demo.json', function(data) {
var incomeCollection = new AmountEntryCollection(data.income);
var controller = new CategorizedController({
title: 'Income Totals'
});
Banknote.central.show(controller.render(incomeCollection));
});
});
Banknote.start();
// Make Banknote available globally
global.Banknote = Banknote;
|
/**
* Main entrypoint for banknote.
*
* Copyright 2015 Ethan Smith
*/
var Backbone = require('backbone'),
Marionette = require('backbone.marionette'),
$ = require('jquery'),
_ = require('underscore'),
MainLayout = require('./src/view/MainLayout'),
RegionModal = require('./src/common/modal/RegionModal.js'),
CategorizedController = require('./src/controller/CategorizedController');
require('./src/common/library/CurrencyInputStyler');
var Banknote = new Marionette.Application();
Banknote.addRegions({
central: '#app',
modal: RegionModal
});
Banknote.addInitializer(function(options) {
$.getJSON('demo.json', function(data) {
var incomeCollection = new AmountEntryCollection(_.map(data.income, function(note) {
return new AmountEntry(note);
}));
var controller = new CategorizedController({
title: 'Income Totals'
});
Banknote.central.show(controller.render(incomeCollection));
});
});
Banknote.start();
// Make Banknote available globally
global.Banknote = Banknote;
|
Fix issue with pathTo and optional express paths like /blog/:id/:tag?
|
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
// The `pathTo()` function is written in ES3 so it's serializable and able to
// run in all JavaScript environments.
module.exports = function pathTo(routeMap) {
return function (routeName, context) {
var route = routeMap[routeName],
path, keys, i, len, key, param, regex;
if (!route) { return ''; }
path = route.path;
keys = route.keys;
if (context && (len = keys.length)) {
for (i = 0; i < len; i += 1) {
key = keys[i];
param = key.name || key;
regex = new RegExp('[:*]' + param + '\\b');
path = path.replace(regex, context[param]);
}
}
// Replace missing params with empty strings.
// pathTo is not correctly handling express optional parameters of the form /blogs/:id/:tag?
// lop off the ? off the end of the result
return path.replace(/([:*])([\w\-]+)?/g, '').replace(/[?]$/, '');
};
};
|
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
// The `pathTo()` function is written in ES3 so it's serializable and able to
// run in all JavaScript environments.
module.exports = function pathTo(routeMap) {
return function (routeName, context) {
var route = routeMap[routeName],
path, keys, i, len, key, param, regex;
if (!route) { return ''; }
path = route.path;
keys = route.keys;
if (context && (len = keys.length)) {
for (i = 0; i < len; i += 1) {
key = keys[i];
param = key.name || key;
regex = new RegExp('[:*]' + param + '\\b');
path = path.replace(regex, context[param]);
}
}
// Replace missing params with empty strings.
return path.replace(/([:*])([\w\-]+)?/g, '');
};
};
|
Resolve Faker\Generator out of the container if it is bound
If Faker\Generator is bound in the container then use that instance instead of creating a default version. This allows you to bind your own custom Faker\Generator and add custom faker providers which will be available when using WithFaker
|
<?php
namespace Illuminate\Foundation\Testing;
use Faker\Factory;
use Faker\Generator;
trait WithFaker
{
/**
* The Faker instance.
*
* @var \Faker\Generator
*/
protected $faker;
/**
* Setup up the Faker instance.
*
* @return void
*/
protected function setUpFaker()
{
$this->faker = $this->makeFaker();
}
/**
* Get the default Faker instance for a given locale.
*
* @param string|null $locale
* @return \Faker\Generator
*/
protected function faker($locale = null)
{
return is_null($locale) ? $this->faker : $this->makeFaker($locale);
}
/**
* Create a Faker instance for the given locale.
*
* @param string|null $locale
* @return \Faker\Generator
*/
protected function makeFaker($locale = null)
{
$locale = $locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE);
if ($this->app->bound(Generator::class)) {
return $this->app->make(Generator::class, [$locale]);
}
return Factory::create($locale);
}
}
|
<?php
namespace Illuminate\Foundation\Testing;
use Faker\Factory;
trait WithFaker
{
/**
* The Faker instance.
*
* @var \Faker\Generator
*/
protected $faker;
/**
* Setup up the Faker instance.
*
* @return void
*/
protected function setUpFaker()
{
$this->faker = $this->makeFaker();
}
/**
* Get the default Faker instance for a given locale.
*
* @param string|null $locale
* @return \Faker\Generator
*/
protected function faker($locale = null)
{
return is_null($locale) ? $this->faker : $this->makeFaker($locale);
}
/**
* Create a Faker instance for the given locale.
*
* @param string|null $locale
* @return \Faker\Generator
*/
protected function makeFaker($locale = null)
{
return Factory::create($locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE));
}
}
|
Add `process` Method to Comments
|
<?php
/**
* Comments
*/
class Comments implements Iterator
{
private $iterator_index;
private $comments;
private $stored_comments;
function __construct($page)
{
$this->iterator_index = 0;
$this->comments = array();
$this->stored_comments = array();
}
// ============
// = Iterator =
// ============
function rewind()
{
$this->iterator_index = 0;
}
function current()
{
return $this->comments[$this->iterator_index];
}
function key()
{
return $this->iterator_index;
}
function next()
{
$this->iterator_index += 1;
}
function valide()
{
return isset($this->comments[$this->iterator_index]);
}
// ===================
// = Process Comment =
// ===================
public function process()
{
}
}
|
<?php
/**
* Comments
*/
class Comments implements Iterator
{
private $iterator_index;
private $comments;
private $stored_comments;
function __construct($page)
{
$this->iterator_index = 0;
$this->comments = array();
$this->stored_comments = array();
}
// ============
// = Iterator =
// ============
function rewind()
{
$this->iterator_index = 0;
}
function current()
{
return $this->comments[$this->iterator_index];
}
function key()
{
return $this->iterator_index;
}
function next()
{
$this->iterator_index += 1;
}
function valide()
{
return isset($this->comments[$this->iterator_index]);
}
}
|
Revert "SYNTAX ERROR SORRY EVERYONE"
This reverts commit 9f9d12108a52875e3106b05ba00604cd891a4ce7.
|
var mongoose = require('mongoose');
module.exports.finderForProperty = function(field, props) {
if (props === undefined) {
props = {};
}
var isFindOne = props['findOne'] === true;
var caseInsensitive = props['caseInsensitive'] === true;
return function(value, cb) {
var lookupHash = {};
lookupHash[field] = caseInsensitive ? new RegExp('^' + value + '$', 'i') : value;
if(isFindOne) {
this.findOne(lookupHash, cb);
} else {
this.find(lookupHash, cb);
}
};
};
module.exports.pushOntoProperty = function(field, props) {
if (props === undefined) {
props = {};
}
var isFindOne = props['findOne'] === true;
var caseInsensitive = props['caseInsensitive'] === true;
return function(value, cb) {
var lookupHash = {};
lookupHash[field] = caseInsensitive ? new RegExp('^' + value + '$', 'i') : value;
if (isFindOne) {
this.
} else {
this.
}
}
}
|
var mongoose = require('mongoose');
module.exports.finderForProperty = function(field, props) {
if (props === undefined) {
props = {};
}
var isFindOne = props['findOne'] === true;
var caseInsensitive = props['caseInsensitive'] === true;
return function(value, cb) {
var lookupHash = {};
lookupHash[field] = caseInsensitive ? new RegExp('^' + value + '$', 'i') : value;
if(isFindOne) {
this.findOne(lookupHash, cb);
} else {
this.find(lookupHash, cb);
}
};
};
module.exports.pushOntoProperty = function(field, props) {
if (props === undefined) {
props = {};
}
var isFindOne = props['findOne'] === true;
var caseInsensitive = props['caseInsensitive'] === true;
return function(value, cb) {
var lookupHash = {};
lookupHash[field] = caseInsensitive ? new RegExp('^' + value + '$', 'i') : value;
if (isFindOne) {
//
} else {
//
}
}
}
|
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
|
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
def render(self, context):
conf = config_settings_loader()
context[self.variable_name] = conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
self.conf = config_settings_loader()
def render(self, context):
context[self.variable_name] = self.conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
Fix incorrect property on fallback location object
|
import { loginUser } from '../../gateways/users';
import { replace } from 'react-router-redux';
import { authSuccess, authFailure } from '../../common/auth/actions';
import { storeUser } from '../../utils/localStorage';
import { setAuthorization } from '../../gateways/index';
export const submitLogin = ({ username, password }) => (dispatch, getState) => {
const { route: { location } } = getState();
const redirectLocation = location.state && location.state.from;
const fallbackLocation = {
pathname: '/',
state: {
from: location,
},
};
return loginUser({ username, password }).then(({ user }) => {
// Set user in local storage to keep user signed in after page refresh
storeUser(user);
// Set Authorization header for future fetching
setAuthorization(user.token);
dispatch(authSuccess(user));
dispatch(replace(redirectLocation || fallbackLocation));
}).catch(() => {
// TODO: Give user feedback on form on error
dispatch(authFailure());
});
};
|
import { loginUser } from '../../gateways/users';
import { replace } from 'react-router-redux';
import { authSuccess, authFailure } from '../../common/auth/actions';
import { storeUser } from '../../utils/localStorage';
import { setAuthorization } from '../../gateways/index';
export const submitLogin = ({ username, password }) => (dispatch, getState) => {
const { route: { location } } = getState();
const redirectLocation = location.state && location.state.from;
const fallbackLocation = {
path: '/',
state: {
from: location,
},
};
return loginUser({ username, password }).then(({ user }) => {
// Set user in local storage to keep user signed in after page refresh
storeUser(user);
// Set Authorization header for future fetching
setAuthorization(user.token);
dispatch(authSuccess(user));
dispatch(replace(redirectLocation || fallbackLocation));
}).catch(() => {
// TODO: Give user feedback on form on error
dispatch(authFailure());
});
};
|
Create a helper function for reading and writing stdout or stderr
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"os/exec"
"github.com/mgutz/ansi"
)
func main() {
cmd := exec.Command("./a.sh")
err := runCommand(cmd)
if err != nil {
log.Fatal(err)
}
}
func runCommand(cmd *exec.Cmd) error {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
go printOutputWithHeader(stdout, ansi.Color("stdout:", "green"))
go printOutputWithHeader(stderr, ansi.Color("stderr:", "red"))
return cmd.Wait()
}
func printOutputWithHeader(r io.Reader, header string) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
fmt.Printf("%s%s\n", header, scanner.Text())
}
}
|
package main
import (
"bufio"
"fmt"
"log"
"os/exec"
"github.com/mgutz/ansi"
)
func main() {
cmd := exec.Command("./a.sh")
err := runCommand(cmd)
if err != nil {
log.Fatal(err)
}
}
func runCommand(cmd *exec.Cmd) error {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
go func() {
stdoutHeader := ansi.Color("stdout:", "green")
stdoutScanner := bufio.NewScanner(stdout)
for stdoutScanner.Scan() {
fmt.Printf("%s%s\n", stdoutHeader, stdoutScanner.Text())
}
}()
go func() {
stderrHeader := ansi.Color("stderr:", "red")
stderrScanner := bufio.NewScanner(stderr)
for stderrScanner.Scan() {
fmt.Printf("%s%s\n", stderrHeader, stderrScanner.Text())
}
}()
return cmd.Wait()
}
|
Allow static files to go through (for now)
|
import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
|
import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
|
Use the spread operator instead of lodash/toArray.
|
'use strict';
const os = require('os');
const defaults = require('lodash/defaults');
const map = require('lodash/map');
const debug = require('debug')('asset-resolver');
const Bluebird = require('bluebird');
const resolver = require('./lib/resolver');
module.exports.getResource = function(file, opts) {
opts = defaults(opts || {}, {
base: [process.cwd()],
filter() {
return true;
}
});
if (typeof opts.base === 'string') {
opts.base = [opts.base];
}
opts.base = resolver.glob([...opts.base]);
return Bluebird.any(
map(opts.base, base => {
return resolver.getResource(base, file, opts);
})
).catch(Bluebird.AggregateError, errs => {
const msg = [
'The file "' + file + '" could not be resolved because of:'
].concat(map(errs, 'message'));
debug(msg);
return Bluebird.reject(new Error(msg.join(os.EOL)));
});
};
|
'use strict';
const os = require('os');
const toarray = require('lodash/toArray');
const defaults = require('lodash/defaults');
const map = require('lodash/map');
const debug = require('debug')('asset-resolver');
const Bluebird = require('bluebird');
const resolver = require('./lib/resolver');
module.exports.getResource = function(file, opts) {
opts = defaults(opts || {}, {
base: [process.cwd()],
filter() {
return true;
}
});
if (typeof opts.base === 'string') {
opts.base = [opts.base];
}
opts.base = resolver.glob(toarray(opts.base));
return Bluebird.any(
map(opts.base, base => {
return resolver.getResource(base, file, opts);
})
).catch(Bluebird.AggregateError, errs => {
const msg = [
'The file "' + file + '" could not be resolved because of:'
].concat(map(errs, 'message'));
debug(msg);
return Bluebird.reject(new Error(msg.join(os.EOL)));
});
};
|
Add support for Laravel Lumen framework
|
<?php
namespace Naughtonium\LaravelDarkSky;
use Illuminate\Support\ServiceProvider;
class LaravelDarkSkyServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source = dirname(__DIR__).'/config/darksky.php';
if ($this->app instanceof LaravelApplication) {
$this->publishes([$source => config_path('darksky.php')]);
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('darksky');
}
$this->mergeConfigFrom($source, 'darksky');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$this->app->singleton('darksky',function($app)
{
return new DarkSky();
});
}
}
|
<?php
namespace Naughtonium\LaravelDarkSky;
use Illuminate\Support\ServiceProvider;
class LaravelDarkSkyServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source = dirname(__DIR__).'/config/darksky.php';
$this->publishes([$source => config_path('darksky.php')]);
$this->mergeConfigFrom($source, 'darksky');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$this->app->singleton('darksky',function($app)
{
return new DarkSky();
});
}
}
|
Update setListener() warning for iOS.
|
/**
* Copyright 2012 The PlayN 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 playn.ios;
import playn.core.Keyboard;
import playn.core.PlayN;
import playn.core.util.Callback;
class IOSKeyboard implements Keyboard
{
@Override
public void setListener(Listener listener) {
PlayN.log().warn("iOS cannot generate keyboard events. Use Keyboard.getText() instead");
}
@Override
public boolean hasHardwareKeyboard() {
return false;
}
@Override
public void getText(TextType textType, String label, String initVal, Callback<String> callback) {
callback.onFailure(new UnsupportedOperationException("Not yet implemented."));
}
}
|
/**
* Copyright 2012 The PlayN 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 playn.ios;
import playn.core.Keyboard;
import playn.core.PlayN;
import playn.core.util.Callback;
class IOSKeyboard implements Keyboard
{
@Override
public void setListener(Listener listener) {
PlayN.log().warn("Keyboard not (currently) supported on iOS.");
}
@Override
public boolean hasHardwareKeyboard() {
return false;
}
@Override
public void getText(TextType textType, String label, String initVal, Callback<String> callback) {
callback.onFailure(new UnsupportedOperationException("Not yet implemented."));
}
}
|
Add unit test for task time processed
|
package task
import (
"reflect"
"testing"
)
func TestTaskState(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.State
want := TaskStateUnknown
if want != got {
t.Errorf("Incorrect task state: want %q, got %q", want, got)
}
}
func TestTaskCommand(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.Command
want := "dummy"
if want != got {
t.Errorf("Incorrect task command: want %q, got %q", want, got)
}
}
func TestTaskArgs(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.Args
want := []string{"foo", "bar"}
if !reflect.DeepEqual(want, got) {
t.Errorf("Incorrect task args: want %q, got %q", want, got)
}
}
func TestTaskTimeReceivedProcessed(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
// Task time received and processed should be 0 when initially created
var want int64 = 0
got := dummyTask.TimeReceived
if want != got {
t.Errorf("Incorrect task time received: want %q, got %q", want, got)
}
got = dummyTask.TimeProcessed
if want != got {
t.Errorf("Incorrect task time processed: want %q, got %q", want, got)
}
}
|
package task
import (
"reflect"
"testing"
)
func TestTaskState(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.State
want := TaskStateUnknown
if want != got {
t.Errorf("Incorrect task state: want %q, got %q", want, got)
}
}
func TestTaskCommand(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.Command
want := "dummy"
if want != got {
t.Errorf("Incorrect task command: want %q, got %q", want, got)
}
}
func TestTaskArgs(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.Args
want := []string{"foo", "bar"}
if !reflect.DeepEqual(want, got) {
t.Errorf("Incorrect task args: want %q, got %q", want, got)
}
}
func TestTaskTimeReceived(t *testing.T) {
dummyTask := NewTask("dummy", "foo", "bar")
got := dummyTask.TimeReceived
var want int64 = 0
if want != got {
t.Errorf("Incorrect task time received: want %q, got %q", want, got)
}
}
|
Fix python3 crash and cleaner error reporting.
|
from __future__ import print_function
import subprocess
import sys
DOCKER_CREATE_IN = 'docker create -it nodev {}'
DOCKER_SIMPLE_CMD_IN = 'docker {} {container_id}'
def nodev(argv=()):
container_id = subprocess.check_output(DOCKER_CREATE_IN.format(' '.join(argv)), shell=True).decode('utf-8').strip()
print('creating container: {container_id}'.format(**locals()))
try:
subprocess.check_call('docker cp . {container_id}:/src '.format(**locals()), shell=True)
subprocess.check_call('docker start -ai {container_id}'.format(**locals()), shell=True)
finally:
print('removing container: {container_id}'.format(**locals()))
subprocess.check_output(DOCKER_SIMPLE_CMD_IN.format('rm -f', **locals()), shell=True)
if __name__ == '__main__':
try:
nodev(sys.argv)
except subprocess.CalledProcessError as ex:
print(ex.args)
sys.exit(1)
|
from __future__ import print_function
import subprocess
import sys
DOCKER_CREATE_IN = 'docker create -it nodev {}'
DOCKER_SIMPLE_CMD_IN = 'docker {} {container_id}'
def nodev(argv=()):
container_id = subprocess.check_output(DOCKER_CREATE_IN.format(' '.join(argv)), shell=True).strip()
print('creating container: {container_id}'.format(**locals()))
try:
subprocess.check_call('docker cp . {container_id}:/src '.format(**locals()), shell=True)
subprocess.check_call('docker start -ai {container_id}'.format(**locals()), shell=True)
finally:
print('removing container: {container_id}'.format(**locals()))
subprocess.check_output(DOCKER_SIMPLE_CMD_IN.format('rm -f', **locals()), shell=True)
if __name__ == '__main__':
nodev(sys.argv)
|
Fix division by two when decrypting (I was actually dividing by 2^e instead of just 2)
|
package cryptopals
import (
"encoding/base64"
"fmt"
"math/big"
"testing"
)
func TestDecryptRsaParityOracle(t *testing.T) {
priv := generateRsaPrivateKey(1024)
pub := priv.public()
encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ=="
message, _ := base64.RawStdEncoding.DecodeString(encoded)
m1 := new(big.Int).SetBytes(message)
server := &parityOracleServer{priv: *priv}
c := pub.encrypt(m1)
m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c)
//s1 := string(m1.Bytes())
//s2 := string(m2.Bytes())
fmt.Println(m1)
fmt.Println(m2)
}
|
package cryptopals
import (
"encoding/base64"
"fmt"
"math/big"
"testing"
)
func TestDecryptRsaParityOracle(t *testing.T) {
priv := generateRsaPrivateKey(1024)
pub := priv.public()
encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ=="
message, _ := base64.RawStdEncoding.DecodeString(encoded)
m1 := new(big.Int).SetBytes(message)
server := &parityOracleServer{priv: *priv}
c := pub.encrypt(m1)
m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c)
s1 := string(m1.Bytes())
s2 := string(m2.Bytes())
fmt.Println(s1)
fmt.Println(s2)
}
|
Create prototype react component for user in list
|
var UserList = React.createClass({
componentDidMount: function() {
socket.on('join', this._join);
socket.on('part', this._part);
},
render: function() {
return (
<ul id='online-list'></ul>
);
},
_join: function(username) {
if (username != myUsername) {
addOnlineUserToList(username);
}
},
_part: function(username) {
$('#online-list li span').filter(function() {
return $(this).text() == username;
}).parent().remove();
}
});
var User = React.createClass({
render: function() {
return (
<li>
</li>
)
}
});
React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
|
var UserList = React.createClass({
componentDidMount: function() {
socket.on('join', this._join);
socket.on('part', this._part);
},
render: function() {
return (
<ul id='online-list'></ul>
);
},
_join: function(username) {
if (username != myUsername) {
addOnlineUserToList(username);
}
},
_part: function(username) {
$('#online-list li span').filter(function() {
return $(this).text() == username;
}).parent().remove();
}
});
React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
|
BHV-12598: Set content property before DOM is updated.
Enyo-DCO-1.1-Signed-off-by: Aaron Tam <aaron.tam@lge.com>
|
(function (enyo, scope) {
/**
* {@link moon.Divider} is a simply styled component that may be used as a separator
* between groups of components.
*
* @class moon.Divider
* @mixes moon.MarqueeSupport
* @mixes moon.MarqueeItem
* @ui
* @public
*/
enyo.kind(
/** @lends moon.Divider.prototype */ {
/**
* @private
*/
name: 'moon.Divider',
/**
* @private
*/
classes: 'moon-divider moon-divider-text',
/**
* @private
*/
mixins: ['moon.MarqueeSupport', 'moon.MarqueeItem'],
/**
* @private
*/
marqueeOnSpotlight: false,
/**
* @private
*/
marqueeOnRender: true,
/**
* @private
*/
contentChanged: enyo.inherit(function (sup) {
return function () {
this.content = this.content.split(' ').map(enyo.cap).join(' ');
sup.apply(this, arguments);
};
})
});
})(enyo, this);
|
(function (enyo, scope) {
/**
* {@link moon.Divider} is a simply styled component that may be used as a separator
* between groups of components.
*
* @class moon.Divider
* @mixes moon.MarqueeSupport
* @mixes moon.MarqueeItem
* @ui
* @public
*/
enyo.kind(
/** @lends moon.Divider.prototype */ {
/**
* @private
*/
name: 'moon.Divider',
/**
* @private
*/
classes: 'moon-divider moon-divider-text',
/**
* @private
*/
mixins: ['moon.MarqueeSupport', 'moon.MarqueeItem'],
/**
* @private
*/
marqueeOnSpotlight: false,
/**
* @private
*/
marqueeOnRender: true,
/**
* @private
*/
contentChanged: enyo.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
this.content = this.content.split(' ').map(enyo.cap).join(' ');
};
})
});
})(enyo, this);
|
Use new line style for Generalization item
|
"""
Generalization --
"""
from gi.repository import GObject
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, Text
from gaphor.diagram.support import represents
@represents(UML.Generalization)
class GeneralizationItem(LinePresentation):
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
)
)
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.close_path()
cr.stroke()
cr.move_to(15, 0)
|
"""
Generalization --
"""
from gi.repository import GObject
from gaphor import UML
from gaphor.diagram.diagramline import DiagramLine
class GeneralizationItem(DiagramLine):
__uml__ = UML.Generalization
__relationship__ = "general", None, "specific", "generalization"
def __init__(self, id=None, model=None):
DiagramLine.__init__(self, id, model)
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.close_path()
cr.stroke()
cr.move_to(15, 0)
|
Change current line if nothing is selected
|
import vscode from 'vscode'
import convert from './convert.js'
function positionFactory (positionObj) {
return new vscode.Position(positionObj._line, positionObj._character)
}
function rangeFactory (selection, length) {
if (length === 0) {
selection.start._character = 0
selection.end._character = vscode.window.activeTextEditor.document.lineAt(
selection.start.line
).text.length
}
return new vscode.Range(
positionFactory(selection.start),
positionFactory(selection.end)
)
}
function activate (context) {
const disposable = vscode.commands.registerCommand(
'extension.convertCSSinJS',
() => {
const editor = vscode.window.activeTextEditor
// return if there's no editor or it's not a javascript file
if (!editor || !/javascript/.test(editor.document.languageId)) {
return
}
const selection = editor.selection
const lineText = editor.document.lineAt(selection.start.line).text
const selectedText = editor.document.getText(selection)
const convertableText = selectedText || lineText
const range = rangeFactory(selection, selectedText.length)
editor.edit(builder => builder.replace(range, convert(convertableText)))
}
)
context.subscriptions.push(disposable)
}
module.exports = { activate }
|
import vscode from 'vscode'
import convert from './convert.js'
function positionFactory (positionObj) {
return new vscode.Position(positionObj._line, positionObj._character)
}
function rangeFactory (selection) {
return new vscode.Range(
positionFactory(selection.start),
positionFactory(selection.end)
)
}
function activate (context) {
const disposable = vscode.commands.registerCommand(
'extension.convertCSSinJS',
() => {
const editor = vscode.window.activeTextEditor
// return if there's no editor or it's not a javascript file
if (!editor || !/javascript/.test(editor.document.languageId)) {
return
}
const selection = editor.selection
const text = editor.document.getText(selection)
if (text.length > 0) {
const range = rangeFactory(selection)
editor.edit(builder => {
return builder.replace(range, convert(text))
})
}
}
)
context.subscriptions.push(disposable)
}
module.exports = { activate }
|
Allow object literals to be IDisposable
RELNOTES[INC]: goog.disposable.IDisposable is now @record
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=129902477
|
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of the disposable interface. A disposable object
* has a dispose method to to clean up references and resources.
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.disposable.IDisposable');
/**
* Interface for a disposable object. If a instance requires cleanup
* (references COM objects, DOM nodes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
* @record
*/
goog.disposable.IDisposable = function() {};
/**
* Disposes of the object and its resources.
* @return {void} Nothing.
*/
goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
/**
* @return {boolean} Whether the object has been disposed of.
*/
goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
|
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of the disposable interface. A disposable object
* has a dispose method to to clean up references and resources.
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.disposable.IDisposable');
/**
* Interface for a disposable object. If a instance requires cleanup
* (references COM objects, DOM notes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
* @interface
*/
goog.disposable.IDisposable = function() {};
/**
* Disposes of the object and its resources.
* @return {void} Nothing.
*/
goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
/**
* @return {boolean} Whether the object has been disposed of.
*/
goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
|
Fix a little bug with cursor
|
'use strict';
/**
* @file Retrieve files for the account
*/
/**
* Download all files from the specified Google Account.
*
* @param {String} refreshToken Refresh_token to identify the account
* @param {Date} since Retrieve contacts updated since this date
* @param {Function} cb Callback. First parameter is the error (if any), second an array of all the contacts.
*/
module.exports = function retrieveFiles(client, oauth2Client, options, changes, cb) {
client.drive.changes
.list(options)
.withAuthClient(oauth2Client)
.execute(function(err, res) {
if(err) {
return cb(err);
}
changes = changes.concat(res.items);
if(res.nextPageToken) {
options.pageToken = res.nextPageToken;
retrieveFiles(client, oauth2Client, options, changes, cb);
}
else {
cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : options.startChangeId, changes);
}
});
};
|
'use strict';
/**
* @file Retrieve files for the account
*/
/**
* Download all files from the specified Google Account.
*
* @param {String} refreshToken Refresh_token to identify the account
* @param {Date} since Retrieve contacts updated since this date
* @param {Function} cb Callback. First parameter is the error (if any), second an array of all the contacts.
*/
module.exports = function retrieveFiles(client, oauth2Client, options, changes, cb) {
client.drive.changes
.list(options)
.withAuthClient(oauth2Client)
.execute(function(err, res) {
if(err) {
return cb(err);
}
changes = changes.concat(res.items);
if(res.nextPageToken) {
options.pageToken = res.nextPageToken;
retrieveFiles(client, oauth2Client, options, changes, cb);
}
else {
cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : null, changes);
}
});
};
|
Change 'year' from persistent to virtual and get from 'releaseDate'
|
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const paginate = require('mongoose-paginate')
const requiredValidationMessage = '{PATH} is required'
let movieSchema = mongoose.Schema({
title: { type: String, required: requiredValidationMessage, trim: true },
image: [{ path: String, alt: String, title: String }],
rating: { type: Number, default: 0 },
description: { type: String, default: '' },
cast: [{ type: String, default: [] }],
categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: requiredValidationMessage }],
releaseDate: { type: Date, default: Date.now }
}, {
timestamps: true,
toObject: { virtuals: true },
toJSON: { virtuals: true }
})
movieSchema
.virtual('year')
.get(function () {
return this.releaseDate.getFullYear()
})
movieSchema.index({ title: 1, year: 1 })
movieSchema.plugin(uniqueValidator)
movieSchema.plugin(paginate)
mongoose.model('Movie', movieSchema)
|
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const paginate = require('mongoose-paginate')
const requiredValidationMessage = '{PATH} is required'
let movieSchema = mongoose.Schema({
title: { type: String, required: requiredValidationMessage, trim: true },
image: [{ path: String, alt: String, title: String }],
year: { type: String },
rating: { type: Number, default: 0 },
description: { type: String, default: '' },
cast: [{ type: String, default: [] }],
categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: requiredValidationMessage }],
releaseDate: { type: Date, default: Date.now }
}, {
timestamps: true
})
movieSchema.index({ title: 1, year: 1 })
movieSchema.plugin(uniqueValidator)
movieSchema.plugin(paginate)
mongoose.model('Movie', movieSchema)
|
Use ResourceBundle caching instead of static field
|
// Copyright (c) 2016 Timothy D. Jones
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package io.github.jonestimd.swing;
import java.awt.Color;
import java.util.ResourceBundle;
import javax.swing.UIManager;
public class ComponentDefaults {
public static Color getColor(String key) {
Color color = UIManager.getColor(key);
if (color == null) {
color = (Color) bundle().getObject(key);
}
return color;
}
private static ResourceBundle bundle() {
return ResourceBundle.getBundle(UIDefaultsBundle.class.getName());
}
}
|
// Copyright (c) 2016 Timothy D. Jones
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package io.github.jonestimd.swing;
import java.awt.Color;
import java.util.ResourceBundle;
import javax.swing.UIManager;
public class ComponentDefaults {
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(UIDefaultsBundle.class.getName());
public static Color getColor(String key) {
Color color = UIManager.getColor(key);
if (color == null) {
color = (Color) BUNDLE.getObject(key);
}
return color;
}
}
|
Add dev and porod mode.
|
import React , { Component , PropTypes }from 'react';
import { Provider } from 'react-redux';
import createStore from './store/create';
import NotificationCenter from './component/notification-center';
import {extendConfig} from './config';
import DevTools from './container/dev-tools';
const metadata = require(`${__PACKAGE_JSON_PATH__}/package.json`);
//Import sass files
import './component/style';
const notificationStore = createStore();
function NotificationCenterDev({onSingleClick, store}){
return <Provider store={store}><div><NotificationCenter hasAddNotif={false} onSingleClick={onSingleClick} /><DevTools/></div></Provider>;
}
NotificationCenterDev.displayName = 'NotificationCenterDev';
function NotificationCenterProd({onSingleClick, store}){
return <Provider store={store}><NotificationCenter hasAddNotif={false} onSingleClick={onSingleClick} /></Provider>;
}
NotificationCenterProd.displayName = 'NotificationCenterProd';
class SmartNotificationCenter extends Component {
componentWillMount() {
const {config} = this.props;
console.log('SMART PROPS',this.props)
extendConfig(config);
}
render() {
const NotificationCenterComponent = !__DEV__ ? NotificationCenterProd : NotificationCenterDev;
return <NotificationCenterComponent onSingleClick={this.props.onSingleClick} store={notificationStore} />
}
}
SmartNotificationCenter.displayName = SmartNotificationCenter;
SmartNotificationCenter.propTypes = {
config: PropTypes.object
};
SmartNotificationCenter.VERSION = metadata.version;
export default SmartNotificationCenter;
export const VERSION = metadata.version;
|
import React , { Component , PropTypes }from 'react';
import { Provider } from 'react-redux';
import createStore from './store/create';
import NotificationCenter from './component/notification-center';
import {extendConfig} from './config';
import metadata from '../package.json';
import DevTools from './container/dev-tools';
//Import sass files
import './component/style';
const store = createStore();
class SmartNotificationCenter extends Component {
componentWillMount() {
const {config} = this.props;
console.log('SMART PROPS',this.props)
extendConfig(config);
}
render() {
return <Provider store={store}><div><NotificationCenter hasAddNotif={false} onSingleClick={this.props.onSingleClick} /><DevTools/></div></Provider>
}
}
SmartNotificationCenter.displayName = SmartNotificationCenter;
SmartNotificationCenter.propTypes = {
config: PropTypes.object
};
SmartNotificationCenter.VERSION = metadata.version;
export default SmartNotificationCenter;
export const VERSION = metadata.version;
|
Add z Patch number as per symver.org
|
import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5.0',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=[
'Django>=1.8',
'factory_boy>=2.7',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=[
'Django>=1.8',
'factory_boy>=2.7',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Revert file to moneymanager master branch.
|
#!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/%s' % (version, fname)
schema = urllib.request.urlopen(url).read().decode('utf-8')
db = sqlite3.connect(':memory:')
db.executescript(schema)
print('\nTesting reports with MMEX db schema v%i:' % version)
print('-' * 40)
for root, dirs, files in os.walk('.'):
for sql in files:
if sql=='sqlcontent.sql':
try: db.executescript(open(os.path.join(root, sql)).read())
except sqlite3.Error as e:
print('ERR', os.path.basename(root).ljust(40), e.args[0])
err = True
else:
print('OK ', os.path.basename(root))
db.rollback()
db.close()
if err: sys.exit(1)
|
#!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/%s' % (version, fname)
schema = urllib.request.urlopen(url).read().decode('utf-8')
db = sqlite3.connect(':memory:')
db.executescript(schema)
print('\nTesting reports with MMEX db schema v%i:' % version)
print('-' * 40)
for root, dirs, files in os.walk('.'):
for sql in files:
if sql=='sqlcontent.sql':
try: db.executescript(open(os.path.join(root, sql)).read())
except sqlite3.Error as e:
print('ERR', os.path.basename(root).ljust(40), e.args[0])
err = True
else:
print('OK ', os.path.basename(root))
db.rollback()
db.close()
if err: sys.exit(1)
|
Fix PHPDoc wrong type annotation
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Component;
use Exception;
use PhpTabs\Music\Song;
use PhpTabs\Component\Importer\ParserBase;
class Importer extends ParserBase
{
/**
* @var \PhpTabs\Music\Song
*/
protected $song;
/**
* @param array $data
*/
public function __construct(array $data)
{
$this->song = new Song();
if (!isset($data['song'])) {
throw new Exception ('Invalid data: song key must be set');
}
$this->parseSong($data['song'], $this->song);
}
/**
* Get built song object
*
* @return \PhpTabs\Music\Song
*/
public function getSong()
{
return $this->song;
}
}
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Component;
use Exception;
use PhpTabs\Music\Song;
use PhpTabs\Component\Importer\ParserBase;
class Importer extends ParserBase
{
/**
* @var \Phptabs\Music\Song
*/
protected $song;
/**
* @param array $data
*/
public function __construct(array $data)
{
$this->song = new Song();
if (!isset($data['song'])) {
throw new Exception ('Invalid data: song key must be set');
}
$this->parseSong($data['song'], $this->song);
}
/**
* Get built song object
*
* @return \PhpTabs\Music\Song
*/
public function getSong()
{
return $this->song;
}
}
|
[Android] Enable test case for presentation API in embedded mode
Extension in embedded mode is now avaialble, reopen the test case for
presentation API
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.runtime.client.embedded.test;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.xwalk.test.util.RuntimeClientApiTestBase;
/**
* Test suite for Presentation API.
*/
public class PresentationTest extends XWalkRuntimeClientTestBase {
@SmallTest
@Feature({"PresentationTest"})
public void testPresentationDisplayAvailable() throws Throwable {
RuntimeClientApiTestBase<XWalkRuntimeClientTestRunnerActivity> helper =
new RuntimeClientApiTestBase<XWalkRuntimeClientTestRunnerActivity>(
getTestUtil(), this);
helper.testPresentationDisplayAvailable();
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.runtime.client.embedded.test;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.xwalk.test.util.RuntimeClientApiTestBase;
/**
* Test suite for Presentation API.
*/
public class PresentationTest extends XWalkRuntimeClientTestBase {
// @SmallTest
// @Feature({"PresentationTest"})
// TODO: Since the embedded extension issue, disable this temporarily.
@DisabledTest
public void testPresentationDisplayAvailable() throws Throwable {
RuntimeClientApiTestBase<XWalkRuntimeClientTestRunnerActivity> helper =
new RuntimeClientApiTestBase<XWalkRuntimeClientTestRunnerActivity>(
getTestUtil(), this);
helper.testPresentationDisplayAvailable();
}
}
|
Use Octicons in Markdown editor
|
from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
|
from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
}),
}
|
Add environment properties: isDev, isTest, isProd
|
const env = process.env.NODE_ENV || 'development';
const config = {
development: {
server: {
port: process.env.PORT || 3000,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-development',
},
},
test: {
server: {
port: process.env.PORT || 3100,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-test',
},
},
production: {
server: {
port: process.env.PORT || 3200,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-production',
},
},
};
config[env].isDev = env === 'development';
config[env].isTest = env === 'test';
config[env].isProd = env === 'production';
module.exports = config[env];
|
const env = process.env.NODE_ENV || 'development';
const config = {
development: {
server: {
port: process.env.PORT || 3000,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-development',
},
},
test: {
server: {
port: process.env.PORT || 3100,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-test',
},
},
production: {
server: {
port: process.env.PORT || 3200,
hostname: process.env.HOSTNAME || 'localhost',
},
database: {
url: 'mongodb://localhost/express-production',
},
},
};
module.exports = config[env];
|
Revert "added geotagging to path"
This reverts commit 54ac4a9ec3ddc0876be202546dc4de00a33389f8.
|
from setuptools import setup, find_packages
setup(
name='django-geotagging-new',
version='0.2.0',
description=('This is a geotagging application. '
'It can be used to localize your content.'),
author='Nicolas Lara',
author_email='nicolaslara@gmail.com',
url='https://github.com/lincolnloop/django-geotagging-new',
package_data={'geotagging': ['static/js/*.js', 'templates/geotagging/*.html', 'templates/olwidget/*.html']},
requires = ['django (>=1.3)'],
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
include_package_data=True,
zip_safe=False,
)
|
from setuptools import setup, find_packages
setup(
name='django-geotagging-new',
version='0.2.0',
description=('This is a geotagging application. '
'It can be used to localize your content.'),
author='Nicolas Lara',
author_email='nicolaslara@gmail.com',
url='https://github.com/lincolnloop/django-geotagging-new',
package_data={'geotagging': ['static/geotagging/js/*.js', 'templates/geotagging/*.html', 'templates/olwidget/*.html']},
requires = ['django (>=1.3)'],
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
include_package_data=True,
zip_safe=False,
)
|
Test for possible array callable with a magic constant
|
<?php
namespace AppendedArrayItem;
// inferred from literal array
$integers = [1, 2, 3];
$integers[] = 4;
$integers['foo'] = 5;
$integers[] = 'foo';
$integers['bar'] = 'baz';
class Foo
{
/**
* @param int[] $integers
* @param callable[] $callables
*/
public function doFoo(
array $integers,
array $callables
)
{
$integers[] = 4;
$integers['foo'] = 5;
$integers[] = 'foo';
$integers['bar'] = 'baz'; // already mixed[] here
$callables[] = [$this, 'doFoo'];
$callables[] = [1, 2, 3];
/** @var callable[] $otherCallables */
$otherCallables = $callables;
$otherCallables[] = ['Foo', 'doFoo'];
/** @var callable[] $anotherCallables */
$anotherCallables = $callables;
$anotherCallables[] = 'doFoo';
/** @var callable[] $yetAnotherCallables */
$yetAnotherCallables = $callables;
$yetAnotherCallables[] = [__CLASS__, 'classMethod'];
}
}
|
<?php
namespace AppendedArrayItem;
// inferred from literal array
$integers = [1, 2, 3];
$integers[] = 4;
$integers['foo'] = 5;
$integers[] = 'foo';
$integers['bar'] = 'baz';
class Foo
{
/**
* @param int[] $integers
* @param callable[] $callables
*/
public function doFoo(
array $integers,
array $callables
)
{
$integers[] = 4;
$integers['foo'] = 5;
$integers[] = 'foo';
$integers['bar'] = 'baz'; // already mixed[] here
$callables[] = [$this, 'doFoo'];
$callables[] = [1, 2, 3];
/** @var callable[] $otherCallables */
$otherCallables = $callables;
$otherCallables[] = ['Foo', 'doFoo'];
/** @var callable[] $anotherCallables */
$anotherCallables = $callables;
$anotherCallables[] = 'doFoo';
}
}
|
Update Nooku Framework, using the row object to get params data
|
<?php
/**
* Belgian Police Web Platform - Districts Component
*
* @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.police.be
*/
namespace Nooku\Component\Districts;
use Nooku\Library;
class DatabaseRowOfficer extends Library\DatabaseRowTable
{
public function __get($column)
{
if($column == 'title' && !isset($this->_data['title'])) {
$this->_data['title'] = $this->firstname.' '.$this->lastname;
}
if($column == 'params' && !is_array($this->_data['params'])) {
$this->_data['params'] = $this->getObject('com:districts.database.row.officer')
->setData(json_decode($this->_data['params'], true));
}
return parent::__get($column);
}
}
|
<?php
/**
* Belgian Police Web Platform - Districts Component
*
* @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.police.be
*/
namespace Nooku\Component\Districts;
use Nooku\Library;
class DatabaseRowOfficer extends Library\DatabaseRowTable
{
public function __get($column)
{
if($column == 'title' && !isset($this->_data['title'])) {
$this->_data['title'] = $this->firstname.' '.$this->lastname;
}
if($column == 'params' && !is_array($this->_data['params'])) {
$this->_data['params'] = json_decode($this->_data['params']);
}
return parent::__get($column);
}
}
|
Convert more tabs to spaces to resolve errors
|
package com.hubspot.jinjava.lib.exptest;
import com.hubspot.jinjava.doc.annotations.JinjavaDoc;
import com.hubspot.jinjava.doc.annotations.JinjavaParam;
import com.hubspot.jinjava.doc.annotations.JinjavaSnippet;
import com.hubspot.jinjava.interpret.InterpretException;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
@JinjavaDoc(value="Return true if variable is pointing at same object as other variable",
params=@JinjavaParam(value="other", type="object", desc="A second object to check the variables value against"),
snippets={
@JinjavaSnippet(
code="{% if var_one is sameas var_two %}\n" +
"<!--code to render if variables have the same value as one another-->\n" +
"{% endif %}"),
}
)
public class IsSameAsExpTest implements ExpTest {
@Override
public String getName() {
return "sameas";
}
@Override
public boolean evaluate(Object var, JinjavaInterpreter interpreter,
Object... args) {
if(args.length == 0) {
throw new InterpretException(getName() + " test requires 1 argument");
}
return var == args[0];
}
}
|
package com.hubspot.jinjava.lib.exptest;
import com.hubspot.jinjava.doc.annotations.JinjavaDoc;
import com.hubspot.jinjava.doc.annotations.JinjavaParam;
import com.hubspot.jinjava.doc.annotations.JinjavaSnippet;
import com.hubspot.jinjava.interpret.InterpretException;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
@JinjavaDoc(value="Return true if variable is pointing at same object as other variable",
params=@JinjavaParam(value="other", type="object", desc="A second object to check the variables value against"),
snippets={
@JinjavaSnippet(
code="{% if var_one is sameas var_two %}\n" +
"<!--code to render if variables have the same value-->\n" +
"{% endif %}"),
}
)
public class IsSameAsExpTest implements ExpTest {
@Override
public String getName() {
return "sameas";
}
@Override
public boolean evaluate(Object var, JinjavaInterpreter interpreter,
Object... args) {
if(args.length == 0) {
throw new InterpretException(getName() + " test requires 1 argument");
}
return var == args[0];
}
}
|
Add coverage in test execution
|
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
moduleDirectories: ['<rootDir>/node_modules', 'node_modules'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser|pmcrypto)/)'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js',
'\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js',
'\\.(md)$': '<rootDir>/src/__mocks__/mdMock.ts',
'sieve.js': 'react-components/__mocks__/sieve.js',
},
reporters: ['default', ['jest-junit', { outputName: 'test-report.xml' }]],
coverageReporters: ['text', 'lcov', 'cobertura'],
};
|
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
moduleDirectories: ['<rootDir>/node_modules', 'node_modules'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser|pmcrypto)/)'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js',
'\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js',
'\\.(md)$': '<rootDir>/src/__mocks__/mdMock.ts',
'sieve.js': 'react-components/__mocks__/sieve.js',
},
};
|
Update interface for sphinxcontrib module
|
# -*- coding: utf-8 -*-
# Copyright 2011 Takeshi KOMIYA
#
# 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 blockdiag.parser
import blockdiag.builder
import blockdiag.drawer
core = blockdiag
import blockdiag.utils.bootstrap
import blockdiag.utils.collections
import blockdiag.utils.fontmap
utils = blockdiag.utils
from blockdiag.utils.rst import nodes
from blockdiag.utils.rst import directives
# FIXME: obsoleted interface (keep for compatibility)
from blockdiag import command, parser, builder, drawer
from blockdiag.utils import collections
from blockdiag.utils.fontmap import FontMap
from blockdiag.utils.rst.directives import blockdiag, BlockdiagDirective
(command, parser, builder, drawer, collections,
FontMap, blockdiag, BlockdiagDirective)
|
# -*- coding: utf-8 -*-
# Copyright 2011 Takeshi KOMIYA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from blockdiag import command, parser, builder, drawer
from blockdiag.utils import collections
from blockdiag.utils.fontmap import FontMap
from blockdiag.utils.rst.directives import blockdiag, BlockdiagDirective
(command, parser, builder, drawer, collections,
FontMap, blockdiag, BlockdiagDirective)
|
Fix Cannot delete invoice(s) that are already opened or paid
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Aquest fitxer XML ja s\'ha processat en els següents IDs')])
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','=','Ja existeix una factura amb el mateix origen')])
#imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
|
Make column names case-insensitively unique
Force added column names to be lowercase, actually
|
'use strict';
function stripTableName(name) {
return name.split('.').pop();
}
// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
constructor (columns) {
this.columns = columns.map(name => stripTableName(name).toLowerCase());
}
uniqueName(baseName) {
baseName = baseName.toLowerCase();
var name = baseName;
var ok = this.isUnique(name);
if (!ok) {
// try adding a numeric suffix
var count = 1;
while (!ok) {
name = baseName + '_' + (++count);
ok = this.isUnique(name);
}
}
this.columns.push(name);
return name;
}
isUnique(name) {
return !this.columns.includes(name);
}
};
|
'use strict';
function stripTableName(name) {
return name.split('.').pop();
}
// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
constructor (columns) {
this.columns = columns.map(name => stripTableName(name));
}
uniqueName(baseName) {
var name = baseName;
var ok = this.isUnique(name);
if (!ok) {
// try adding a numeric suffix
var count = 1;
while (!ok) {
name = baseName + '_' + (++count);
ok = this.isUnique(name);
}
}
this.columns.push(name); // ?
return name;
}
isUnique(name) {
// TODO: should this be case-insensitive?
return !this.columns.includes(name);
}
};
|
Add summary & verbose error description to SWORDAPPErrorDocument
|
<?php
require_once("swordappentry.php");
require_once("utils.php");
class SWORDAPPErrorDocument extends SWORDAPPEntry {
// The error URI
public $sac_erroruri;
// Summary description of error
public $sac_error_summary;
// Verbose description of error
public $sac_verbose_description;
// Construct a new deposit response by passing in the http status code
function __construct($sac_newstatus, $sac_thexml) {
// Call the super constructor
parent::__construct($sac_newstatus, $sac_thexml);
}
// Build the error document hierarchy
function buildhierarchy($sac_dr, $sac_ns) {
// Call the super version
parent::buildhierarchy($sac_dr, $sac_ns);
foreach($sac_dr->attributes() as $key => $value) {
if ($key == 'href') {
$this->sac_erroruri = (string)$value;
}
}
// Set error summary & verbose description, if available
if(isset($sac_dr->children($sac_ns['atom'])->summary)) {
$this->sac_error_summary = (string)$sac_dr->children($sac_ns['atom'])->summary;
}
if(isset($sac_dr->children($sac_ns['sword'])->verboseDescription)) {
$this->sac_verbose_description = (string)$sac_dr->children($sac_ns['sword'])->verboseDescription;
}
}
}
?>
|
<?php
require_once("swordappentry.php");
require_once("utils.php");
class SWORDAPPErrorDocument extends SWORDAPPEntry {
// The error URI
public $sac_erroruri;
// Construct a new deposit response by passing in the http status code
function __construct($sac_newstatus, $sac_thexml) {
// Call the super constructor
parent::__construct($sac_newstatus, $sac_thexml);
}
// Build the error document hierarchy
function buildhierarchy($sac_dr, $sac_ns) {
// Call the super version
parent::buildhierarchy($sac_dr, $sac_ns);
foreach($sac_dr->attributes() as $key => $value) {
if ($key == 'href') {
$this->sac_erroruri = (string)$value;
}
}
$this->sac_erroruri = (string)$sac_dr->attributes()->href;
}
}
?>
|
Handle streams without a resume method
Closes #9
|
'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
return Promise.resolve()
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
if (stream.resume) stream.resume()
return promise
.then(function concat (parts) {
return Buffer.concat(parts.map(bufferize))
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}
|
'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
return Promise.resolve()
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
stream.resume()
return promise
.then(function concat (parts) {
return Buffer.concat(parts.map(bufferize))
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}
|
Add tests for disabled sympification of vectors
|
"""Tests for vectors."""
import pytest
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
# Vectors should not be sympified.
with pytest.raises(TypeError):
sympify(i)
|
"""Tests for vectors."""
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
|
Add missing newline at end of file
See #2509
|
<?php
namespace wcf\system\form\builder\field;
/**
* Provides default implementations of `INullableFormField` methods.
*
* @author Matthias Schmidt
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 3.2
*/
trait TNullableFormField {
/**
* `true` if this field supports `null` as its value and `false` otherwise
* @var bool
*/
protected $__nullable = false;
/**
* Returns `true` if this field supports `null` as its value and returns `false`
* otherwise.
*
* Per default, fields do not support `null` as their value.
*
* @return bool
*/
public function isNullable() {
return $this->__nullable;
}
/**
* Sets whether this field supports `null` as its value and returns this field.
*
* @param bool $nullable determines if field supports `null` as its value
* @return static this node
*
* @throws \InvalidArgumentException if the given value is no boolean
*/
public function nullable($nullable = true) {
if (!is_bool($nullable)) {
throw new \InvalidArgumentException("Given value is no bool, " . gettype($nullable) . " given.");
}
$this->__nullable = $nullable;
return $this;
}
}
|
<?php
namespace wcf\system\form\builder\field;
/**
* Provides default implementations of `INullableFormField` methods.
*
* @author Matthias Schmidt
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 3.2
*/
trait TNullableFormField {
/**
* `true` if this field supports `null` as its value and `false` otherwise
* @var bool
*/
protected $__nullable = false;
/**
* Returns `true` if this field supports `null` as its value and returns `false`
* otherwise.
*
* Per default, fields do not support `null` as their value.
*
* @return bool
*/
public function isNullable() {
return $this->__nullable;
}
/**
* Sets whether this field supports `null` as its value and returns this field.
*
* @param bool $nullable determines if field supports `null` as its value
* @return static this node
*
* @throws \InvalidArgumentException if the given value is no boolean
*/
public function nullable($nullable = true) {
if (!is_bool($nullable)) {
throw new \InvalidArgumentException("Given value is no bool, " . gettype($nullable) . " given.");
}
$this->__nullable = $nullable;
return $this;
}
}
|
[FIX] Modify display style of points on team dashboard
|
import React from 'react';
import PropTypes from 'prop-types';
import { Spinner } from '@blueprintjs/core';
import '../../scss/views/_team-panel.scss';
class TeamPanel extends React.Component {
static propTypes = {
loading: PropTypes.bool.isRequired,
team: PropTypes.shape({
teamName: PropTypes.string.isRequired,
points: PropTypes.number.isRequired,
memberCount: PropTypes.number.isRequired,
members: PropTypes.array,
})
}
render() {
if (this.props.team) {
const { points, members } = this.props.team;
return (
<div id='dashboard-team-panel'>
<div className='pt-callout'>
<div className='points'>
{points} points
</div>
</div>
</div>
);
}
else if (this.props.loading) {
return (
<div className='pt-callout'>
Getting the latest stats...
</div>
);
}
else {
return (
<div className='pt-callout pt-intent-danger pt-icon-error'>
You have not been allocated into a team.
</div>
);
}
}
}
export default TeamPanel;
|
import React from 'react';
import PropTypes from 'prop-types';
import { Spinner } from '@blueprintjs/core';
import '../../scss/views/_team-panel.scss';
class TeamPanel extends React.Component {
static propTypes = {
loading: PropTypes.bool.isRequired,
team: PropTypes.shape({
teamName: PropTypes.string.isRequired,
points: PropTypes.number.isRequired,
memberCount: PropTypes.number.isRequired,
members: PropTypes.array,
})
}
render() {
if (this.props.team) {
const { points, members } = this.props.team;
return (
<div id='dashboard-team-panel'>
<div className='pt-callout'>
<div className='points'>
Points: {points}
</div>
</div>
</div>
);
}
else if (this.props.loading) {
return (
<div className='pt-callout'>
Getting the latest stats...
</div>
);
}
else {
return (
<div className='pt-callout pt-intent-danger pt-icon-error'>
You have not been allocated into a team.
</div>
);
}
}
}
export default TeamPanel;
|
Add a docstring for Related.
|
package containers
import (
"github.com/fsouza/go-dockerclient"
)
type DockerRuntime struct {
Client *docker.Client
}
func isRelated(volume string, container *docker.Container) bool {
for _, mount := range container.Mounts {
if mount.Name == volume && mount.Driver == "dvol" {
return true
}
}
return false
}
// Related determines which containers are related to a particular volume.
// A container is deemed to be related if a dvol volume with the same name appears
// in the Mounts information for a container which is also currently running.
// Related returns an array of related container names and any error encountered.
func (runtime DockerRuntime) Related(volume string) ([]string, error) {
relatedContainers := make([]string, 0)
containers, err := runtime.Client.ListContainers(docker.ListContainersOptions{})
if err != nil {
return relatedContainers, err
}
for _, c := range containers {
container, err := runtime.Client.InspectContainer(c.ID)
if err != nil {
return relatedContainers, err
}
if isRelated(volume, container) && container.State.Running {
relatedContainers = append(relatedContainers, container.Name)
}
}
return relatedContainers, nil
}
func (runtime DockerRuntime) Start(volume string) error {
return nil
}
func (runtime DockerRuntime) Stop(volume string) error {
return nil
}
func (runtime DockerRuntime) Remove(volume string) error {
return nil
}
|
package containers
import (
"github.com/fsouza/go-dockerclient"
)
type DockerRuntime struct {
Client *docker.Client
}
func isRelated(volume string, container *docker.Container) bool {
for _, mount := range container.Mounts {
if mount.Name == volume && mount.Driver == "dvol" {
return true
}
}
return false
}
func (runtime DockerRuntime) Related(volume string) ([]string, error) {
relatedContainers := make([]string, 0)
containers, err := runtime.Client.ListContainers(docker.ListContainersOptions{})
if err != nil {
return relatedContainers, err
}
for _, c := range containers {
container, err := runtime.Client.InspectContainer(c.ID)
if err != nil {
return relatedContainers, err
}
if isRelated(volume, container) && container.State.Running {
relatedContainers = append(relatedContainers, container.Name)
}
}
return relatedContainers, nil
}
func (runtime DockerRuntime) Start(volume string) error {
return nil
}
func (runtime DockerRuntime) Stop(volume string) error {
return nil
}
func (runtime DockerRuntime) Remove(volume string) error {
return nil
}
|
Rearrange imports of gettext and release because of dependencies in
circular import.
|
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
|
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
from fedora import release
__version__ = release.VERSION
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
|
Add more info to the AuthController
|
'use strict';
var authController = {};
var UserCollection = require('../models').collections.UserCollection;
var User = require('../models').models.User;
authController.getUser = function (req, res) {
var userId = null;
if (req.user && req.user.get('id') && typeof req.user.get('id') === 'number') {
userId = req.user.get('id');
}
res.json({
userId: userId,
userName: req.user.get('username'),
email: req.user.get('email'),
});
};
authController.logout = function (req, res) {
res.logout();
res.status(200).end();
};
authController.login = function (req, res) {
res.redirect('/#/home');
};
authController.signup = function (req, res) {
var email = req.body.email || req.param('email');
var password = req.body.password || req.param('password');
if (!email || !password) {
res.status(400).end(); // Client Error
return;
}
new UserCollection()
.query('where', 'email', '=', email)
.fetchOne()
.then(function (user) {
if (user !== null) {
res.redirect('/#/home');
return;
}
new User({
email: email,
password: password
}).save()
.then(function () {
res.redirect('/#/home');
});
});
};
module.exports = authController;
|
var authController = {};
var UserCollection = require('../models').collections.UserCollection;
var User = require('../models').models.User;
authController.getUser = function (req, res) {
var userId = null;
if (req.user && req.user.get('id') && typeof req.user.get('id') === 'number') {
userId = req.user.get('id');
}
res.json({
userId: userId,
});
};
authController.logout = function (req, res) {
res.logout();
res.status(200).end();
};
authController.login = function (req, res) {
res.redirect('/#/home');
};
authController.signup = function (req, res) {
var email = req.body.email || req.param('email');
var password = req.body.password || req.param('password');
if (!email || !password) {
res.status(400).end(); // Client Error
return;
}
new UserCollection()
.query('where', 'email', '=', email)
.fetchOne()
.then(function (user) {
if (user !== null) {
res.redirect('/#/home');
return;
}
var user = new User({
email: email,
password: password
}).save()
.then(function (userModel) {
res.redirect('/#/home');
});
});
};
module.exports = authController;
|
Set proper file perms for newly created directories.
|
var app = require('server'),
fs = require('fs');
/**
* Bootstrap the application - ensure that directories
* exist, etc
*/
function bootstrap() {
try {
fs.statSync(app.set('settings')('mapfile_dir'));
} catch (Exception) {
console.log('Creating mapfile dir %s', app.set('settings')('mapfile_dir'));
fs.mkdirSync(app.set('settings')('mapfile_dir'), 0777);
}
try {
fs.statSync(app.set('settings')('data_dir'));
} catch (Exception) {
console.log('Creating mapfile dir %s', app.set('settings')('data_dir'));
fs.mkdirSync(app.set('settings')('data_dir'), 0777);
}
}
module.exports = bootstrap;
|
var app = require('server'),
fs = require('fs');
/**
* Bootstrap the application - ensure that directories
* exist, etc
*/
function bootstrap() {
try {
fs.statSync(app.set('settings')('mapfile_dir'));
} catch (Exception) {
console.log('Creating mapfile dir %s', app.set('settings')('mapfile_dir'));
fs.mkdirSync(app.set('settings')('mapfile_dir'), 777);
}
try {
fs.statSync(app.set('settings')('data_dir'));
} catch (Exception) {
console.log('Creating mapfile dir %s', app.set('settings')('data_dir'));
fs.mkdirSync(app.set('settings')('data_dir'), 777);
}
}
module.exports = bootstrap;
|
Fix bug where Navigation Timing info could be accessed to quickly and hence produce weird values
|
'use strict';
// DEV TIME CODE
if (FAKE_SERVER) {
require('fake');
}
// DEV TIME CODE
require('./index.scss');
var $ = require('$jquery');
var util = require('lib/util');
var state = require('./state');
var repository = require('./repository');
var sections = require('./sections/section');
//var details = args.newData.hud;
var setup = state.current();
// only load things when we have the data ready to go
repository.getData(function(details) {
$(function() { setTimeout(function() {
// generate the html needed for the sections
var html = sections.render(details, setup);
html = '<div class="glimpse"><div class="glimpse-icon"></div><div class="glimpse-hud">' + html + '</div></div>';
// insert the html into the dom
var holder = $(html).appendTo('body')
// force the correct state from previous load
state.setup(holder);
// setup events that we need to listen to
sections.postRender(holder);
// TODO: need to find a better place for this
$('.glimpse-icon').click(function() {
window.open(util.resolveClientUrl(util.currentRequestId(), true), 'GlimpseClient');
});
}, 0); });
});
|
'use strict';
// DEV TIME CODE
if (FAKE_SERVER) {
require('fake');
}
// DEV TIME CODE
require('./index.scss');
var $ = require('$jquery');
var util = require('lib/util');
var state = require('./state');
var repository = require('./repository');
var sections = require('./sections/section');
//var details = args.newData.hud;
var setup = state.current();
// only load things when we have the data ready to go
repository.getData(function(details) {
// generate the html needed for the sections
var html = sections.render(details, setup);
html = '<div class="glimpse"><div class="glimpse-icon"></div><div class="glimpse-hud">' + html + '</div></div>';
// insert the html into the dom
var holder = $(html).appendTo('body')
// force the correct state from previous load
state.setup(holder);
// setup events that we need to listen to
sections.postRender(holder);
// TODO: need to find a better place for this
$('.glimpse-icon').click(function() {
window.open(util.resolveClientUrl(util.currentRequestId(), true), 'GlimpseClient');
});
});
|
Update reverse relationship lookup to expect exceptions.
|
<?php
namespace li3_fake_model\extensions\data\relationships;
use lithium\core\ConfigException;
class HasMany extends Relation {
public function appendData() {
$foreignField = current($this->meta['key']);
$currentField = key($this->meta['key']);
$fieldName = $this->meta['fieldName'];
foreach ($this->data as $data) {
foreach ($this->results() as $result) {
try {
$reverseRelation = $result->retrieveRelationship(get_class($data));
$type = $reverseRelation instanceof $result::$classes['hasOne'] ? 'hasOne' : 'hasMany';
} catch (ConfigException $e) {
$type = 'hasMany';
}
if ($this->compare($type, $result->{$foreignField}, $data->{$currentField})) {
$data->data[$fieldName][] = $result;
}
}
}
return;
}
public function compare($type, $result1, $result2) {
if ($type === 'hasOne') {
return $result1 == $result2;
}
return in_array($result1, $result2);
}
public function results() {
$class = $this->meta['to'];
return $class::all(
array(
current($this->meta['key']) => array(
'$in' => $this->retrieveFields(),
),
),
array(
'with' => $this->with(),
)
);
}
}
|
<?php
namespace li3_fake_model\extensions\data\relationships;
class HasMany extends Relation {
public function appendData() {
$foreignField = current($this->meta['key']);
$currentField = key($this->meta['key']);
$fieldName = $this->meta['fieldName'];
foreach ($this->data as $data) {
foreach ($this->results() as $result) {
$reverseRelation = $result->retrieveRelationship(get_class($data));
$type = $reverseRelation instanceof $result->classes['hasOne'] ? 'hasOne' : 'hasMany';
if ($this->compare($type, $result->{$foreignField}, $data->{$currentField})) {
$data->data[$fieldName][] = $result;
}
}
}
return;
}
public function compare($type, $result1, $result2) {
if ($type === 'hasOne') {
return $result1 == $result2;
}
return in_array($result1, $result2);
}
public function results() {
$class = $this->meta['to'];
return $class::all(
array(
current($this->meta['key']) => array(
'$in' => $this->retrieveFields(),
),
),
array(
'with' => $this->with(),
)
);
}
}
|
Add period to end of long comment
|
import errno
import os
def file_exists(path):
"""Return True if a file exists at `path` (even if it can't be read),
otherwise False.
This is different from os.path.isfile and os.path.exists which return
False if a file exists but the user doesn't have permission to read it.
"""
try:
os.stat(path)
return True
except OSError as e:
# Permission denied: someone chose the wrong permissions but it exists.
if e.errno == errno.EACCES:
return True
# File doesn't exist
elif e.errno == errno.ENOENT:
return False
# Unknown case
raise
|
import errno
import os
def file_exists(path):
"""Return True if a file exists at `path` (even if it can't be read),
otherwise False.
This is different from os.path.isfile and os.path.exists which return
False if a file exists but the user doesn't have permission to read it.
"""
try:
os.stat(path)
return True
except OSError as e:
# Permission denied: someone chose the wrong permissions but it exists
if e.errno == errno.EACCES:
return True
# File doesn't exist
elif e.errno == errno.ENOENT:
return False
# Unknown case
raise
|
Add the auth path for onboarding
|
function getRoute(path, subComponentName) {
return {
path: path,
subComponentName: subComponentName,
onEnter() {
require('../../networking/auth')
},
getComponents(location, cb) {
require.ensure([], (require) => {
cb(null, require('../../components/views/OnboardingView'))
})
},
}
}
export default {
path: 'onboarding',
onEnter() {
require('../../networking/auth')
},
getChildRoutes(location, cb) {
require.ensure([], () => {
cb(null, [
getRoute('communities', 'CommunityPicker'),
getRoute('awesome-people', 'PeoplePicker'),
getRoute('profile-header', 'CoverPicker'),
getRoute('profile-avatar', 'AvatarPicker'),
getRoute('profile-bio', 'InfoPicker'),
])
})
},
}
|
function getRoute(path, subComponentName) {
return {
path: path,
subComponentName: subComponentName,
getComponents(location, cb) {
require.ensure([], (require) => {
cb(null, require('../../components/views/OnboardingView'))
})
},
}
}
export default {
path: 'onboarding',
onEnter() {
require('../../networking/auth')
},
getChildRoutes(location, cb) {
require.ensure([], () => {
cb(null, [
getRoute('communities', 'CommunityPicker'),
getRoute('awesome-people', 'PeoplePicker'),
getRoute('profile-header', 'CoverPicker'),
getRoute('profile-avatar', 'AvatarPicker'),
getRoute('profile-bio', 'InfoPicker'),
])
})
},
}
|
Use babel loader instead of babel to production
|
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs
output: {
path: path.resolve('./webapp/assets/bundles/'),
filename: "[name]-[hash].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['react', 'es2015', 'stage-2']
}
}, // to transform JSX into JS
],
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx']
},
watchOptions: {
poll: 1000,
aggregateTimeout: 1000
},
}
|
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs
output: {
path: path.resolve('./webapp/assets/bundles/'),
filename: "[name]-[hash].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query:
{
presets:['react', 'es2015', 'stage-2']
}
}, // to transform JSX into JS
],
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx']
},
watchOptions: {
poll: 1000,
aggregateTimeout: 1000
},
}
|
Fix KeyboardInterrupt exception filtering.
Add exception information and not just the stack trace.
Make the url easier to change at runtime.
Review URL: http://codereview.chromium.org/2109001
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@47179 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import socket
import sys
# Configure these values.
DEFAULT_URL = 'http://chromium-status.appspot.com/breakpad'
def SendStack(last_tb, stack, url=None):
if not url:
url = DEFAULT_URL
print 'Sending crash report ...'
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
'exception': last_tb,
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
def CheckForException():
last_value = getattr(sys, 'last_value', None)
if last_value and not isinstance(last_value, KeyboardInterrupt):
last_tb = getattr(sys, 'last_traceback', None)
if last_tb:
SendStack(repr(last_value), ''.join(traceback.format_tb(last_tb)))
if (not 'test' in sys.modules['__main__'].__file__ and
socket.gethostname().endswith('.google.com')):
# Skip unit tests and we don't want anything from non-googler.
atexit.register(CheckForException)
|
# Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import socket
import sys
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
print 'Sending crash report ...'
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
def CheckForException():
last_tb = getattr(sys, 'last_traceback', None)
if last_tb and sys.last_type is not KeyboardInterrupt:
SendStack(''.join(traceback.format_tb(last_tb)))
if (not 'test' in sys.modules['__main__'].__file__ and
socket.gethostname().endswith('.google.com')):
# Skip unit tests and we don't want anything from non-googler.
atexit.register(CheckForException)
|
Configuration: Fix Silly Code and cleanup JavaDoc
|
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final File file;
private final Configuration configuration = new Configuration();
/**
* Creates a @link{ConfigFile} from the Path
*
* @param path the path to load the configuration from
*/
public ConfigFile(Path path)
{
this(path.toFile());
}
/**
* Creates a {@link ConfigFile} from the file
* @param file the file to load the configuration from
*/
public ConfigFile(File file)
{
this.file = file;
}
/**
* Loads the configuration file
*/
@Override
public void load()
{
try
{
configuration.load(file);
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the configuration file
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the {@link Configuration} from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
|
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final Path path;
private final Configuration configuration = new Configuration();
/**
* Creates a ConfigFile from the path
*
* @param path path
*/
public ConfigFile(Path path)
{
this.path = path;
}
/**
* Creates a ConfigFile from the file
* @param file file
*/
public ConfigFile(File file)
{
this.path = file.toPath();
}
/**
* Loads the Configuration File
*/
@Override
public void load()
{
try
{
configuration.load(path.toFile());
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the Configuration File
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the Configuration from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
|
Remove python 3.3 from trove classifiers [skip ci]
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Make CommentsEmail Constructor more Generic
|
<?php
/**
* Email
*/
class CommentsEmail
{
public $to;
public $subject;
public $message;
private $comment;
function __construct($to, $subject, $comment)
{
$this->comment = $comment;
$this->to = $to;
$this->subject = $this->format($subject);
$this->message = strip_tags($comment->message());
}
public function format($x)
{
$placeholders = array(
'comment.user.name' => $this->comment->name(),
'comment.user.email' => $this->comment->email(),
'comment.user.website' => $this->comment->website(),
'comment.message' => strip_tags($this->comment->message()),
'page.name' => $this->comment->content_page->{Comments::option('setup.page.title_key')}(),
'page.url' => $this->comment->content_page->url()
);
return preg_replace_callback('/\{\{\s*(\S+)\s*\}\}/', function ($matches) use ($placeholders)
{
return $placeholders[$matches[1]];
}, $x);
}
public function send()
{
}
}
|
<?php
/**
* Email
*/
class CommentsEmail
{
public $to;
public $subject;
public $message;
private $comment;
function __construct($comment)
{
$this->comment = $comment;
$this->to = Comments::option('email.to');
$this->subject = $this->format(Comments::option('email.subject'));
$this->message = strip_tags($comment->message());
}
public function format($x)
{
$placeholders = array(
'comment.user.name' => $this->comment->name(),
'comment.user.email' => $this->comment->email(),
'comment.user.website' => $this->comment->website(),
'comment.message' => strip_tags($this->comment->message()),
'page.name' => $this->comment->content_page->{Comments::option('setup.page.title_key')}(),
'page.url' => $this->comment->content_page->url()
);
return preg_replace_callback('/\{\{\s*(\S+)\s*\}\}/', function ($matches) use ($placeholders)
{
return $placeholders[$matches[1]];
}, $x);
}
public function send()
{
}
}
|
Write FASTA output to standard out.
|
"""
Convert a prepared JSON file from augur into a FASTA file.
"""
import argparse
import Bio
import json
import logging
import sys
sys.path.append('..')
from base.sequences_process import sequence_set
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert a prepared JSON file from augur into a FASTA file.")
parser.add_argument("json", help="prepared JSON from augur")
args = parser.parse_args()
# Setup the logger.
logger = logging.getLogger(__name__)
# Load the JSON data.
with open(args.json, "r") as fh:
data = json.load(fh)
# Prepare a sequence set.
sequences = sequence_set(
logger,
data["sequences"],
data["reference"],
data["info"]["date_format"]
)
# Add the reference to output sequences if it isn't already included.
output_sequences = sequences.seqs.values()
if not sequences.reference_in_dataset:
output_sequences.append(sequences.reference_seq)
# Write sequences to standard out.
Bio.SeqIO.write(output_sequences, sys.stdout, "fasta")
|
"""
Convert a prepared JSON file from augur into a FASTA file.
"""
import argparse
import Bio
import json
import logging
import sys
sys.path.append('..')
from base.sequences_process import sequence_set
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("json", help="prepared JSON from augur")
parser.add_argument("fasta", help="FASTA output for sequences in JSON file")
args = parser.parse_args()
# Setup the logger.
logger = logging.getLogger(__name__)
# Load the JSON data.
with open(args.json, "r") as fh:
data = json.load(fh)
# Prepare a sequence set.
sequences = sequence_set(
logger,
data["sequences"],
data["reference"],
data["info"]["date_format"]
)
# Add the reference to output sequences if it isn't already included.
output_sequences = sequences.seqs.values()
if not sequences.reference_in_dataset:
output_sequences.append(sequences.reference_seq)
# Write sequences to disk.
Bio.SeqIO.write(output_sequences, args.fasta, "fasta")
|
Add Python 3.7 to the list of Trove classifiers
|
from setuptools import setup
import codecs
import schema
setup(
name=schema.__name__,
version=schema.__version__,
author="Vladimir Keleshev",
author_email="vladimir@keleshev.com",
description="Simple data validation library",
license="MIT",
keywords="schema json validation",
url="https://github.com/keleshev/schema",
py_modules=['schema'],
long_description=codecs.open('README.rst', 'r', 'utf-8').read(),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: PyPy",
"License :: OSI Approved :: MIT License",
],
)
|
from setuptools import setup
import codecs
import schema
setup(
name=schema.__name__,
version=schema.__version__,
author="Vladimir Keleshev",
author_email="vladimir@keleshev.com",
description="Simple data validation library",
license="MIT",
keywords="schema json validation",
url="https://github.com/keleshev/schema",
py_modules=['schema'],
long_description=codecs.open('README.rst', 'r', 'utf-8').read(),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: PyPy",
"License :: OSI Approved :: MIT License",
],
)
|
Fix multivar for nodes with variable length stacks
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
def prepare(self, stack):
self.node_1.prepare(stack)
self.node_2.prepare(stack)
self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
rtn = self.node_2(stack[:self.node_2.args])
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
if len(stack) == 0:
self.add_arg(stack)
@Node.is_func
def apply(self, *stack):
self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
Add support for scoping the query to an element
|
const { querySelectorDeep } = require('query-selector-shadow-dom');
exports.getDocument = () => document.getElementById('app').contentDocument;
exports.querySelectorDeep = querySelectorDeep;
exports.waitFor = seconds => new Promise((resolve) => {
setTimeout(resolve, seconds);
});
exports.waitForElement = (selector, ensureNoError = true, container = null) => new Promise(
(resolve, reject) => {
const parentElement = container || exports.getDocument();
if (ensureNoError) {
try {
exports.assertNoError();
} catch (e) {
reject(e);
return;
}
}
const element = querySelectorDeep(selector, parentElement);
if (element) {
resolve(element);
return;
}
exports.waitFor(100)
.then(() => exports.waitForElement(selector, ensureNoError, parentElement))
.then(resolve, reject);
},
);
exports.assertNoError = () => {
const alertDialog = querySelectorDeep('noflo-ui noflo-alert', exports.getDocument());
if (!alertDialog.classList.contains('show')) {
return;
}
if (!alertDialog.classList.contains('error')) {
return;
}
const alertContents = querySelectorDeep('noflo-ui noflo-alert slot span', exports.getDocument());
throw new Error(alertContents.innerHTML);
};
|
const { querySelectorDeep } = require('query-selector-shadow-dom');
exports.getDocument = () => document.getElementById('app').contentDocument;
exports.querySelectorDeep = querySelectorDeep;
exports.waitFor = seconds => new Promise((resolve) => {
setTimeout(resolve, seconds);
});
exports.waitForElement = (selector, ensureNoError = true) => new Promise((resolve, reject) => {
if (ensureNoError) {
try {
exports.assertNoError();
} catch (e) {
reject(e);
return;
}
}
const element = querySelectorDeep(selector, exports.getDocument());
if (element) {
resolve(element);
return;
}
exports.waitFor(100)
.then(() => exports.waitForElement(selector, ensureNoError))
.then(resolve, reject);
});
exports.assertNoError = () => {
const alertDialog = querySelectorDeep('noflo-ui noflo-alert', exports.getDocument());
if (!alertDialog.classList.contains('show')) {
return;
}
if (!alertDialog.classList.contains('error')) {
return;
}
const alertContents = querySelectorDeep('noflo-ui noflo-alert slot span', exports.getDocument());
throw new Error(alertContents.innerHTML);
};
|
Revert "changing decodeURIComponent to decodeURI since it was causing problems with URLs with &"
Some people were having problems where URLs were coming through with an escaped ? as %3F which was not being decoded correctly. Reverting until I can do more research
This reverts commit 46697ccaaf74f2047209f0eedc204482bcc46832.
|
/*jshint sub: true */
var url = require('url');
var util = exports = module.exports = {};
// Normalizes unimportant differences in URLs - e.g. ensures
// http://google.com/ and http://google.com normalize to the same string
util.normalizeUrl = function (u) {
return url.format(url.parse(u, true));
};
// Gets the URL to prerender from a request, stripping out unnecessary parts
util.getUrl = function (req) {
var decodedUrl
, parts;
try {
decodedUrl = decodeURIComponent(req.url);
} catch (e) {
decodedUrl = req.url;
}
parts = url.parse(decodedUrl, true);
// Remove the _escaped_fragment_ query parameter
if (parts.query.hasOwnProperty('_escaped_fragment_')) {
if(parts.query['_escaped_fragment_']) parts.hash = '#!' + parts.query['_escaped_fragment_'];
delete parts.query['_escaped_fragment_'];
delete parts.search;
}
var newUrl = url.format(parts);
if(newUrl[0] === '/') newUrl = newUrl.substr(1);
return newUrl;
};
util.log = function() {
if(process.env.DISABLE_LOGGING) {
return;
}
console.log.apply(console.log, [new Date().toISOString()].concat(Array.prototype.slice.call(arguments, 0)));
};
|
/*jshint sub: true */
var url = require('url');
var util = exports = module.exports = {};
// Normalizes unimportant differences in URLs - e.g. ensures
// http://google.com/ and http://google.com normalize to the same string
util.normalizeUrl = function (u) {
return url.format(url.parse(u, true));
};
// Gets the URL to prerender from a request, stripping out unnecessary parts
util.getUrl = function (req) {
var decodedUrl
, parts;
try {
decodedUrl = decodeURI(req.url);
} catch (e) {
decodedUrl = req.url;
}
parts = url.parse(decodedUrl, true);
// Remove the _escaped_fragment_ query parameter
if (parts.query.hasOwnProperty('_escaped_fragment_')) {
if(parts.query['_escaped_fragment_']) parts.hash = '#!' + parts.query['_escaped_fragment_'];
delete parts.query['_escaped_fragment_'];
delete parts.search;
}
var newUrl = url.format(parts);
if(newUrl[0] === '/') newUrl = newUrl.substr(1);
return newUrl;
};
util.log = function() {
if(process.env.DISABLE_LOGGING) {
return;
}
console.log.apply(console.log, [new Date().toISOString()].concat(Array.prototype.slice.call(arguments, 0)));
};
|
Make Button plugin usable inside Text plugin
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
Change duplicate variable in httpconnection
|
module.exports = HttpConnection;
var request = require('requestretry');
var HttpConfig = require("./HttpConfig");
var PaymayaApiError = require("./PaymayaApiError");
function HttpConnection(httpConfig) {
this._httpConfig = httpConfig;
}
HttpConnection.prototype = {
/* PUBLIC FUNCTIONS */
execute: function(data, callback) {
var httpOptions = {
url: this._httpConfig.getUrl(),
method: this._httpConfig.getMethod(),
headers: this._httpConfig.getHeaders(),
maxAttempts: this._httpConfig.getMaximumRequestAttempt()
};
if(data) {
httpOptions['body'] = JSON.stringify(data);
}
request(httpOptions, function(err, response, body) {
if(err) {
return callback(err);
}
if(!body && response.statusCode >= 400) {
var paymayaApiError = new PaymayaApiError(response.statusCode);
return callback(paymayaApiError.message);
}
if(typeof body !== 'object') {
body = JSON.parse(body);
}
if(body.error) {
var paymayaApiError = new PaymayaApiError(response.statusCode, body.error);
return callback(paymayaApiError.message);
}
if(body.message && response.statusCode !== 200) {
return callback(body.message);
}
callback(null, body);
});
}
};
|
module.exports = HttpConnection;
var request = require('requestretry');
var HttpConfig = require("./HttpConfig");
var PaymayaApiError = require("./PaymayaApiError");
function HttpConnection(httpConfig) {
this._httpConfig = httpConfig;
}
HttpConnection.prototype = {
/* PUBLIC FUNCTIONS */
execute: function(data, callback) {
var httpOptions = {
url: this._httpConfig.getUrl(),
method: this._httpConfig.getMethod(),
headers: this._httpConfig.getHeaders(),
maxAttempts: this._httpConfig.getMaximumRequestAttempt()
};
if(data) {
httpOptions['body'] = JSON.stringify(data);
}
request(httpOptions, function(err, response, body) {
if(err) {
return callback(err);
}
if(!body && response.statusCode >= 400) {
var err = new PaymayaApiError(response.statusCode);
return callback(err);
}
if(typeof body !== 'object') {
body = JSON.parse(body);
}
if(body.error) {
var paymayaApiError = new PaymayaApiError(response.statusCode, body.error);
return callback(paymayaApiError.message);
}
if(body.message && response.statusCode !== 200) {
return callback(body.message);
}
callback(null, body);
});
}
};
|
Fix a new ExecutableSign not being added to the register
|
package tk.martijn_heil.kingdomessentials.signs;
import lombok.Getter;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
public class ExecutableSignRegister
{
@Getter private List<ExecutableSign> registeredSigns = new ArrayList<>();
public void addExecutableSign(ExecutableSign sign)
{
checkArgument(!registeredSigns.contains(sign), "this sign is already registered.");
this.registeredSigns.add(sign);
}
@Nullable
public ExecutableSign get(String action)
{
for (ExecutableSign sign : registeredSigns)
{
if(sign.getAction().equals(action)) return sign;
}
return null;
}
}
|
package tk.martijn_heil.kingdomessentials.signs;
import lombok.Getter;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
public class ExecutableSignRegister
{
@Getter private List<ExecutableSign> registeredSigns = new ArrayList<>();
public void addExecutableSign(ExecutableSign sign)
{
checkArgument(!registeredSigns.contains(sign), "this sign is already registered.");
}
@Nullable
public ExecutableSign get(String action)
{
for (ExecutableSign sign : registeredSigns)
{
if(sign.getAction().equals(action)) return sign;
}
return null;
}
}
|
Change to use evdev 0.6.4
Signed-off-by: tom <3abfbc22eec6ecd173d744487905db1fa6a502d5@gmail.com>
|
__author__ = 'tom'
from setuptools import setup
# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use
# 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will
# only work for Tom as they need the pypi account credentials.
setup(
name='approxeng.input',
version='0.6',
description='Python game controller support using evDev for Raspberry Pi and other Linux systems',
classifiers=['Programming Language :: Python :: 2.7'],
url='https://github.com/ApproxEng/approxeng.input/',
author='Tom Oinn',
author_email='tomoinn@gmail.com',
license='ASL2.0',
packages=['approxeng.input'],
install_requires=['evdev==0.6.4'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose'],
dependency_links=[],
zip_safe=False)
|
__author__ = 'tom'
from setuptools import setup
# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use
# 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will
# only work for Tom as they need the pypi account credentials.
setup(
name='approxeng.input',
version='0.6',
description='Python game controller support using evDev for Raspberry Pi and other Linux systems',
classifiers=['Programming Language :: Python :: 2.7'],
url='https://github.com/ApproxEng/approxeng.input/',
author='Tom Oinn',
author_email='tomoinn@gmail.com',
license='ASL2.0',
packages=['approxeng.input'],
install_requires=['evdev==0.5.0'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose'],
dependency_links=[],
zip_safe=False)
|
Set default to once a day for now
|
#!/bin/env node
module.exports = function()
{
var scope = this;
this.CronJob = require('cron').CronJob;
this.NewReleases = require(__dirname + '/newreleases');
this.User = require(__dirname + '/db/user');
this.jobs = [];
this.init = function()
{
// TODO: select distinct crontime and timezone from database users
scope.jobs.push(
new scope.CronJob(
{
cronTime: '* 00 11 * * *',
onTick: scope.runCheck,
start: true,
timeZone: "Europe/Amsterdam"
})
);
};
this.runCheck = function()
{
console.log(this.cronTime.source);
console.log(this.cronTime.zone);
scope.User.find({active:true, crontime: this.cronTime.source, timezone: this.cronTime.zone}, function(err, users)
{
if(err) { console.log('Error getting users from the database: '+ err); }
users.forEach(function(user)
{
var releases = new scope.NewReleases();
releases.checkNewReleases(user);
});
});
};
};
|
#!/bin/env node
module.exports = function()
{
var scope = this;
this.CronJob = require('cron').CronJob;
this.NewReleases = require(__dirname + '/newreleases');
this.User = require(__dirname + '/db/user');
this.jobs = [];
this.init = function()
{
// TODO: select distinct crontime and timezone from database users
scope.jobs.push(
new scope.CronJob(
{
cronTime: '10 * * * * *',
onTick: scope.runCheck,
start: true,
timeZone: "Europe/Amsterdam"
})
);
};
this.runCheck = function()
{
console.log(this.cronTime.source);
console.log(this.cronTime.zone);
scope.User.find({active:true, crontime: this.cronTime.source, timezone: this.cronTime.zone}, function(err, users)
{
if(err) { console.log('Error getting users from the database: '+ err); }
users.forEach(function(user)
{
var releases = new scope.NewReleases();
releases.checkNewReleases(user);
});
});
};
};
|
Fix removal of namespace when deriving error code from class name
|
<?php
namespace Amp\Optimizer\Error;
/**
* Default set of properties and methods to use for errors.
*
* @package Amp\Optimizer
*/
trait ErrorProperties
{
/**
* Instantiate an Error object.
*
* @param string $message Message for the error.
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Message of the error.
*
* @var string
*/
protected $message;
/**
* Get the code of the error.
*
* @return string Code of the error.
*/
public function getCode()
{
return preg_replace('/^.+\\\\/', '', get_class($this));
}
/**
* Get the message of the error.
*
* @return string Message of the error.
*/
public function getMessage()
{
return $this->message;
}
}
|
<?php
namespace Amp\Optimizer\Error;
/**
* Default set of properties and methods to use for errors.
*
* @package Amp\Optimizer
*/
trait ErrorProperties
{
/**
* Instantiate an Error object.
*
* @param string $message Message for the error.
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Message of the error.
*
* @var string
*/
protected $message;
/**
* Get the code of the error.
*
* @return string Code of the error.
*/
public function getCode()
{
return basename(get_class($this));
}
/**
* Get the message of the error.
*
* @return string Message of the error.
*/
public function getMessage()
{
return $this->message;
}
}
|
Add expres cors headers middleware
|
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) require('dotenv').config();
var app = express();
const PORT = process.env.PORT || 4000;
const server = http.createServer(app);
const io = require('socket.io')(server, {
origins: '*:*'
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Attach the io instance to the express app object
// to make it accessible from the routes
app.io = io;
io.on('connection', (socket) => {
console.log('New client connected');
});
app.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())
.use(cors({
origin: true,
credentials: true
}))
.use('/', require('./routes'));
// Must use http server as listener rather than express app
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
|
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) require('dotenv').config();
var app = express();
const PORT = process.env.PORT || 4000;
const server = http.createServer(app);
const io = require('socket.io')(server, {
origins: '*:*'
});
// Attach the io instance to the express app object
// to make it accessible from the routes
app.io = io;
io.on('connection', (socket) => {
console.log('New client connected');
});
app.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())
.use(cors({
origin: true,
credentials: true
}))
.use('/', require('./routes'));
// Must use http server as listener rather than express app
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
|
Correct path to util submodule.
|
var _ = require('underscore')
, proxy = require(__dirname + '/src/proxy')
, callbackHandler = require(__dirname + '/src/callbackHandler')
, core = require(__dirname + '/src/core')
, hashcore = require(__dirname + '/src/hash-core')
, listcore = require(__dirname + '/src/list-core')
, model = require(__dirname + '/src/model')
, remitter = require(__dirname + '/src/redisEmitter.js')
, relay = require(__dirname + '/src/relay.js')
, service = require(__dirname + '/src/service.js')
;
// model proxy enqeues prototype functions to be called. if there is nothing on the target queue, it will start invoking the prototype functions
var log = console.log;
exports.CallbackHandler = callbackHandler.CallbackHandler;
exports.Core = core.Core;
exports.HashCore = hashcore.HashCore;
exports.ListCore = listcore.ListCore;
exports.Model = model.Model;
exports.Proxy = proxy.Proxy;
exports.redisClient = require(__dirname + '/src/redisClient');
exports.RedisEmitter = remitter.RedisEmitter;
exports.Relay = relay.Relay;
exports.Service = service.Service;
exports.util = require(__dirname + '/src/util');
|
var _ = require('underscore')
, proxy = require(__dirname + '/src/proxy')
, callbackHandler = require(__dirname + '/src/callbackHandler')
, core = require(__dirname + '/src/core')
, hashcore = require(__dirname + '/src/hash-core')
, listcore = require(__dirname + '/src/list-core')
, model = require(__dirname + '/src/model')
, remitter = require(__dirname + '/src/redisEmitter.js')
, relay = require(__dirname + '/src/relay.js')
, service = require(__dirname + '/src/service.js')
;
// model proxy enqeues prototype functions to be called. if there is nothing on the target queue, it will start invoking the prototype functions
var log = console.log;
exports.CallbackHandler = callbackHandler.CallbackHandler;
exports.Core = core.Core;
exports.HashCore = hashcore.HashCore;
exports.ListCore = listcore.ListCore;
exports.Model = model.Model;
exports.Proxy = proxy.Proxy;
exports.redisClient = require(__dirname + '/src/redisClient');
exports.RedisEmitter = remitter.RedisEmitter;
exports.Relay = relay.Relay;
exports.Service = service.Service;
exports.util = require(__dirname + 'src/util');
|
Change bypass logic to be more flexible on authentication middleware
|
const jwt = require('jsonwebtoken')
const config = require('config')
const isBypassed = (req) => {
const bypassed = [
{
'path': '/auth',
'method': 'POST'
},
{
'path': '/users',
'method': 'POST'
}
]
return bypassed.filter((item) => {
return req.path === item.path && req.method === item.method
}).length
}
const authMiddleware = (req, res, next) => {
if (isBypassed(req)) { return next() }
const token = req.header('Authorization')
console.log('[AUTHENTICATION] Authenticating...')
jwt.verify(token, config.get('secret'), (error, decoded) => {
if (error) {
console.log('[AUTHENTICATION] Authentication failure :(')
return res.status(401).send({
user: {
errors: {
token: 'O token informado não é válido'
}
}
})
}
console.log('[AUTHENTICATION] Authenticated :)')
next()
})
}
module.exports = authMiddleware
|
const jwt = require('jsonwebtoken')
const config = require('config')
const authMiddleware = (req, res, next) => {
if (req.path === '/auth') { return next() }
const token = req.header('Authorization')
console.log('[AUTHENTICATION] Authenticating...')
jwt.verify(token, config.get('secret'), (error, decoded) => {
if (error) {
console.log('[AUTHENTICATION] Authentication failure :(')
return res.send({
user: {
errors: {
token: 'O token informado não é válido'
}
}
})
}
console.log('[AUTHENTICATION] Authenticated :)')
next()
})
}
module.exports = authMiddleware
|
Allow to set body and headers
|
const http = require("http");
/**
* Sends an HTTP request to the server and returns a Promise which resolve
* with the HTTP response containing the body too.
*
* @param {String} host
* @param {String} port
* @param {String} method
* @param {String} path
* @return {Promise}
*/
module.exports.request = (host, port, method, path, headers, body) => {
return new Promise((resolve, reject) => {
const req = http.request({ host: host, port: port, method: method, headers: headers, path: path }, (res) => {
res.body = "";
res.on("data", (chunk) => {
res.body += chunk;
});
res.on("end", () => {
resolve(res);
});
});
req.on("error", (err) => {
reject(err);
});
if (body) {
req.write(body);
}
req.end();
});
};
|
const http = require("http");
/**
* Sends an HTTP request to the server and returns a Promise which resolve
* with the HTTP response containing the body too.
*
* @param {String} host
* @param {String} port
* @param {String} method
* @param {String} path
* @return {Promise}
*/
module.exports.request = (host, port, method, path) => {
return new Promise((resolve, reject) => {
const req = http.request({ host: host, port: port, method: method, path: path }, (res) => {
res.body = "";
res.on("data", (chunk) => {
res.body += chunk;
});
res.on("end", () => {
resolve(res);
});
});
req.on("error", (err) => {
reject(err);
});
req.end();
});
};
|
Add handling to InvalidChannelNameError for generating reply messages for several other commands
|
var
extend = req('/lib/utilities/extend'),
BaseError = req('/lib/errors/base'),
ErrorCodes = req('/lib/constants/error-codes'),
ErrorReasons = req('/lib/constants/error-reasons'),
createMessage = req('/lib/utilities/create-message'),
ReplyNumerics = req('/lib/constants/reply-numerics'),
Commands = req('/lib/constants/commands');
class InvalidChannelNameError extends BaseError {
getBody() {
switch (this.reason) {
case ErrorReasons.OMITTED:
return 'You must specify a channel name';
case ErrorReasons.INVALID_CHARACTERS:
return 'Invalid channel name: ' + this.getChannelName();
case ErrorReasons.NOT_FOUND:
return 'Channel did not exist: ' + this.getChannelName();
default:
return 'Invalid channel name: ' + this.reason;
}
}
getChannelName() {
return this.value;
}
toMessage() {
var command = this.getCommand();
switch (command) {
case Commands.JOIN:
case Commands.MODE:
case Commands.PART:
let message = createMessage(ReplyNumerics.ERR_NOSUCHCHANNEL);
return message.setChannelName(this.getValue());
default:
throw new Error('implement');
}
}
}
extend(InvalidChannelNameError.prototype, {
code: ErrorCodes.INVALID_CHANNEL_NAME
});
module.exports = InvalidChannelNameError;
|
var
extend = req('/lib/utilities/extend'),
BaseError = req('/lib/errors/base'),
ErrorCodes = req('/lib/constants/error-codes'),
ErrorReasons = req('/lib/constants/error-reasons'),
createMessage = req('/lib/utilities/create-message'),
ReplyNumerics = req('/lib/constants/reply-numerics'),
Commands = req('/lib/constants/commands');
class InvalidChannelNameError extends BaseError {
getBody() {
switch (this.reason) {
case ErrorReasons.OMITTED:
return 'You must specify a channel name';
case ErrorReasons.INVALID_CHARACTERS:
return 'Invalid channel name: ' + this.getChannelName();
case ErrorReasons.NOT_FOUND:
return 'Channel did not exist: ' + this.getChannelName();
default:
return 'Invalid channel name: ' + this.reason;
}
}
getChannelName() {
return this.value;
}
toMessage() {
var command = this.getCommand();
switch (command) {
case Commands.MODE:
let message = createMessage(ReplyNumerics.ERR_NOSUCHCHANNEL);
return message.setChannelName(this.getValue());
default:
throw new Error('implement');
}
}
}
extend(InvalidChannelNameError.prototype, {
code: ErrorCodes.INVALID_CHANNEL_NAME
});
module.exports = InvalidChannelNameError;
|
Add single-quotes setting to scss
|
import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
"ignore": [ "node_modules", ".git" ]
}
def parseModuleKey(self, value):
if "/" in value:
if value.startswith("./"):
value = value[2:]
if path.basename(value).startswith("_"):
value = path.join(path.dirname(value), path.basename(value)[1:])
return super().parseModuleKey(value)
def onSearchResultChosen(self, interpreted, option_key, value, mode=SIMode.REPLACE_MODE):
if option_key == "extra_files":
interpreted.handler_name = "file"
super().onSearchResultChosen(interpreted, option_key, value, mode)
def stringifyStatements(self, statements, handler_name=None, insert_type=Interpreted.IT_REPLACE):
if handler_name == "file":
return "url({0})".format(statements["module"])
if self.getSetting("single-quotes"):
return "@import \'{0}\';".format(statements["module"])
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpreted):
return {
"file": interpreted.statements["module"]
}
|
import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
"ignore": [ "node_modules", ".git" ]
}
def parseModuleKey(self, value):
if "/" in value:
if value.startswith("./"):
value = value[2:]
if path.basename(value).startswith("_"):
value = path.join(path.dirname(value), path.basename(value)[1:])
return super().parseModuleKey(value)
def onSearchResultChosen(self, interpreted, option_key, value, mode=SIMode.REPLACE_MODE):
if option_key == "extra_files":
interpreted.handler_name = "file"
super().onSearchResultChosen(interpreted, option_key, value, mode)
def stringifyStatements(self, statements, handler_name=None, insert_type=Interpreted.IT_REPLACE):
if handler_name == "file":
return "url({0})".format(statements["module"])
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpreted):
return {
"file": interpreted.statements["module"]
}
|
Update length of Times to go to 10pm
|
import React, { Component, PropTypes } from 'react';
export default class TimeColumn extends Component {
// static propTypes = {
// times: PropTypes.array.isRequired
// };
render() {
const hours = ['12', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const minutes = ['00', '15', '30', '45']
const times = _.flatten(hours.map((hour) => {
return minutes.map((min) => {
return `${hour}:${min}`;
});
}));
const timesToRender = times.map((ts, i) => {
return <li key={i}>{ts}</li>;
});
return <div>
<h1>Times</h1>
<ul>
{timesToRender}
</ul>
</div>;
}
}
|
import React, { Component, PropTypes } from 'react';
export default class TimeColumn extends Component {
// static propTypes = {
// times: PropTypes.array.isRequired
// };
render() {
const hours = ['12', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];
const minutes = ['00', '15', '30', '45']
const times = _.flatten(hours.map((hour) => {
return minutes.map((min) => {
return `${hour}:${min}`;
});
}));
const timesToRender = times.map((ts, i) => {
return <li key={i}>{ts}</li>;
});
return <div>
<h1>Times</h1>
<ul>
{timesToRender}
</ul>
</div>;
}
}
|
Fix point of importing module
|
#!/usr/bin/env python
import setuptools
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
import shakyo
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
|
#!/usr/bin/env python
import setuptools
import shakyo
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
|
Revert "Enable v1.3.0 on the development channel"
This reverts commit a252c7d19a9149b8c1d9bc0ec4788ae1bb3c6b22.
|
{
"stable": {
"CSIDE_version": "1.2.1",
"nw_version": "0.21.4",
"desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
},
"latest": {
"CSIDE_version": "1.2.1",
"nw_version": "0.21.4",
"desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
},
"development": {
"CSIDE_version": "1.2.1",
"nw_version": "0.21.4",
"desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
},
"accessible": {
"CSIDE_version": "1.1.2",
"nw_version": "0.21.4",
"desc": "",
"target": ""
}
}
|
{
"stable": {
"CSIDE_version": "1.2.1",
"nw_version": "0.21.4",
"desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
},
"latest": {
"CSIDE_version": "1.2.1",
"nw_version": "0.21.4",
"desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
},
"development": {
"CSIDE_version": "1.3.0",
"nw_version": "0.21.4",
"desc": "v1.3.0 Feature release: User dictionary improvements, custom themes and bug fixes.",
"target": "https://choicescriptide.github.io/downloads/updates/targets/130.zip"
},
"accessible": {
"CSIDE_version": "1.1.2",
"nw_version": "0.21.4",
"desc": "",
"target": ""
}
}
|
Fix typehint that is invalid in python 3.8
|
from typing import List
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
|
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> list[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
|
gui: Move global map url before session url.
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
Set published date so the posts come in order.
|
import feedparser, sys, urllib2
from bs4 import BeautifulSoup as BS
from feedgen.feed import FeedGenerator
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
d = feedparser.parse('http://thecodinglove.com/rss')
fg = FeedGenerator()
fg.title('The coding love with images.')
fg.link(href='http://thecodinglove.com')
fg.description('The coding love with images.')
for entry in d.entries:
title = entry.title
href = entry.links[0].href
bs = BS(urllib2.urlopen(href), "lxml")
published = entry.published
image = bs.p.img.get('src')
imgsrc='<img src="%s">' % image
fe = fg.add_entry()
fe.id(href)
fe.link(href=href)
fe.pubdate(published)
fe.title(title)
fe.description(imgsrc)
rssfeed = fg.rss_str(pretty=True)
return rssfeed
|
import feedparser, sys, urllib2
from bs4 import BeautifulSoup as BS
from feedgen.feed import FeedGenerator
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
d = feedparser.parse('http://thecodinglove.com/rss')
fg = FeedGenerator()
fg.title('The coding love with images.')
fg.link(href='http://thecodinglove.com')
fg.description('The coding love with images.')
for entry in d.entries:
title = entry.title
href = entry.links[0].href
bs = BS(urllib2.urlopen(href), "lxml")
image = bs.p.img.get('src')
imgsrc='<img src="%s">' % image
fe = fg.add_entry()
fe.id(href)
fe.link(href=href)
fe.title(title)
fe.description(imgsrc)
rssfeed = fg.rss_str(pretty=True)
return rssfeed
|
Sort trains by stop order as a default
|
var mongoose = require( "mongoose" );
var Schema = mongoose.Schema;
var TransitStopSchema = Schema ( {
system: String,
name: String,
latitude: Number,
longitude: Number,
route_id: String,
route_name: String,
route_type: String,
route_direction: String,
route_direction_slug: String
} );
TransitStopSchema.index( {
system: 1,
route_type: 1,
route_id: 1,
route_direction_slug: 1
} );
TransitStopSchema.statics.forTrain = function ( filter, done ) {
filter.route_type = "train";
this.find( filter )
.select( "name latitude longitude system route_direction stop_order" )
.sort( {
route_id: 1,
stop_order: 1
} )
.exec( done );
};
TransitStopSchema.statics.forBus = function ( filter, done ) {
filter.route_type = "bus";
this.find( filter )
.select( "name latitude longitude system route_direction" )
.sort( { name: 1 } )
.exec( done );
};
exports.TransitStop = mongoose.model( "transit_stops", TransitStopSchema );
|
var mongoose = require( "mongoose" );
var Schema = mongoose.Schema;
var TransitStopSchema = Schema ( {
system: String,
name: String,
latitude: Number,
longitude: Number,
route_id: String,
route_name: String,
route_type: String,
route_direction: String,
route_direction_slug: String
} );
TransitStopSchema.index( {
system: 1,
route_type: 1,
route_id: 1,
route_direction_slug: 1
} );
TransitStopSchema.statics.forTrain = function ( filter, done ) {
filter.route_type = "train";
this.find( filter )
.select( "name latitude longitude system route_direction" )
.sort( { name: 1 } )
.exec( done );
};
TransitStopSchema.statics.forBus = function ( filter, done ) {
filter.route_type = "bus";
this.find( filter )
.select( "name latitude longitude system route_direction" )
.sort( { name: 1 } )
.exec( done );
};
exports.TransitStop = mongoose.model( "transit_stops", TransitStopSchema );
|
Fix merge array Ancestors (RBAC)
|
<?php
/**
* @link http://www.letyii.com/
* @copyright Copyright (c) 2014 Let.,ltd
* @license https://github.com/letyii/cms/blob/master/LICENSE
* @author Ngua Go <nguago@let.vn>, CongTS <congts.vn@gmail.com>
*/
namespace app\modules\member\models;
use yii\helpers\ArrayHelper;
use Yii;
class LetAuthItemChild extends base\LetAuthItemChildBase
{
public static function getAncestors($items = [], $result = []) {
// Get parent list of $item
$list = self::find()->select('parent')->where(['child' => $items])->asArray()->all();
$list = ArrayHelper::map($list, 'parent', 'parent');
$list = array_values($list);
$result = array_merge($result, $list);
if (!empty($list)) {
return self::getAncestors($list, $result);
} else {
return $result;
}
}
}
|
<?php
/**
* @link http://www.letyii.com/
* @copyright Copyright (c) 2014 Let.,ltd
* @license https://github.com/letyii/cms/blob/master/LICENSE
* @author Ngua Go <nguago@let.vn>, CongTS <congts.vn@gmail.com>
*/
namespace app\modules\member\models;
use Yii;
class LetAuthItemChild extends base\LetAuthItemChildBase
{
public static function getAncestors($items = [], $result = []) {
// Get parent list of $item
$list = self::find()->select('parent')->where(['child' => $items])->asArray()->all();
$list = \yii\helpers\ArrayHelper::map($list, 'parent', 'parent');
$result += $list;
if (!empty($list)) {
return self::getAncestors($list, $result);
} else {
return $result;
}
}
}
|
Move XMP init into setUp()
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to
from blister.xmp import XMP
class XMPTest (unittest.TestCase):
def setUp (self):
self.xmp = XMP()
def test_degenerate (self):
assert_that(self.xmp, evaluates_to(False))
assert_that(self.xmp, has_length(0))
assert_that(list(self.xmp), is_(equal_to([])))
def test_not_all_attrs_exist (self):
assert_that(calling(getattr).with_args(self.xmp,
"fake_namespace"),
raises(AttributeError))
assert_that(calling(getattr).with_args(self.xmp, "also_fake"),
raises(AttributeError))
def test_default_xmp_namespaces_exist (self):
no_error = self.xmp.stRef
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to
from blister.xmp import XMP
class XMPTest (unittest.TestCase):
def test_degenerate (self):
xmp = XMP()
assert_that(xmp, evaluates_to(False))
assert_that(xmp, has_length(0))
assert_that(list(xmp), is_(equal_to([])))
def test_not_all_attrs_exist (self):
xmp = XMP()
assert_that(calling(getattr).with_args(xmp, "fake_namespace"),
raises(AttributeError))
assert_that(calling(getattr).with_args(xmp, "also_fake"),
raises(AttributeError))
def test_default_xmp_namespaces_exist (self):
xmp = XMP()
no_error = xmp.stRef
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.