text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add a bug link field
|
from django.db import models
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=200)
language = models.CharField(max_length=200)
icon_url = models.URLField(max_length=200)
class Bug(models.Model):
project = models.ForeignKey(Project)
title = models.CharField(max_length=200)
description = models.TextField()
status = models.CharField(max_length=200)
importance = models.CharField(max_length=200)
people_involved = models.IntegerField()
date_reported = models.DateTimeField()
last_touched = models.DateTimeField()
last_polled = models.DateTimeField()
submitter_username = models.CharField(max_length=200)
submitter_realname = models.CharField(max_length=200)
canonical_bug_link = models.URLField(max_length=200)
|
from django.db import models
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=200)
language = models.CharField(max_length=200)
icon_url = models.URLField(max_length=200)
class Bug(models.Model):
project = models.ForeignKey(Project)
title = models.CharField(max_length=200)
description = models.TextField()
status = models.CharField(max_length=200)
importance = models.CharField(max_length=200)
people_involved = models.IntegerField()
date_reported = models.DateTimeField()
last_touched = models.DateTimeField()
last_polled = models.DateTimeField()
submitter_username = models.CharField(max_length=200)
submitter_realname = models.CharField(max_length=200)
|
Add totalCount on contact.
Remove excess new line.
|
<?php
namespace Yajra\Datatables\Contracts;
interface DataTableEngineContract
{
/**
* Get results
*
* @return mixed
*/
public function results();
/**
* Count results
*
* @return integer
*/
public function count();
/**
* Count total items.
*
* @return integer
*/
public function totalCount();
/**
* Set auto filter off and run your own filter.
* Overrides global search
*
* @param \Closure $callback
* @return $this
*/
public function filter(\Closure $callback);
/**
* Perform global search
*
* @return void
*/
public function filtering();
/**
* Perform column search
*
* @return void
*/
public function columnSearch();
/**
* Perform pagination
*
* @return void
*/
public function paging();
/**
* Perform sorting of columns
*
* @return void
*/
public function ordering();
/**
* Organizes works
*
* @param bool $mDataSupport
* @return \Illuminate\Http\JsonResponse
*/
public function make($mDataSupport = false);
}
|
<?php
namespace Yajra\Datatables\Contracts;
interface DataTableEngineContract
{
/**
* Get results
*
* @return mixed
*/
public function results();
/**
* Count results
*
* @return integer
*/
public function count();
/**
* Set auto filter off and run your own filter.
* Overrides global search
*
* @param \Closure $callback
* @return $this
*/
public function filter(\Closure $callback);
/**
* Perform global search
*
* @return void
*/
public function filtering();
/**
* Perform column search
*
* @return void
*/
public function columnSearch();
/**
* Perform pagination
*
* @return void
*/
public function paging();
/**
* Perform sorting of columns
*
* @return void
*/
public function ordering();
/**
* Organizes works
*
* @param bool $mDataSupport
* @return \Illuminate\Http\JsonResponse
*/
public function make($mDataSupport = false);
}
|
Remove performance link from features nav
The features nav is supposed to navigate your between pages in the app.
It’s very unexpected to have it open an external link.
Performance isn’t strictly a part of Support, but it’s worked having it
there for long enough that it’s probably not a bother.
|
def features_nav():
return [
{
"name": "Features",
"link": "main.features",
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Security",
"link": "main.security",
},
{
"name": "Terms of use",
"link": "main.terms",
},
{
"name": "Using Notify",
"link": "main.using_notify",
},
]
|
def features_nav():
return [
{
"name": "Features",
"link": "main.features",
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Security",
"link": "main.security",
},
{
"name": "Performance",
"link": "https://www.gov.uk/performance/govuk-notify",
"external_link": True,
},
{
"name": "Terms of use",
"link": "main.terms",
},
{
"name": "Using Notify",
"link": "main.using_notify",
},
]
|
Fix bug with email attachments
|
<?php
namespace Ice\MailerBundle\PreCompiler;
use Ice\MailerBundle\Attachment\Attachment;
use Ice\MailerBundle\Attachment\AttachmentException;
use Ice\MailerBundle\Attachment\AttachmentFactory;
use Ice\MailerBundle\Attachment\AttachmentKeyCDN;
use Ice\MailerBundle\Event\PreCompileEvent;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class AttachmentInformation
* @package Ice\MailerBundle\PreCompiler
*/
class AttachmentInformation
{
/**
*
* @param PreCompileEvent $event
* @throws AttachmentException
*/
public function onPreCompile(PreCompileEvent $event)
{
$vars = $event->getTemplate()->getVars();
/** @var \Ice\MailerBundle\Entity\Mail $mail */
$mail = $event->getMail();
if (isset($vars['attachments']) && count($vars['attachments'])) {
$attachmentsInstances = [];
foreach ($vars['attachments'] as $i => $attach) {
$attachment = AttachmentFactory::build($attach);
$attachmentsInstances[] = $attachment;
}
$mail->setAttachments(new ArrayCollection($attachmentsInstances));
}
}
}
|
<?php
namespace Ice\MailerBundle\PreCompiler;
use Ice\MailerBundle\Attachment\Attachment;
use Ice\MailerBundle\Attachment\AttachmentException;
use Ice\MailerBundle\Attachment\AttachmentFactory;
use Ice\MailerBundle\Attachment\AttachmentKeyCDN;
use Ice\MailerBundle\Event\PreCompileEvent;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class AttachmentInformation
* @package Ice\MailerBundle\PreCompiler
*/
class AttachmentInformation
{
/**
*
* @param PreCompileEvent $event
* @throws AttachmentException
*/
public function onPreCompile(PreCompileEvent $event)
{
$vars = $event->getTemplate()->getVars();
/** @var \Ice\MailerBundle\Entity\Mail $mail */
$mail = $event->getMail();
if ($vars['attachments']) {
$attachmentsInstances = [];
foreach ($vars['attachments'] as $i => $attach) {
$attachment = AttachmentFactory::build($attach);
$attachmentsInstances[] = $attachment;
}
$mail->setAttachments(new ArrayCollection($attachmentsInstances));
}
}
}
|
Fix after build script for other platforms
|
const { resolve, extname } = require('path')
const { copyFileSync, readdirSync } = require('fs')
const NATIVE_ADDON_RELEASE_PATH = resolve(__dirname, '..', 'bindings', 'build', 'Release')
const BUNDLE_PATH = resolve(__dirname, '..', 'dist', 'bundled')
const actions = {
win32: windows
}
function windows () {
const nativeFiles = readdirSync(NATIVE_ADDON_RELEASE_PATH)
nativeFiles.forEach((filename) => {
if (['.dll', '.lib'].includes(extname(filename))) {
console.log(`Moving ${filename} to ${BUNDLE_PATH}`)
copyFileSync(
resolve(NATIVE_ADDON_RELEASE_PATH, filename),
resolve(BUNDLE_PATH, filename)
)
}
})
}
(
actions[process.platform] || (() => {})
)()
|
const { resolve, extname } = require('path')
const { copyFileSync, readdirSync } = require('fs')
const NATIVE_ADDON_RELEASE_PATH = resolve(__dirname, '..', 'bindings', 'build', 'Release')
const BUNDLE_PATH = resolve(__dirname, '..', 'dist', 'bundled')
const actions = {
win32: windows
}
function windows () {
const nativeFiles = readdirSync(NATIVE_ADDON_RELEASE_PATH)
nativeFiles.forEach((filename) => {
if (['.dll', '.lib'].includes(extname(filename))) {
console.log(`Moving ${filename} to ${BUNDLE_PATH}`)
copyFileSync(
resolve(NATIVE_ADDON_RELEASE_PATH, filename),
resolve(BUNDLE_PATH, filename)
)
}
})
}
module.exports = actions[process.platform]()
|
Add hapi extension to redirect route.
New behavior looks at query string for keyword 'hapi_method'. The value will override the current route-method.
This is currently used to map http-POST requests to PUT-defined routes.
Ideally, a form-value would be used to do the same thing, but there does not appear to be a way to read
form-values early in the request pipeline.
Hapi authors does not too keen to add this feature: https://github.com/hapijs/hapi/issues/1217
|
import Hapi from 'hapi'
import Path from 'path'
import controllers from './controllers/index'
import _ from './extensions'
import Lazy from 'lazy.js'
spawnServer('App', 3000, controllers, {
engines: {
hbs: require('handlebars')
},
path: Path.join(__dirname, './views'),
layoutPath: Path.join(__dirname, './views/layouts'),
layout: 'layout'
})
function spawnServer(name, port, controllers, viewOptions) {
var server = new Hapi.Server()
server.connection({
port
})
if (viewOptions)
server.views(viewOptions);
server.ext('onRequest', function (request, reply) {
var methodOverride = request.query['hapi_method'];
if (methodOverride) {
request.setMethod(methodOverride);
}
return reply.continue();
});
controllers(server)
server.start(() => {
console.log(name + ' server running at:', server.info.uri)
outputRoutes(server)
})
}
function outputRoutes(server) {
console.log('Available Routes:')
Lazy(server.table()[0].table)
.map(route => route.method + ' ' + route.path)
.sort()
.each(e => console.log(e))
}
|
import Hapi from 'hapi'
import Path from 'path'
import controllers from './controllers/index'
import _ from './extensions'
import Lazy from 'lazy.js'
spawnServer('App', 3000, controllers, {
engines: {
hbs: require('handlebars')
},
path: Path.join(__dirname, './views'),
layoutPath: Path.join(__dirname, './views/layouts'),
layout: 'layout'
})
function spawnServer(name, port, controllers, viewOptions) {
var server = new Hapi.Server()
server.connection({
port
})
if (viewOptions)
server.views(viewOptions);
controllers(server)
server.start(() => {
console.log(name + ' server running at:', server.info.uri)
outputRoutes(server)
})
}
function outputRoutes(server) {
console.log('Available Routes:')
Lazy(server.table()[0].table)
.map(route => route.method + ' ' + route.path)
.sort()
.each(e => console.log(e))
}
|
Use an iterator to get pages
|
from itertools import count
from demands import HTTPServiceClient
from yoconfig import get_config
class CloudFlareService(HTTPServiceClient):
def __init__(self, **kwargs):
config = get_config('cloudflare')
headers = {
'Content-Type': 'application/json',
'X-Auth-Key': config['api_key'],
'X-Auth-Email': config['email']
}
super(CloudFlareService, self).__init__(config['url'], headers=headers)
def iter_zones(self):
for page in count():
batch = self.get('zones?page=%i&per_page=50' % page).json()['result']
if not batch:
return
for result in batch:
yield result
def get_zones(self):
return list(self.iter_zones())
def get_zone(self, zone_id):
return self.get('zones/%s' % zone_id).json()['result']
|
from itertools import count
from demands import HTTPServiceClient
from yoconfig import get_config
class CloudFlareService(HTTPServiceClient):
def __init__(self, **kwargs):
config = get_config('cloudflare')
headers = {
'Content-Type': 'application/json',
'X-Auth-Key': config['api_key'],
'X-Auth-Email': config['email']
}
super(CloudFlareService, self).__init__(config['url'], headers=headers)
def get_zones(self):
zones = []
for page in count():
batch = self.get(
'zones?page=%s&per_page=50' % page).json()['result']
if batch:
zones.extend(batch)
else:
break
return zones
def get_zone(self, zone_id):
return self.get('zones/%s' % zone_id).json()['result']
|
CLEAN simplify example: no need to force Ansi.ON
|
/*
Copyright 2017 Remko Popma
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 picocli;
import org.fusesource.jansi.AnsiConsole;
import picocli.CommandLine.Command;
/**
* Demonstrates usage help with ansi colors on Windows DOS (without Cygwin or MSYS(2)).
* Requires Jansi on the classpath.
*/
@Command(name = "picocli.WindowsJansiDemo")
public class WindowsJansiDemo extends Demo {
public static void main(String[] args) {
// Since https://github.com/remkop/picocli/issues/491 was fixed in picocli 3.6.0,
// Ansi.AUTO is automatically enabled if the AnsiConsole is installed.
AnsiConsole.systemInstall(); // Jansi magic
new CommandLine(new WindowsJansiDemo()).execute(args);
AnsiConsole.systemUninstall();
}
}
|
/*
Copyright 2017 Remko Popma
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 picocli;
import org.fusesource.jansi.AnsiConsole;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Ansi;
/**
* Demonstrates usage help with ansi colors on Windows DOS (without Cygwin or MSYS(2)).
* Requires Jansi on the classpath.
*/
@Command(name = "picocli.WindowsJansiDemo")
public class WindowsJansiDemo extends Demo {
public static void main(String[] args) {
// Since https://github.com/remkop/picocli/issues/491 was fixed in picocli 3.6.0,
// Ansi.AUTO is automatically enabled if the AnsiConsole is installed.
AnsiConsole.systemInstall(); // Jansi magic
new CommandLine(new WindowsJansiDemo())
.setColorScheme(CommandLine.Help.defaultColorScheme(Ansi.ON))
.execute(args);
AnsiConsole.systemUninstall();
}
}
|
Add G Suite verification tag
|
// @flow
import React from 'react'
import Helmet from 'react-helmet'
import PropTypes from 'prop-types'
import Background from '../Background'
import Navbar from '../Navbar'
import { Container } from '../Grid'
import './normalize.css'
import './fonts.css'
import './skeleton.css'
import styles from './styles.module.css'
const Layout = ({ children }) => (
<div className={styles.wrapper}>
<Helmet
title="Kabir Goel"
meta={[
{
name: 'description',
content: '16 year old maker from New Delhi, India.',
},
{
name: 'google-site-verification',
content: 'mYCbMoGP2dt071GwtAtMtstdSx4tkrIBffu2E2fGbOA',
},
]}
htmlAttributes={{ lang: 'en' }}
/>
<Background />
<main>
<Container>
<Navbar />
{children}
</Container>
</main>
</div>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
// @flow
import React from 'react'
import Helmet from 'react-helmet'
import PropTypes from 'prop-types'
import Background from '../Background'
import Navbar from '../Navbar'
import { Container, Row, Column } from '../Grid'
import './normalize.css'
import './fonts.css'
import './skeleton.css'
import styles from './styles.module.css'
const Layout = ({ children }) => (
<div className={styles.wrapper}>
<Helmet
title="Kabir Goel"
meta={[
{
name: 'description',
content: '16 year old maker from New Delhi, India.',
},
]}
htmlAttributes={{ lang: 'en' }}
/>
<Background />
<main>
<Container>
<Navbar />
{children}
</Container>
</main>
</div>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
Update index @ fix livereload port server :+1:
|
<!DOCTYPE html>
<html ng-app="applications" ng-controller="AppController">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="{!! asset('css/vendor.css') !!}">
<link rel="stylesheet" href="{!! asset('css/app.css') !!}">
<link href='//fonts.googleapis.com/css?family=Roboto:500,400' rel='stylesheet' type='text/css'>
<title ng-bind="title"></title>
<!--[if lte IE 10]>
<script type="text/javascript">document.location.href = '/unsupported-browser'</script>
<![endif]-->
</head>
<body>
<div ui-view="layout"></div>
<script src="{!! asset('js/vendor.js') !!}"></script>
<script src="{!! asset('js/app.js') !!}"></script>
{{--livereload--}}
@if ( Config::get('app.debug') )
<script type="text/javascript">
document.write('<script src="'+ location.protocol + '//' + (location.host || 'localhost') +':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')
</script>
@endif
</body>
</html>
{{--Created by anonymoussc on 22/11/15 4:12.--}}
|
<!DOCTYPE html>
<html ng-app="applications" ng-controller="AppController">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="{!! asset('css/vendor.css') !!}">
<link rel="stylesheet" href="{!! asset('css/app.css') !!}">
<link href='//fonts.googleapis.com/css?family=Roboto:500,400' rel='stylesheet' type='text/css'>
<title ng-bind="title"></title>
<!--[if lte IE 10]>
<script type="text/javascript">document.location.href = '/unsupported-browser'</script>
<![endif]-->
</head>
<body>
<div ui-view="layout"></div>
<script src="{!! asset('js/vendor.js') !!}"></script>
<script src="{!! asset('js/app.js') !!}"></script>
{{--livereload--}}
@if ( Config::get('app.debug') )
<script type="text/javascript">
document.write('<script src="'+ location.protocol + '//' + (location.host || 'localhost') +':8000/livereload.js?snipver=1" type="text/javascript"><\/script>')
</script>
@endif
</body>
</html>
{{--Created by anonymoussc on 22/11/15 4:12.--}}
|
Use http agent for kubecross version retrieval
This agent allows retries and should be more future proof.
Signed-off-by: Sascha Grunert <70ab469ddb2ac3e35f32ed7c2fd1cca514b2e879@redhat.com>
|
/*
Copyright 2021 The Kubernetes 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 kubecross
import (
"bytes"
"sigs.k8s.io/release-utils/http"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//counterfeiter:generate . impl
type impl interface {
GetURLResponse(url string, trim bool) (string, error)
}
type defaultImpl struct{}
func (*defaultImpl) GetURLResponse(url string, trim bool) (string, error) {
content, err := http.NewAgent().Get(url)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(content)), nil
}
|
/*
Copyright 2021 The Kubernetes 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 kubecross
import "sigs.k8s.io/release-utils/http"
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//counterfeiter:generate . impl
type impl interface {
GetURLResponse(url string, trim bool) (string, error)
}
type defaultImpl struct{}
func (*defaultImpl) GetURLResponse(url string, trim bool) (string, error) {
return http.GetURLResponse(url, trim)
}
|
Remove selector method because it's not needed.
|
export default {
/* jshint expr: true */
create (opts) {
var elem = document.createElement(opts.extends || opts.id);
opts.extends && elem.setAttribute('is', opts.id);
return elem;
},
filterDefinitions (elem, defs) {
var attrs = elem.attributes;
var definitions = [];
var isAttr = attrs.is;
var isAttrValue = isAttr && (isAttr.value || isAttr.nodeValue);
var tag = elem.tagName.toLowerCase();
var definition = defs[isAttrValue || tag];
if (definition && definition.type === this) {
let tagToExtend = definition.extends;
if (isAttrValue) {
if (tag === tagToExtend) {
definitions.push(definition);
}
} else if (!tagToExtend) {
definitions.push(definition);
}
}
return definitions;
}
};
|
export default {
/* jshint expr: true */
create (opts) {
var elem = document.createElement(opts.extends || opts.id);
opts.extends && elem.setAttribute('is', opts.id);
return elem;
},
filterDefinitions (elem, defs) {
var attrs = elem.attributes;
var definitions = [];
var isAttr = attrs.is;
var isAttrValue = isAttr && (isAttr.value || isAttr.nodeValue);
var tag = elem.tagName.toLowerCase();
var definition = defs[isAttrValue || tag];
if (definition && definition.type === this) {
let tagToExtend = definition.extends;
if (isAttrValue) {
if (tag === tagToExtend) {
definitions.push(definition);
}
} else if (!tagToExtend) {
definitions.push(definition);
}
}
return definitions;
},
selector (opts) {
return opts.extends ? `${opts.extends}[is="${opts.id}"]` : opts.id;
}
};
|
Fix name (copy paste fail...)
|
import json
from ppp_nlp_classical import Triple, TriplesBucket, computeTree, simplify, buildBucket, DependenciesTree, tripleProduce1, tripleProduce2, tripleProduce3, buildTree
from ppp_datamodel import Triple, Resource, Missing
import data
from unittest import TestCase
class StandardTripleTests(TestCase):
def testBuildFromBucket(self):
tree = computeTree(data.give_president_of_USA()['sentences'][0])
qw = simplify(tree)
triple = buildTree(buildBucket(tree,qw))
self.assertIsInstance(triple,Triple)
self.assertEqual(triple.get("predicate"),Resource("identity"))
self.assertEqual(triple.get("object"),Missing())
subj=triple.get("subject")
self.assertEqual(subj.get("subject"),Missing())
self.assertEqual(subj.get("predicate"),Resource("president of"))
self.assertEqual(subj.get("object"),Resource("United States"))
|
import json
from ppp_nlp_classical import Triple, TriplesBucket, computeTree, simplify, buildBucket, DependenciesTree, tripleProduce1, tripleProduce2, tripleProduce3, buildTree
from ppp_datamodel import Triple, Resource, Missing
import data
from unittest import TestCase
class StandardTripleTests(TestCase):
def testBuildBucket(self):
tree = computeTree(data.give_president_of_USA()['sentences'][0])
qw = simplify(tree)
triple = buildTree(buildBucket(tree,qw))
self.assertIsInstance(triple,Triple)
self.assertEqual(triple.get("predicate"),Resource("identity"))
self.assertEqual(triple.get("object"),Missing())
subj=triple.get("subject")
self.assertEqual(subj.get("subject"),Missing())
self.assertEqual(subj.get("predicate"),Resource("president of"))
self.assertEqual(subj.get("object"),Resource("United States"))
|
Ch03: Add options to Startup model fields. [skip ci]
Field options allow us to easily customize behavior of a field.
Global Field Options:
https://docs.djangoproject.com/en/1.8/ref/models/fields/#db-index
https://docs.djangoproject.com/en/1.8/ref/models/fields/#help-text
https://docs.djangoproject.com/en/1.8/ref/models/fields/#unique
https://docs.djangoproject.com/en/1.8/ref/models/fields/#verbose-name
Verbose names are further documented in:
https://docs.djangoproject.com/en/1.8/topics/db/models/#verbose-field-names
The max_length field option is defined in CharField and inherited by all
CharField subclasses (but is typically optional in these subclasses,
unlike CharField itself).
The 255 character limit of the URLField is based on RFC 3986.
https://tools.ietf.org/html/rfc3986
|
from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Startup(models.Model):
name = models.CharField(
max_length=31, db_index=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
description = models.TextField()
founded_date = models.DateField(
'date founded')
contact = models.EmailField()
website = models.URLField(max_length=255)
tags = models.ManyToManyField(Tag)
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField('date published')
link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup)
|
from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Startup(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
description = models.TextField()
founded_date = models.DateField()
contact = models.EmailField()
website = models.URLField()
tags = models.ManyToManyField(Tag)
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField('date published')
link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup)
|
Read query prarms for lat, long and date.
|
var express = require('express');
var xml = require('xml');
var app = express();
var suncalc = require('suncalc');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sunrisedb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function callback() {
console.log('multivision db opened');
});
app.get('/xml', function(req, res) {
var xmlresult = {
APe: "35", Mandis: "32"
};
res.set('Content-Type', 'text/xml');
res.send(xml(xmlresult));
});
app.get('*', function(req, res) {
var lat = req.query.lat;
var lon = req.query.lon;
var date = new Date(req.query.date);
var times = suncalc.getTimes(date, lat, lon);
res.json(times);
});
var port = 3000;
app.listen(port);
console.log('Listen on port: ' + port + '...');
|
var express = require('express');
var xml = require('xml');
var app = express();
var suncalc = require('suncalc');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sunrisedb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function callback() {
console.log('multivision db opened');
});
app.get('/xml', function(req, res) {
var xmlresult = {
APe: "35", Mandis: "32"
};
res.set('Content-Type', 'text/xml');
res.send(xml(xmlresult));
});
app.get('*', function(req, res) {
// get today's sunlight times for London
var times = suncalc.getTimes(new Date(), 59.313, 18.065);
res.json(times);
});
var port = 3000;
app.listen(port);
console.log('Listen on port: ' + port + '...');
|
Remove unnecessary call to collapse the accordion
bootstrap does that for us
|
// Javascript specific to guide admin
$(function() {
var sortable_opts = {
axis: "y",
handle: "a.accordion-toggle",
stop: function(event, ui) {
$('.part').each(function (i, elem) {
$(elem).find('input.order').val(i + 1);
ui.item.find("a.accordion-toggle").addClass("highlight");
setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 )
});
}
}
$('#parts').sortable(sortable_opts)
.find("a.accordion-toggle").css({cursor: 'move'});
// simulate a click on the first part to open it
$('#parts .part .accordion-body').first().collapse('show');
$('input.title').
live('change', function () {
var elem = $(this);
var value = elem.val();
// Set slug on change.
var slug_field = elem.closest('.part').find('.slug');
if (slug_field.text() === '') {
slug_field.val(GovUKGuideUtils.convertToSlug(value));
}
// Set header on change.
var header = elem.closest('fieldset').prev('h3').find('a');
header.text(value);
});
});
|
// Javascript specific to guide admin
$(function() {
// collapse the parts using the bootstrap accordion
$(".collapse").collapse();
var sortable_opts = {
axis: "y",
handle: "a.accordion-toggle",
stop: function(event, ui) {
$('.part').each(function (i, elem) {
$(elem).find('input.order').val(i + 1);
ui.item.find("a.accordion-toggle").addClass("highlight");
setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 )
});
}
}
$('#parts').sortable(sortable_opts)
.find("a.accordion-toggle").css({cursor: 'move'});
// simulate a click on the first part to open it
$('#parts .part .accordion-body').first().collapse('show');
$('input.title').
live('change', function () {
var elem = $(this);
var value = elem.val();
// Set slug on change.
var slug_field = elem.closest('.part').find('.slug');
if (slug_field.text() === '') {
slug_field.val(GovUKGuideUtils.convertToSlug(value));
}
// Set header on change.
var header = elem.closest('fieldset').prev('h3').find('a');
header.text(value);
});
});
|
Move check to constructor for faster failure
|
package org.ambraproject.rhino.view.asset;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import org.ambraproject.models.ArticleAsset;
import org.ambraproject.rhino.identity.AssetIdentity;
import org.ambraproject.rhino.view.JsonOutputView;
import java.util.Collection;
import java.util.List;
public class AssetsAsFigureView implements JsonOutputView {
private final ImmutableList<ArticleAsset> assets;
private final Figure figure;
public AssetsAsFigureView(Collection<ArticleAsset> assets) {
this.assets = ImmutableList.copyOf(assets);
List<Figure> figures = Figure.listFigures(this.assets);
if (figures.size() != 1) {
String message = "ArticleAsset objects passed to AssetsAsFigureView must all have one DOI in common";
throw new IllegalArgumentException(message);
}
this.figure = figures.get(0);
}
@Override
public JsonElement serialize(JsonSerializationContext context) {
AssetIdentity assetId = figure.getId();
ArticleAsset original = figure.getOriginal();
JsonObject serialized = new JsonObject();
serialized.addProperty("doi", assetId.getIdentifier());
serialized.addProperty("contextElement", original.getContextElement());
serialized.addProperty("title", original.getTitle());
serialized.addProperty("description", original.getDescription());
serialized.add("assetfiles", context.serialize(new AssetFileCollectionView(assets)));
return serialized;
}
}
|
package org.ambraproject.rhino.view.asset;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import org.ambraproject.models.ArticleAsset;
import org.ambraproject.rhino.identity.AssetIdentity;
import org.ambraproject.rhino.view.JsonOutputView;
import java.util.Collection;
import java.util.List;
public class AssetsAsFigureView implements JsonOutputView {
private final ImmutableList<ArticleAsset> assets;
public AssetsAsFigureView(Collection<ArticleAsset> assets) {
this.assets = ImmutableList.copyOf(assets);
}
@Override
public JsonElement serialize(JsonSerializationContext context) {
List<Figure> figures = Figure.listFigures(assets);
if (figures.size() != 1) {
throw new RuntimeException("Expected exactly one figure among supplied assets");
}
Figure figure = figures.get(0);
AssetIdentity assetId = figure.getId();
ArticleAsset original = figure.getOriginal();
JsonObject serialized = new JsonObject();
serialized.addProperty("doi", assetId.getIdentifier());
serialized.addProperty("contextElement", original.getContextElement());
serialized.addProperty("title", original.getTitle());
serialized.addProperty("description", original.getDescription());
serialized.add("assetfiles", context.serialize(new AssetFileCollectionView(assets)));
return serialized;
}
}
|
Fix finder does not exist directory
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Autoload Files.
|--------------------------------------------------------------------------
|
| You may add files which you want pine annotations to autoload. Annotations
| in these files will be valid for the Reader to parse. Feel free
| to add as many files as you need.
|
*/
'autoload_files' => [
// app_path('Annotations/FooAnnotation.php')
],
/*
|--------------------------------------------------------------------------
| Autoload Namespaces
|--------------------------------------------------------------------------
|
| You may add namespaces here which you want pine annotations to autoload.
| Annotations in these namespaces will be valid for the Reader to
| parse. Feel free to add as many files as you need.
|
*/
'autoload_namespaces' => [
// 'App\Annotations' => app_path('Annotations'),
],
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Autoload Files.
|--------------------------------------------------------------------------
|
| You may add files which you want pine annotations to autoload. Annotations
| in these files will be valid for the Reader to parse. Feel free
| to add as many files as you need.
|
*/
'autoload_files' => [
// app_path('Annotations/FooAnnotation.php')
],
/*
|--------------------------------------------------------------------------
| Autoload Namespaces
|--------------------------------------------------------------------------
|
| You may add namespaces here which you want pine annotations to autoload.
| Annotations in these namespaces will be valid for the Reader to
| parse. Feel free to add as many files as you need.
|
*/
'autoload_namespaces' => [
'App\Annotations' => app_path('Annotations'),
],
];
|
Exclude cordova files from karma
|
module.exports = function(config){
config.set({
basePath : './',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/components/version/*.js',
'app/view*/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
module.exports = function(config){
config.set({
basePath : './',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/components/**/*.js',
'app/view*/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
Fix error, made command assume extras are params for now
|
#!/usr/bin/env python
import json
import os
import sys
def raw_aliases():
'''
Reads in the aliases file as a Python object
'''
with open(os.environ['AKA_ALIASES'], 'r') as f:
return json.loads(f.read())
def make_lookup(alias_object, current_path=[], current_command=[], result={}):
'''
Given a raw alias object, make it easily searchable
'''
def simple_lookup(command_pieces):
return lambda args: ' '.join(command_pieces + args)
for alias in alias_object:
p = current_path + [alias['token']]
c = current_command + [alias['command']]
result[tuple(p)] = simple_lookup(c)
make_lookup(alias.get('branches', []), p, c, result)
return result
def chopback_lookup(alias_dict, args):
for i in xrange(len(alias_dict), -1, -1):
seek = tuple(args[:i])
if seek in alias_dict:
return alias_dict[seek](args[i:])
return None
if __name__ == '__main__':
lookup = make_lookup(raw_aliases())
command = chopback_lookup(lookup, sys.argv[1:])
if command:
os.system(command)
else:
print 'Couldn\'t find alias for', (' '.join(sys.argv[1:]) or 'the absence of a pattern')
|
#!/usr/bin/env python
import json
import os
import sys
def raw_aliases():
'''
Reads in the aliases file as a Python object
'''
with open(os.environ['AKA_ALIASES'], 'r') as f:
return json.loads(f.read())
def make_lookup(alias_object, current_path=[], current_command=[], result={}):
'''
Given a raw alias object, make it easily searchable
'''
def simple_lookup(command_pieces):
return lambda _: ' '.join(command_pieces)
for alias in alias_object:
p = current_path + [alias['token']]
c = current_command + [alias['command']]
result[tuple(p)] = simple_lookup(c)
make_lookup(alias.get('branches', []), p, c, result)
return result
def chopback_lookup(alias_dict, args):
i = len(args)
while i != 0:
seek = tuple(args[:i])
if seek in alias_dict:
return alias_dict[seek](args[i:])
return None
lookup = make_lookup(raw_aliases())
try:
command = chopback_lookup(lookup, sys.argv[1:])
os.system(command)
except KeyError:
print 'Couldn\'t find alias for', (' '.join(sys.argv[1:]) or 'the absence of a pattern')
|
Use receiver decorator instead of `signal.connect`
I've contributed to this decorator upstream! It should be used. :-)
|
from autoslug.fields import AutoSlugField
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
class Company(models.Model):
""" Organization. """
slug = AutoSlugField(populate_from='name', unique=True)
name = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.name
class FortuitusProfile(models.Model):
""" User profile. """
user = models.OneToOneField(User)
# TODO: support multiple organizations.
company = models.ForeignKey(Company, null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
""" User post_save signal handler, creates user profile instance. """
if created:
FortuitusProfile.objects.create(user=instance)
|
from autoslug.fields import AutoSlugField
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class Company(models.Model):
""" Organization. """
slug = AutoSlugField(populate_from='name', unique=True)
name = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.name
class FortuitusProfile(models.Model):
""" User profile. """
user = models.OneToOneField(User)
# TODO: support multiple organizations.
company = models.ForeignKey(Company, null=True, blank=True)
def create_user_profile(sender, instance, created, **kwargs):
""" User post_save signal handler, creates user profile instance. """
if created:
FortuitusProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
|
FIX problem after reorganizing test.
|
# -*- coding: UTF-8 -*-
"""
https://github.com/behave/behave/issues/619
When trying to do something like::
foo = getattr(context, '_foo', 'bar')
Behave fails with::
File "[...]/behave/runner.py", line 208, in __getattr__
return self.__dict__[attr]
KeyError: '_foo'
I think this is because the __getattr__ method in Context (here) don't raise
properly AttributeError when the key don't exists in the dict,
so the default behaviour of getattr is not executed (see docs).
"""
from __future__ import absolute_import
from behave.runner import Context, scoped_context_layer
from mock import Mock
def test_issue__getattr_with_protected_unknown_context_attribute_raises_no_error():
context = Context(runner=Mock())
with scoped_context_layer(context): # CALLS-HERE: context._push()
value = getattr(context, "_UNKNOWN_ATTRIB", "__UNKNOWN__")
assert value == "__UNKNOWN__"
# -- ENSURED: No exception is raised, neither KeyError nor AttributeError
|
# -*- coding: UTF-8 -*-
"""
https://github.com/behave/behave/issues/619
When trying to do something like::
foo = getattr(context, '_foo', 'bar')
Behave fails with::
File "[...]/behave/runner.py", line 208, in __getattr__
return self.__dict__[attr]
KeyError: '_foo'
I think this is because the __getattr__ method in Context (here) don't raise
properly AttributeError when the key don't exists in the dict,
so the default behaviour of getattr is not executed (see docs).
"""
from __future__ import absolute_import
from behave.runner import Context, scoped_context_layer
from mock import Mock
def test_issue__getattr_with_protected_unknown_context_attribute_raises_no_error(self):
context = Context(runner=Mock())
with scoped_context_layer(context): # CALLS-HERE: context._push()
value = getattr(context, "_UNKNOWN_ATTRIB", "__UNKNOWN__")
assert value == "__UNKNOWN__"
# -- ENSURED: No exception is raised, neither KeyError nor AttributeError
|
Make 'example pipelines' link the same blue link
|
import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a className="blue hover-navy text-decoration-none hover-underline" target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
|
import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
|
Make starship remember its coordinates
|
var hammer = require ('hammerjs')
, canvas = document.getElementById('canvas')
, ctx = canvas.getContext('2d')
, img = new Image() // Create new img element
, i = 0
, star = new Starship(0, 100)
, EventEmitter = require('events').EventEmitter
, gameLoop = require('./gameloop')
, currentTime = 0
, delta = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.src = '/img/ship_orange.svg'; // Set source path
var hammertime = hammer(canvas).on("tap", function(event) {
// console.log(event);
emitter.emit('tap', event);
});
var emitter = new EventEmitter();
emitter.on('tap', function(event) {
console.log(event.gesture.center.pageX, event.gesture.center.pageY);
});
function Starship(x, y) {
this.x = x;
this.y = y;
this.draw = function() {
return ctx.drawImage(img, this.x-100, Math.sin(this.x*0.5)+this.y, 70,80);
};
}
function draw() {
star.x = (star.x + 1) % (canvas.width + 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
star.draw();
}
document.addEventListener('DOMContentLoaded', function(){
if (typeof (canvas.getContext) !== undefined) {
gameLoop(draw);
}
});
|
var hammer = require ('hammerjs')
, canvas = document.getElementById('canvas')
, ctx = canvas.getContext('2d')
, img = new Image() // Create new img element
, i = 0
, starship = function() {}
, star = new starship()
, EventEmitter = require('events').EventEmitter
, gameLoop = require('./gameloop')
, currentTime = 0
, delta = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.src = '/img/ship_orange.svg'; // Set source path
var hammertime = hammer(canvas).on("tap", function(event) {
// console.log(event);
emitter.emit('tap', event);
});
var emitter = new EventEmitter();
emitter.on('tap', function(event) {
console.log(event.gesture.center.pageX, event.gesture.center.pageY);
});
starship.prototype.draw = function() {
return ctx.drawImage(img, i-100, Math.sin(i*0.5), 100, 100);
};
function draw() {
i = (i + 1) % (canvas.width + 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
star.draw();
}
document.addEventListener('DOMContentLoaded', function(){
if (typeof (canvas.getContext) !== undefined) {
gameLoop(draw);
}
});
|
Add javadoc description to resolve @doubt comment
git-svn-id: 1a1fa68050bcaed5349a5b70a2a7ea3fbc73e3e8@949492 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core;
/**
* Exception thrown when a exception occurs while logging. In most cases exceptions will be handled
* within Log4j but certain Appenders may be configured to allow exceptions to propagate to the
* application. This is a RuntimeException so that the exception may be thrown in those cases without
* requiring all Logger methods be contained with try/catch blocks.
*
*/
public class LoggingException extends RuntimeException {
public LoggingException(String msg) {
super(msg);
}
public LoggingException(String msg, Exception ex) {
super(msg, ex);
}
public LoggingException(Exception ex) {
super(ex);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core;
/**
*
*
* @doubt Unchecked?
*
*/
public class LoggingException extends RuntimeException {
public LoggingException(String msg) {
super(msg);
}
public LoggingException(String msg, Exception ex) {
super(msg, ex);
}
public LoggingException(Exception ex) {
super(ex);
}
}
|
Add user models on Published class models
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
user = models.ForeignKey(User, related_name='users')
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
Clean up the error imports
The new errors that had been added for _intersphinx.py had left
the sphobjinv.error import line split. No need, when it all fits on
one line.
|
r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn/sphobjinv
**Documentation**
https://sphobjinv.readthedocs.io/en/latest
**License**
The MIT License; see |license_txt|_ for full license terms
**Members**
"""
from sphobjinv.data import DataFields, DataObjBytes, DataObjStr
from sphobjinv.enum import HeaderFields, SourceTypes
from sphobjinv.error import SphobjinvError, VersionError
from sphobjinv.fileops import readbytes, readjson, urlwalk, writebytes, writejson
from sphobjinv.inventory import Inventory
from sphobjinv.re import p_data, pb_comments, pb_data, pb_project, pb_version
from sphobjinv.schema import json_schema
from sphobjinv.version import __version__
from sphobjinv.zlib import compress, decompress
|
r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn/sphobjinv
**Documentation**
https://sphobjinv.readthedocs.io/en/latest
**License**
The MIT License; see |license_txt|_ for full license terms
**Members**
"""
from sphobjinv.data import DataFields, DataObjBytes, DataObjStr
from sphobjinv.enum import HeaderFields, SourceTypes
from sphobjinv.error import (
SphobjinvError,
VersionError,
)
from sphobjinv.fileops import readbytes, readjson, urlwalk, writebytes, writejson
from sphobjinv.inventory import Inventory
from sphobjinv.re import p_data, pb_comments, pb_data, pb_project, pb_version
from sphobjinv.schema import json_schema
from sphobjinv.version import __version__
from sphobjinv.zlib import compress, decompress
|
Update to new codegangsta/cli api
|
package main
import (
"fmt"
"os"
"github.com/Bowbaq/scala-imports"
"github.com/codegangsta/cli"
"github.com/spf13/viper"
)
var (
Version string
config scalaimports.Config
)
func init() {
viper.SetConfigName(".fix-imports")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME")
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Error reading config file: %s\n", err)
os.Exit(-1)
}
viper.Unmarshal(&config)
}
func main() {
app := cli.NewApp()
app.Name = "fix-imports"
app.Usage = "organize imports in a scala project"
app.Version = Version
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "enable debug output",
},
}
app.Action = func(c *cli.Context) error {
if c.Bool("verbose") {
config.Verbose = true
}
scalaimports.SetConfig(config)
if len(c.Args()) > 0 {
for _, path := range c.Args() {
scalaimports.Format(path)
}
} else {
scalaimports.Format(".")
}
return nil
}
app.Run(os.Args)
}
|
package main
import (
"fmt"
"os"
"github.com/Bowbaq/scala-imports"
"github.com/codegangsta/cli"
"github.com/spf13/viper"
)
var (
Version string
config scalaimports.Config
)
func init() {
viper.SetConfigName(".fix-imports")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME")
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Error reading config file: %s\n", err)
os.Exit(-1)
}
viper.Unmarshal(&config)
}
func main() {
app := cli.NewApp()
app.Name = "fix-imports"
app.Usage = "organize imports in a scala project"
app.Version = Version
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "enable debug output",
},
}
app.Action = func(c *cli.Context) {
if c.Bool("verbose") {
config.Verbose = true
}
scalaimports.SetConfig(config)
if len(c.Args()) > 0 {
for _, path := range c.Args() {
scalaimports.Format(path)
}
} else {
scalaimports.Format(".")
}
}
app.Run(os.Args)
}
|
Define valor padrão como desabilitado no plugin ProfileCompletion
|
<?php
namespace ProfileCompletion;
use MapasCulturais\App;
class Module extends \MapasCulturais\Module
{
public function __construct(array $config = [])
{
$app = App::i();
$config += ['enable' => false];
parent::__construct($config);
}
function _init()
{
/** @var MapasCulturais\App $app */
$app = App::i();
//Caso config estiver em false, o modulo nao irá iniciar
if(!$this->config['enable']){
return;
}
//Insere uma mensagem no topo da página de edição do agente
$app->hook('template(agent.edit.name):after', function() use ($app){
if($app->user->profile->status === 0){
$this->part('profile-complete-message');
}
});
}
function register(){}
}
|
<?php
namespace ProfileCompletion;
use MapasCulturais\App;
class Module extends \MapasCulturais\Module
{
public function __construct(array $config = [])
{
$app = App::i();
$config += [];
parent::__construct($config);
}
function _init()
{
/** @var MapasCulturais\App $app */
$app = App::i();
//Caso config estiver em false, o modulo nao irá iniciar
if(!$this->config['enable']){
return;
}
//Insere uma mensagem no topo da página de edição do agente
$app->hook('template(agent.edit.name):after', function() use ($app){
if($app->user->profile->status === 0){
$this->part('profile-complete-message');
}
});
}
function register(){}
}
|
Fix possible crash with <4.0 devices when opening More.
OTRS:
https://ticket.wikimedia.org/otrs/index.pl?Action=AgentTicketZoom&TicketID=7601473
Change-Id: I673e26d0288c71940f551ad9cdb72db262dbe406
|
package org.wikipedia.settings;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
public class PreferenceActivityWithBack extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hmm. Can't use ActionBarActivity?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
throw new RuntimeException("WAT");
}
}
}
|
package org.wikipedia.settings;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
public class PreferenceActivityWithBack extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hmm. Can't use ActionBarActivity?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
throw new RuntimeException("WAT");
}
}
}
|
Set mode and theme custom dimensions instead of sending event
|
'use strict';
var localforage = require('localforage');
var $body = $('body');
['theme', 'mode'].forEach(function (property) {
localforage.getItem(property, function (value) {
if (!value) {
value = 'default';
localforage.setItem(property, value);
} else {
// For non-first time users, we want to see what modes/themes they are using.
if (property === 'theme') {
// Set theme custom dimension
ga('set', 'dimension3', value);
}
if (property === 'mode') {
// Set mode custom dimension
ga('set', 'dimension4', value);
}
}
$body.addClass(property + '-' + value);
$body.attr('data-' + property, value);
if (property === 'mode' && value !== 'default') {
$('#mode').attr('href', '/styles/' + value + '.min.css');
}
});
});
var App = require('./app');
App.start();
|
'use strict';
var localforage = require('localforage');
var $body = $('body');
['theme', 'mode'].forEach(function (property) {
localforage.getItem(property, function (value) {
if (!value) {
value = 'default';
localforage.setItem(property, value);
} else {
// For non-first time users, we want to see what modes/themes they are using.
if (property === 'theme') {
ga('send', 'event', 'Theme', 'Load page with theme', value);
}
if (property === 'mode') {
ga('send', 'event', 'Mode', 'Load page with mode', value);
}
}
$body.addClass(property + '-' + value);
$body.attr('data-' + property, value);
if (property === 'mode' && value !== 'default') {
$('#mode').attr('href', '/styles/' + value + '.min.css');
}
});
});
var App = require('./app');
App.start();
|
Add source to author build index query
|
from __future__ import absolute_import, division, unicode_literals
from flask import session
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':
if not session.get('email'):
return
return Author.query.filter_by(email=session['email']).first()
return Author.query.get(author_id)
def get(self, author_id):
author = self._get_author(author_id)
if not author:
return self.respond([])
queryset = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
joinedload('source'),
).filter(
Build.author_id == author.id,
).order_by(Build.date_created.desc(), Build.date_started.desc())
return self.paginate(queryset)
def get_stream_channels(self, author_id):
author = self._get_author(author_id)
if not author:
return []
return ['authors:{0}:builds'.format(author.id.hex)]
|
from __future__ import absolute_import, division, unicode_literals
from flask import session
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':
if not session.get('email'):
return
return Author.query.filter_by(email=session['email']).first()
return Author.query.get(author_id)
def get(self, author_id):
author = self._get_author(author_id)
if not author:
return self.respond([])
queryset = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
).filter(
Build.author_id == author.id,
).order_by(Build.date_created.desc(), Build.date_started.desc())
return self.paginate(queryset)
def get_stream_channels(self, author_id):
author = self._get_author(author_id)
if not author:
return []
return ['authors:{0}:builds'.format(author.id.hex)]
|
Update pet insurance nav links
|
const submenuItems = [
{
header: 'Advice',
subHeader: 'What Does Pet Insurance Cover?',
link: '/pet-insurance/learn/pet-insurance-101/',
imageSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet-guide-opt',
},
{
header: 'Advice',
subHeader: 'Pet Insurance FAQ',
link: '/pet-insurance/learn/pet-insurance-faqs/',
imageSrc: 'https://res-2.cloudinary.com/policygenius/image/upload/v1/general/pet-faq-opt',
},
{
header: 'Advice',
subHeader: 'Typical Pet Insurance Policy',
link: '/pet-insurance/learn/pet-insurance-policy-features/',
imageSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet-policy-opt',
},
];
export default {
menu: {
header: 'Pet Insurance',
link: '/pet-insurance/',
activeName: 'pet-insurance',
},
intro: {
cta: 'Get A Free Quote',
imgSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet',
linkHref: '/pet-insurance/',
},
list: {
alt: 'Pet Insurance',
items: submenuItems,
type: 'articles',
}
};
|
const submenuItems = [
{
header: 'Advice',
subHeader: 'What Does Pet Insurance Cover?',
link: '/pet-insurance/guide/',
imageSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet-guide-opt',
},
{
header: 'Advice',
subHeader: 'Pet Insurance FAQ',
link: '/pet-insurance/guide/faqs',
imageSrc: 'https://res-2.cloudinary.com/policygenius/image/upload/v1/general/pet-faq-opt',
},
{
header: 'Advice',
subHeader: 'Typical Pet Insurance Policy',
link: '/pet-insurance/guide/common-policy-features',
imageSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet-policy-opt',
},
];
export default {
menu: {
header: 'Pet Insurance',
link: '/pet-insurance/',
activeName: 'pet-insurance',
},
intro: {
cta: 'Get A Free Quote',
imgSrc: 'https://res-4.cloudinary.com/policygenius/image/upload/v1/general/pet',
linkHref: '/pet-insurance/',
},
list: {
alt: 'Pet Insurance',
items: submenuItems,
type: 'articles',
}
};
|
Update license and add networkx dependency
|
#!/usr/bin/env python
'''Setuptools params'''
from setuptools import setup, find_packages
from os.path import join
scripts = [join('bin', filename) for filename in
['mn', 'mnclean']]
modname = distname = 'mininet'
setup(
name=distname,
version='0.0.0',
description='Process-based OpenFlow emulator',
author='Bob Lantz',
author_email='rlantz@cs.stanford.edu',
packages=find_packages(exclude='test'),
long_description="""\
Insert longer description here.
""",
classifiers=[
"License :: OSI Approved :: GNU General Public License (GPL)",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet",
],
keywords='networking protocol Internet OpenFlow',
license='unspecified',
install_requires=[
'setuptools',
'networkx'
],
scripts=scripts,
)
|
#!/usr/bin/env python
'''Setuptools params'''
from setuptools import setup, find_packages
from os.path import join
scripts = [join('bin', filename) for filename in
['mn', 'mnclean']]
modname = distname = 'mininet'
setup(
name=distname,
version='0.0.0',
description='Process-based OpenFlow emulator',
author='Bob Lantz',
author_email='rlantz@cs.stanford.edu',
packages=find_packages(exclude='test'),
long_description="""\
Insert longer description here.
""",
classifiers=[
"License :: OSI Approved :: GNU General Public License (GPL)",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet",
],
keywords='networking protocol Internet OpenFlow',
license='GPL',
install_requires=[
'setuptools'
],
scripts=scripts,
)
|
Check for null & undefined
|
const _ = require("lodash");
module.exports = function omitDeepLodash(input, props) {
function omitDeepOnOwnProps(obj) {
if (!_.isArray(obj) && !_.isObject(obj)) {
return obj;
}
if (_.isArray(obj)) {
return omitDeepLodash(obj, props);
}
const o = {};
_.forOwn(obj, (value, key) => {
o[key] = !_.isNil(value) ? omitDeepLodash(value, props) : value;
});
return _.omit(o, props);
}
if (arguments.length > 2) {
props = Array.prototype.slice.call(arguments).slice(1);
}
if (typeof input === "undefined") {
return {};
}
if (_.isArray(input)) {
return input.map(omitDeepOnOwnProps);
}
return omitDeepOnOwnProps(input);
};
|
const _ = require("lodash");
module.exports = function omitDeepLodash(input, props) {
function omitDeepOnOwnProps(obj) {
if (!_.isArray(obj) && !_.isObject(obj)) {
return obj;
}
if (_.isArray(obj)) {
return omitDeepLodash(obj, props);
}
const o = {};
_.forOwn(obj, (value, key) => {
o[key] = omitDeepLodash(value, props);
});
return _.omit(o, props);
}
if (arguments.length > 2) {
props = Array.prototype.slice.call(arguments).slice(1);
}
if (typeof input === "undefined") {
return {};
}
if (_.isArray(input)) {
return input.map(omitDeepOnOwnProps);
}
return omitDeepOnOwnProps(input);
};
|
Add type attribute set to button
|
document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var form = document.createElement("FORM");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
label.appendChild(input);
var submit = document.createElement("BUTTON");
submit.setAttribute("id", "submit");
submit.setAttribute("type", "button");
var t = document.createTextNode("Consultar descargas de última versión");
submit.appendChild(t);
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
$(document).ready(function () {
$("#submit").click(function () {
$.getJSON("https://api.github.com/repos/releases/latest", function(json) {
var name = json.name;
});
});
});
|
document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var form = document.createElement("FORM");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
label.appendChild(input);
var submit = document.createElement("BUTTON");
submit.setAttribute("id", "submit");
var t = document.createTextNode("Consultar descargas de última versión");
submit.appendChild(t);
p.appendChild(label);
form.appendChild(p);
aside.appendChild(form);
aside.appendChild(submit);
$(document).ready(function () {
$("#submit").click(function () {
$.getJSON("https://api.github.com/repos/releases/latest", function(json) {
var name = json.name;
});
});
});
|
Add print statement for request URL
|
package com.johnstarich.ee461l;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Handles all requests sent to the root ("/") of this server.
* Created by johnstarich on 1/30/16.
*/
public class RootServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>Hey there!</h1><h2>This is our EE461L design project</h2> <p>This is the request path we received: " + request.getPathInfo() + "</p>");
System.out.println("Request was = GET " + request.getPathInfo());
}
}
|
package com.johnstarich.ee461l;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Handles all requests sent to the root ("/") of this server.
* Created by johnstarich on 1/30/16.
*/
public class RootServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>Hey there!</h1><h2>This is our EE461L design project</h2> <p>This is the request path we received: " + request.getPathInfo() + "</p>");
}
}
|
Add properties to column DTO
|
/*
* CODENVY CONFIDENTIAL
* __________________
*
* [2013] - [2014] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.ide.ext.datasource.shared;
import com.codenvy.dto.shared.DTO;
@DTO
public interface ColumnDTO extends DatabaseMetadataEntityDTO {
ColumnDTO withName(String name);
ColumnDTO withColumnDataType(String datatypeName);
String getColumnDataType();
void setColumnDataType(String columnDataTypeName);
ColumnDTO withDefaultValue(String defaultValue);
void setDefaultValue(String defaultValue);
String getDefalulValue();
ColumnDTO withDataSize(int size);
void setDataSize(int size);
int getDataSize();
ColumnDTO withDecimalDigits(int digits);
void setDecimalDigits(int digits);
int getDecimalDigits();
ColumnDTO withNullable(boolean nullable);
void setNullable(boolean nullable);
boolean getNullable();
}
|
/*
* CODENVY CONFIDENTIAL
* __________________
*
* [2013] - [2014] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.ide.ext.datasource.shared;
import com.codenvy.dto.shared.DTO;
@DTO
public interface ColumnDTO extends DatabaseMetadataEntityDTO {
ColumnDTO withName(String name);
ColumnDTO withColumnDataType(String datatypeName);
String getColumnDataType();
void setColumnDataType(String columnDataTypeName);
}
|
Make sortProperties an optional config attribute
|
import Em from 'ember';
import Row from 'llama-table/controllers/row';
import { makeArray } from 'llama-table/computed';
var computed = Em.computed;
var map = computed.map;
var sort = computed.sort;
var reads = computed.reads;
var SortedRowsMixin = Em.Mixin.create({
_rowsSource: makeArray('rows'),
_rowsSortOrder: makeArray('sortProperties'),
_rowsMapped: map('_rowsSource', function (model) {
if (!(model instanceof Row)) {
return Row.create({ model });
}
return model;
}),
_rowsSorted: sort('_rowsMapped', '_rowsSortOrder'),
/**
* Row values array with added sorting functionality. Uses a custom
* 'RowsController' if table has subcontent. Does not construct this
* custom controller if it is not necessary.
* @property {Ember.ArrayProxy} sortedRows
*/
sortedRows: computed('_rowsMapped', '_rowsSortOrder', function () {
if (Em.isEmpty(this.get('_rowsSortOrder'))){
return this.get('_rowsMapped');
} else {
return this.get('_rowsSorted');
}
}),
});
export default SortedRowsMixin;
|
import Em from 'ember';
import Row from 'llama-table/controllers/row';
import { makeArray } from 'llama-table/computed';
var computed = Em.computed;
var map = computed.map;
var sort = computed.sort;
var reads = computed.reads;
var SortedRowsMixin = Em.Mixin.create({
_rowsSource: makeArray('rows'),
_rowsSortOrder: makeArray('sortProperties'),
_rowsMapped: map('_rowsSource', function (model) {
if (!(model instanceof Row)) {
return Row.create({ model });
}
return model;
}),
_rowsSorted: sort('_rowsMapped', '_rowsSortOrder'),
/**
* Row values array with added sorting functionality. Uses a custom
* 'RowsController' if table has subcontent. Does not construct this
* custom controller if it is not necessary.
* @property {Ember.ArrayProxy} sortedRows
*/
sortedRows: reads('_rowsSorted'),
});
export default SortedRowsMixin;
|
Use project-routes module to get route for projects.
|
var mount = require('koa-mount');
var router = require('koa-router')();
var koa = require('koa');
var Bus = require('busmq');
var app = koa();
require('koa-qs')(app);
var ropts = {
db: 'materialscommons',
port: 30815
};
var r = require('rethinkdbdash')(ropts);
var projectsModel = require('./model/db/projects')(r);
var projects = require('./resources/projects-routes')(projectsModel);
var bus = Bus.create({redis: ['redis://localhost:6379']});
var q;
bus.on('online', function() {
q = bus.queue('samples');
q.attach();
});
function* samples(next) {
yield next;
this.body = {samples:['a', 'b']};
}
var router2 = require('koa-router')();
router2.get('/samples', samples);
var usersModel = require('./model/db/users')(r);
var keycache = require('./apikey-cache')(usersModel);
var apikey = require('./apikey');
app.use(apikey(keycache));
app.use(mount('/', projects.routes())).use(projects.allowedMethods());
app.use(mount('/', router2.routes()));
app.listen(3000);
|
var mount = require('koa-mount');
var router = require('koa-router')();
var koa = require('koa');
var Bus = require('busmq');
var app = koa();
require('koa-qs')(app);
var ropts = {
db: 'materialscommons',
port: 30815
};
var r = require('rethinkdbdash')(ropts);
var projectsModel = require('./model/db/projects')(r);
var projects = require('./resources/projects')(projectsModel);
var bus = Bus.create({redis: ['redis://localhost:6379']});
var q;
bus.on('online', function() {
q = bus.queue('samples');
q.attach();
});
function* samples(next) {
yield next;
this.body = {samples:['a', 'b']};
}
var router2 = require('koa-router')();
router2.get('/samples', samples);
var usersModel = require('./model/db/users')(r);
var keycache = require('./apikey-cache')(usersModel);
var apikey = require('./apikey');
app.use(apikey(keycache));
app.use(mount('/', projects.routes())).use(projects.allowedMethods());
app.use(mount('/', router2.routes()));
app.listen(3000);
|
Fix computation of ticks for yAxis on responsive
|
export default chart => {
if (chart.responsive) {
const {
width,
height
} = chart
// preserve original values
chart._originWidth = width
chart._originHeight = height
// setup height calculation
const heightRatio = height / width
const xTicksRatio = chart.xTicks / width
const yTicksRatio = chart.yTicks / height
chart._getHeight = width => parseInt(width * heightRatio)
// show at least two ticks
chart._getXTicks = width => {
const ticks = parseInt(width * xTicksRatio)
return ticks < 2 ? 2 : ticks > chart.xTicks ? chart.xTicks : ticks
}
chart._getYTicks = height => {
const ticks = parseInt(width * yTicksRatio)
return ticks < 2 ? 2 : ticks > chart.yTicks ? chart.yTicks : ticks
}
// add event listener
window.addEventListener('resize', () => {
if (chart.updateDimensions(chart)) {
chart.resize()
}
})
}
}
|
export default chart => {
if (chart.responsive) {
const {
width,
height
} = chart
// preserve original values
chart._originWidth = width
chart._originHeight = height
// setup height calculation
const heightRatio = height / width
const xTicksRatio = chart.xTicks / width
const yTicksRatio = chart.yTicks / height
chart._getHeight = width => parseInt(width * heightRatio)
// show at least two ticks
chart._getXTicks = width => {
const ticks = parseInt(width * xTicksRatio)
return ticks < 2 ? 2 : ticks > chart.xTicks ? chart.xTicks : ticks
}
chart._getYTicks = width => {
const ticks = parseInt(width * yTicksRatio)
return ticks < 2 ? 2 : ticks > chart.yTicks ? chart.yTicks : ticks
}
// add event listener
window.addEventListener('resize', () => {
if (chart.updateDimensions(chart)) {
chart.resize()
}
})
}
}
|
Update w/ Readme & scripts
|
import os
from setuptools import setup, find_packages
import glob
src_dir = os.path.dirname(__file__)
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == '__main__':
setup(
name='stacker',
version='0.1.0',
author='Michael Barrett',
author_email='loki77@gmail.com',
license="New BSD license",
url="https://github.com/remind101/stacker",
description='Opinionated AWS CloudFormation Stack manager',
long_description=read('README.rst'),
packages=find_packages(),
scripts=glob.glob(os.path.join(src_dir, 'scripts', '*')),
)
|
import os
from setuptools import setup, find_packages
# import glob
src_dir = os.path.dirname(__file__)
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == '__main__':
setup(
name='stacker',
version='0.1.0',
author='Michael Barrett',
author_email='loki77@gmail.com',
license="New BSD license",
url="https://github.com/remind101/stacker",
description='Opinionated AWS CloudFormation Stack manager',
# long_description=read('README.rst'),
packages=find_packages(),
)
|
Test query is actually created.
|
<?php
namespace Gt\Database\Query;
class QueryFactoryTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
*/
public function testFindQueryFilePathExists(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
$this->assertFileExists($queryFilePath);
}
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathNotExistsProvider
* @expectedException \Gt\Database\Query\QueryNotFoundException
*/
public function testFindQueryFilePathNotExists(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathExtensionNotValidProvider
* @expectedException \Gt\Database\Query\QueryNotFoundException
*/
public function testFindQueryFilePathWithInvalidExtension(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
*/
public function testQueryCreated(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$query = $queryFactory->create($queryName);
$this->assertInstanceOf(
"\Gt\Database\Query\QueryInterface",
$query
);
}
}#
|
<?php
namespace Gt\Database\Query;
class QueryFactoryTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
*/
public function testFindQueryFilePathExists(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
$this->assertFileExists($queryFilePath);
}
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathNotExistsProvider
* @expectedException \Gt\Database\Query\QueryNotFoundException
*/
public function testFindQueryFilePathNotExists(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}
/**
* @dataProvider \Gt\Database\Test\Helper::queryPathExtensionNotValidProvider
* @expectedException \Gt\Database\Query\QueryNotFoundException
*/
public function testFindQueryFilePathWithInvalidExtension(
string $queryName, string $directoryOfQueries) {
$queryFactory = new QueryFactory($directoryOfQueries);
$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}
}#
|
Fix gap left in status bar on OS X after quit
|
// This file is ES5; it's loaded before Babel.
require('babel/register')({
extensions: ['.desktop.js', '.es6', '.es', '.jsx', '.js']
})
const menubar = require('menubar')
const ipc = require('ipc')
const Window = require('./window')
const mb = menubar({
index: `file://${__dirname}/../renderer/launcher.html`,
width: 200, height: 250,
preloadWindow: true,
icon: 'Icon.png'
})
const trackerWindow = new Window('tracker', {
width: 500, height: 300,
resizable: false,
fullscreen: false,
frame: false
})
const mainWindow = new Window('index', {
width: 1600, height: 1200, openDevTools: true
})
mb.on('ready', () => {
require('../../react-native/react/native/notifications').init()
})
// Work around an OS X bug that leaves a gap in the status bar if you exit
// without removing your status bar icon.
if (process.platform === 'darwin') {
mb.app.on('quit', () => { mb.tray.destroy() })
}
ipc.on('showMain', () => { mainWindow.show() })
ipc.on('showTracker', () => { trackerWindow.show() })
|
// This file is ES5; it's loaded before Babel.
require('babel/register')({
extensions: ['.desktop.js', '.es6', '.es', '.jsx', '.js']
})
const menubar = require('menubar')
const ipc = require('ipc')
const Window = require('./window')
const mb = menubar({
index: `file://${__dirname}/../renderer/launcher.html`,
width: 200, height: 250,
preloadWindow: true,
icon: 'Icon.png'
})
const trackerWindow = new Window('tracker', {
width: 500, height: 300,
resizable: false,
fullscreen: false,
frame: false
})
const mainWindow = new Window('index', {
width: 1600, height: 1200, openDevTools: true
})
mb.on('ready', () => {
require('../../react-native/react/native/notifications').init()
})
ipc.on('showMain', () => { mainWindow.show() })
ipc.on('showTracker', () => { trackerWindow.show() })
|
Fix Order filter to work with sorting by keys again
|
<?php
namespace allejo\stakx\Twig;
use allejo\stakx\Object\ContentItem;
class OrderFilter
{
public function __invoke ($array, $key, $order = "ASC")
{
usort($array, function ($a, $b) use ($key, $order) {
$a = ($a instanceof ContentItem) ? $a->getFrontMatter() : $a;
$b = ($b instanceof ContentItem) ? $b->getFrontMatter() : $b;
if ($a[$key] == $b[$key]) return 0;
if (strtolower($order) === "desc") {
return ($a[$key] < $b[$key]) ? 1 : -1;
}
return ($a[$key] > $b[$key]) ? 1 : -1;
});
return $array;
}
public static function get ()
{
return new \Twig_SimpleFilter('order', new self());
}
}
|
<?php
namespace allejo\stakx\Twig;
use allejo\stakx\Object\ContentItem;
class OrderFilter
{
public function __invoke ($array, $key, $order = "ASC")
{
usort($array, function ($a, $b) use ($key, $order) {
$a = !($a instanceof ContentItem) ?: $a->getFrontMatter();
$b = !($b instanceof ContentItem) ?: $b->getFrontMatter();
if ($a[$key] == $b[$key]) return 0;
if (strtolower($order) === "desc") {
return ($a[$key] < $b[$key]) ? 1 : -1;
}
return ($a[$key] > $b[$key]) ? 1 : -1;
});
return $array;
}
public static function get ()
{
return new \Twig_SimpleFilter('order', new self());
}
}
|
:art: Move BottomTab's child element creation logic from attachedCallback to prepare
|
'use strict';
class BottomTab extends HTMLElement{
prepare(name){
this.name = name
this.attached = false
this.active = false
this.classList.add('linter-tab')
this.countSpan = document.createElement('span')
this.countSpan.classList.add('count')
this.countSpan.textContent = '0'
this.innerHTML = this.name + ' '
this.appendChild(this.countSpan)
return this
}
attachedCallback() {
this.attached = true
}
detachedCallback(){
this.attached = false
}
get active() {
return this._active
}
set active(value) {
this._active = value
if (value) {
this.classList.add('active')
} else {
this.classList.remove('active')
}
}
set count(value) {
this.countSpan.textContent = value
}
}
module.exports = BottomTab = document.registerElement('linter-bottom-tab', {
prototype: BottomTab.prototype
})
|
'use strict';
class BottomTab extends HTMLElement{
prepare(name){
this.name = name
this.attached = false
this.active = false
return this
}
attachedCallback() {
this.attached = true
this.classList.add('linter-tab')
this.countSpan = document.createElement('span')
this.countSpan.classList.add('count')
this.countSpan.textContent = '0'
this.innerHTML = this.name + ' '
this.appendChild(this.countSpan)
}
detachedCallback(){
this.attached = false
}
get active() {
return this._active
}
set active(value) {
this._active = value
if (value) {
this.classList.add('active')
} else {
this.classList.remove('active')
}
}
set count(value) {
this.countSpan.textContent = value
}
}
module.exports = BottomTab = document.registerElement('linter-bottom-tab', {
prototype: BottomTab.prototype
})
|
Switch to primarily using the GUI instead of CLI
|
/*
* The MIT License
*
* Copyright 2016 veeti "walther" haapsamo.
*
* 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 minesweeper;
/**
*
* @author veeti "walther" haapsamo
*/
public class Main {
public static void main(String[] args) {
//CLI gui = new CLI();
GUI gui = new GUI();
}
}
|
/*
* The MIT License
*
* Copyright 2016 veeti "walther" haapsamo.
*
* 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 minesweeper;
/**
*
* @author veeti "walther" haapsamo
*/
public class Main {
public static void main(String[] args) {
CLI gui = new CLI();
//GUI gui = new GUI();
}
}
|
Handle scientific notation in response
|
#!/usr/bin/env python
import json
import re
from urllib import urlopen
api = 'http://www.google.com/ig/calculator?hl=en&q={}{}=?{}'
def convert(value, src_units, dst_units):
url = api.format(value, src_units, dst_units)
# read and preprocess the response
resp = urlopen(url).read()
resp = resp.replace(r'\x', r'\u00')
resp = re.sub('([a-z]+):', '"\\1" :', resp)
data = json.loads(resp)
if len(data['error']) > 0:
raise Exception(data['error'])
# postprocess the answer from Google to deal with HTML-formatted scientific
# notation
rhs = data['rhs']
rhs = re.sub(r'\s*×\s*10\s*<sup>-(\d+)</sup>', 'e-\\1', rhs)
rhs = re.sub(r'\s*×\s*10\s*<sup>(\d+)</sup>', 'e+\\1', rhs)
data['rhs'] = rhs
value = data['rhs'].split(' ')[0]
value = float(value) if '.' in value else int(value)
return value, data['rhs']
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('value', type=float)
parser.add_argument('source_units')
parser.add_argument('dest_units')
args = parser.parse_args()
print convert(args.value, args.source_units, args.dest_units)
|
#!/usr/bin/env python
import json
import re
from urllib import urlopen
api = 'http://www.google.com/ig/calculator?hl=en&q={}{}=?{}'
def convert(value, src_units, dst_units):
url = api.format(value, src_units, dst_units)
data = urlopen(url).read().decode('utf-8', 'ignore')
# Convert to valid JSON: {foo: "1"} -> {"foo" : "1"}
data = re.sub('([a-z]+):', '"\\1" :', data)
data = json.loads(data)
if len(data['error']) > 0:
raise Exception(data['error'])
value = data['rhs'].split(' ')[0]
value = float(value) if '.' in value else int(value)
return value, data['rhs']
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('value', type=float)
parser.add_argument('source_units')
parser.add_argument('dest_units')
args = parser.parse_args()
print convert(args.value, args.source_units, args.dest_units)
|
Clarify behavior documented in tests.
|
package cli
import (
"fmt"
"github.com/jwaldrip/odin/cli/values"
)
// Flag returns the Value interface to the value of the named flag,
// panics if none exists.
func (cmd *CLI) Flag(name string) values.Value {
flag := cmd.getFlag(name)
value := cmd.flagValues[flag]
return value
}
// Flags returns the flags as a map of strings with Values
func (cmd *CLI) Flags() values.Map {
flags := make(values.Map)
for name := range cmd.inheritedFlags.Merge(cmd.flags) {
flags[name] = cmd.Flag(name)
}
return flags
}
func (cmd *CLI) getFlag(name string) *Flag {
flag, exists := cmd.inheritedFlags.Merge(cmd.flags)[name]
if !exists {
panic(fmt.Sprintf("flag not defined %v", name))
}
return flag
}
func (cmd *CLI) hasFlags() bool {
var internalFlagCount int
if flag, ok := cmd.flags["help"]; ok && flag == cmd.flagHelp {
internalFlagCount++
}
if flag, ok := cmd.flags["version"]; ok && flag == cmd.flagVersion {
internalFlagCount++
}
return len(cmd.flags) > internalFlagCount
}
|
package cli
import (
"fmt"
"github.com/jwaldrip/odin/cli/values"
)
// Flag returns the Value interface to the value of the named flag,
// returning nil if none exists.
func (cmd *CLI) Flag(name string) values.Value {
flag := cmd.getFlag(name)
value := cmd.flagValues[flag]
return value
}
// Flags returns the flags as a map of strings with Values
func (cmd *CLI) Flags() values.Map {
flags := make(values.Map)
for name := range cmd.inheritedFlags.Merge(cmd.flags) {
flags[name] = cmd.Flag(name)
}
return flags
}
func (cmd *CLI) getFlag(name string) *Flag {
flag, exists := cmd.inheritedFlags.Merge(cmd.flags)[name]
if !exists {
panic(fmt.Sprintf("flag not defined %v", name))
}
return flag
}
func (cmd *CLI) hasFlags() bool {
var internalFlagCount int
if flag, ok := cmd.flags["help"]; ok && flag == cmd.flagHelp {
internalFlagCount++
}
if flag, ok := cmd.flags["version"]; ok && flag == cmd.flagVersion {
internalFlagCount++
}
return len(cmd.flags) > internalFlagCount
}
|
Update tests to cover every Roman WFI filter
|
import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_jwst_miri_bands():
for bandname in ['f1130w']:
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_ztf_bandpass():
bp = sncosmo.get_bandpass('ztfg')
@pytest.mark.might_download
def test_roman_bandpass():
sncosmo.get_bandpass('f062')
sncosmo.get_bandpass('f087')
sncosmo.get_bandpass('f106')
sncosmo.get_bandpass('f129')
sncosmo.get_bandpass('f158')
sncosmo.get_bandpass('f184')
sncosmo.get_bandpass('f213')
sncosmo.get_bandpass('f146')
|
import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_jwst_miri_bands():
for bandname in ['f1130w']:
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_ztf_bandpass():
bp = sncosmo.get_bandpass('ztfg')
@pytest.mark.might_download
def test_roman_bandpass():
bp = sncosmo.get_bandpass('f087')
|
Add quoted string expression example
|
// Disallows the use of bare strings in a template
//
// passes:
// <div>{{evaluatesToAString}}</div>
// <div>{{'A string'}}</div>
//
// breaks:
// <div>A bare string</div>
var calculateLocationDisplay = require('../helpers/calculate-location-display');
module.exports = function(addonContext) {
var config = addonContext.loadConfig()['bare-strings'];
function LogStaticStrings(options) {
this.options = options;
this.syntax = null; // set by HTMLBars
}
LogStaticStrings.prototype.transform = function(ast) {
if (config === false) {
return ast;
}
var pluginContext = this;
var walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (pluginContext.detectStaticString(node)) {
return pluginContext.processStaticString(node);
}
});
return ast;
};
LogStaticStrings.prototype.processStaticString = function(node) {
var locationDisplay = calculateLocationDisplay(this.options.moduleName, node.loc);
var warning = 'Non-translated string used ' + locationDisplay + ' `' + node.chars + '`';
addonContext.logLintingError("bare-strings", this.options.moduleName, warning);
}
LogStaticStrings.prototype.detectStaticString = function(node) {
return node.type === 'TextNode' && !node.raw && node.chars.trim() !== '';
};
return LogStaticStrings
};
|
// Disallows the use of bare strings in a template
//
// passes:
// <div>{{evaluatesToAString}}</div>
//
// breaks:
// <div>A bare string</div>
var calculateLocationDisplay = require('../helpers/calculate-location-display');
module.exports = function(addonContext) {
var config = addonContext.loadConfig()['bare-strings'];
function LogStaticStrings(options) {
this.options = options;
this.syntax = null; // set by HTMLBars
}
LogStaticStrings.prototype.transform = function(ast) {
if (config === false) {
return ast;
}
var pluginContext = this;
var walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (pluginContext.detectStaticString(node)) {
return pluginContext.processStaticString(node);
}
});
return ast;
};
LogStaticStrings.prototype.processStaticString = function(node) {
var locationDisplay = calculateLocationDisplay(this.options.moduleName, node.loc);
var warning = 'Non-translated string used ' + locationDisplay + ' `' + node.chars + '`';
addonContext.logLintingError("bare-strings", this.options.moduleName, warning);
}
LogStaticStrings.prototype.detectStaticString = function(node) {
return node.type === 'TextNode' && !node.raw && node.chars.trim() !== '';
};
return LogStaticStrings
};
|
Change null check to throw NPE.
|
package uk.ac.ebi.quickgo.annotation.download.converter.helpers;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* A home for the logic to format ConnectedXRefs into Strings.
*
* @author Tony Wardell
* Date: 09/04/2018
* Time: 13:06
* Created with IntelliJ IDEA.
*/
public class ConnectedXRefs {
private static final String PIPE = "|";
private static final String COMMA = ",";
private ConnectedXRefs() {}
public static String asString(List<Annotation.ConnectedXRefs<Annotation.SimpleXRef>> connectedXRefs) {
Objects.requireNonNull(connectedXRefs);
return connectedXRefs.stream()
.map(ConnectedXRefs::simpleRefAndToString)
.collect(Collectors.joining(PIPE));
}
private static String simpleRefAndToString(Annotation.ConnectedXRefs<Annotation.SimpleXRef> itemList) {
return itemList.getConnectedXrefs()
.stream()
.map(Annotation.SimpleXRef::asXref)
.collect(Collectors.joining(COMMA));
}
}
|
package uk.ac.ebi.quickgo.annotation.download.converter.helpers;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import java.util.List;
import java.util.stream.Collectors;
/**
* A home for the logic to format ConnectedXRefs into Strings.
*
* @author Tony Wardell
* Date: 09/04/2018
* Time: 13:06
* Created with IntelliJ IDEA.
*/
public class ConnectedXRefs {
private static final String PIPE = "|";
private static final String COMMA = ",";
private ConnectedXRefs() {}
public static String asString(List<Annotation.ConnectedXRefs<Annotation.SimpleXRef>> connectedXRefs) {
if (connectedXRefs == null || connectedXRefs.isEmpty()) {
return "";
}
return connectedXRefs.stream()
.map(ConnectedXRefs::simpleRefAndToString)
.collect(Collectors.joining(PIPE));
}
private static String simpleRefAndToString(Annotation.ConnectedXRefs<Annotation.SimpleXRef> itemList) {
return itemList.getConnectedXrefs()
.stream()
.map(Annotation.SimpleXRef::asXref)
.collect(Collectors.joining(COMMA));
}
}
|
Fix Error: `cannot use `attributeBindings` on a tag-less component`
Modify touch-action mixin to smartly add `attributeBindings` to prevent
assertion error from being thrown in ember beta/canary.
Error is thrown when using 2.8.0-beta.3+cf714821 and 2.9.0-master+3f4ba8d4
|
import Ember from 'ember';
const {
computed,
Mixin,
String: { htmlSafe }
} = Ember;
export default Mixin.create({
init() {
this._super(...arguments);
if (this.tagName) {
this.attributeBindings = ['touchActionStyle:style'];
this.applyStyle = true;
} else {
this.applyStyle = false;
}
},
touchActionStyle: computed(function() {
// we apply if click is present and tagName is present
let applyStyle = this.applyStyle && this.click;
if (!applyStyle) {
// we apply if tagName
const tagName = this.get('tagName');
const type = this.get('type');
let isFocusable = ['button', 'input', 'a', 'textarea'].indexOf(tagName) !== -1;
if (isFocusable) {
if (tagName === 'input') {
isFocusable = ['button', 'submit', 'text', 'file'].indexOf(type) !== -1;
}
}
applyStyle = isFocusable;
}
return htmlSafe(applyStyle ? 'touch-action: manipulation; -ms-touch-action: manipulation; cursor: pointer;' : '');
})
});
|
import Ember from 'ember';
const {
computed,
Mixin,
String: { htmlSafe }
} = Ember;
export default Mixin.create({
attributeBindings: ['touchActionStyle:style'],
touchActionStyle: computed(function() {
// we apply if click is present
let applyStyle = this.click;
if (!applyStyle) {
// we apply if tagName
const tagName = this.get('tagName');
const type = this.get('type');
let isFocusable = ['button', 'input', 'a', 'textarea'].indexOf(tagName) !== -1;
if (isFocusable) {
if (tagName === 'input') {
isFocusable = ['button', 'submit', 'text', 'file'].indexOf(type) !== -1;
}
}
applyStyle = isFocusable;
}
return htmlSafe(applyStyle ? 'touch-action: manipulation; -ms-touch-action: manipulation; cursor: pointer;' : '');
})
});
|
Use normal function for normal test
|
import test from 'ava';
import removeTrailingSeparator from '..';
test('strip trailing separator:', t => {
t.is(removeTrailingSeparator('foo/'), 'foo');
t.is(removeTrailingSeparator('foo\\'), 'foo');
});
test('don\'t strip when it\'s the only char in the string', t => {
t.is(removeTrailingSeparator('/'), '/');
t.is(removeTrailingSeparator('\\'), '\\');
});
test('strip only trailing separator:', t => {
t.is(removeTrailingSeparator('/test/foo/bar/'), '/test/foo/bar');
t.is(removeTrailingSeparator('\\test\\foo\\bar\\'), '\\test\\foo\\bar');
});
test('strip multiple trailing separators', t => {
t.is(removeTrailingSeparator('/test//'), '/test');
t.is(removeTrailingSeparator('\\test\\\\'), '\\test');
});
test('leave 1st separator in a string of only separators', t => {
t.is(removeTrailingSeparator('//'), '/');
t.is(removeTrailingSeparator('////'), '/');
t.is(removeTrailingSeparator('\\\\'), '\\');
t.is(removeTrailingSeparator('\\\\\\\\'), '\\');
});
test('return back empty string', t => {
t.is(removeTrailingSeparator(''), '');
});
|
import test from 'ava';
import removeTrailingSeparator from '..';
test('strip trailing separator:', t => {
t.is(removeTrailingSeparator('foo/'), 'foo');
t.is(removeTrailingSeparator('foo\\'), 'foo');
});
test('don\'t strip when it\'s the only char in the string', async t => {
t.is(removeTrailingSeparator('/'), '/');
t.is(removeTrailingSeparator('\\'), '\\');
});
test('strip only trailing separator:', t => {
t.is(removeTrailingSeparator('/test/foo/bar/'), '/test/foo/bar');
t.is(removeTrailingSeparator('\\test\\foo\\bar\\'), '\\test\\foo\\bar');
});
test('strip multiple trailing separators', t => {
t.is(removeTrailingSeparator('/test//'), '/test');
t.is(removeTrailingSeparator('\\test\\\\'), '\\test');
});
test('leave 1st separator in a string of only separators', t => {
t.is(removeTrailingSeparator('//'), '/');
t.is(removeTrailingSeparator('////'), '/');
t.is(removeTrailingSeparator('\\\\'), '\\');
t.is(removeTrailingSeparator('\\\\\\\\'), '\\');
});
test('return back empty string', t => {
t.is(removeTrailingSeparator(''), '');
});
|
Increase timeout for agent update to 5 minutes.
|
#!/usr/bin/env python
__metaclass__ = type
from jujupy import (
check_wordpress,
Environment,
format_listing,
until_timeout,
)
from collections import defaultdict
import sys
def agent_update(environment, version):
env = Environment(environment)
for ignored in until_timeout(300):
versions = defaultdict(list)
status = env.get_status()
for item_name, item in env.agent_items(status):
versions[item.get('agent-version', 'unknown')].append(item_name)
if versions.keys() == [version]:
break
print format_listing(versions, version)
sys.stdout.flush()
else:
raise Exception('Some versions did not update.')
def main():
try:
agent_update(sys.argv[1], sys.argv[2])
except Exception as e:
print e
sys.exit(1)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
__metaclass__ = type
from jujupy import (
check_wordpress,
Environment,
format_listing,
until_timeout,
)
from collections import defaultdict
import sys
def agent_update(environment, version):
env = Environment(environment)
for ignored in until_timeout(30):
versions = defaultdict(list)
status = env.get_status()
for item_name, item in env.agent_items(status):
versions[item.get('agent-version', 'unknown')].append(item_name)
if versions.keys() == [version]:
break
print format_listing(versions, version)
sys.stdout.flush()
else:
raise Exception('Some versions did not update.')
def main():
try:
agent_update(sys.argv[1], sys.argv[2])
except Exception as e:
print e
sys.exit(1)
if __name__ == '__main__':
main()
|
Fix broken test (not the intermittent one, this was just a dumb thing)
|
from django.test import TestCase
from django.conf import settings
from django.utils.html import escape
from django.template import Context, Template
from bongo.apps.bongo.tests import factories
def render_template(string, context=None):
context = Context(context) if context else None
return Template(string).render(context)
class TemplateTagsTestCase(TestCase):
def test_dump_templatetag(self):
"""Test the dump() template tag (print object representation)"""
article = factories.PostFactory.create()
rendered = render_template(
"{% load dump %}{{ article | dump }}",
context = {
"article": article
}
)
self.assertEqual(rendered, escape(article.__dict__))
def test_class_name_templatetag(self):
"""Test the class_name() template tag (print object's class name)"""
article = factories.PostFactory.create()
rendered = render_template(
"{% load class_name %}{{ article | class_name }}",
context = {
"article": article
}
)
self.assertEqual(rendered, "Post")
|
from django.test import TestCase
from django.conf import settings
from django.template import Context, Template
from bongo.apps.bongo.tests import factories
def render_template(string, context=None):
context = Context(context) if context else None
return Template(string).render(context)
class TemplateTagsTestCase(TestCase):
def test_dump_templatetag(self):
"""Test the dump() template tag (print object representation)"""
article = factories.PostFactory.create()
rendered = render_template(
"{% load dump %}{{ article | dump }}",
context = {
"article": article
}
)
self.assertEqual(rendered, article.__dict__)
def test_class_name_templatetag(self):
"""Test the class_name() template tag (print object's class name)"""
article = factories.PostFactory.create()
rendered = render_template(
"{% load class_name %}{{ article | class_name }}",
context = {
"article": article
}
)
self.assertEqual(rendered, "Post")
|
Fix: Allow database name to be configured
We broke the honoring of the database name
settings when we 'refactored' server.js a
couple commits ago.
|
// server.js
//
// The main entry point for Circle Blvd. Handles
// command-line arguments and the highest level
// config for the app.
//
//
// Process command-line arguments
var isDebugging = false;
for (var index in process.argv) {
if (process.argv[index] === '--debug') {
isDebugging = true;
}
}
// Process environment variables, for now
//
// TODO: Put all of these in a more robust
// config situation, and get out of messing
// with process.env so that we can have a
// healthy test environment.
process.env.PORT = process.env.PORT || 3000;
process.env.SSL_PORT = process.env.SSL_PORT || 4000;
process.env.DATABASE_NAME = 'circle-blvd';
var config = {
isDebugging: isDebugging
};
// This line must be after the env variables are set.
var app = require('./app.js');
// Start the app.
app.init(config);
// Wait for the database and such to initialize
app.whenReady(start);
function start () {
app.startServer();
}
|
// server.js
//
// The main entry point for Circle Blvd. Handles
// command-line arguments and the highest level
// config for the app.
//
//
var app = require('./app.js');
// Process command-line arguments
var isDebugging = false;
for (var index in process.argv) {
if (process.argv[index] === '--debug') {
isDebugging = true;
}
}
// Process environment variables, for now
//
// TODO: Put all of these in a more robust
// config situation, and get out of messing
// with process.env so that we can have a
// healthy test environment.
process.env.PORT = process.env.PORT || 3000;
process.env.SSL_PORT = process.env.SSL_PORT || 4000;
process.env.DATABASE_NAME = 'circle-blvd';
var config = {
isDebugging: isDebugging
};
// Start the app.
app.init(config);
// Wait for the database and such to initialize
app.whenReady(start);
function start () {
app.startServer();
}
|
Add a missing SDK suppression for migration test on platform backend.
Test: Presubmit
Change-Id: I743e5f77a088e7f260d6cc18541b7d9a204dc1f5
|
/*
* Copyright 2021 The Android Open Source Project
*
* 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.
*/
// @exportToFramework:skipFile()
package androidx.appsearch.app.cts;
import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.appsearch.app.AppSearchSession;
import androidx.appsearch.platformstorage.PlatformStorage;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.filters.SdkSuppress;
import com.google.common.util.concurrent.ListenableFuture;
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
public class AppSearchSchemaMigrationPlatformCtsTest extends AppSearchSchemaMigrationCtsTestBase{
@Override
protected ListenableFuture<AppSearchSession> createSearchSession(@NonNull String dbName) {
Context context = ApplicationProvider.getApplicationContext();
return PlatformStorage.createSearchSession(
new PlatformStorage.SearchContext.Builder(context, dbName).build());
}
}
|
/*
* Copyright 2021 The Android Open Source Project
*
* 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.
*/
// @exportToFramework:skipFile()
package androidx.appsearch.app.cts;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.appsearch.app.AppSearchSession;
import androidx.appsearch.platformstorage.PlatformStorage;
import androidx.test.core.app.ApplicationProvider;
import com.google.common.util.concurrent.ListenableFuture;
public class AppSearchSchemaMigrationPlatformCtsTest extends AppSearchSchemaMigrationCtsTestBase{
@Override
protected ListenableFuture<AppSearchSession> createSearchSession(@NonNull String dbName) {
Context context = ApplicationProvider.getApplicationContext();
return PlatformStorage.createSearchSession(
new PlatformStorage.SearchContext.Builder(context, dbName).build());
}
}
|
Move event managers imports to setup in auditor
|
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def __init__(self):
self.tracker = None
self.activitylogs = None
def get_event(self, event_type, instance, **kwargs):
return {
'event_type': event_type,
'instance': instance,
'kwargs': kwargs
}
def record_event(self, event):
self.tracker.record(event_type=event['event_type'],
instance=event['instance'],
**event['kwargs'])
self.activitylogs.record(event_type=event['event_type'],
instance=event['instance'],
**event['kwargs'])
def setup(self):
# Load default event types
import auditor.events # noqa
import activitylogs
import tracker
self.tracker = tracker
self.activitylogs = activitylogs
|
import activitylogs
import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instance, **kwargs):
return {
'event_type': event_type,
'instance': instance,
'kwargs': kwargs
}
def record_event(self, event):
tracker.record(event_type=event['event_type'],
instance=event['instance'],
**event['kwargs'])
activitylogs.record(event_type=event['event_type'],
instance=event['instance'],
**event['kwargs'])
def setup(self):
# Load default event types
import auditor.events # noqa
|
Fix index out of bounds exception by first checking to make sure the configuration option parsed correctly.
r5374
|
package org.openqa.selenium.server;
public class BrowserConfigurationOptions {
private String profile = "";
public BrowserConfigurationOptions(String browserConfiguration) {
//"name:value;name:value"
String[] optionsPairList = browserConfiguration.split(";");
for (int i = 0; i < optionsPairList.length; i++) {
String[] option = optionsPairList[i].split(":", 2);
if (2 == option.length) {
String optionsName = option[0].trim();
String optionValue = option[1].trim();
if ("profile".equalsIgnoreCase(optionsName)) {
this.profile = optionValue;
}
}
}
}
public BrowserConfigurationOptions() {}
/**
* Sets the profile name for this configuration object.
* @param profile_name The name of the profile to use
*/
public void setProfile(String profile_name) {
this.profile = profile_name;
}
public String serialize() {
//"profile:XXXXXXXXXX"
return String.format("profile:%s", profile);
}
public String getProfile() {
return profile;
}
}
|
package org.openqa.selenium.server;
public class BrowserConfigurationOptions {
private String profile = "";
public BrowserConfigurationOptions(String browserConfiguration) {
//"name:value;name:value"
String[] optionsPairList = browserConfiguration.split(";");
for (int i = 0; i < optionsPairList.length; i++) {
String[] option = optionsPairList[i].split(":", 2);
String optionsName = option[0].trim();
String optionValue = option[1].trim();
if ("profile".equalsIgnoreCase(optionsName)) {
this.profile = optionValue;
}
}
}
public BrowserConfigurationOptions() {}
/**
* Sets the profile name for this configuration object.
* @param profile_name The name of the profile to use
*/
public void setProfile(String profile_name) {
this.profile = profile_name;
}
public String serialize() {
//"profile:XXXXXXXXXX"
return String.format("profile:%s", profile);
}
public String getProfile() {
return profile;
}
}
|
Change ropsten port to 8546 to avoid confusion
|
var HDWalletProvider = require("truffle-hdwallet-provider");
// 12-word mnemonic
var mnemonic = "onyx aloof polio bronco spearfish clustered refined earflap darkroom slashing casualty curled";
module.exports = {
networks: {
ropsten: {
network_id: 3, // Official ropsten network id
//provider: new HDWalletProvider(mnemonic, "https://ropsten.infura.io/"), // Use our custom provider
host: 'localhost',
port: 8546
},
development: {
host: "localhost",
port: 8545,
network_id: "*"
}
}
};
|
var HDWalletProvider = require("truffle-hdwallet-provider");
// 12-word mnemonic
var mnemonic = "onyx aloof polio bronco spearfish clustered refined earflap darkroom slashing casualty curled";
module.exports = {
networks: {
ropsten: {
network_id: 3, // Official ropsten network id
//provider: new HDWalletProvider(mnemonic, "https://ropsten.infura.io/"), // Use our custom provider
host: 'localhost',
port: 8545
},
development: {
host: "localhost",
port: 8545,
network_id: "*"
}
}
};
|
Add constant for unicode byte order mark
|
package com.alexrnl.commons.io;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility methods for IO stuff.<br />
* @author Alex
*/
public final class IOUtils {
/** Logger */
private static Logger lg = Logger.getLogger(IOUtils.class.getName());
/** The byte order mark used at the beginning of unicode files */
public static final Character UNICODE_BYTE_ORDER_MARK = '\ufeff';
/**
* Constructor #1.<br />
* Default private constructor.
*/
private IOUtils () {
super();
}
/**
* Read the next line on the buffered reader provided.<br />
* @param reader
* the stream to read.
* @return the next line in the stream.
* @throws IOException
* if there was an issue when reading the stream.
* @throws EOFException
* if the line returned is <code>null</code>.
*/
public static String readLine (final BufferedReader reader) throws IOException, EOFException {
Objects.requireNonNull(reader);
final String line = reader.readLine();
if (lg.isLoggable(Level.FINE)) {
lg.fine("Read line: " + line);
}
if (line == null) {
throw new EOFException("End of stream reached");
}
return line;
}
}
|
package com.alexrnl.commons.io;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility methods for IO stuff.<br />
* @author Alex
*/
public final class IOUtils {
/** Logger */
private static Logger lg = Logger.getLogger(IOUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private IOUtils () {
super();
}
/**
* Read the next line on the buffered reader provided.<br />
* @param reader
* the stream to read.
* @return the next line in the stream.
* @throws IOException
* if there was an issue when reading the stream.
* @throws EOFException
* if the line returned is <code>null</code>.
*/
public static String readLine (final BufferedReader reader) throws IOException, EOFException {
Objects.requireNonNull(reader);
final String line = reader.readLine();
if (lg.isLoggable(Level.FINE)) {
lg.fine("Read line: " + line);
}
if (line == null) {
throw new EOFException("End of stream reached");
}
return line;
}
}
|
tests: Cover one more branch in unit tests
|
const Client = require('../lib/client');
const options = {
baseUrl: 'some value',
username: 'some value',
password: 'some value'
};
describe('Client', () => {
it('should be constructor and factory function', () => {
expect(Client).toBeFunction();
expect(new Client(options)).toBeObject();
expect(Client(options)).toBeObject();
});
it('should have properties with api', () => {
const client = new Client(options);
const apiKeys = Object.keys(client);
expect(apiKeys.length).toEqual(1);
expect(client['branchPermissions']).toBeObject();
});
it('should have validation for options', () => {
expect(() => new Client()).toThrow();
expect(() => new Client(123)).toThrow();
expect(() => new Client({})).toThrow();
expect(() => new Client({ baseUrl: null, username: null, password: null })).toThrow();
expect(() => new Client({ baseUrl: '123' })).toThrow();
expect(() => new Client({ username: '123', password: '123' })).toThrow();
expect(() => new Client({ username: '123', baseUrl: '123' })).toThrow();
expect(() => new Client({ username: '123', password: '123', baseUrl: '123' })).not.toThrow();
});
});
|
const Client = require('../lib/client');
const options = {
baseUrl: 'some value',
username: 'some value',
password: 'some value'
};
describe('Client', () => {
it('should be constructor and factory function', () => {
expect(Client).toBeFunction();
expect(new Client(options)).toBeObject();
expect(Client(options)).toBeObject();
});
it('should have properties with api', () => {
const client = new Client(options);
const apiKeys = Object.keys(client);
expect(apiKeys.length).toEqual(1);
expect(client['branchPermissions']).toBeObject();
});
it('should have validation for options', () => {
expect(() => new Client()).toThrow();
expect(() => new Client(123)).toThrow();
expect(() => new Client({})).toThrow();
expect(() => new Client({ baseUrl: null, username: null, password: null })).toThrow();
expect(() => new Client({ baseUrl: '123' })).toThrow();
expect(() => new Client({ username: '123', password: '123' })).toThrow();
expect(() => new Client({ username: '123', password: '123', baseUrl: '123' })).not.toThrow();
});
});
|
Revert "Revert "Add Total Volunteer members.""
This reverts commit cf41f093a19059a4d849c2ab16a96c826fe5474b.
|
<?php
// Get user type
$userType = 'volunteer';
// Query retrieving user ID, first name, last name of volunteers
$result = db_query('SELECT f.field_first_name_value, l.field_last_name_value, u.name FROM {role} r, {users_roles} ur, {field_data_field_first_name} f, {field_data_field_last_name} l, {users} u WHERE u.uid = ur.uid AND f.entity_id = ur.uid AND l.entity_id = ur.uid AND ur.rid = r.rid AND r.name = :userType', array(':userType' => $userType));
$count = 0;
// Output
foreach ($result as $record) {
$userName = $record->name;
$firstName = $record->field_first_name_value;
$lastName = $record->field_last_name_value;
++$count;
echo '<a href="../users/' . $userName . '/">' . $firstName . ' ' . $lastName . '</a>';
echo "<br /><br />";
}
// Total volunteer members
echo "Total Volunteer Members: $count";
|
<?php
// Get user type
$userType = 'volunteer';
// Query retrieving user ID, first name, last name of volunteers
$result = db_query('SELECT f.field_first_name_value, l.field_last_name_value, u.name FROM {role} r, {users_roles} ur, {field_data_field_first_name} f, {field_data_field_last_name} l, {users} u WHERE u.uid = ur.uid AND f.entity_id = ur.uid AND l.entity_id = ur.uid AND ur.rid = r.rid AND r.name = :userType', array(':userType' => $userType));
echo "<br />";
// Output
foreach ($result as $record) {
$userName = $record->name;
$firstName = $record->field_first_name_value;
$lastName = $record->field_last_name_value;
echo '<a href="../users/' . $userName . '/">' . $firstName . ' ' . $lastName . '</a>';
echo "<br /><br />";
}
|
Add additional fields to permission type
|
import graphene
from django.contrib.auth.models import Permission as DjangoPermission
from graphene_django import DjangoObjectType
from . import models
class ClientUser(DjangoObjectType):
name = graphene.String()
has_cms_access = graphene.Boolean()
user_id = graphene.Int()
permissions = graphene.List(graphene.Int)
class Meta:
model = models.FalmerUser
fields = (
'id',
'name',
)
def resolve_name(self, info):
return self.get_full_name()
def resolve_user_id(self, info):
return self.pk
# this is a quick hack until we work on permissions etc
def resolve_has_cms_access(self, info):
return self.has_perm('wagtailadmin.access_admin')
def resolve_permissions(self, info):
return self.get_permissions()
class Permission(DjangoObjectType):
content_type = graphene.String()
class Meta:
model = DjangoPermission
fields = (
'id',
'name',
'codename',
'content_type',
)
def resolve_content_type(self, info):
return self.content_type.app_label
|
import graphene
from django.contrib.auth.models import Permission as DjangoPermission
from graphene_django import DjangoObjectType
from . import models
class ClientUser(DjangoObjectType):
name = graphene.String()
has_cms_access = graphene.Boolean()
user_id = graphene.Int()
permissions = graphene.List(graphene.Int)
class Meta:
model = models.FalmerUser
fields = (
'id',
'name',
)
def resolve_name(self, info):
return self.get_full_name()
def resolve_user_id(self, info):
return self.pk
# this is a quick hack until we work on permissions etc
def resolve_has_cms_access(self, info):
return self.has_perm('wagtailadmin.access_admin')
def resolve_permissions(self, info):
return self.get_permissions()
class Permission(DjangoObjectType):
content_type = graphene.String()
class Meta:
model = DjangoPermission
fields = (
'content_type',
)
def resolve_content_type(self, info):
return self.content_type.app_label
|
Use the actual DynamicTest type
? was only used with the previous solution,
with the new solution, code can refer to the type
without any problem
|
package io.quarkus.it.main;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import io.quarkus.it.arc.UnusedBean;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
public class DynamicTestsTestCase {
@Inject
UnusedBean bean;
@Test
public void testInjection() {
assertNotNull(bean);
}
@TestFactory
public List<DynamicTest> dynamicTests() {
return Arrays.asList(
DynamicTest.dynamicTest("test 1", () -> {
assertNotNull(bean);
}),
DynamicTest.dynamicTest("test 2", () -> {
assertEquals(1, 1);
}));
}
}
|
package io.quarkus.it.main;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import io.quarkus.it.arc.UnusedBean;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
public class DynamicTestsTestCase {
@Inject
UnusedBean bean;
@Test
public void testInjection() {
assertNotNull(bean);
}
@TestFactory
public List<?> dynamicTests() {
return Arrays.asList(
DynamicTest.dynamicTest("test 1", () -> {
assertNotNull(bean);
}),
DynamicTest.dynamicTest("test 2", () -> {
assertEquals(1, 1);
}));
}
}
|
Check the file extension before requiring a test.
My vim swap files kept getting caught in the test runner so I made the
change to only load up .js files.
|
var fs = require('fs'),
path = require('path'),
fileModule = require('file'),
testDir = '/tests',
testFileName = 'integration_test.js';
process.env.INTEGRATION = true;
describe('endpoint', function() {
it('should load the server and set everything up properly',function(done){
this.timeout(1000); //Server should not take more than 1 sek to boot
var app = require(process.cwd() + '/server');
app.on('ready',function(){
fileModule.walkSync('./endpoints', function(dirPath, dirs, files){
if (dirPath.indexOf(testDir) < 0) return;
files.forEach(function(file){
if (file != testFileName) return;
var fullPath = dirPath + '/' + file;
if (!fs.existsSync(fullPath)) return;
if (path.extname(fullPath) !== '.js') return;
require('../../' + fullPath);
});
});
done();
});
});
});
|
var fs = require('fs'),
fileModule = require('file'),
testDir = '/tests',
testFileName = 'integration_test.js';
process.env.INTEGRATION = true;
describe('endpoint', function() {
it('should load the server and set everything up properly',function(done){
this.timeout(1000); //Server should not take more than 1 sek to boot
var app = require(process.cwd() + '/server');
app.on('ready',function(){
fileModule.walkSync('./endpoints', function(dirPath, dirs, files){
if (dirPath.indexOf(testDir) < 0) return;
files.forEach(function(file){
if (file != testFileName) return;
var path = dirPath + '/' + file;
if (!fs.existsSync(path)) return;
require('../../' + path);
});
});
done();
});
});
});
|
Add background color for loading photos
|
import { withStyles } from '@material-ui/core/styles'
import { Link } from 'client/routes'
const styles = theme => ({
photo: {
backgroundColor: theme.palette.primary.light,
position: 'absolute',
textAlign: 'center',
whiteSpace: 'nowrap',
},
})
const PhotoGridItem = ({ albumSlug, item, classes }) => {
const { versions } = item.photo
return (
<Link
route='photo'
params={{slug: albumSlug, filename: item.photo.filename}}>
<a>
<img
style={{
top: item.top,
left: item.left,
height: item.height,
width: item.width,
}}
className={classes.photo}
srcSet={Object.keys(versions).map(
key => `${versions[key].url} ${versions[key].width}w`
).join(', ')}
sizes={`${item.width}px`}
src={item.photo.urls.mobile_sm}
alt={item.photo.alt} />
</a>
</Link>
)
}
export default withStyles(styles)(PhotoGridItem)
|
import { withStyles } from '@material-ui/core/styles'
import { Link } from 'client/routes'
const styles = theme => ({
photo: {
position: 'absolute',
textAlign: 'center',
color: theme.palette.text.secondary,
whiteSpace: 'nowrap',
},
})
const PhotoGridItem = ({ albumSlug, item, classes }) => {
const { versions } = item.photo
return (
<Link
route='photo'
params={{slug: albumSlug, filename: item.photo.filename}}>
<a>
<img
style={{
top: item.top,
left: item.left,
height: item.height,
width: item.width,
}}
className={classes.photo}
srcSet={Object.keys(versions).map(
key => `${versions[key].url} ${versions[key].width}w`
).join(', ')}
sizes={`${item.width}px`}
src={item.photo.urls.mobile_sm}
alt={item.photo.alt} />
</a>
</Link>
)
}
export default withStyles(styles)(PhotoGridItem)
|
Add comment for object types
|
#!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
# type and id are unique
# ref: https://docs.python.org/2/reference/datamodel.html
# mutable object: value can be changed
# immutable object: value can NOT be changed after created
# This means readonly
# ex: string, numbers, tuple
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
|
#!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
|
Fix broken merge from Master.
|
package uk.ac.ebi.quickgo.index.annotation;
/**
* A class for creating stubbed annotations, representing rows of data read from
* annotation source files.
*
* Created 22/04/16
* @author Edd
*/
class AnnotationMocker {
static Annotation createValidAnnotation() {
Annotation annotation = new Annotation();
annotation.db = "IntAct";
annotation.dbObjectId = "EBI-10043081";
annotation.dbReferences = "PMID:12871976";
annotation.qualifier = "enables";
annotation.goId = "GO:0000977";
annotation.interactingTaxonId = "taxon:12345";
annotation.ecoId = "ECO:0000353";
annotation.with = "GO:0036376,GO:1990573";
annotation.assignedBy = "IntAct";
annotation.annotationExtension = "occurs_in(CL:1000428)";
annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein|db_object_type=protein|target_set=BHF-UCL,Exosome,KRUK";
return annotation;
}
}
|
package uk.ac.ebi.quickgo.index.annotation;
/**
* A class for creating stubbed annotations, representing rows of data read from
* annotation source files.
*
* Created 22/04/16
* @author Edd
*/
class AnnotationMocker {
static Annotation createValidAnnotation() {
Annotation annotation = new Annotation();
annotation.db = "IntAct";
annotation.dbObjectId = "EBI-10043081";
annotation.dbReferences = "PMID:12871976";
annotation.qualifier = "enables";
annotation.goId = "GO:0000977";
annotation.interactingTaxonId = "taxon:12345";
annotation.ecoId = "ECO:0000353";
annotation.with = "GO:0036376,GO:1990573";
annotation.assignedBy = "IntAct";
annotation.annotationExtension = "occurs_in(CL:1000428)";
annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein|db_object_type=protein|target_set=BHF-UCL,Exosome,KRUK";
annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein|target_set=BHF-UCL,Exosome,KRUK";
return annotation;
}
}
|
Add some more clarification in the docs
|
package datamanclient
import (
"context"
"time"
"github.com/jacksontj/dataman/src/query"
)
// TODO: support per-query config?
// TODO support switching config in-flight? If so then we'll need to store a
// pointer to it in the context -- which would require implementing one ourself
type Client struct {
Transport DatamanClientTransport
// TODO: config
}
// TODO: add these convenience methods
/*
Get(query.QueryArgs) *query.Result
Set(query.QueryArgs) *query.Result
Insert(query.QueryArgs) *query.Result
Update(query.QueryArgs) *query.Result
Delete(query.QueryArgs) *query.Result
*/
// DoQuery will execute a given query. This will return a (result, error) -- where the
// error is any transport level error (NOTE: any response errors due to the query will *not*
// be reported in this error, they will be in the normal Result.Error location)
func (d *Client) DoQuery(ctx context.Context, q *query.Query) (*query.Result, error) {
// TODO: timeout should come from config
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel() // Cancel ctx as soon as handleSearch returns.
results, err := d.Transport.DoQuery(c, q)
if err != nil {
return nil, err
} else {
return results, err
}
}
|
package datamanclient
import (
"context"
"time"
"github.com/jacksontj/dataman/src/query"
)
// TODO: support per-query config?
// TODO support switching config in-flight? If so then we'll need to store a
// pointer to it in the context -- which would require implementing one ourself
type Client struct {
Transport DatamanClientTransport
// TODO: config
}
// TODO: add these convenience methods
/*
Get(query.QueryArgs) *query.Result
Set(query.QueryArgs) *query.Result
Insert(query.QueryArgs) *query.Result
Update(query.QueryArgs) *query.Result
Delete(query.QueryArgs) *query.Result
*/
func (d *Client) DoQuery(ctx context.Context, q *query.Query) (*query.Result, error) {
// TODO: timeout should come from config
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel() // Cancel ctx as soon as handleSearch returns.
results, err := d.Transport.DoQuery(c, q)
if err != nil {
return nil, err
} else {
return results, err
}
}
|
Remove author and description meta tags
|
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#464646">
<?php wp_head(); ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body <?php body_class(); ?>>
<header id="masthead" class="site-header" role="banner">
<nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
<?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
</nav>
</header>
|
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#464646">
<meta name="author" content="">
<meta name="description" content="">
<?php wp_head(); ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body <?php body_class(); ?>>
<header id="masthead" class="site-header" role="banner">
<nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
<?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
</nav>
</header>
|
Fix polygon particle rounding errors
Fixes #418
|
package de.gurkenlabs.litiengine.graphics.emitters.particles;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
public class PolygonParticle extends ShapeParticle {
private int sides;
public PolygonParticle(float width, float height, int sides) {
super(width, height);
this.sides = sides;
}
@Override
protected Shape getShape(Point2D emitterOrigin) {
Path2D path = new Path2D.Double();
double x = this.getAbsoluteX(emitterOrigin) + this.getWidth() / 2;
double y = this.getAbsoluteY(emitterOrigin) + this.getHeight() / 2;
double theta = 2 * Math.PI / this.sides;
path.moveTo(x + this.getWidth(), y + 0);
for (int i = 0; i < this.sides; i++) {
path.lineTo(
x + this.getWidth() * Math.cos(theta * i),
y + this.getHeight() * Math.sin(theta * i));
}
path.closePath();
final AffineTransform rotate =
AffineTransform.getRotateInstance(
Math.toRadians(this.getAngle()),
this.getAbsoluteX(emitterOrigin) + this.getWidth() * 0.5,
this.getAbsoluteY(emitterOrigin) + this.getHeight() * 0.5);
return rotate.createTransformedShape(path);
}
}
|
package de.gurkenlabs.litiengine.graphics.emitters.particles;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
public class PolygonParticle extends ShapeParticle {
private int sides;
public PolygonParticle(float width, float height, int sides) {
super(width, height);
this.sides = sides;
}
@Override
protected Shape getShape(Point2D emitterOrigin) {
Polygon p = new Polygon();
float x = this.getAbsoluteX(emitterOrigin) + this.getWidth() / 2;
float y = this.getAbsoluteY(emitterOrigin) + this.getHeight() / 2;
float theta = (float) (2 * Math.PI / this.sides);
for (int i = 0; i < this.sides; i++) {
p.addPoint(
(int) (x + this.getWidth() * Math.cos(theta * i)),
(int) (y + this.getHeight() * Math.sin(theta * i)));
}
final AffineTransform rotate =
AffineTransform.getRotateInstance(
Math.toRadians(this.getAngle()),
this.getAbsoluteX(emitterOrigin) + this.getWidth() * 0.5,
this.getAbsoluteY(emitterOrigin) + this.getHeight() * 0.5);
return rotate.createTransformedShape(p);
}
}
|
Fix mismatch in development WebTestCase method signature
|
<?php
// Settings to make all errors more obvious during testing
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
date_default_timezone_set('UTC');
use There4\Slim\Test\WebTestCase;
define('PROJECT_ROOT', realpath(__DIR__ . '/..'));
require_once PROJECT_ROOT . '/vendor/autoload.php';
// Initialize our own copy of the slim application
class LocalWebTestCase extends WebTestCase {
public function getSlimInstance() {
$app = new \Slim\Slim(array(
'version' => '0.0.0',
'debug' => false,
'mode' => 'testing',
'templates.path' => __DIR__ . '/../app/templates'
));
// Include our core application file
require PROJECT_ROOT . '/app/app.php';
return $app;
}
};
/* End of file bootstrap.php */
|
<?php
// Settings to make all errors more obvious during testing
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
date_default_timezone_set('UTC');
use There4\Slim\Test\WebTestCase;
define('PROJECT_ROOT', realpath(__DIR__ . '/..'));
require_once PROJECT_ROOT . '/vendor/autoload.php';
// Initialize our own copy of the slim application
class LocalWebTestCase extends WebTestCase {
public function createApplication() {
$app = new \Slim\Slim(array(
'version' => '0.0.0',
'debug' => false,
'mode' => 'testing',
'templates.path' => __DIR__ . '/../app/templates'
));
// Include our core application file
require PROJECT_ROOT . '/app/app.php';
return $app;
}
};
/* End of file bootstrap.php */
|
Set version to 0.2.1. Ready for PyPI.
|
import os
try:
from setuptools import setup, Extension
except ImportError:
# Use distutils.core as a fallback.
# We won't be able to build the Wheel file on Windows.
from distutils.core import setup, Extension
extensions = []
if os.name == 'nt':
ext = Extension(
'asyncio._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
setup(
name="asyncio",
version="0.2.1",
description="reference implementation of PEP 3156",
long_description=open("README").read(),
url="http://www.python.org/dev/peps/pep-3156/",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
],
packages=["asyncio"],
ext_modules=extensions,
)
|
import os
try:
from setuptools import setup, Extension
except ImportError:
# Use distutils.core as a fallback.
# We won't be able to build the Wheel file on Windows.
from distutils.core import setup, Extension
extensions = []
if os.name == 'nt':
ext = Extension(
'asyncio._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
setup(
name="asyncio",
version="0.1.1",
description="reference implementation of PEP 3156",
long_description=open("README").read(),
url="http://www.python.org/dev/peps/pep-3156/",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
],
packages=["asyncio"],
ext_modules=extensions,
)
|
Handle shell args in python scripts
|
#!/usr/bin/env python
import sys
import json
import struct
import subprocess
import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
args = shlex.split("mpv " + mpv_args)
subprocess.call(args)
sys.exit(0)
|
#!/usr/bin/env python
# and add mpv.json to ~/.mozilla/native-messaging-hosts
import sys
import json
import struct
import subprocess
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
subprocess.call(["mpv", mpv_args])
|
Update testes (Chamber of Deputies changed real world data)
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
CC-5781: Upgrade script for new storage quota implementation
|
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
Fix target channel of !welcome
|
'use strict';
const
Command = require('../Command'),
MentionsMiddleware = require('../../middleware/MentionsMiddleware'),
RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
class CommandWelcome extends Command {
constructor(module, commandConfig) {
super(module, commandConfig);
this.id = 'welcome';
this.helpText = 'Welcomes people to the server and directs them to the read-first channel.';
this.shortHelpText = 'Welcomes people to the server';
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionsMiddleware({ types: 'mention' })
];
}
onCommand(response) {
const welcomeChannel = response.message.guild.channels.get(this.config.target_channel);
return (
`Hey there {mentions}, welcome to The Raiders Inn! ` +
`Be sure to head over to ${welcomeChannel} to get started. ` +
'You will find our rules and general information there. ' +
`Don't forget to assign yourself to a server!\n\n` +
'Enjoy your stay! :beers:'
);
}
}
module.exports = CommandWelcome;
|
'use strict';
const
Command = require('../Command'),
MentionsMiddleware = require('../../middleware/MentionsMiddleware'),
RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
class CommandWelcome extends Command {
constructor(module, commandConfig) {
super(module, commandConfig);
this.id = 'welcome';
this.helpText = 'Welcomes people to the server and directs them to the read-first channel.';
this.shortHelpText = 'Welcomes people to the server';
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionsMiddleware({ types: 'mention' })
];
}
onCommand(response) {
const welcomeChannel = response.message.guild.channels.get(this.config.get.target_channel);
return (
`Hey there {mentions}, welcome to The Raiders Inn! ` +
`Be sure to head over to ${welcomeChannel} to get started. ` +
'You will find our rules and general information there. ' +
`Don't forget to assign yourself to a server!\n\n` +
'Enjoy your stay! :beers:'
);
}
}
module.exports = CommandWelcome;
|
US2086: Clear RSA key area when showing/hiding. Improve indentation.
|
$(document).ready(function() {
$("#addKeyBtn").unbind("click");
$("#addKeyBtn").click(function() {
$("#rsaKeyField").toggle(250);
$("#rsaKeyField").find(':input').val('');
$("#key_arrow").toggleClass("icon-chevron-left, icon-chevron-down");
});
if (is_sandbox) {
var buttonEnableForCustom = function() {
if($("#custom_ed_org").val().length == 0) {
$("#provisionButton").attr("disabled","disabled")
}
else {
$("#provisionButton").removeAttr("disabled")
}
}
$("input[type=radio][id!=custom]").click(function() {
$("#custom_ed_org").attr("disabled","disabled");
$("#provisionButton").removeAttr("disabled")
});
$("#custom").click(function() {
$("#custom_ed_org").removeAttr("disabled");
buttonEnableForCustom()
});
$("#custom_ed_org").bind('input propertychange', buttonEnableForCustom);
if($("#custom").attr("type") == "radio"){
$("#custom_ed_org").attr("disabled","disabled")
}
$("#provisionButton").attr("disabled", "disabled")
}
})
|
$(document).ready(function() {
$("#addKeyBtn").unbind("click");
$("#addKeyBtn").click(function() {
$("#rsaKeyField").toggle(250);
$("#rsaKeyField").val(""); // this doesn't work, want to clear the text whenever shown/hidden
$("#key_arrow").toggleClass("icon-chevron-left, icon-chevron-down");
});
if (is_sandbox) {
var buttonEnableForCustom = function() {
if($("#custom_ed_org").val().length == 0) {
$("#provisionButton").attr("disabled","disabled")
}
else {
$("#provisionButton").removeAttr("disabled")
}
}
$("input[type=radio][id!=custom]").click(function() {
$("#custom_ed_org").attr("disabled","disabled");
$("#provisionButton").removeAttr("disabled")});
$("#custom").click(function() {
$("#custom_ed_org").removeAttr("disabled");
buttonEnableForCustom()});
$("#custom_ed_org").bind('input propertychange', buttonEnableForCustom);
if($("#custom").attr("type") == "radio"){
$("#custom_ed_org").attr("disabled","disabled")
}
$("#provisionButton").attr("disabled", "disabled")
}
})
|
Add product name to model.
|
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
var Models = {};
Models.Want = Backbone.Model.extend({
defaults: {
id: '',
name: '',
price: '',
location: '',
buyers: [],
owner: '',
imageUrl: '',
dateStart: '',
dateExpire: ''
},
initialize: function() {
},
parse: function(response) {
var listing = response.ProductListing;
var product = listing.product;
var attributes = {
id: listing.id,
name: product.name,
owner: listing.creator_id,
dateStart: listing.date_start,
dateExpire: listing.date_expire,
location: listing.location,
productId: listing.product_id,
price: product.price,
imageUrl: product.images[0]
};
return attributes;
}
});
return Models;
});
|
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
var Models = {};
Models.Want = Backbone.Model.extend({
defaults: {
id: '',
name: '',
price: '',
location: '',
buyers: [],
owner: '',
imageUrl: '',
dateStart: '',
dateExpire: ''
},
initialize: function() {
},
parse: function(response) {
var listing = response.ProductListing;
var product = listing.product;
var attributes = {
id: listing.id,
owner: listing.creator_id,
dateStart: listing.date_start,
dateExpire: listing.date_expire,
location: listing.location,
productId: listing.product_id,
price: product.price,
imageUrl: product.images[0]
};
return attributes;
}
});
return Models;
});
|
Check match with identity operator against a boolean
|
<?php
namespace PHPSpec2\Matcher;
abstract class BasicMatcher implements MatcherInterface
{
final public function positiveMatch($name, $subject, array $arguments)
{
if (false === $this->matches($subject, $arguments)) {
throw $this->getFailureException($name, $subject, $arguments);
}
return $subject;
}
final public function negativeMatch($name, $subject, array $arguments)
{
if (true === $this->matches($subject, $arguments)) {
throw $this->getNegativeFailureException($name, $subject, $arguments);
}
return $subject;
}
abstract protected function matches($subject, array $arguments);
abstract protected function getFailureException($name, $subject, array $arguments);
abstract protected function getNegativeFailureException($name, $subject, array $arguments);
}
|
<?php
namespace PHPSpec2\Matcher;
abstract class BasicMatcher implements MatcherInterface
{
final public function positiveMatch($name, $subject, array $arguments)
{
if (!$this->matches($subject, $arguments)) {
throw $this->getFailureException($name, $subject, $arguments);
}
return $subject;
}
final public function negativeMatch($name, $subject, array $arguments)
{
if ($this->matches($subject, $arguments)) {
throw $this->getNegativeFailureException($name, $subject, $arguments);
}
return $subject;
}
abstract protected function matches($subject, array $arguments);
abstract protected function getFailureException($name, $subject, array $arguments);
abstract protected function getNegativeFailureException($name, $subject, array $arguments);
}
|
Fix issue of not working for multipe tabs
Rename for clarity:
scriptInjected -> injected
attachedTabs -> activeTabs
Change injected type for proper work with multiple tabs.
Injected property is still a boolean.
Change activeTabs[tabId] toggling to boolean for clarity.
|
// Global variables only exist for the life of the page, so they get reset
// each time the page is unloaded.
const activeTabs = {};
const injected = {};
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener((tab) => {
const tabId = tab.id;
if (!injected[tabId]) {
chrome.tabs.executeScript(tabId, { file: 'src/bg/injecthtml.js' }, (response) => {
injected[tabId] = response;
chrome.browserAction.setIcon({ tabId, path: 'icons/continue.png' });
chrome.browserAction.setTitle({ tabId, title: 'Enable collapsing' });
chrome.tabs.insertCSS(tabId, { file: 'css/toggle.css' });
chrome.tabs.executeScript(tabId, { file: 'src/bg/toggle_collapse.js' });
});
} else if (!activeTabs[tabId]) {
activeTabs[tabId] = true;
chrome.browserAction.setIcon({ tabId, path: 'icons/pause.png' });
chrome.browserAction.setTitle({ tabId, title: 'Pause collapsing' });
chrome.tabs.sendMessage(tabId, { collapse: true });
} else if (activeTabs[tabId]) {
activeTabs[tabId] = false;
chrome.browserAction.setIcon({ tabId, path: 'icons/continue.png' });
chrome.browserAction.setTitle({ tabId, title: 'Enable collapsing' });
chrome.tabs.sendMessage(tabId, { collapse: false });
}
});
|
// Global variables only exist for the life of the page, so they get reset
// each time the page is unloaded.
const attachedTabs = {};
let scriptInjected = false;
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener((tab) => {
const tabId = tab.id;
if (!scriptInjected) {
chrome.tabs.executeScript(tabId, { file: 'src/bg/injecthtml.js' }, (response) => {
scriptInjected = response;
chrome.browserAction.setIcon({ tabId, path: 'icons/continue.png' });
chrome.browserAction.setTitle({ tabId, title: 'Enable collapsing' });
chrome.tabs.insertCSS(tabId, { file: 'css/toggle.css' });
chrome.tabs.executeScript(tabId, { file: 'src/bg/toggle_collapse.js' });
});
} else if (!attachedTabs[tabId]) {
attachedTabs[tabId] = 'collapsed';
chrome.browserAction.setIcon({ tabId, path: 'icons/pause.png' });
chrome.browserAction.setTitle({ tabId, title: 'Pause collapsing' });
chrome.tabs.sendMessage(tabId, { collapse: true });
} else if (attachedTabs[tabId]) {
delete attachedTabs[tabId];
chrome.browserAction.setIcon({ tabId, path: 'icons/continue.png' });
chrome.browserAction.setTitle({ tabId, title: 'Enable collapsing' });
chrome.tabs.sendMessage(tabId, { collapse: false });
}
});
|
Support any later versions of SQLAlchemy
|
import collections
import numbers
import os
from sqlalchemy import __version__
from sqlalchemy_imageattach.version import VERSION, VERSION_INFO
def test_version_info():
assert isinstance(VERSION_INFO, collections.Sequence)
assert len(VERSION_INFO) == 3
assert isinstance(VERSION_INFO[0], numbers.Integral)
assert isinstance(VERSION_INFO[1], numbers.Integral)
assert isinstance(VERSION_INFO[2], numbers.Integral)
def test_sqlalchemy_version():
sqla_version_info = list(map(int, __version__.split('.')[:2]))
assert sqla_version_info >= list(VERSION_INFO[:2])
assert __version__.split('.')[:2] >= VERSION.split('.')[:2]
def test_version():
assert isinstance(VERSION, str)
assert list(map(int, VERSION.split('.'))) == list(VERSION_INFO)
def test_print():
with os.popen('python -m sqlalchemy_imageattach.version') as pipe:
printed_version = pipe.read().strip()
assert printed_version == VERSION
|
import collections
import numbers
import os
from sqlalchemy import __version__
from sqlalchemy_imageattach.version import VERSION, VERSION_INFO
def test_version_info():
assert isinstance(VERSION_INFO, collections.Sequence)
assert len(VERSION_INFO) == 3
assert isinstance(VERSION_INFO[0], numbers.Integral)
assert isinstance(VERSION_INFO[1], numbers.Integral)
assert isinstance(VERSION_INFO[2], numbers.Integral)
def test_sqlalchemy_version():
assert list(map(int, __version__.split('.')[:2])) == list(VERSION_INFO[:2])
assert __version__.split('.')[:2] == VERSION.split('.')[:2]
def test_version():
assert isinstance(VERSION, str)
assert list(map(int, VERSION.split('.'))) == list(VERSION_INFO)
def test_print():
with os.popen('python -m sqlalchemy_imageattach.version') as pipe:
printed_version = pipe.read().strip()
assert printed_version == VERSION
|
Fix yet another 3k issue (stderr not flushing automatically).
Signed-off-by: Thomas Hori <7133b3a0da8e60bd3295f2c8559ef184054a68ed@liddicott.com>
|
from repugeng.StaticClass import StaticClass
import sys
class Compat3k(StaticClass):
@classmethod
def str_to_bytes(cls, s):
"""Convert a string of either width to a byte string."""
try:
try:
return bytes(s)
except NameError:
return str(s)
except ValueError:
pass #Not ASCII? Not really a problem...
except TypeError:
pass #I didn't specify an encoding? Oh, boo hoo...
return s.encode("latin1") #Not utf-8, m'kay...
@classmethod
def prompt_user(cls, s="", file=None):
"""Substitute of py2k's raw_input()."""
(file or sys.stderr).write(s)
(file or sys.stderr).flush()
return sys.stdin.readline().rstrip("\r\n")
|
from repugeng.StaticClass import StaticClass
import sys
class Compat3k(StaticClass):
@classmethod
def str_to_bytes(cls, s):
"""Convert a string of either width to a byte string."""
try:
try:
return bytes(s)
except NameError:
return str(s)
except ValueError:
pass #Not ASCII? Not really a problem...
except TypeError:
pass #I didn't specify an encoding? Oh, boo hoo...
return s.encode("latin1") #Not utf-8, m'kay...
@classmethod
def prompt_user(cls, s="", file=None):
"""Substitute of py2k's raw_input()."""
(file or sys.stderr).write(s)
return sys.stdin.readline().rstrip("\r\n")
|
Fix version endpoint returning a Content-Type of application/xml instead of application/json when client specifies Accept-Content-Type: application/xml
RB=596810
G=pinot-dev-reviewers
R=kgopalak,jfim,ssubrama,dpatel,mshrivas
A=mshrivas
|
package com.linkedin.pinot.controller.api.restlet.resources;
import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.controller.api.swagger.HttpVerb;
import com.linkedin.pinot.controller.api.swagger.Paths;
import com.linkedin.pinot.controller.api.swagger.Summary;
import com.linkedin.pinot.controller.api.swagger.Tags;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
/**
* API endpoint that returns the versions of Pinot components.
*/
public class PinotVersionRestletResource extends PinotRestletResourceBase {
@Override
@Get
public Representation get() {
return buildVersionResponse();
}
@HttpVerb("get")
@Summary("Obtains the version number of the Pinot components")
@Tags({ "version" })
@Paths({ "/version" })
private Representation buildVersionResponse() {
JSONObject jsonObject = new JSONObject(Utils.getComponentVersions());
return new StringRepresentation(jsonObject.toString(), MediaType.APPLICATION_JSON);
}
}
|
package com.linkedin.pinot.controller.api.restlet.resources;
import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.controller.api.swagger.HttpVerb;
import com.linkedin.pinot.controller.api.swagger.Paths;
import com.linkedin.pinot.controller.api.swagger.Summary;
import com.linkedin.pinot.controller.api.swagger.Tags;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
/**
* API endpoint that returns the versions of Pinot components.
*/
public class PinotVersionRestletResource extends PinotRestletResourceBase {
@Override
@Get
public Representation get() {
return buildVersionResponse();
}
@HttpVerb("get")
@Summary("Obtains the version number of the Pinot components")
@Tags({ "version" })
@Paths({ "/version" })
private Representation buildVersionResponse() {
JSONObject jsonObject = new JSONObject(Utils.getComponentVersions());
return new StringRepresentation(jsonObject.toString(), MediaType.APPLICATION_ALL_JSON);
}
}
|
Revert "remove line to apply for new team"
This reverts commit e9cc064a440db8457387a8ce527453679446b327.
|
package sg.ncl.service.registration.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sg.ncl.service.registration.RegistrationService;
import sg.ncl.service.registration.dtos.RegistrationData;
import sg.ncl.service.registration.dtos.RegistrationInfo;
import javax.inject.Inject;
/**
* @author Te Ye & Desmond
*/
@RestController
@RequestMapping(path = "/registrations", produces = MediaType.APPLICATION_JSON_VALUE)
public class RegistrationController {
private final RegistrationService registrationService;
@Inject
protected RegistrationController(final RegistrationService registrationService) {
this.registrationService = registrationService;
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void register(@RequestBody RegistrationInfo registrationInfo) {
// System.out.println("User: " + registrationInfo.getUser());
// System.out.println("Team: " + registrationInfo.getTeam());
// System.out.println("Registration: " + registrationInfo.getRegistration());
if (registrationInfo.getIsJoinTeam())
registrationService.register(registrationInfo.getCredentials(), registrationInfo.getUser(), registrationInfo.getTeam(), registrationInfo.getIsJoinTeam());
}
}
|
package sg.ncl.service.registration.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sg.ncl.service.registration.RegistrationService;
import sg.ncl.service.registration.dtos.RegistrationInfo;
import javax.inject.Inject;
/**
* @author Te Ye & Desmond
*/
@RestController
@RequestMapping(path = "/registrations", produces = MediaType.APPLICATION_JSON_VALUE)
public class RegistrationController {
private final RegistrationService registrationService;
@Inject
protected RegistrationController(final RegistrationService registrationService) {
this.registrationService = registrationService;
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void register(@RequestBody RegistrationInfo registrationInfo) {
registrationService.register(registrationInfo.getCredentials(), registrationInfo.getUser(), registrationInfo.getTeam(), registrationInfo.getIsJoinTeam());
}
}
|
Add prettier-ignore to generated files
Summary:
When prettier is run on the generated files, it removes the parenthesis resulting in flow failing.
Adding the prettier-ignore comment skip formatting of this line.
Fixes #2426
Closes https://github.com/facebook/relay/pull/2427
Reviewed By: devknoll
Differential Revision: D7759820
Pulled By: kassens
fbshipit-source-id: d447281c7e702f8feb4138210e7e3a90a95730b4
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import type {FormatModule} from './writeRelayGeneratedFile';
const formatGeneratedModule: FormatModule = ({
moduleName,
documentType,
docText,
concreteText,
flowText,
hash,
relayRuntimeModule,
sourceHash,
}) => {
const docTextComment = docText ? '\n/*\n' + docText.trim() + '\n*/\n' : '';
const hashText = hash ? `\n * ${hash}` : '';
return `/**
* ${'@'}flow${hashText}
*/
/* eslint-disable */
'use strict';
/*::
import type { ${documentType} } from '${relayRuntimeModule}';
${flowText || ''}
*/
${docTextComment}
const node/*: ${documentType}*/ = ${concreteText};
// prettier-ignore
(node/*: any*/).hash = '${sourceHash}';
module.exports = node;
`;
};
module.exports = formatGeneratedModule;
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import type {FormatModule} from './writeRelayGeneratedFile';
const formatGeneratedModule: FormatModule = ({
moduleName,
documentType,
docText,
concreteText,
flowText,
hash,
relayRuntimeModule,
sourceHash,
}) => {
const docTextComment = docText ? '\n/*\n' + docText.trim() + '\n*/\n' : '';
const hashText = hash ? `\n * ${hash}` : '';
return `/**
* ${'@'}flow${hashText}
*/
/* eslint-disable */
'use strict';
/*::
import type { ${documentType} } from '${relayRuntimeModule}';
${flowText || ''}
*/
${docTextComment}
const node/*: ${documentType}*/ = ${concreteText};
(node/*: any*/).hash = '${sourceHash}';
module.exports = node;
`;
};
module.exports = formatGeneratedModule;
|
Add Changelog podcast to default tracks... for a while
|
import skin from "../skins/base-2.91-png.wsz";
import llamaAudio from "../mp3/llama-2.91.mp3";
/* global SENTRY_DSN */
const { hash } = window.location;
let config = {};
if (hash) {
try {
config = JSON.parse(decodeURIComponent(hash).slice(1));
} catch (e) {
console.error("Failed to decode config from hash: ", hash);
}
}
// Backwards compatibility with the old syntax
if (config.audioUrl && !config.initialTracks) {
config.initialTracks = [{ url: config.audioUrl }];
}
// Turn on the incomplete playlist window
export const skinUrl = config.skinUrl === undefined ? skin : config.skinUrl;
export const initialTracks = config.initialTracks || [
{
metaData: { artist: "DJ Mike Llama", title: "Llama Whippin' Intro" },
url: llamaAudio
},
{
url: "https://cdn.changelog.com/uploads/podcast/291/the-changelog-291.mp3",
metaData: {
artist: "Changelog Media",
title: "Winamp2-js with Jordan Eldredge"
},
duration: 4841
}
];
export const hideAbout = config.hideAbout || false;
export const initialState = config.initialState || undefined;
export const sentryDsn = SENTRY_DSN;
|
import skin from "../skins/base-2.91-png.wsz";
import llamaAudio from "../mp3/llama-2.91.mp3";
/* global SENTRY_DSN */
const { hash } = window.location;
let config = {};
if (hash) {
try {
config = JSON.parse(decodeURIComponent(hash).slice(1));
} catch (e) {
console.error("Failed to decode config from hash: ", hash);
}
}
// Backwards compatibility with the old syntax
if (config.audioUrl && !config.initialTracks) {
config.initialTracks = [{ url: config.audioUrl }];
}
// Turn on the incomplete playlist window
export const skinUrl = config.skinUrl === undefined ? skin : config.skinUrl;
export const initialTracks = config.initialTracks || [
{
metaData: { artist: "DJ Mike Llama", title: "Llama Whippin' Intro" },
url: llamaAudio
}
];
export const hideAbout = config.hideAbout || false;
export const initialState = config.initialState || undefined;
export const sentryDsn = SENTRY_DSN;
|
Load all stylesheets for public preview
fixes #88
Signed-off-by: Robin Appelman <474ee9ee179b0ecf0bc27408079a0b15eda4c99d@icewind.nl>
|
<?php
$eventDispatcher = \OC::$server->getEventDispatcher();
$eventDispatcher->addListener(
'OCA\Files::loadAdditionalScripts',
function () {
$policy = new \OC\Security\CSP\ContentSecurityPolicy();
$policy->setAllowedImageDomains(['*']);
$frameDomains = $policy->getAllowedFrameDomains();
$frameDomains[] = 'www.youtube.com';
$frameDomains[] = 'prezi.com';
$frameDomains[] = 'player.vimeo.com';
$frameDomains[] = 'vine.co';
$policy->setAllowedFrameDomains($frameDomains);
\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy);
//load the required files
OCP\Util::addscript('files_markdown', '../build/editor');
OCP\Util::addStyle('files_markdown', '../build/styles');
OCP\Util::addStyle('files_markdown', 'preview');
});
$eventDispatcher->addListener(
'OCA\Files_Sharing::loadAdditionalScripts',
function () {
OCP\Util::addScript('files_markdown', '../build/editor');
OCP\Util::addStyle('files_markdown', '../build/styles');
OCP\Util::addStyle('files_markdown', 'preview');
});
|
<?php
$eventDispatcher = \OC::$server->getEventDispatcher();
$eventDispatcher->addListener(
'OCA\Files::loadAdditionalScripts',
function () {
$policy = new \OC\Security\CSP\ContentSecurityPolicy();
$policy->setAllowedImageDomains(['*']);
$frameDomains = $policy->getAllowedFrameDomains();
$frameDomains[] = 'www.youtube.com';
$frameDomains[] = 'prezi.com';
$frameDomains[] = 'player.vimeo.com';
$frameDomains[] = 'vine.co';
$policy->setAllowedFrameDomains($frameDomains);
\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy);
//load the required files
OCP\Util::addscript('files_markdown', '../build/editor');
OCP\Util::addStyle('files_markdown', '../build/styles');
OCP\Util::addStyle('files_markdown', 'preview');
});
$eventDispatcher->addListener(
'OCA\Files_Sharing::loadAdditionalScripts',
function () {
OCP\Util::addScript('files_markdown', '../build/editor');
OCP\Util::addStyle('files_markdown', 'preview');
});
|
Fix Promise rejection for save()
|
// @flow
import mongoose from 'mongoose'
import Message from './model/message'
export const homePage = () => null
export const helloPage = () =>
new Promise((resolve, reject) => {
const helloMessage = new Message({
key: 'hello-msg',
content: 'Server-side preloaded message from the DB',
})
mongoose.connection.db.collection('messages').drop()
.then(
/* eslint-disable no-console */
() => console.log('Message collection dropped'),
() => console.log('Message collection already empty'),
/* eslint-enable no-console */
)
.then(() => helloMessage.save((err) => { if (err) reject(err) }))
.then(() => Message
.findOne({ key: 'hello-msg' })
.exec((err, result) => {
if (err) reject(err)
resolve({ hello: { message: result.content } })
}),
)
})
export const helloAsyncPage = () => ({
hello: { messageAsync: 'Server-side preloaded message for async page' },
})
export const helloEndpoint = (num: number) => ({
serverMessage: `Hello from the server! (received ${num})`,
})
|
// @flow
import mongoose from 'mongoose'
import Message from './model/message'
export const homePage = () => null
export const helloPage = () =>
new Promise((resolve, reject) => {
const helloMessage = new Message({
key: 'hello',
content: 'Server-side preloaded message from the DB',
})
mongoose.connection.db.collection('messages').drop()
.then(
/* eslint-disable no-console */
() => console.log('Message collection dropped'),
() => console.log('Message collection not found'),
/* eslint-enable no-console */
)
.then(() => helloMessage.save(err => reject(err)))
.then(() => Message
.findOne({ key: 'hello' })
.exec((err, result) => {
if (err) reject(err)
resolve({ hello: { message: result.content } })
}),
)
})
export const helloAsyncPage = () => ({
hello: { messageAsync: 'Server-side preloaded message for async page' },
})
export const helloEndpoint = (num: number) => ({
serverMessage: `Hello from the server! (received ${num})`,
})
|
Replace variable class name field by function get class name field
|
<?php namespace ThibaudDauce\EloquentVariableModelConstructor;
trait VariableModelConstructorTrait {
/**
* Get class name field.
*
* @return string
*/
protected function getClassnameField()
{
return 'class_name';
}
/**
* Create a new model instance that is existing.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = array())
{
if (!isset($attributes[$this->getClassnameField()]))
return parent::newFromBuilder($attributes);
$class = $attributes[$this->getClassnameField()];
$instance = new $class;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
}
|
<?php namespace ThibaudDauce\EloquentVariableModelConstructor;
trait VariableModelConstructorTrait {
/**
* Database field indicated class name.
*
* @var string
*/
protected $class_name_field = 'class_name';
/**
* Create a new model instance that is existing.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = array())
{
if (!isset($attributes->$class_name_field))
return parent::newFromBuilder($attributes);
$class = $attributes->$class_name_field;
$instance = new $class;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
}
|
Break a line exceeding 80 chars into two
|
// Copyright (C) 2017 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package main
import (
"testing"
)
func runTemplateFunctionTest(t *testing.T,
funcName, arg, expected string) {
result := funcMap[funcName].(func(string) string)(arg)
if result != expected {
t.Error("Error: \"" + result + "\" != \"" + expected + "\"")
}
}
func TestTemplateFunctions(t *testing.T) {
runTemplateFunctionTest(t, "VarName", "C++11", "Cxx11")
runTemplateFunctionTest(t, "VarName", "one-half", "one_half")
runTemplateFunctionTest(t, "VarNameUC", "C++11", "CXX11")
runTemplateFunctionTest(t, "VarNameUC",
"cross-country", "CROSS_COUNTRY")
runTemplateFunctionTest(t, "LibName", "libc++11", "libc++11")
runTemplateFunctionTest(t, "LibName", "dash-dot.", "dash-dot.")
}
|
// Copyright (C) 2017 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package main
import (
"testing"
)
func runTemplateFunctionTest(t *testing.T,
funcName, arg, expected string) {
result := funcMap[funcName].(func(string) string)(arg)
if result != expected {
t.Error("Error: \"" + result + "\" != \"" + expected + "\"")
}
}
func TestTemplateFunctions(t *testing.T) {
runTemplateFunctionTest(t, "VarName", "C++11", "Cxx11")
runTemplateFunctionTest(t, "VarName", "one-half", "one_half")
runTemplateFunctionTest(t, "VarNameUC", "C++11", "CXX11")
runTemplateFunctionTest(t, "VarNameUC", "cross-country", "CROSS_COUNTRY")
runTemplateFunctionTest(t, "LibName", "libc++11", "libc++11")
runTemplateFunctionTest(t, "LibName", "dash-dot.", "dash-dot.")
}
|
Hide the „IsValid“ property in JSON
|
package data
// Definition stores information about a system, used for importing data.
type Definition struct {
Title string
Type string
Env string
Location string
User string
Password string
URL string
Notes string
Tags []string
}
// YamlData stores information about all systems, used for importing data.
type YamlData struct {
Defs []Definition
}
// Config stores data about a system, used for exporting data.
type Config struct {
ID string `json:"id,"`
Title string `json:"title"`
Location string `json:"location"`
Environment string `json:"environment"`
User string `json:"user"`
Password string `json:"password,omitempty"`
Host string `json:"host,omitempty"`
IsValid bool `json:"-"`
}
|
package data
// Definition stores information about a system, used for importing data.
type Definition struct {
Title string
Type string
Env string
Location string
User string
Password string
URL string
Notes string
Tags []string
}
// YamlData stores information about all systems, used for importing data.
type YamlData struct {
Defs []Definition
}
// Config stores data about a system, used for exporting data.
type Config struct {
ID string `json:"id,"`
Title string `json:"title"`
Location string `json:"location"`
Environment string `json:"environment"`
User string `json:"user"`
Password string `json:"password,omitempty"`
Host string `json:"host,omitempty"`
IsValid bool `json:"valid"`
}
|
Set focus after click to next element
The clearSelection function in clipboard.js blurs the button which hands focus back to the top of body so this plops it back
|
function Copy ($module) {
this.$module = $module
}
Copy.prototype.init = function () {
var $module = this.$module
if (!$module) {
return
}
var $button = document.createElement('button')
$button.className = 'app-copy-button js-copy-button'
$button.setAttribute('aria-live', 'assertive')
$button.textContent = 'Copy code'
$module.insertBefore($button, $module.firstChild)
this.copyAction()
}
Copy.prototype.copyAction = function () {
// Copy to clipboard
try {
new ClipboardJS('.js-copy-button', {
target: function (trigger) {
return trigger.nextElementSibling
}
}).on('success', function (e) {
e.trigger.textContent = 'Code copied'
e.clearSelection()
e.trigger.nextElementSibling.focus()
setTimeout(function () {
e.trigger.textContent = 'Copy code'
}, 5000)
})
} catch (err) {
if (err) {
console.log(err.message)
}
}
}
var $codeBlocks = document.querySelectorAll('pre');
$codeBlocks.forEach((item, i) => {
new Copy(item).init();
});
|
function Copy ($module) {
this.$module = $module
}
Copy.prototype.init = function () {
var $module = this.$module
if (!$module) {
return
}
var $button = document.createElement('button')
$button.className = 'app-copy-button js-copy-button'
$button.setAttribute('aria-live', 'assertive')
$button.textContent = 'Copy code'
$module.insertBefore($button, $module.firstChild)
this.copyAction()
}
Copy.prototype.copyAction = function () {
// Copy to clipboard
try {
new ClipboardJS('.js-copy-button', {
target: function (trigger) {
return trigger.nextElementSibling
}
}).on('success', function (e) {
e.trigger.textContent = 'Code copied'
e.clearSelection()
setTimeout(function () {
e.trigger.textContent = 'Copy code'
}, 5000)
})
} catch (err) {
if (err) {
console.log(err.message)
}
}
}
var $codeBlocks = document.querySelectorAll('pre');
$codeBlocks.forEach((item, i) => {
new Copy(item).init();
});
|
Clear the layout delay timer when unplugging the cards list view.
|
module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
addMethod: 'prepend',
layoutTimer: null,
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
_.bindAll(this, ['layout']);
},
triggerLayout: function() {
this.layoutTimer = _.delay(this.layout, 1);
},
layout: function() {
if (this.collection.isEmpty()) return this;
if (this.$list.data('masonry')) this.$list.masonry('destroy');
this.$list.masonry({
gutter: 15,
itemSelector: 'li.card'
});
return this;
},
onRenderItems: function() {
this.triggerLayout();
},
onPrependItem: function() {
if (!this.isFirstCollectionRender()) this.triggerLayout();
},
onUnplug: function() {
clearTimeout(this.layoutTimer);
if (this.$list.data('masonry')) this.$list.masonry('destroy');
}
});
|
module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
addMethod: 'prepend',
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
_.bindAll(this, ['layout']);
},
onRenderItems: function() {
this.triggerLayout();
},
onPrependItem: function() {
if (!this.isFirstCollectionRender()) this.triggerLayout();
},
triggerLayout: function() {
_.delay(this.layout, 1);
},
layout: function() {
if (this.collection.isEmpty()) return this;
if (this.$list.data('masonry')) this.$list.masonry('destroy');
this.$list.masonry({
gutter: 15,
itemSelector: 'li.card'
});
return this;
}
});
|
Change unuique keys to MySQL varchar
|
from app import app
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, prompt_bool
from datetime import datetime
db = SQLAlchemy(app)
manager = Manager(usage="Manage the database")
@manager.command
def create():
"Create the database"
db.create_all()
@manager.command
def drop():
"Empty the database"
if prompt_bool("Are you sure you want to drop all tables from the database?"):
db.drop_all()
@manager.command
def recreate():
"Recreate the database"
drop()
create()
class Urls(db.Model):
__tablename__ = 'urls'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.VARCHAR(length=255), unique=True)
code = db.Column(db.VARCHAR(length=255), unique=True)
clicks = db.Column(db.Integer, default=0)
created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
def __init__(self, url, code):
self.url = url
self.code = code
def __repr__(self):
return "<Url ('%r', '%r')>" % (self.url, self.code)
|
from app import app
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, prompt_bool
from datetime import datetime
db = SQLAlchemy(app)
manager = Manager(usage="Manage the database")
@manager.command
def create():
"Create the database"
db.create_all()
@manager.command
def drop():
"Empty the database"
if prompt_bool("Are you sure you want to drop all tables from the database?"):
db.drop_all()
@manager.command
def recreate():
"Recreate the database"
drop()
create()
class Urls(db.Model):
__tablename__ = 'urls'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.Text, unique=True)
code = db.Column(db.Text, unique=True)
clicks = db.Column(db.Integer, default=0)
created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
def __init__(self, url, code):
self.url = url
self.code = code
def __repr__(self):
return "<Url ('%r', '%r')>" % (self.url, self.code)
|
Use !! to convert variables to booleans
|
var helper = require('../helper')
var Response = function(id, content, error, internal) {
this.id = parseFloat(id)
this.content = content
this.error = !!error
this.internal = !!internal
}
Response.prototype = {
toString: function() {
return (this.error ? '?' : '=') + (!isNaN(this.id) ? this.id : '') + ' ' + this.content
},
toHtml: function() {
if (!helper) return this.toString()
if (!this.internal) {
var c = this.error ? 'error' : 'success'
return '<span class="' + c + '">' + (this.error ? '?' : '=') + '</span>'
+ (!isNaN(this.id) ? '<span class="id">' + this.id + '</span>' : '')
+ ' ' + helper.htmlify(this.content, true, true, true)
} else {
return '<span class="internal">' + this.content + '</span>'
}
}
}
module.exports = Response
|
var helper = require('../helper')
var Response = function(id, content, error, internal) {
this.id = parseFloat(id)
this.content = content
this.error = error ? true : false
this.internal = internal ? true : false
}
Response.prototype = {
toString: function() {
return (this.error ? '?' : '=') + (!isNaN(this.id) ? this.id : '') + ' ' + this.content
},
toHtml: function() {
if (!helper) return this.toString()
if (!this.internal) {
var c = this.error ? 'error' : 'success'
return '<span class="' + c + '">' + (this.error ? '?' : '=') + '</span>'
+ (!isNaN(this.id) ? '<span class="id">' + this.id + '</span>' : '')
+ ' ' + helper.htmlify(this.content, true, true, true)
} else {
return '<span class="internal">' + this.content + '</span>'
}
}
}
module.exports = Response
|
Revert "Display the tag/facet of the selected term in the input"
This reverts commit f85613a9af711a4aeb27b3bbe6efe8592e8318ce.
|
/*
javascript in this file controls the html page demonstrating the autosubject functionality
*/
/**************************************************************************************/
/* Set up and initialization */
/**************************************************************************************/
/*
initial setup - called from onLoad
attaches the autocomplete function to the search box
*/
var currentSuggestIndexDefault = "suggest50"; //initial default value
function setUpPage(number) {
// connect the autoSubject to the input areas
$('#keyword' + number).autocomplete( {
source: autoSubjectExample,
minLength: 1,
select: function(event, ui) {
$('#fastID' + number).val(ui.item.idroot);
$('#fastType' + number).val(ui.item.tag);
$('#fastInd' + number).val(ui.item.indicator);
} //end select
}
).data( "autocomplete" )._renderItem = function( ul, item ) { formatSuggest(ul, item);};
} //end setUpPage()
/*
example style - simple reformatting
*/
function autoSubjectExample(request, response) {
currentSuggestIndex = currentSuggestIndexDefault;
autoSubject(request, response, exampleStyle);
}
/*
For this example, replace the common subfield break of -- with /
*/
function exampleStyle(res) {
return res["auth"].replace("--","/");
}
|
/*
javascript in this file controls the html page demonstrating the autosubject functionality
*/
/**************************************************************************************/
/* Set up and initialization */
/**************************************************************************************/
/*
initial setup - called from onLoad
attaches the autocomplete function to the search box
*/
var currentSuggestIndexDefault = "suggestall"; //initial default value
function setUpPage(number) {
// connect the autoSubject to the input areas
$('#keyword' + number).autocomplete( {
source: autoSubjectExample,
minLength: 1,
select: function(event, ui) {
$('#fastID' + number).val(ui.item.idroot);
$('#fastType' + number).val(ui.item.tag);
$('#fastInd' + number).val(ui.item.indicator);
} //end select
}
).data( "autocomplete" )._renderItem = function( ul, item ) { formatSuggest(ul, item);};
} //end setUpPage()
/*
example style - simple reformatting
*/
function autoSubjectExample(request, response) {
currentSuggestIndex = currentSuggestIndexDefault;
autoSubject(request, response, exampleStyle);
}
/*
For this example, replace the common subfield break of -- with /
*/
function exampleStyle(res) {
return res["auth"].replace("--","/") + ' (' + getTypeFromTag(res['tag']) + ')';
}
|
Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
|
"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
|
"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.