text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Enable list support in state persist helper
|
import Storage from 'store2';
/**
* @param {String} ns Local storage namespace
* @param {String[]} persistMutations
* @return {function(...[*]=)} Vuex plugin
*/
export default function persistFactory(ns, persistMutations) {
const storage = Storage.namespace(ns);
return function(store) {
const load = () => {
persistMutations.forEach(mutation => {
if (storage.has(mutation)) {
const payloads = /^ADD/.test(mutation) ? storage(mutation) : [storage(mutation)];
payloads.forEach(payload => store.commit(mutation, payload));
}
});
};
window.addEventListener('focus', load);
load();
store.subscribe(mutation => {
if (persistMutations.indexOf(mutation.type) >= 0) {
let oldValue = storage(mutation.type);
// If ADD vs SET, then we'll keep a list of payloads
if (/^ADD/.test(mutation.type)) {
oldValue = oldValue || [];
oldValue.push(mutation.payload);
storage(mutation.type, oldValue);
} else if (oldValue !== mutation.payload) {
storage(mutation.type, mutation.payload);
}
}
});
};
}
|
import Storage from 'store2';
/**
* @param {String} ns Local storage namespace
* @param {String[]} persistMutations
* @return {function(...[*]=)} Vuex plugin
*/
export default function persistFactory(ns, persistMutations) {
const storage = Storage.namespace(ns);
return function(store) {
const load = () => {
persistMutations.forEach(mutation => {
if (storage.has(mutation)) {
store.commit(mutation, storage(mutation));
}
});
};
window.addEventListener('focus', load);
load();
store.subscribe(mutation => {
if (
persistMutations.indexOf(mutation.type) >= 0 &&
storage(mutation.type) !== mutation.payload
) {
storage(mutation.type, mutation.payload);
}
});
};
}
|
Fix example Article.__str__ in Python 3
|
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.six import python_2_unicode_compatible
from fluent_comments.moderation import moderate_model, comments_are_open, comments_are_moderated
from fluent_comments.models import get_comments_for_model, CommentsRelation
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = models.TextField("Content")
publication_date = models.DateTimeField("Publication date")
enable_comments = models.BooleanField("Enable comments", default=True)
# Optional reverse relation, allow ORM querying:
comments_set = CommentsRelation()
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article-details', kwargs={'slug': self.slug})
# Optional, give direct access to moderation info via the model:
comments = property(get_comments_for_model)
comments_are_open = property(comments_are_open)
comments_are_moderated = property(comments_are_moderated)
# Give the generic app support for moderation by django-fluent-comments:
moderate_model(
Article,
publication_date_field='publication_date',
enable_comments_field='enable_comments'
)
|
from django.core.urlresolvers import reverse
from django.db import models
from fluent_comments.moderation import moderate_model, comments_are_open, comments_are_moderated
from fluent_comments.models import get_comments_for_model, CommentsRelation
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = models.TextField("Content")
publication_date = models.DateTimeField("Publication date")
enable_comments = models.BooleanField("Enable comments", default=True)
# Optional reverse relation, allow ORM querying:
comments_set = CommentsRelation()
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('article-details', kwargs={'slug': self.slug})
# Optional, give direct access to moderation info via the model:
comments = property(get_comments_for_model)
comments_are_open = property(comments_are_open)
comments_are_moderated = property(comments_are_moderated)
# Give the generic app support for moderation by django-fluent-comments:
moderate_model(
Article,
publication_date_field='publication_date',
enable_comments_field='enable_comments'
)
|
Use thenShowInternal on action condition to avoid visibility colision
|
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component;
import org.apache.wicket.model.IModel;
import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction;
public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> {
private static final long serialVersionUID = 5629930352899730245L;
@Override
public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) {
if (onAjaxClick == null) {
throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName()));
}
AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>(
wicketId, model, form, titleModelFactory, contentModelFactory,
yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel,
cssClassNamesModel, keepMarkup, onAjaxClick
);
ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShowInternal());
return ajaxConfirmLink;
}
}
|
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component;
import org.apache.wicket.model.IModel;
import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction;
public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> {
private static final long serialVersionUID = 5629930352899730245L;
@Override
public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) {
if (onAjaxClick == null) {
throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName()));
}
AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>(
wicketId, model, form, titleModelFactory, contentModelFactory,
yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel,
cssClassNamesModel, keepMarkup, onAjaxClick
);
ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShow());
return ajaxConfirmLink;
}
}
|
Drop the ';' in the Python codegen as it's not necessary.
|
<% if (showSetup) { -%>
from KalturaClient import *
from KalturaClient.Plugins.Core import *
<% plugins.forEach(function(p) { -%>
from KalturaClient.Plugins.<%- p.charAt(0).toUpperCase() + p.substring(1) %> import *
<% }) -%>
config = KalturaConfiguration(<%- answers.partnerId %>)
config.serviceUrl = "https://www.kaltura.com/"
client = KalturaClient(config)
<% if (!noSession) { -%>
ks = client.session.start(
<%- codegen.constant(answers.secret) %>,
<%- codegen.constant(answers.userId) %>,
<%- answers.sessionType === 0 ? 'KalturaSessionType.USER' : 'KalturaSessionType.ADMIN' %>,
<%- codegen.constant(answers.partnerId) || 'YOUR_PARTNER_ID' %>)
client.setKs(ks)
<% } -%>
<% } -%>
<%- codegen.assignAllParameters(parameters, answers) -%>
result = client.<%- service %>.<%- action %>(<%- parameterNames.join(', ') %>)
print(result)
<% -%>
|
<% if (showSetup) { -%>
from KalturaClient import *
from KalturaClient.Plugins.Core import *
<% plugins.forEach(function(p) { -%>
from KalturaClient.Plugins.<%- p.charAt(0).toUpperCase() + p.substring(1) %> import *
<% }) -%>
config = KalturaConfiguration(<%- answers.partnerId %>)
config.serviceUrl = "https://www.kaltura.com/"
client = KalturaClient(config)
<% if (!noSession) { -%>
ks = client.session.start(
<%- codegen.constant(answers.secret) %>,
<%- codegen.constant(answers.userId) %>,
<%- answers.sessionType === 0 ? 'KalturaSessionType.USER' : 'KalturaSessionType.ADMIN' %>,
<%- codegen.constant(answers.partnerId) || 'YOUR_PARTNER_ID' %>)
client.setKs(ks)
<% } -%>
<% } -%>
<%- codegen.assignAllParameters(parameters, answers) -%>
result = client.<%- service %>.<%- action %>(<%- parameterNames.join(', ') %>);
print(result);
<% -%>
|
Fix filter for disabled accounts
|
<?php
if ($GLOBALS['Session']->hasAccountLevel('User')) {
SearchRequestHandler::$searchClasses[Emergence\People\User::class] = [
'fields' => [
[
'field' => 'FirstName',
'method' => 'like'
],
[
'field' => 'LastName',
'method' => 'like'
],
[
'field' => 'Username',
'method' => 'like'
],
[
'field' => 'FullName',
'method' => 'sql',
'sql' => 'CONCAT(FirstName, " ", LastName) = "%s"'
]
],
'conditions' => ['AccountLevel != "Disabled"']
];
}
|
<?php
if ($GLOBALS['Session']->hasAccountLevel('User')) {
SearchRequestHandler::$searchClasses[Emergence\People\User::class] = [
'fields' => [
[
'field' => 'FirstName',
'method' => 'like'
],
[
'field' => 'LastName',
'method' => 'like'
],
[
'field' => 'Username',
'method' => 'like'
],
[
'field' => 'FullName',
'method' => 'sql',
'sql' => 'CONCAT(FirstName, " ", LastName) = "%s"'
]
],
'conditions' => ['AccountLevel != "Deleted"']
];
}
|
Fix allow rules (admin check)
|
ActivityTypes = new Mongo.Collection('activityTypes');
var ActivityTypesSchema = new SimpleSchema({
name: {
type: String
}
});
ActivityTypes.allow({
insert () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId, 'admin');
// Only Admin user can insert
return userIsAdmin;
},
remove () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId, 'admin');
// Only Admin user can remove
return userIsAdmin;
},
update () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId, 'admin');
// Only Admin user can update
return userIsAdmin;
}
});
// Add i18n tags
ActivityTypesSchema.i18n("activityTypes");
ActivityTypes.attachSchema(ActivityTypesSchema);
|
ActivityTypes = new Mongo.Collection('activityTypes');
var ActivityTypesSchema = new SimpleSchema({
name: {
type: String
}
});
ActivityTypes.allow({
insert () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId);
// Only Admin user can insert
return userIsAdmin;
},
remove () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId);
// Only Admin user can remove
return userIsAdmin;
},
update () {
// Get current user ID
const currentUserId = Meteor.userId();
// Chack if user is administrator
const userIsAdmin = Roles.userIsInRole(currentUserId);
// Only Admin user can update
return userIsAdmin;
}
});
// Add i18n tags
ActivityTypesSchema.i18n("activityTypes");
ActivityTypes.attachSchema(ActivityTypesSchema);
|
Fix this context in ready callback.
|
define(['render',
'events',
'class'],
function(render, Emitter, clazz) {
function Application() {
Application.super_.call(this);
this.render = render;
this.controller = undefined;
}
clazz.inherits(Application, Emitter);
Application.prototype.run = function() {
this.willLaunch();
this.launch();
this.didLaunch();
var self = this;
render.$(document).ready(function() {
self.willDisplay();
self.display();
self.didDisplay();
});
};
Application.prototype.launch = function() {};
Application.prototype.display = function() {
if (!this.controller) throw new Error('No controller initialized by application.');
this.controller.willAddEl();
this.controller.el.prependTo(document.body);
this.controller.didAddEl();
};
Application.prototype.willLaunch = function() {};
Application.prototype.didLaunch = function() {};
Application.prototype.willDisplay = function() {};
Application.prototype.didDisplay = function() {};
return Application;
});
|
define(['render',
'events',
'class'],
function(render, Emitter, clazz) {
function Application() {
Application.super_.call(this);
this.render = render;
this.controller = undefined;
}
clazz.inherits(Application, Emitter);
Application.prototype.run = function() {
this.willLaunch();
this.launch();
this.didLaunch();
render.$(document).ready(function() {
this.willDisplay();
this.display();
this.didDisplay();
});
};
Application.prototype.launch = function() {};
Application.prototype.display = function() {
if (!this.controller) throw new Error('No controller initialized by application.');
this.controller.willAddEl();
this.controller.el.prependTo(document.body);
this.controller.didAddEl();
};
Application.prototype.willLaunch = function() {};
Application.prototype.didLaunch = function() {};
Application.prototype.willDisplay = function() {};
Application.prototype.didDisplay = function() {};
return Application;
});
|
Fix Operations table (copy/pasted, blame me..)
|
package com.loyaltyplant.test.domain.operation;
import com.loyaltyplant.test.domain.BalanceOperation;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
/**
* @author Maksim Zakharov
* @since 1.0
*/
@Entity
@Table(name = "loyalty_operation")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "operation_type")
public abstract class AbstractOperation implements BalanceOperation {
@Id
@GeneratedValue
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
package com.loyaltyplant.test.domain.operation;
import com.loyaltyplant.test.domain.BalanceOperation;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
/**
* @author Maksim Zakharov
* @since 1.0
*/
@Entity
@Table(name = "loyalty_order")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "operation_type")
public abstract class AbstractOperation implements BalanceOperation {
@Id
@GeneratedValue
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
Fix chart scale on download stats page.
|
<?php
class DownloadStatsPage extends Page {
}
class DownloadStatsPage_Controller extends Page_Controller {
function DownloadStatsChartUrl() {
$downloads = DataObject::get("DownloadPage");
$values = array();
$labels = array();
foreach ($downloads as $download) {
$values[] = $download->DownloadCount;
$label = explode(" ", $download->Title);
$labels[] = $label[0];
}
$url = "https://chart.googleapis.com/chart?cht=bvs&chd=t:" .
implode(",", $values); //Chart data
sort($values);
$min = $values[0];
$max = $values[count($values) - 1];
$url = $url . "&chds=0,$max&chxr=1,$min,$max"; //Chart scale
$url = $url . "&chs=400x200"; //Chart size
$url = $url . "&chxt=x,y&chxl=0:|" .
implode("|", $labels); //Chart labels
$url = $url . "&chbh=50,15&chxs=0,FFFFFF,13,0,l,FFFFFF|1,FFFFFF,13,0,l,FFFFFF&chf=bg,s,000000&chtt=Download+Count&chts=FFFFFF,13";
return $url;
}
}
?>
|
<?php
class DownloadStatsPage extends Page {
}
class DownloadStatsPage_Controller extends Page_Controller {
function DownloadStatsChartUrl() {
$downloads = DataObject::get("DownloadPage");
$values = array();
$labels = array();
foreach ($downloads as $download) {
$values[] = $download->DownloadCount;
$label = explode(" ", $download->Title);
$labels[] = $label[0];
}
$url = "https://chart.googleapis.com/chart?cht=bvs&chd=t:" .
implode(",", $values); //Chart data
sort($values);
$min = $values[0];
$max = $values[count($values) - 1];
$url = $url . "&chds=$min,$max&chxr=1,$min,$max"; //Chart scale
$url = $url . "&chs=400x200"; //Chart size
$url = $url . "&chxt=x,y&chxl=0:|" .
implode("|", $labels); //Chart labels
$url = $url . "&chbh=50,15&chxs=0,FFFFFF,13,0,l,FFFFFF|1,FFFFFF,13,0,l,FFFFFF&chf=bg,s,000000&chtt=Download+Count&chts=FFFFFF,13";
return $url;
}
}
?>
|
Improve error handling of git process to commit installation of application. Mainly of use in tests
|
package io.liveoak.container.tenancy.service;
import java.io.File;
import java.util.function.Consumer;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* @author Ken Finnigan
*/
public class ApplicationGitInstallCommitService implements Service<Void> {
public ApplicationGitInstallCommitService(Consumer<File> gitCommit, File installDir) {
this.gitCommit = gitCommit;
this.installDir = installDir;
}
@Override
public void start(StartContext context) throws StartException {
try {
this.gitCommit.accept(this.installDir);
} catch (RuntimeException re) {
log.error("Unable to commit to git on application install", re);
} finally {
// remove ourselves
context.getController().setMode(ServiceController.Mode.REMOVE);
}
}
@Override
public void stop(StopContext context) {
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
private Consumer<File> gitCommit;
private File installDir;
private static final Logger log = Logger.getLogger(ApplicationGitInstallCommitService.class);
}
|
package io.liveoak.container.tenancy.service;
import java.io.File;
import java.util.function.Consumer;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* @author Ken Finnigan
*/
public class ApplicationGitInstallCommitService implements Service<Void> {
public ApplicationGitInstallCommitService(Consumer<File> gitCommit, File installDir) {
this.gitCommit = gitCommit;
this.installDir = installDir;
}
@Override
public void start(StartContext context) throws StartException {
this.gitCommit.accept(this.installDir);
// remove ourselves
context.getController().setMode(ServiceController.Mode.REMOVE);
}
@Override
public void stop(StopContext context) {
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
private Consumer<File> gitCommit;
private File installDir;
}
|
Update sample to also fetch the object, and delete the object and bucket.
|
# Copyright 2013. Amazon Web Services, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Import the SDK
import boto
import uuid
# Create an S3 client
s3 = boto.connect_s3()
# Create a new bucket.
bucket_name = "python-sdk-sample-" + str(uuid.uuid4())
print "Creating new bucket with name: " + bucket_name
bucket = s3.create_bucket(bucket_name)
# Upload some data
from boto.s3.key import Key
k = Key(bucket)
k.key = 'hello_world.txt'
print "Uploading some data to " + bucket_name + " with key: " + k.key
k.set_contents_from_string('This is a test of S3. Hello World!')
# Fetch the key to show that we stored something.
print "Downloading the object we just uploaded:\n"
print k.get_contents_as_string() + "\n"
print "Now delete the same object"
k.delete()
print "And finally, delete the bucket."
s3.delete_bucket(bucket_name)
|
# Copyright 2013. Amazon Web Services, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Import the SDK
import boto
import uuid
# Create an S3 client
s3 = boto.connect_s3()
# Create a new bucket.
bucket_name = "python-sdk-sample-" + str(uuid.uuid4())
print "Creating new bucket with name: " + bucket_name
bucket = s3.create_bucket(bucket_name)
# Upload some data
from boto.s3.key import Key
k = Key(bucket)
k.key = 'hello_world.txt'
print "Uploading some data to " + bucket_name + " with key: " + k.key
k.set_contents_from_string('This is a test of S3. Hello World!')
|
Add comment explaining explicit setting of output
|
'use strict';
var peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
// The output of the below peg.generate() function must be a string, not an
// object
this.config.output = 'source';
}
compile(file) {
var parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = "javascript";
// The extension for files to process
PegJsPlugin.prototype.extension = "pegjs";
module.exports = PegJsPlugin;
|
'use strict';
var peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
this.config.output = 'source';
}
compile(file) {
var parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = "javascript";
// The extension for files to process
PegJsPlugin.prototype.extension = "pegjs";
module.exports = PegJsPlugin;
|
Make utils to be watched
|
/*global module:false*/
module.exports = function(grunt) {
grunt.initConfig({
watch: {
reload: {
files: ['src/*', 'src/js/*.js', 'src/js/utils/*.js', 'src/css/*.css', 'grunt.js'],
tasks: 'tinylr-reload'
}
}
});
grunt.registerTask('default', 'tinylr-start serve watch');
grunt.registerTask('serve', 'Start server', function() {
grunt.log.writeln('Surf to :8080/dev.html now!');
require('./serve').listen(8080);
});
['tiny-lr'].forEach(grunt.loadNpmTasks);
};
|
/*global module:false*/
module.exports = function(grunt) {
grunt.initConfig({
watch: {
reload: {
files: ['src/*', 'src/js/*.js', 'src/css/*.css', 'grunt.js'],
tasks: 'tinylr-reload'
}
}
});
grunt.registerTask('default', 'tinylr-start serve watch');
grunt.registerTask('serve', 'Start server', function() {
grunt.log.writeln('Surf to :8080/dev.html now!');
require('./serve').listen(8080);
});
['tiny-lr'].forEach(grunt.loadNpmTasks);
};
|
Initialize the machine assignments and assertions
|
import string
class Steckerbrett:
def __init__(self):
pass
class Umkehrwalze:
def __init__(self, wiring):
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
class Walzen:
def __init__(self, notch, wiring):
assert isinstance(notch, str)
assert isinstance(wiring, str)
assert len(wiring) == len(string.ascii_uppercase)
self.notch = notch
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
def encode_reverse(self, letter):
return string.ascii_uppercase[self.wiring.index(letter)]
class Enigma:
def __init__(self, rotors, reflector):
# Assert that rotors is a tuple and each tuple element is a Walzen
assert isinstance(rotors, tuple)
for index in range(len(rotors)):
assert isinstance(rotors[index], Walzen)
# Assert that reflector is an Umkehrwalze
assert isinstance(reflector, Umkehrwalze)
self.rotors = rotors
self.reflector = reflector
def cipher(self, message):
pass
|
import string
class Steckerbrett:
def __init__(self):
pass
class Umkehrwalze:
def __init__(self, wiring):
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
class Walzen:
def __init__(self, notch, wiring):
assert isinstance(notch, str)
assert isinstance(wiring, str)
assert len(wiring) == len(string.ascii_uppercase)
self.notch = notch
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
def encode_reverse(self, letter):
return string.ascii_uppercase[self.wiring.index(letter)]
class Enigma:
def __init__(self):
pass
def cipher(self, message):
pass
|
Convert $value to string to prevent strict_types errors
|
<?php
/**
* Wrapper for PHP's pgsql extension providing conversion of complex DB types
*
* LICENSE
*
* This source file is subject to BSD 2-Clause License that is bundled
* with this package in the file LICENSE and available at the URL
* https://raw.githubusercontent.com/sad-spirit/pg-wrapper/master/LICENSE
*
* @package sad_spirit\pg_wrapper
* @copyright 2014-2020 Alexey Borzov
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause license
* @link https://github.com/sad-spirit/pg-wrapper
*/
declare(strict_types=1);
namespace sad_spirit\pg_wrapper\converters;
use sad_spirit\pg_wrapper\TypeConverter;
/**
* Implementation of TypeConverter that performs no conversion
*
* Always returned by StubTypeConverterFactory, returned by DefaultTypeConverterFactory in case proper converter
* could not be determined.
*/
class StubConverter implements TypeConverter
{
/**
* {@inheritdoc}
*/
public function output($value): ?string
{
return null === $value ? null : (string)$value;
}
/**
* {@inheritdoc}
*/
public function input(?string $native)
{
return $native;
}
/**
* {@inheritdoc}
*/
public function dimensions(): int
{
return 0;
}
}
|
<?php
/**
* Wrapper for PHP's pgsql extension providing conversion of complex DB types
*
* LICENSE
*
* This source file is subject to BSD 2-Clause License that is bundled
* with this package in the file LICENSE and available at the URL
* https://raw.githubusercontent.com/sad-spirit/pg-wrapper/master/LICENSE
*
* @package sad_spirit\pg_wrapper
* @copyright 2014-2020 Alexey Borzov
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause license
* @link https://github.com/sad-spirit/pg-wrapper
*/
declare(strict_types=1);
namespace sad_spirit\pg_wrapper\converters;
use sad_spirit\pg_wrapper\TypeConverter;
/**
* Implementation of TypeConverter that performs no conversion
*
* Always returned by StubTypeConverterFactory, returned by DefaultTypeConverterFactory in case proper converter
* could not be determined.
*/
class StubConverter implements TypeConverter
{
/**
* {@inheritdoc}
*/
public function output($value): ?string
{
return $value;
}
/**
* {@inheritdoc}
*/
public function input(?string $native)
{
return $native;
}
/**
* {@inheritdoc}
*/
public function dimensions(): int
{
return 0;
}
}
|
Throw exception if input date is not parsable
|
<?php
namespace Jaybizzle;
class Seasons
{
/**
* Seasons.
*
* @var array
*/
public $seasons = array(
'Winter',
'Spring',
'Summer',
'Autumn',
);
/**
* Parse input date and return numeric month.
*
* @param string
* @return int
*/
public function getMonth($date)
{
if(is_null($date)) {
return date('n');
} else {
if($parsed_date = strtotime($date)) {
return date('n', strtotime($date));
}
throw new \Exception('Input date must be parsable by strtotime().');
}
}
/**
* Parse date, return season.
*
* @param string
*
* @return string
*/
public function get($date = null)
{
return $this->seasons[(int) (($this->getMonth($date) % 12) / 3)];
}
}
|
<?php
namespace Jaybizzle;
class Seasons
{
/**
* Seasons.
*
* @var array
*/
public $seasons = array(
'Winter',
'Spring',
'Summer',
'Autumn',
);
/**
* Parse input date and return numeric month.
*
* @param string
*
* @return int
*/
public function getMonth($date)
{
if (is_null($date)) {
return date('n');
} else {
return date('n', strtotime($date));
}
}
/**
* Parse date, return season.
*
* @param string
*
* @return string
*/
public function get($date = null)
{
return $this->seasons[(int) (($this->getMonth($date) % 12) / 3)];
}
}
|
Add the decoratable behavior to the dispatcher and add the winddow controller as decorator
|
<?php
/**
* Kodekit Component - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-pages for the canonical source repository
*/
return array(
'aliases' => array(
'pages' => 'com:pages.model.composite.pages',
'pages.menus' => 'com:pages.model.composite.menus',
'pages.modules' => 'com:pages.model.composite.modules',
),
'identifiers' => array(
'dispatcher' => array(
'behaviors'=> array('decoratable' => array('decorators' => 'com:pages.controller.window')),
),
'template.locator.factory' => array(
'locators' => array('com:pages.template.locator.module')
)
)
);
|
<?php
/**
* Kodekit Component - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-pages for the canonical source repository
*/
return array(
'aliases' => array(
'pages' => 'com:pages.model.composite.pages',
'pages.menus' => 'com:pages.model.composite.menus',
'pages.modules' => 'com:pages.model.composite.modules',
),
'identifiers' => array(
'template.locator.factory' => array(
'locators' => array('com:pages.template.locator.module')
),
'dispatcher' => array(
'behaviors' => array('com:pages.dispatcher.behavior.windowable')
),
)
);
|
FIX disable sale require contract
|
# -*- coding: utf-8 -*-
{
'name': 'Sale Order Require Contract on Confirmation',
'version': '1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Sale Order Require Contract on Confirmation
===========================================
""",
'author': 'ADHOC SA',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'sale',
],
'data': [
],
'demo': [
],
'test': [
],
'installable': False,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
{
'name': 'Sale Order Require Contract on Confirmation',
'version': '1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Sale Order Require Contract on Confirmation
===========================================
""",
'author': 'ADHOC SA',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'sale',
],
'data': [
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Move import to top level to avoid import fail after fist time on sys.modules hack
|
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import DataFrame
from sparknlp.annotation import Annotation
import sys
import sparknlp
def map_annotations(f, output_type: DataType):
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level
return udf(
lambda content: f(content),
output_type
)
def map_annotations_strict(f):
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level
return udf(
lambda content: f(content),
ArrayType(Annotation.dataType())
)
def map_annotations_col(dataframe: DataFrame, f, column, output_column, output_type):
dataframe.withColumn(output_column, map_annotations(f, output_type)(column))
def filter_by_annotations_col(dataframe, f, column):
this_udf = udf(
lambda content: f(content),
BooleanType()
)
return dataframe.filter(this_udf(column))
def explode_annotations_col(dataframe: DataFrame, column, output_column):
from pyspark.sql.functions import explode
return dataframe.withColumn(output_column, explode(column))
|
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import DataFrame
import sys
import sparknlp
def map_annotations(f, output_type: DataType):
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level
return udf(
lambda content: f(content),
output_type
)
def map_annotations_strict(f):
from sparknlp.annotation import Annotation
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level
return udf(
lambda content: f(content),
ArrayType(Annotation.dataType())
)
def map_annotations_col(dataframe: DataFrame, f, column, output_column, output_type):
dataframe.withColumn(output_column, map_annotations(f, output_type)(column))
def filter_by_annotations_col(dataframe, f, column):
this_udf = udf(
lambda content: f(content),
BooleanType()
)
return dataframe.filter(this_udf(column))
def explode_annotations_col(dataframe: DataFrame, column, output_column):
from pyspark.sql.functions import explode
return dataframe.withColumn(output_column, explode(column))
|
Use auto_register's filter_func to filter tests
|
from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(item_type, item_id, item):
if item_type == "check" and item_id in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
"com.google.fonts/check/038", # Fontforge
"com.google.fonts/check/039", # Fontforge
):
return False
return True
def test_external_specification():
"""Test the creation of external specifications."""
specification = spec_factory(default_section=Section("Dalton Maag OpenType"))
specification.auto_register(
globals(),
spec_imports=["fontbakery.specifications.opentype"],
filter_func=check_filter)
# Probe some tests
expected_tests = ["com.google.fonts/check/002", "com.google.fonts/check/171"]
specification.test_expected_checks(expected_tests)
# Probe tests we don't want
assert "com.google.fonts/check/035" not in specification._check_registry.keys()
assert len(specification.sections) > 1
|
from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
"com.google.fonts/check/038", # Fontforge
"com.google.fonts/check/039", # Fontforge
):
return False, "Skipping external tools."
return True, None
def test_external_specification():
"""Test the creation of external specifications."""
specification = spec_factory(default_section=Section("Dalton Maag OpenType"))
specification.set_check_filter(check_filter)
specification.auto_register(
globals(), spec_imports=["fontbakery.specifications.opentype"])
# Probe some tests
expected_tests = ["com.google.fonts/check/002", "com.google.fonts/check/180"]
specification.test_expected_checks(expected_tests)
# Probe tests we don't want
assert "com.google.fonts/check/035" not in specification._check_registry.keys()
assert len(specification.sections) > 1
|
Fix coding standard [skip fix]
|
<?php
namespace Miaoxing\User\Controller\Admin;
class UserSettings extends \Miaoxing\Plugin\BaseController
{
protected $controllerName = '用户设置';
protected $actionPermissions = [
'index,update' => '设置',
];
public function indexAction()
{
$bgImage = &$this->setting('user.bgImage');
wei()->event->trigger('postImageLoad', [&$bgImage]);
return get_defined_vars();
}
public function updateAction($req)
{
$settings = (array) $req['settings'];
wei()->event->trigger('preImageDataSave', [&$settings, ['user.bgImage']]);
$this->setting->setValues($settings, 'user.');
return $this->suc();
}
}
|
<?php
namespace Miaoxing\User\Controller\Admin;
class UserSettings extends \Miaoxing\Plugin\BaseController
{
protected $controllerName = '用户设置';
protected $actionPermissions = [
'index,update' => '设置',
];
public function indexAction()
{
$bgImage = &$this->setting('user.bgImage');
wei()->event->trigger('postImageLoad', [&$bgImage]);
return get_defined_vars();
}
public function updateAction($req)
{
$settings = (array)$req['settings'];
wei()->event->trigger('preImageDataSave', [&$settings, ['user.bgImage']]);
$this->setting->setValues($settings, 'user.');
return $this->suc();
}
}
|
Add user activated and logged in events to analytics subscriber
|
<?php
namespace OpenDominion\Listeners\Subscribers;
use Illuminate\Events\Dispatcher;
use OpenDominion\Contracts\Services\Analytics\AnalyticsService;
use OpenDominion\Events\HasAnalyticsEvent;
use OpenDominion\Events\UserActivatedEvent;
use OpenDominion\Events\UserLoggedInEvent;
use OpenDominion\Events\UserRegisteredEvent;
class AnalyticsSubscriber implements SubscriberInterface
{
/** @var AnalyticsService */
protected $analyticsService;
/** @var string[] */
protected $events = [
UserActivatedEvent::class,
UserLoggedInEvent::class,
UserRegisteredEvent::class,
];
/**
* AnalyticsSubscriber constructor.
*
* @param AnalyticsService $analyticsService
*/
public function __construct(AnalyticsService $analyticsService)
{
$this->analyticsService = $analyticsService;
}
/**
* {@inheritdoc}
*/
public function subscribe(Dispatcher $events): void
{
$events->listen($this->events, function (HasAnalyticsEvent $event) {
$this->analyticsService->queueFlashEvent($event->getAnalyticsEvent());
});
}
}
|
<?php
namespace OpenDominion\Listeners\Subscribers;
use Illuminate\Events\Dispatcher;
use OpenDominion\Contracts\Services\Analytics\AnalyticsService;
use OpenDominion\Events\HasAnalyticsEvent;
use OpenDominion\Events\UserRegisteredEvent;
class AnalyticsSubscriber implements SubscriberInterface
{
/** @var AnalyticsService */
protected $analyticsService;
/** @var string[] */
protected $events = [
UserRegisteredEvent::class,
];
/**
* AnalyticsSubscriber constructor.
*
* @param AnalyticsService $analyticsService
*/
public function __construct(AnalyticsService $analyticsService)
{
$this->analyticsService = $analyticsService;
}
/**
* {@inheritdoc}
*/
public function subscribe(Dispatcher $events): void
{
$events->listen($this->events, function (HasAnalyticsEvent $event) {
$this->analyticsService->queueFlashEvent($event->getAnalyticsEvent());
});
}
}
|
Add column support for sql server
|
from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
add_column_string = 'ALTER TABLE %s ADD %s;'
def create_table(self, table_name, fields):
# Tweak stuff as needed
for name,f in fields:
if isinstance(f, BooleanField):
if f.default == True:
f.default = 1
if f.default == False:
f.default = 0
# Run
generic.DatabaseOperations.create_table(self, table_name, fields)
|
from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
def create_table(self, table_name, fields):
# Tweak stuff as needed
for name,f in fields:
if isinstance(f, BooleanField):
if f.default == True:
f.default = 1
if f.default == False:
f.default = 0
# Run
generic.DatabaseOperations.create_table(self, table_name, fields)
|
Expand content type detection to jpg and htm.
|
/*
* Copyright 2017, Sascha Häberling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.retrostore.request;
/**
* Resolves content types.
*/
final class ContentType {
/** Return a content type depending on the filename. */
static Responder.ContentType fromFilename(String filename) {
filename = filename.toLowerCase();
if (filename.endsWith(".html") || filename.endsWith(".htm")) {
return Responder.ContentType.HTML;
} else if (filename.endsWith(".css")) {
return Responder.ContentType.CSS;
} else if (filename.endsWith(".js")) {
return Responder.ContentType.JS;
} else if (filename.endsWith(".json")) {
return Responder.ContentType.JSON;
} else if (filename.endsWith(".jpeg") || filename.endsWith(".jpg")) {
return Responder.ContentType.JPEG;
} else if (filename.endsWith(".png")) {
return Responder.ContentType.PNG;
} else {
return Responder.ContentType.PLAIN;
}
}
}
|
/*
* Copyright 2017, Sascha Häberling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.retrostore.request;
/**
* Resolves content types.
*/
final class ContentType {
/** Return a content type depending on the filename. */
static Responder.ContentType fromFilename(String filename) {
filename = filename.toLowerCase();
if (filename.endsWith(".html")) {
return Responder.ContentType.HTML;
} else if (filename.endsWith(".css")) {
return Responder.ContentType.CSS;
} else if (filename.endsWith(".js")) {
return Responder.ContentType.JS;
} else if (filename.endsWith(".json")) {
return Responder.ContentType.JSON;
} else if (filename.endsWith(".jpeg")) {
return Responder.ContentType.JPEG;
} else if (filename.endsWith(".png")) {
return Responder.ContentType.PNG;
} else {
return Responder.ContentType.PLAIN;
}
}
}
|
Fix scope used for Cloud Search.
|
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create / interact with gcloud search connections."""
from gcloud import connection as base_connection
class Connection(base_connection.JSONConnection):
"""A connection to Google Cloud Search via the JSON REST API."""
API_BASE_URL = 'https://cloudsearch.googleapis.com'
"""The base of the API call URL."""
API_VERSION = 'v1'
"""The version of the API, used in building the API call's URL."""
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
SCOPE = ('https://www.googleapis.com/auth/cloudsearch',)
"""The scopes required for authenticating as a Cloud Search consumer."""
|
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create / interact with gcloud search connections."""
from gcloud import connection as base_connection
class Connection(base_connection.JSONConnection):
"""A connection to Google Cloud Search via the JSON REST API."""
API_BASE_URL = 'https://cloudsearch.googleapis.com'
"""The base of the API call URL."""
API_VERSION = 'v1'
"""The version of the API, used in building the API call's URL."""
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
SCOPE = ('https://www.googleapis.com/auth/ndev.cloudsearch',)
"""The scopes required for authenticating as a Cloud Search consumer."""
|
Add default value for package name.
If all else fails assume the name of the current folder is the packoge name.
|
<?php
namespace Respect\Foundation\InfoProviders;
use DirectoryIterator;
class PackageName extends AbstractProvider
{
public function providerPackageIni()
{
$iniPath = realpath($this->projectFolder.'/package.ini');
if (!file_exists($iniPath))
return '';
$ini = parse_ini_file($iniPath, true);
return $ini['package']['name'];
}
public function providerFolderStructure()
{
$vendorFolder = new LibraryFolder($this->projectFolder);
if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder)))
foreach (new DirectoryIterator((string) $vendorFolder) as $vendor)
if (!$vendor->isDot() && $vendor->isDir())
return $vendor->getFileName();
}
public function providerDefault()
{
return ucfirst(preg_replace('#^.*'.DIRECTORY_SEPARATOR.'(?=\w$)#U', '', $this->projectFolder));
}
}
|
<?php
namespace Respect\Foundation\InfoProviders;
use DirectoryIterator;
class PackageName extends AbstractProvider
{
public function providerPackageIni()
{
$iniPath = realpath($this->projectFolder.'/package.ini');
if (!file_exists($iniPath))
return '';
$ini = parse_ini_file($iniPath, true);
return $ini['package']['name'];
}
public function providerFolderStructure()
{
$vendorFolder = new LibraryFolder($this->projectFolder);
if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder)))
foreach (new DirectoryIterator((string) $vendorFolder) as $vendor)
if (!$vendor->isDot() && $vendor->isDir())
return $vendor->getFileName();
}
}
|
Increase JVM heap for logserver-container
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.handler.ThreadpoolConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author hmusum
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
@Override
public void getConfig(ThreadpoolConfig.Builder builder) {
builder.maxthreads(10);
}
@Override
public void getConfig(QrStartConfig.Builder builder) {
super.getConfig(builder);
builder.jvm.heapsize(512);
}
protected boolean messageBusEnabled() { return false; }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("http://*/logs");
addComponent(logHandler);
}
}
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.handler.ThreadpoolConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author hmusum
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
@Override
public void getConfig(ThreadpoolConfig.Builder builder) {
builder.maxthreads(10);
}
@Override
public void getConfig(QrStartConfig.Builder builder) {
super.getConfig(builder);
builder.jvm.heapsize(384);
}
protected boolean messageBusEnabled() { return false; }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("http://*/logs");
addComponent(logHandler);
}
}
|
Change Manuscript JSON storage to same basedir
|
/*
*/
package org.datadryad.rest.storage.resolvers;
import org.datadryad.rest.storage.json.ManuscriptJSONStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractManuscriptStorage;
/**
*
* @author Dan Leehr <dan.leehr@nescent.org>
*/
@Provider
public class ManuscriptStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractManuscriptStorage> {
private static final String PATH = "/tmp/dryad_rest";
public ManuscriptStorageResolver() {
super(AbstractManuscriptStorage.class, new ManuscriptJSONStorageImpl(new File(PATH)));
File directory = new File(PATH);
if(!directory.exists()) {
directory.mkdir();
}
}
}
|
/*
*/
package org.datadryad.rest.storage.resolvers;
import org.datadryad.rest.storage.json.ManuscriptJSONStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractManuscriptStorage;
/**
*
* @author Dan Leehr <dan.leehr@nescent.org>
*/
@Provider
public class ManuscriptStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractManuscriptStorage> {
private static final String PATH = "/tmp/dryad_rest_manuscripts";
public ManuscriptStorageResolver() {
super(AbstractManuscriptStorage.class, new ManuscriptJSONStorageImpl(new File(PATH)));
File directory = new File(PATH);
if(!directory.exists()) {
directory.mkdir();
}
}
}
|
Fix bad function name call
|
var AlexaAppServer = require('alexa-app-server');
var MpdInterface = require('./apps/alexa-mpd-control/mpd_interface');
var mpd = new MpdInterface();
AlexaAppServer.start({
// server_root:__dirname, // Path to root
// public_html:"public_html", // Static content
// app_dir:"apps", // Where alexa-app modules are stored
// app_root:"/alexa/", // Service root
preRequest: function(json,req,res) {
console.log("preRequest fired", json.request.intent && json.request.intent.name);
json.userDetails = { "name":"Bob Smith" };
var retPromise = new Promise(function(resolve, reject){
if(json.request.intent && json.request.intent.name === "randalbum"){
mpd.getRandomAlbum().then(function(albumInfo){
json[json.request.intent.name] = albumInfo;
resolve(json);
});
}else{
resolve(json);
}
});
return retPromise;
},
port:8092, // What port to use, duh
httpsPort:443,
httpsEnabled:true,
privateKey:'private-key.pem',
certificate:'certificate.pem'
});
|
var AlexaAppServer = require('alexa-app-server');
var MpdInterface = require('./apps/alexa-mpd-control/mpd_interface');
var mpd = new MpdInterface();
AlexaAppServer.start({
// server_root:__dirname, // Path to root
// public_html:"public_html", // Static content
// app_dir:"apps", // Where alexa-app modules are stored
// app_root:"/alexa/", // Service root
preRequest: function(json,req,res) {
console.log("preRequest fired", json.request.intent && json.request.intent.name);
json.userDetails = { "name":"Bob Smith" };
var retPromise = new Promise(function(resolve, reject){
if(json.request.intent && json.request.intent.name === "randalbum"){
mpd.getRandomAlbumName().then(function(albumInfo){
json[json.request.intent.name] = albumInfo;
resolve(json);
});
}else{
resolve(json);
}
});
return retPromise;
},
port:8092, // What port to use, duh
httpsPort:443,
httpsEnabled:true,
privateKey:'private-key.pem',
certificate:'certificate.pem'
});
|
Revise the way that searching for food is handled.
|
var CommandUtil = require('../../src/command_util')
.CommandUtil;
var l10n_file = __dirname + '/../../l10n/scripts/rooms/8.js.yml';
var l10n = require('../../src/l10n')(l10n_file);
exports.listeners = {
//TODO: Use cleverness stat for spot checks such as this.
examine: l10n => {
return (args, player, players) => {
var poi = [
'crates',
'boxes',
'bags',
'food'
];
if (poi.indexOf(args.toLowerCase()) > -1 && getRand() > 3) {
findFood(player, players);
}
};
}
};
function getRand() {
return Math
.floor(Math
.random() * 5) + 1;
}
function findFood(player, players) {
player.setAttribute('health', player.getAttribute('health') +
getRand());
player.sayL10n(l10n, 'FOUND_FOOD');
players.eachIf(p => CommandUtil.otherPlayerInRoom(p),
p => { p.sayL10n(l10n, 'OTHER_FOUND_FOOD', player.getName()); });
}
|
var CommandUtil = require('../../src/command_util')
.CommandUtil;
var l10n_file = __dirname + '/../../l10n/scripts/rooms/8.js.yml';
var l10n = require('../../src/l10n')(l10n_file);
exports.listeners = {
//TODO: Use cleverness stat for spot checks such as this.
examine: l10n => {
return (args, player, players) => {
var poi = [
'crates',
'boxes',
'bags',
'food'
];
if (poi.indexOf(args.toLowerCase()) > -1) {
findFood(player, players);
if (!player.explore('found food')) {
player.emit('experience', 100);
}
}
};
}
};
function getRand() {
return Math
.floor(Math
.random() * 5) + 5;
}
function seeDisturbance(player, players) {
player.setAttribute('health', player.getAttribute('health') +
getRand());
player.sayL10n(l10n, 'FOUND_FOOD');
players.eachIf(p => CommandUtil.otherPlayerInRoom(p),
p => { p.sayL10n(l10n, 'OTHER_FOUND_FOOD', player.getName()); });
}
|
Fix regression due to typo
|
package org.fxmisc.richtext;
import javafx.css.CssMetaData;
import javafx.css.StyleConverter;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.css.StyleableProperty;
import java.util.function.Function;
public class CustomCssMetaData<S extends Styleable, V> extends CssMetaData<S, V> {
private final Function<S, StyleableObjectProperty<V>> property;
CustomCssMetaData(String property, StyleConverter<?, V> converter, V initialValue,
Function<S, StyleableObjectProperty<V>> getStyleableProperty) {
super(property, converter, initialValue);
this.property = getStyleableProperty;
}
@Override
public boolean isSettable(S styleable) {
return !property.apply(styleable).isBound();
}
@Override
public StyleableProperty<V> getStyleableProperty(S styleable) {
return property.apply(styleable);
}
}
|
package org.fxmisc.richtext;
import javafx.css.CssMetaData;
import javafx.css.StyleConverter;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.css.StyleableProperty;
import java.util.function.Function;
public class CustomCssMetaData<S extends Styleable, V> extends CssMetaData<S, V> {
private final Function<S, StyleableObjectProperty<V>> property;
CustomCssMetaData(String property, StyleConverter<?, V> converter, V initialValue,
Function<S, StyleableObjectProperty<V>> getStyleableProperty) {
super(property, converter, initialValue);
this.property = getStyleableProperty;
}
@Override
public boolean isSettable(S styleable) {
return property.apply(styleable).isBound();
}
@Override
public StyleableProperty<V> getStyleableProperty(S styleable) {
return property.apply(styleable);
}
}
|
Add class_machine_name var to paramaters array
|
<?php
/**
* @file
* Containt Drupal\AppConsole\Generator\ControllerGenerator.
*/
namespace Drupal\AppConsole\Generator;
class ControllerGenerator extends Generator
{
public function generate($module, $class_name, $method_name, $route, $test, $services, $class_machine_name)
{
$parameters = array(
'class_name' => $class_name,
'services' => $services,
'module' => $module,
'method_name' => $method_name,
'class_machine_name' => $class_machine_name,
'route' => $route,
);
$this->renderFile(
'module/module.controller.php.twig',
$this->getControllerPath($module).'/'.$class_name.'.php',
$parameters
);
$this->renderFile(
'module/controller-routing.yml.twig',
$this->getModulePath($module).'/'.$module.'.routing.yml',
$parameters,
FILE_APPEND
);
if ($test) {
$this->renderFile(
'module/module.test.twig',
$this->getTestPath($module).'/'.$class_name.'Test.php',
$parameters
);
}
}
}
|
<?php
/**
* @file
* Containt Drupal\AppConsole\Generator\ControllerGenerator.
*/
namespace Drupal\AppConsole\Generator;
class ControllerGenerator extends Generator
{
public function generate($module, $class_name, $method_name, $route, $test, $services, $class_machine_name)
{
$parameters = array(
'class_name' => $class_name,
'services' => $services,
'module' => $module,
'method_name' => $method_name,
'route' => $route,
);
$this->renderFile(
'module/module.controller.php.twig',
$this->getControllerPath($module).'/'.$class_name.'.php',
$parameters
);
$this->renderFile(
'module/controller-routing.yml.twig',
$this->getModulePath($module).'/'.$module.'.routing.yml',
$parameters,
FILE_APPEND
);
if ($test) {
$this->renderFile(
'module/module.test.twig',
$this->getTestPath($module).'/'.$class_name.'Test.php',
$parameters
);
}
}
}
|
Fix for ignoring passed in output directory and file extension
|
var fs, path, mkdirp
function toFileName(delimiter, name) {
if (delimiter === "") {
return name
}
return name
.replace(/[a-z][A-Z]/g, function(str) {
return str[0] + delimiter + str[1]
})
.toLowerCase()
}
if (typeof IN_BROWSER === "undefined") {
fs = require("fs")
path = require("path")
mkdirp = require("mkdirp")
function writeToFS(components, options) {
options = options || {}
var outPath = path.resolve(options.output && options.output.path ? options.output.path : "components")
var delimiter = options.moduleFileNameDelimiter || ""
var ext = options.output && options.output.fileExtension ? options.output.fileExtension : "js"
mkdirp.sync(outPath)
Object.keys(components).forEach(function(name) {
fs.writeFileSync(
path.join(outPath, toFileName(delimiter, name)) + "." + ext,
components[name],
"utf8"
)
})
}
module.exports = {
toFileName: toFileName,
writeToFS: writeToFS
}
} else {
module.exports = {
toFileName: toFileName
}
}
|
var fs, path, mkdirp
function toFileName(delimiter, name) {
if (delimiter === "") {
return name
}
return name
.replace(/[a-z][A-Z]/g, function(str) {
return str[0] + delimiter + str[1]
})
.toLowerCase()
}
if (typeof IN_BROWSER === "undefined") {
fs = require("fs")
path = require("path")
mkdirp = require("mkdirp")
function writeToFS(components, options) {
options = options || {}
var outPath = path.resolve(options.path || "components")
var delimiter = options.moduleFileNameDelimiter || ""
var ext = options.fileExtension || "js"
mkdirp.sync(outPath)
Object.keys(components).forEach(function(name) {
fs.writeFileSync(
path.join(outPath, toFileName(delimiter, name)) + "." + ext,
components[name],
"utf8"
)
})
}
module.exports = {
toFileName: toFileName,
writeToFS: writeToFS
}
} else {
module.exports = {
toFileName: toFileName
}
}
|
cr: Fix the run command on Linux
TEST=cr run chrome
NOTRY=true
Review URL: https://codereview.chromium.org/105313004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@240638 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux platform.
This supports directly executing the binaries from the output directory.
"""
@property
def enabled(self):
return cr.LinuxPlatform.GetInstance().is_active
def Kill(self, context, targets, arguments):
# TODO(iancottrell): Think about how to implement this, or even if we should
print '**WARNING** Kill not yet implemented on linux'
def Run(self, context, target, arguments):
cr.Host.Execute(target, '{CR_BINARY}', '{CR_RUN_ARGUMENTS}', *arguments)
def Test(self, context, target, arguments):
self.Run(context, target, arguments)
class LinuxInstaller(cr.Installer):
"""An implementation of cr.Installer for the linux platform.
This does nothing, the linux runner works from the output directory, there
is no need to install anywhere.
"""
@property
def enabled(self):
return cr.LinuxPlatform.GetInstance().is_active
def Uninstall(self, context, targets, arguments):
pass
def Install(self, context, targets, arguments):
pass
def Reinstall(self, context, targets, arguments):
pass
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux platform.
This supports directly executing the binaries from the output directory.
"""
@property
def enabled(self):
return cr.LinuxPlatform.GetInstance().is_active
def Kill(self, context, targets, arguments):
# TODO(iancottrell): Think about how to implement this, or even if we should
print '**WARNING** Kill not yet implemented on linux'
def Run(self, context, target, arguments):
cr.Host.Execute(target, ['{CR_BINARY}', '{CR_RUN_ARGUMENTS}'] + arguments)
def Test(self, context, target, arguments):
self.Run(context, target, arguments)
class LinuxInstaller(cr.Installer):
"""An implementation of cr.Installer for the linux platform.
This does nothing, the linux runner works from the output directory, there
is no need to install anywhere.
"""
@property
def enabled(self):
return cr.LinuxPlatform.GetInstance().is_active
def Uninstall(self, context, targets, arguments):
pass
def Install(self, context, targets, arguments):
pass
def Reinstall(self, context, targets, arguments):
pass
|
Fix log plugin breaking standalone
|
define(function(require, exports, module) {
main.consumes = [
"Plugin", "dialog.error"
];
main.provides = ["readonly"];
return main;
function main(options, imports, register) {
var Plugin = imports.Plugin;
var showError = imports["dialog.error"].show;
/***** Initialization *****/
var plugin = new Plugin("Ajax.org", main.consumes);
var loaded = false;
function load() {
if (loaded) return false;
loaded = true;
showError("This workspace is read only; see the Collaborate tab if you would like write access.");
}
/***** Lifecycle *****/
plugin.on("load", function(){
load();
});
/***** Register and define API *****/
plugin.freezePublicAPI({});
register(null, { readonly : plugin });
}
});
|
define(function(require, exports, module) {
main.consumes = [
"Plugin", "dialog.error"
];
main.provides = ["readonly"];
return main;
function main(options, imports, register) {
var Plugin = imports.Plugin;
var showError = imports["dialog.error"].show;
/***** Initialization *****/
var plugin = new Plugin("Ajax.org", main.consumes);
var loaded = false;
function load() {
if (loaded) return false;
loaded = true;
showError("Workspace is read only");
}
/***** Lifecycle *****/
plugin.on("load", function(){
load();
});
/***** Register and define API *****/
plugin.freezePublicAPI({});
register(null, { readonly : plugin });
}
});
|
Disable npm steps on DDC bot for now
This will only regression test compilation (no running of generated
code), but that appears to work.
R=leafp@google.com
Review-Url: https://codereview.chromium.org/2646493003 .
|
#!/usr/bin/env python
#
# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.ChangedWorkingDirectory('pkg/dev_compiler'):
dart_exe = utils.CheckedInSdkExecutable()
# These two calls mirror pkg/dev_compiler/tool/test.sh.
bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test'])
bot.RunProcess([dart_exe, 'test/all_tests.dart'])
# TODO(vsm): Our bots do not have node / npm installed.
# These mirror pkg/dev_compiler/tool/browser_test.sh.
# bot.RunProcess(['npm', 'install'])
# bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
|
#!/usr/bin/env python
#
# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.ChangedWorkingDirectory('pkg/dev_compiler'):
dart_exe = utils.CheckedInSdkExecutable()
# These two calls mirror pkg/dev_compiler/tool/test.sh.
bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test'])
bot.RunProcess([dart_exe, 'test/all_tests.dart'])
# These mirror pkg/dev_compiler/tool/browser_test.sh.
bot.RunProcess(['npm', 'install'])
bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
|
Apply various and CS fixes as per review
|
<?php
namespace Doctrine\ORM\Utility;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
/**
* @internal This class exists only to avoid code duplication, do not reuse it externally
*/
final class HierarchyDiscriminatorResolver
{
private function __construct()
{
}
/**
* This method is needed to make INSTANCEOF work correctly with inheritance: if the class at hand has inheritance,
* it extracts all the discriminators from the child classes and returns them
*/
public static function resolveDiscriminatorsForClass(
ClassMetadata $rootClassMetadata,
EntityManagerInterface $entityManager
): array {
$hierarchyClasses = $rootClassMetadata->subClasses;
$hierarchyClasses[] = $rootClassMetadata->name;
$discriminators = [];
foreach ($hierarchyClasses as $class) {
$currentMetadata = $entityManager->getClassMetadata($class);
$currentDiscriminator = $currentMetadata->discriminatorValue;
if (null !== $currentDiscriminator) {
$discriminators[$currentDiscriminator] = null;
}
}
return $discriminators;
}
}
|
<?php
namespace Doctrine\ORM\Utility;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
/**
* Class HierarchyDiscriminatorResolver
* @package Doctrine\ORM\Utility
* @internal This class exists only to avoid code duplication, do not reuse it externally
*/
class HierarchyDiscriminatorResolver
{
public static function resolveDiscriminatorsForClass(
ClassMetadata $rootClassMetadata,
EntityManagerInterface $entityManager
) {
$hierarchyClasses = $rootClassMetadata->subClasses;
$hierarchyClasses[] = $rootClassMetadata->name;
$discriminators = [];
foreach ($hierarchyClasses as $class) {
$currentMetadata = $entityManager->getClassMetadata($class);
$currentDiscriminator = $currentMetadata->discriminatorValue;
if (null !== $currentDiscriminator) {
$discriminators[$currentDiscriminator] = null;
}
}
return $discriminators;
}
}
|
Change how we get config settings
- Flask recommends using `app.config.from_object` to get config settings.
- Don't get config settings if we're using travis, since it won't have the
settings from the repo.
|
import flask
import sqlalchemy
import os
from Donut import constants
from Donut.modules import example
app = flask.Flask(__name__)
app.debug = False
# Get app config, if we're not testing on travis.
if 'TRAVIS' not in os.environ:
app.config.from_object('Donut.config')
# Maximum file upload size, in bytes.
app.config['MAX_CONTENT_LENGTH'] = constants.MAX_CONTENT_LENGTH
# Load blueprint modules
app.register_blueprint(example.blueprint, url_prefix='/example')
# Create database engine object.
# TODO##DatabaseWork: We currently don't have a database set up, so we can't
# reference sqlalchemy yet. However, it serves as a good example implementation.
# engine = sqlalchemy.create_engine(app.config['DB_URI'], convert_unicode=True)
@app.before_request
def before_request():
"""Logic executed before request is processed."""
# TODO#DatabaseWork uncomment this line
# flask.g.db = engine.connect()
@app.teardown_request
def teardown_request(exception):
"""Logic executed after every request is finished."""
# TODO#DatabaseWork uncomment these lines
# if flask.g.db != None:
# flask.g.db.close()
# After initialization, import the routes.
from Donut import routes
|
import flask
import sqlalchemy
from Donut import config, constants
from Donut.modules import example
app = flask.Flask(__name__)
app.debug = False
app.secret_key = config.SECRET_KEY
# Maximum file upload size, in bytes.
app.config['MAX_CONTENT_LENGTH'] = constants.MAX_CONTENT_LENGTH
# Load blueprint modules
app.register_blueprint(example.blueprint, url_prefix='/example')
# Create database engine object.
# TODO##DatabaseWork: We currently don't have a database set up, so we can't
# reference sqlalchemy yet. However, it serves as a good example implementation.
# engine = sqlalchemy.create_engine(config.DB_URI, convert_unicode=True)
@app.before_request
def before_request():
"""Logic executed before request is processed."""
# TODO#DatabaseWork uncomment this line
# flask.g.db = engine.connect()
@app.teardown_request
def teardown_request(exception):
"""Logic executed after every request is finished."""
# TODO#DatabaseWork uncomment these lines
# if flask.g.db != None:
# flask.g.db.close()
# After initialization, import the routes.
from Donut import routes
|
Fix the navigation generating js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require highlight.pack
//= require_tree .
$(document).ready(function() {
$('pre').each(function(i, el) {
hljs.highlightBlock(el);
});
$('code').each(function(i, el) {
hljs.highlightBlock(el);
});
$('.vivus-documentation h1').each(function(i, el) {
$('#vivus-navigation ul').append("<li><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>");
$(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>");
})
});
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require highlight.pack
//= require_tree .
$(document).ready(function() {
$('pre').each(function(i, el) {
hljs.highlightBlock(el);
});
$('code').each(function(i, el) {
hljs.highlightBlock(el);
});
$('.vivus-documentation h1').each(function(i, el) {
$('#vivus-navigation ul').append("<li><a href='#" + i + "'>" + $(el).text() + "</a></li>");
$(el).prepend("<a name='" + i + "'></a>");
})
});
|
Fix styling of body cells
|
import Ember from 'ember';
import layout from './template';
export default Ember.Component.extend({
layout: layout,
classNames: ['cell', 'eg-body-cell'],
attributeBindings: ['style', 'rowIndex:data-row-index'],
width: Ember.computed.alias('column.width'),
style: Ember.computed('column.offset', 'width', function(){
var offset = this.get('column.offset');
var width = this.get('width');
if (!isNaN(offset)) {
return Ember.String.htmlSafe(
'display: inline-block; width: ' + width + 'px;');
}
else {
return Ember.String.htmlSafe('display: none;');
}
}),
didInsertElement: function() {
this._super.apply(this, arguments);
var element = this.element;
var sourceElement = this.get('column._zones.body.element');
if (sourceElement == null) { return; }
var cellElement = $(sourceElement)
.find('.eg-body-cell[data-row-index=' + this.get('rowIndex') + ']')[0];
if (cellElement == null) { return; }
while (cellElement.childNodes.length > 0) {
element.appendChild(cellElement.childNodes[0]);
}
}
});
|
import Ember from 'ember';
import layout from './template';
export default Ember.Component.extend({
layout: layout,
classNames: ['eg-body-cell'],
attributeBindings: ['style', 'rowIndex:data-row-index'],
width: Ember.computed.alias('column.width'),
style: Ember.computed('column.offset', 'width', function(){
var offset = this.get('column.offset');
var width = this.get('width');
if (!isNaN(offset)) {
return Ember.String.htmlSafe(
'display: inline-block; width: ' + width + 'px;');
}
else {
return Ember.String.htmlSafe('display: none;');
}
}),
didInsertElement: function() {
this._super.apply(this, arguments);
var element = this.element;
var sourceElement = this.get('column._zones.body.element');
if (sourceElement == null) { return; }
var cellElement = $(sourceElement)
.find('.eg-body-cell[data-row-index=' + this.get('rowIndex') + ']')[0];
if (cellElement == null) { return; }
while (cellElement.childNodes.length > 0) {
element.appendChild(cellElement.childNodes[0]);
}
}
});
|
Add markdown content type for README
|
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
def readme():
with open('README.md') as f:
return f.read()
packages = find_packages(SRC_PREFIX)
setup(
name='cmdline',
version='0.0.0',
description='Utilities for consistent command line tools',
author='Roberto Aguilar',
author_email='r@rreboto.com',
package_dir={'': SRC_PREFIX},
packages=packages,
long_description=readme(),
long_description_content_type='text/markdown',
url='http://github.com/rca/cmdline',
license='LICENSE',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Natural Language :: English',
'Topic :: Utilities'
],
install_requires=[
'PyYAML>=3',
],
)
|
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
packages = find_packages(SRC_PREFIX)
setup(
name='cmdline',
version='0.0.0',
description='Utilities for consistent command line tools',
author='Roberto Aguilar',
author_email='r@rreboto.com',
package_dir={'': SRC_PREFIX},
packages=packages,
long_description=open('README.md').read(),
url='http://github.com/rca/cmdline',
license='LICENSE',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Natural Language :: English',
'Topic :: Utilities'
],
install_requires=[
'PyYAML>=3',
],
)
|
Document and inherit please :D
|
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : sebastien.bordes@jrebirth.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
|
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : sebastien.bordes@jrebirth.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.concurrent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to.
*
* @author Sébastien Bordes
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RunInto {
/**
* Define the RunType value.
*
* The default value is RunType.JIT
*/
RunType value() default RunType.JIT;
}
|
Add type annotations for globus
|
import typeguard
from typing import Optional
from parsl.utils import RepresentationMixin
class GlobusScheme(RepresentationMixin):
"""Specification for accessing data on a remote executor via Globus.
Parameters
----------
endpoint_uuid : str
Universally unique identifier of the Globus endpoint at which the data can be accessed.
This can be found in the `Manage Endpoints <https://www.globus.org/app/endpoints>`_ page.
endpoint_path : str, optional
FIXME
local_path : str, optional
FIXME
"""
@typeguard.typechecked
def __init__(self, endpoint_uuid: str, endpoint_path: Optional[str] = None, local_path: Optional[str] = None):
self.endpoint_uuid = endpoint_uuid
self.endpoint_path = endpoint_path
self.local_path = local_path
|
from parsl.utils import RepresentationMixin
class GlobusScheme(RepresentationMixin):
"""Specification for accessing data on a remote executor via Globus.
Parameters
----------
endpoint_uuid : str
Universally unique identifier of the Globus endpoint at which the data can be accessed.
This can be found in the `Manage Endpoints <https://www.globus.org/app/endpoints>`_ page.
endpoint_path : str, optional
FIXME
local_path : str, optional
FIXME
"""
def __init__(self, endpoint_uuid, endpoint_path=None, local_path=None):
self.endpoint_uuid = endpoint_uuid
self.endpoint_path = endpoint_path
self.local_path = local_path
|
Correct redirect after search from submission
|
from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class SimpleSearchForm(FlaskForm):
nct_id = StringField('nct_id', validators=[DataRequired()])
import api_client
# Initialize the Flask application
app = Flask(__name__)
app.secret_key = 'ctrp'
app.debug = True
# Install our Bootstrap extension
Bootstrap(app)
# We initialize the navigation as well
nav = Nav()
nav.init_app(app)
@app.route('/')
def home():
return search_form()
@app.route('/display_trial/<string:nct_id>')
def display_trial(nct_id):
# retrieving trial as dictionary from the CTRP API client
trial_dict = api_client.get_trial_by_nct_id(nct_id)
# Render template
return render_template('display_trial.html', trial=trial_dict)
@app.route('/search_form', methods=('GET', 'POST'))
def search_form():
form = SimpleSearchForm()
if form.validate_on_submit():
return redirect(url_for('display_trial', nct_id=form.nct_id.data))
# Render template
return render_template('search_form.html', form=form)
# Run Flask webapp
if __name__ == '__main__':
app.run()
|
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class SimpleSearchForm(FlaskForm):
nct_id = StringField('nct_id', validators=[DataRequired()])
import api_client
# Initialize the Flask application
app = Flask(__name__)
app.secret_key = 'ctrp'
app.debug = True
# Install our Bootstrap extension
Bootstrap(app)
# We initialize the navigation as well
nav = Nav()
nav.init_app(app)
@app.route('/')
def home():
return search_form()
@app.route('/display_trial')
def display_trial(nct_id):
# retrieving trial as dictionary from the CTRP API client
trial_dict = api_client.get_trial_by_nct_id(nct_id)
# Render template
return render_template('display_trial.html', trial=trial_dict)
@app.route('/search_form', methods=('GET', 'POST'))
def search_form():
form = SimpleSearchForm()
if form.validate_on_submit():
return display_trial(form.nct_id.data)
# Render template
return render_template('search_form.html', form=form)
# Run Flask webapp
if __name__ == '__main__':
app.run()
|
OAK-2833: Refactor TarMK
bump export package version as required
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1682176 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.
*/
@Version("2.0.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;
import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;
|
/*
* 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.
*/
@Version("1.2.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;
import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;
|
Add field to indicate admin permission
|
/*-
* Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
* All rights reserved
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package msg
import (
)
type Supervisor struct {
Verdict uint16
VerictAdmin bool
RemoteAddr string
// Fields for encrypted requests
KexId string
Data []byte
Kex auth.Kex
// Fields for basic authentication requests
BasicAuthUser string
BasicAuthToken string
Restricted bool
// Fields for permission authorization requests
PermAction string
PermRepository string
PermMonitoring string
PermNode string
// Fields for map update notifications
Action string
Object string
User proto.User
Team proto.Team
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
|
/*-
* Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
* All rights reserved
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package msg
import (
)
type Supervisor struct {
Verdict uint16
RemoteAddr string
// Fields for encrypted requests
KexId string
Data []byte
Kex auth.Kex
// Fields for basic authentication requests
BasicAuthUser string
BasicAuthToken string
Restricted bool
// Fields for permission authorization requests
PermAction string
PermRepository string
PermMonitoring string
PermNode string
// Fields for map update notifications
Action string
Object string
User proto.User
Team proto.Team
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
|
Add existence check for firestore before invoking.
|
import { merge } from 'lodash/fp';
import { firestoreActions } from './actions';
import { mapWithFirebaseAndDispatch } from './utils/actions';
import { defaultConfig } from './constants';
/**
* Create a firebase instance that has helpers attached for dispatching actions
* @param {Object} firebase - Firebase instance which to extend
* @param {Object} configs - Configuration object
* @param {Function} dispatch - Action dispatch function
* @return {Object} Extended Firebase instance
*/
export default function createFirestoreInstance(firebase, configs, dispatch) {
// Setup internal variables
const defaultInternals = {
// Setup empty listeners object (later used to track listeners)
listeners: {},
// Extend default config with provided config
config: { defaultConfig, ...configs },
};
// extend existing firebase internals (using redux-firestore along with redux-firebase)
firebase._ = merge(defaultInternals, firebase._); // eslint-disable-line no-param-reassign
// Aliases for methods
const aliases = [
{ action: firestoreActions.deleteRef, name: 'delete' },
{ action: firestoreActions.setListener, name: 'onSnapshot' },
];
// Create methods with internal firebase object and dispatch passed
const methods = mapWithFirebaseAndDispatch(
firebase,
dispatch,
firestoreActions,
aliases,
);
return Object.assign(
firebase && firebase.firestore ? firebase.firestore() : {},
firebase.firestore,
{ _: firebase._ },
configs.helpersNamespace
? // Attach helpers to specified namespace
{ [configs.helpersNamespace]: methods }
: methods,
);
}
|
import { merge } from 'lodash/fp';
import { firestoreActions } from './actions';
import { mapWithFirebaseAndDispatch } from './utils/actions';
import { defaultConfig } from './constants';
/**
* Create a firebase instance that has helpers attached for dispatching actions
* @param {Object} firebase - Firebase instance which to extend
* @param {Object} configs - Configuration object
* @param {Function} dispatch - Action dispatch function
* @return {Object} Extended Firebase instance
*/
export default function createFirestoreInstance(firebase, configs, dispatch) {
// Setup internal variables
const defaultInternals = {
// Setup empty listeners object (later used to track listeners)
listeners: {},
// Extend default config with provided config
config: { defaultConfig, ...configs },
};
// extend existing firebase internals (using redux-firestore along with redux-firebase)
firebase._ = merge(defaultInternals, firebase._); // eslint-disable-line no-param-reassign
// Aliases for methods
const aliases = [
{ action: firestoreActions.deleteRef, name: 'delete' },
{ action: firestoreActions.setListener, name: 'onSnapshot' },
];
// Create methods with internal firebase object and dispatch passed
const methods = mapWithFirebaseAndDispatch(
firebase,
dispatch,
firestoreActions,
aliases,
);
return Object.assign(
firebase.firestore(),
firebase.firestore,
{ _: firebase._ },
configs.helpersNamespace
? // Attach helpers to specified namespace
{ [configs.helpersNamespace]: methods }
: methods,
);
}
|
Add season to Convention filter
|
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
'season': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
|
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
|
Sort subscription list by date
|
define([
'backbone', 'handlebars', 'moment',
'connect/collections/Subscriptions',
'connect/views/SubscriptionListItemView',
'text!connect/templates/subscriptionList.handlebars'
], function(Backbone, Handlebars, moment, Subscriptions, SubscriptionListItemView, tpl) {
'use strict';
var SubscriptionListView = Backbone.View.extend({
template: Handlebars.compile(tpl),
initialize: function() {
this.subscriptions = new Subscriptions();
this.listenTo(this.subscriptions, 'sync', this.render);
this.subscriptions.fetch();
this.render();
},
render: function() {
this.$el.html(this.template());
var sortedSubscriptions = new Subscriptions(
this.subscriptions.sortBy(function(subscription) {
return -moment(subscription.get('created')).unix();
})
);
var $tableBody = this.$('#user-subscriptions-table-body');
sortedSubscriptions.each(function(subscription) {
var view = new SubscriptionListItemView({
subscription: subscription});
$tableBody.append(view.el);
});
}
});
return SubscriptionListView;
});
|
define([
'backbone', 'handlebars', 'moment',
'connect/collections/Subscriptions',
'connect/views/SubscriptionListItemView',
'text!connect/templates/subscriptionList.handlebars'
], function(Backbone, Handlebars, moment, Subscriptions, SubscriptionListItemView, tpl) {
'use strict';
var SubscriptionListView = Backbone.View.extend({
template: Handlebars.compile(tpl),
initialize: function() {
this.subscriptions = new Subscriptions();
this.listenTo(this.subscriptions, 'sync', this.render);
this.subscriptions.fetch();
this.render();
},
render: function() {
this.$el.html(this.template());
var $tableBody = this.$('#user-subscriptions-table-body');
this.subscriptions.each(function(subscription) {
var view = new SubscriptionListItemView({
subscription: subscription});
$tableBody.append(view.el);
});
}
});
return SubscriptionListView;
});
|
Update for plug-in : Weibo
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
name: 'Weibo',
version: '1.0',
prepareImgLinks: function(callback) {
var res = [];
hoverZoom.urlReplace(res,
'img[src]',
/\/thumb\d+\//,
'/large/'
);
hoverZoom.urlReplace(res,
'img[src]',
/\/(orj|mw)\d+\//,
'/large/'
);
hoverZoom.urlReplace(res,
'img[src]',
/\/crop.*\//,
'/large/'
);
hoverZoom.urlReplace(res,
'img[src]',
/\/square.*\//,
'//'
);
callback($(res), this.name);
}
});
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
name: 'Weibo',
version: '0.1',
prepareImgLinks: function(callback) {
var res = [];
hoverZoom.urlReplace(res,
'img[src*="sinaimg.cn/thumbnail/"]',
/thumbnail\/([0-9a-z]+)\.jpg/,
'large/$1.jpg'
);
hoverZoom.urlReplace(res,
'img[src*="sinaimg.cn"]',
/50/,
'180'
);
hoverZoom.urlReplace(res,
'img[src*="thumbnail"]',
/thumbnail/,
'bmiddle'
);
callback($(res));
}
});
|
Use span tag for InPlaceFieldView
|
//
//https://github.com/mszoernyi/ember-inplace-edit
//
var InPlaceFieldView = Ember.View.extend({
tagName: 'span',
isEditing: false,
layoutName: "in_place_edit",
templateName: function(){
if(this.get("contentType") === 'currency'){
return 'in_place_currency_field';
} else {
return 'in_place_text_field';
}
}.property(),
isEmpty: function(){
return Ember.isEmpty(this.get('content'));
}.property('content'),
inputField: Ember.TextField.extend({}),
emptyValue: "Click to Edit",
focusOut: function(){
this.get('controller').get('store').commit();
this.set('isEditing', false);
},
click: function(){
this.set("isEditing", true);
}
});
export default InPlaceFieldView;
|
//
//https://github.com/mszoernyi/ember-inplace-edit
//
var InPlaceFieldView = Ember.View.extend({
tagName: 'div',
isEditing: false,
layoutName: "in_place_edit",
templateName: function(){
if(this.get("contentType") === 'currency'){
return 'in_place_currency_field';
} else {
return 'in_place_text_field';
}
}.property(),
isEmpty: function(){
return Ember.isEmpty(this.get('content'));
}.property('content'),
inputField: Ember.TextField.extend({}),
emptyValue: "Click to Edit",
focusOut: function(){
this.get('controller').get('store').commit();
this.set('isEditing', false);
},
click: function(){
this.set("isEditing", true);
}
});
export default InPlaceFieldView;
|
[Dns] Add rcode constants to message
|
<?php
namespace React\Dns;
class Message
{
const TYPE_A = 1;
const TYPE_NS = 2;
const TYPE_CNAME = 5;
const TYPE_SOA = 6;
const TYPE_PTR = 12;
const TYPE_MX = 15;
const TYPE_TXT = 16;
const CLASS_IN = 1;
const OPCODE_QUERY = 0;
const OPCODE_IQUERY = 1; // inverse query
const OPCODE_STATUS = 2;
const RCODE_OK = 0;
const RCODE_FORMAT_ERROR = 1;
const RCODE_SERVER_FAILURE = 2;
const RCODE_NAME_ERROR = 3;
const RCODE_NOT_IMPLEMENTED = 4;
const RCODE_REFUSED = 5;
public $data = '';
public $header = array();
public $question = array();
public $answer = array();
public $authority = array();
public $additional = array();
public function getId()
{
return $this->header['id'];
}
public function isQuery()
{
return 0 === $this->header['qr'];
}
public function isResponse()
{
return 1 === $this->header['qr'];
}
}
|
<?php
namespace React\Dns;
class Message
{
const TYPE_A = 1;
const TYPE_NS = 2;
const TYPE_CNAME = 5;
const TYPE_SOA = 6;
const TYPE_PTR = 12;
const TYPE_MX = 15;
const TYPE_TXT = 16;
const CLASS_IN = 1;
const OPCODE_QUERY = 0;
const OPCODE_IQUERY = 1; // inverse query
const OPCODE_STATUS = 2;
public $data = '';
public $header = array();
public $question = array();
public $answer = array();
public $authority = array();
public $additional = array();
public function getId()
{
return $this->header['id'];
}
public function isQuery()
{
return 0 === $this->header['qr'];
}
public function isResponse()
{
return 1 === $this->header['qr'];
}
}
|
Include low and hidpi icon toggle support
|
// Global variables for isolated world
var iconActive = false;
function toggle(){
// Show "on" icon when showing the help
if(iconActive == false){
activate();
} else{
deactivate();
}
}
function deactivate(){
iconActive = false;
chrome.browserAction.setIcon({"path":"icon-" + "off" + ".png"});
chrome.tabs.executeScript(null, {file: "jquery-2.1.1.min.js"}, function() {
chrome.tabs.executeScript(null, {file: "github-off.js"});
chrome.browserAction.setIcon(
{
"path": {
19: "icon-19-" + "off" + ".png",
38: "icon-38-" + "off" + ".png"
}
}
);
});
}
function activate(){
iconActive = true;
chrome.browserAction.setIcon(
{
"path": {
19: "icon-19-" + "on" + ".png",
38: "icon-38-" + "on" + ".png"
}
}
);
chrome.tabs.executeScript(null, {file: "jquery-2.1.1.min.js"}, function() {
chrome.tabs.executeScript(null, {file: "github-on.js"});
});
}
//////////////////////////////////////
// Tab event bindings
//////////////////////////////////////
chrome.tabs.onUpdated.addListener(function(){
deactivate();
});
chrome.tabs.onRemoved.addListener(function(){
deactivate();
});
chrome.browserAction.onClicked.addListener(function(tab) {
toggle();
});
|
// Global variables for isolated world
var iconActive = false;
function toggle(){
// Show "on" icon when showing the help
if(iconActive == false){
activate();
} else{
deactivate();
}
}
function deactivate(){
iconActive = false;
chrome.browserAction.setIcon({path:"icon-" + "off" + ".png"});
chrome.tabs.executeScript(null, {file: "jquery-2.1.1.min.js"}, function() {
chrome.tabs.executeScript(null, {file: "github-off.js"});
});
}
function activate(){
iconActive = true;
chrome.browserAction.setIcon({path:"icon-" + "on" + ".png"});
chrome.tabs.executeScript(null, {file: "jquery-2.1.1.min.js"}, function() {
chrome.tabs.executeScript(null, {file: "github-on.js"});
});
}
//////////////////////////////////////
// Tab event bindings
//////////////////////////////////////
chrome.tabs.onUpdated.addListener(function(){
deactivate();
});
chrome.tabs.onRemoved.addListener(function(){
deactivate();
});
chrome.browserAction.onClicked.addListener(function(tab) {
toggle();
});
|
Fix string formatting in URL path
`go vet` message:
```
src/cf-metrics/events.go:29: arg url.QueryEscape(since.Format(time.RFC3339)) for printf verb %E of wrong type: string
```
I suspect that this wasn’t doing quite what I thought it was, due to
string formatting and URL encoding collisions.
|
package main
import (
"fmt"
"time"
"net/url"
"code.cloudfoundry.org/cli/cf/api/resources"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/models"
"code.cloudfoundry.org/cli/cf/net"
)
type EventRepo struct {
config coreconfig.Reader
gateway net.Gateway
}
func NewEventRepo(config coreconfig.Repository, gateway net.Gateway) (repo EventRepo) {
repo.config = config
repo.gateway = gateway
return
}
func (r EventRepo) GetAppEvents(app models.Application, since time.Time, callback func(models.EventFields) bool) error {
return r.gateway.ListPaginatedResources(
r.config.APIEndpoint(),
fmt.Sprintf("/v2/events?q=actee:%s&q=timestamp%s", app.GUID, url.QueryEscape(">"+since.Format(time.RFC3339))),
resources.EventResourceNewV2{},
func(resource interface{}) bool {
return callback(resource.(resources.EventResourceNewV2).ToFields())
})
}
|
package main
import (
"fmt"
"time"
"net/url"
"code.cloudfoundry.org/cli/cf/api/resources"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/models"
"code.cloudfoundry.org/cli/cf/net"
)
type EventRepo struct {
config coreconfig.Reader
gateway net.Gateway
}
func NewEventRepo(config coreconfig.Repository, gateway net.Gateway) (repo EventRepo) {
repo.config = config
repo.gateway = gateway
return
}
func (r EventRepo) GetAppEvents(app models.Application, since time.Time, callback func(models.EventFields) bool) error {
return r.gateway.ListPaginatedResources(
r.config.APIEndpoint(),
fmt.Sprintf("/v2/events?q=actee:%s&q=timestamp%3E%s", app.GUID, url.QueryEscape(since.Format(time.RFC3339))),
resources.EventResourceNewV2{},
func(resource interface{}) bool {
return callback(resource.(resources.EventResourceNewV2).ToFields())
})
}
|
Fix broken comment field in CfP
|
// This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import 'jquery-ui';
import 'jquery-ui/ui/effect';
import 'jquery-ui/ui/effects/effect-pulsate';
import 'jquery-ui/ui/effects/effect-highlight';
import 'jquery-ui/ui/effects/effect-blind';
import 'jquery-ui/ui/widgets/datepicker';
import 'jquery-ui/ui/widgets/dialog';
import 'jquery-ui/ui/widgets/draggable';
import 'jquery-ui/ui/widgets/droppable';
import 'jquery-ui/ui/widgets/resizable';
import 'jquery-ui/ui/widgets/sortable';
import 'jquery-ui/ui/widgets/slider';
import 'jquery-ui/ui/widgets/tabs';
import 'jquery-ui/themes/base/all.css';
|
// This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import 'jquery-ui';
import 'jquery-ui/ui/effect';
import 'jquery-ui/ui/effects/effect-pulsate';
import 'jquery-ui/ui/effects/effect-highlight';
import 'jquery-ui/ui/widgets/datepicker';
import 'jquery-ui/ui/widgets/dialog';
import 'jquery-ui/ui/widgets/draggable';
import 'jquery-ui/ui/widgets/droppable';
import 'jquery-ui/ui/widgets/resizable';
import 'jquery-ui/ui/widgets/sortable';
import 'jquery-ui/ui/widgets/slider';
import 'jquery-ui/ui/widgets/tabs';
import 'jquery-ui/themes/base/all.css';
|
Allow users of the Machine Provider to specify the dev instance for API calls
BUG=489837
Review URL: https://codereview.chromium.org/1572793002
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from google.appengine.ext import ndb
from components import net
from components import utils
from components.datastore_utils import config
MACHINE_PROVIDER_SCOPES = (
'https://www.googleapis.com/auth/userinfo.email',
)
class MachineProviderConfiguration(config.GlobalConfig):
"""Configuration for talking to the Machine Provider."""
# URL of the Machine Provider instance to use.
instance_url = ndb.StringProperty(required=True)
@classmethod
def get_instance_url(cls):
"""Returns the URL of the Machine Provider instance."""
return cls.cached().instance_url
def set_defaults(self):
"""Sets default values used to initialize the config."""
self.instance_url = 'https://machine-provider.appspot.com'
def add_machines(requests):
"""Add machines to the Machine Provider's Catalog.
Args:
requests: A list of rpc_messages.CatalogMachineAdditionRequest instances.
"""
logging.info('Sending batched add_machines request')
return net.json_request(
'%s/_ah/api/catalog/v1/add_machines' %
MachineProviderConfiguration.get_instance_url(),
method='POST',
payload=utils.to_json_encodable({'requests': requests}),
scopes=MACHINE_PROVIDER_SCOPES,
)
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from components import net
from components import utils
MACHINE_PROVIDER_API_URL = 'https://machine-provider.appspot.com/_ah/api'
CATALOG_BASE_URL = '%s/catalog/v1' % MACHINE_PROVIDER_API_URL
MACHINE_PROVIDER_BASE_URL = '%s/machine_provider/v1' % MACHINE_PROVIDER_API_URL
MACHINE_PROVIDER_SCOPES = (
'https://www.googleapis.com/auth/userinfo.email',
)
def add_machines(requests):
"""Add machines to the Machine Provider's Catalog.
Args:
requests: A list of rpc_messages.CatalogMachineAdditionRequest instances.
"""
logging.info('Sending batched add_machines request')
return net.json_request(
'%s/add_machines' % CATALOG_BASE_URL,
method='POST',
payload=utils.to_json_encodable({'requests': requests}),
scopes=MACHINE_PROVIDER_SCOPES,
)
|
Fix nosetests for config file loading
|
import json
import sys
def load_config_file(out=sys.stdout):
if sys.argv[0].endswith('nosetests'):
default_filepath = "./resources/config/default-config.json"
user_filepath = "./resources/config/user-config.json"
else:
default_filepath = "../resources/config/default-config.json"
user_filepath = "../resources/config/user-config.json"
try:
default_json = read_json(default_filepath)
user_json = read_json(user_filepath)
for property in user_json:
default_json[property] = user_json[property]
except FileNotFoundError as e:
out.write("Cannot find file: " + e.filename)
else:
out.write("Read styling config JSON correctly.")
return default_json
def read_json(filepath):
config_string = ''
with open(filepath) as f:
for line in f:
line = line.lstrip()
if not line.startswith("//"):
config_string += line
config_json = json.loads(config_string)
return config_json
if __name__ == "__main__":
load_config_file()
|
import json
import sys
def load_config_file(out=sys.stdout):
default_filepath = "../resources/config/default-config.json"
user_filepath = "../resources/config/user-config.json"
try:
default_json = read_json(default_filepath)
user_json = read_json(user_filepath)
for property in user_json:
default_json[property] = user_json[property]
except FileNotFoundError as e:
out.write("Cannot find file: " + e.filename)
else:
out.write("Read styling config JSON correctly.")
return default_json
def read_json(filepath):
config_string = ''
with open(filepath) as f:
for line in f:
line = line.lstrip()
if not line.startswith("//"):
config_string += line
config_json = json.loads(config_string)
return config_json
if __name__ == "__main__":
load_config_file()
|
Fix rq jobs registration check
|
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
Test entity should not be allowed to change the created date after it's been created.
|
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;
import java.util.Date;
import ca.corefacility.bioinformatics.irida.model.IridaThing;
/**
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> {
Long id;
private Date createdDate;
private Date modifiedDate;
public IdentifiableTestEntity() {
}
public Long getId() {
return this.id;
}
public void setId(Long identifier) {
this.id = identifier;
}
@Override
public int compareTo(IdentifiableTestEntity o) {
return createdDate.compareTo(o.createdDate);
}
@Override
public Date getTimestamp() {
return createdDate;
}
@Override
public String getLabel() {
return null;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;
import java.util.Date;
import ca.corefacility.bioinformatics.irida.model.IridaThing;
/**
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> {
Long id;
private Date createdDate;
private Date modifiedDate;
public IdentifiableTestEntity() {
}
public Long getId() {
return this.id;
}
public void setId(Long identifier) {
this.id = identifier;
}
@Override
public int compareTo(IdentifiableTestEntity o) {
return createdDate.compareTo(o.createdDate);
}
@Override
public Date getTimestamp() {
return createdDate;
}
@Override
public void setTimestamp(Date timestamp) {
this.createdDate = timestamp;
}
@Override
public String getLabel() {
return null;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
}
|
Fix key and cert file params when using personal version
|
module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
} else {
serverOptions.key = fs.readFileSync(options.key, 'utf8')
serverOptions.cert = fs.readFileSync(options.cert, 'utf8')
}
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
|
module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
}
serverOptions.key = fs.readFileSync(serverOptions.key, 'utf8')
serverOptions.cert = fs.readFileSync(serverOptions.cert, 'utf8')
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
|
Fix user, album factories; add setup for photo test case
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
user = factory.SubFactory(UserFactory)
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
user = factory.SubFactory(UserFactory)
class PhotoTestCase(TestCase):
"""docstring for PhotoTestCase"""
@classmethod
def setUp(cls):
user = UserFactory()
user.set_password('secret')
user.save()
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
Set version number to 0.7.0.
|
from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
|
from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
|
Make sure everything is in lowercase.
|
var toNumber = require("underscore.string/toNumber"),
ltrim = require("underscore.string/ltrim");
// Generate a random justinfan username
function generateJustinfan() {
return "justinfan" + Math.floor((Math.random() * 80000) + 1000);
}
// Determine if value is a valid integer
function isInteger(value) {
//0 decimal places
var maybeNumber = toNumber(value, 0);
return isNaN(maybeNumber);
}
// Normalize channel name by including the hash
function normalizeChannel(name) {
return "#" + ltrim(name.toLoweCase(), "#");
}
// Normalize username by removing the hash
function normalizeUsername(username) {
return ltrim(username.toLoweCase(), "#");
}
exports.generateJustinfan = generateJustinfan;
exports.isInteger = isInteger;
exports.normalizeChannel = normalizeChannel;
exports.normalizeUsername = normalizeUsername;
|
var toNumber = require("underscore.string/toNumber"),
ltrim = require("underscore.string/ltrim");
// Generate a random justinfan username
function generateJustinfan() {
return "justinfan" + Math.floor((Math.random() * 80000) + 1000);
}
// Determine if value is a valid integer
function isInteger(value) {
//0 decimal places
var maybeNumber = toNumber(value, 0);
return isNaN(maybeNumber);
}
// Normalize channel name by including the hash
function normalizeChannel(name) {
return "#" + ltrim(name, "#");
}
// Normalize username by removing the hash
function normalizeUsername(username) {
return ltrim(username, "#");
}
exports.generateJustinfan = generateJustinfan;
exports.isInteger = isInteger;
exports.normalizeChannel = normalizeChannel;
exports.normalizeUsername = normalizeUsername;
|
Add trademark symbol to control component
|
/*renders control panel with associated buttons and display*/
import React from 'react';
import CountDisplay from 'CountDisplay';
import StrictButton from 'StrictButton';
import OnOffButton from 'OnOffButton';
class Control extends React.Component{
render(){
return (
<div id="control-panel">
<div id="controls">
<h1>Simon™</h1>
<div className="control-row">
<CountDisplay countDisplayText={ this.props.countDisplayText } isOn={ this.props.isOn }/>
<div id="start">
<button id="start-btn" onClick={ this.props.onStartClick }></button>
<label>START</label>
</div>
<StrictButton onStrictClick={ this.props.onStrictClick } strictOn={ this.props.strictOn } />
</div>
<div className="control-row">
<OnOffButton onOnClick={ this.props.onOnClick } isOn={ this.props.isOn }/>
</div>
</div>
</div>
);
}
}
export default Control;
|
/*renders control panel with associated buttons and display*/
import React from 'react';
import CountDisplay from 'CountDisplay';
import StrictButton from 'StrictButton';
import OnOffButton from 'OnOffButton';
class Control extends React.Component{
render(){
return (
<div id="control-panel">
<div id="controls">
<h1>Simon(tm)</h1>
<div className="control-row">
<CountDisplay countDisplayText={ this.props.countDisplayText } isOn={ this.props.isOn }/>
<div id="start">
<button id="start-btn" onClick={ this.props.onStartClick }></button>
<label>START</label>
</div>
<StrictButton onStrictClick={ this.props.onStrictClick } strictOn={ this.props.strictOn } />
</div>
<div className="control-row">
<OnOffButton onOnClick={ this.props.onOnClick } isOn={ this.props.isOn }/>
</div>
</div>
</div>
);
}
}
export default Control;
|
Print a list of aliases, if any exist.
|
import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
Name [] aliases = lookup.getAliases();
if (aliases.length > 0) {
System.out.print("# aliases: ");
for (int i = 0; i < aliases.length; i++) {
System.out.print(aliases[i]);
if (i < aliases.length - 1)
System.out.print(" ");
}
System.out.println();
}
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
Make test module for Copy runnable
|
import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.uniform(-1, 1, (10, 5)).astype(numpy.float32)
def test_check_forward_cpu(self):
x = chainer.Variable(self.x_data)
y = functions.copy(x, -1)
gradient_check.assert_allclose(self.x_data, y.data, atol=0, rtol=0)
def test_check_backward_cpu(self):
x = chainer.Variable(self.x_data)
y = functions.copy(x, -1)
y.grad = self.gy
y.backward()
gradient_check.assert_allclose(x.grad, self.gy, atol=0, rtol=0)
testing.run_module(__name__, __file__)
|
import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.uniform(-1, 1, (10, 5)).astype(numpy.float32)
def test_check_forward_cpu(self):
x = chainer.Variable(self.x_data)
y = functions.copy(x, -1)
gradient_check.assert_allclose(self.x_data, y.data, atol=0, rtol=0)
def test_check_backward_cpu(self):
x = chainer.Variable(self.x_data)
y = functions.copy(x, -1)
y.grad = self.gy
y.backward()
gradient_check.assert_allclose(x.grad, self.gy, atol=0, rtol=0)
|
Fix timing issue in firefox where cycle wouldn't start before replay
|
import {run} from '@cycle/core';
import Rx from 'rx';
import restartable from './restartable';
function restart (main, drivers, {sources, sinks}, isolate = {}, timeToTravelTo = null) {
sources.dispose();
sinks && sinks.dispose();
if (typeof isolate === 'function' && 'reset' in isolate) {
isolate.reset();
}
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPreReplay) {
driver.onPreReplay();
}
}
const newSourcesAndSinks = run(main, drivers);
setTimeout(() => {
const scheduler = new Rx.HistoricalScheduler();
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.replayLog) {
const log$ = sources[driverName].log$;
driver.replayLog(scheduler, log$, timeToTravelTo);
}
}
scheduler.scheduleAbsolute({}, new Date(), () => {
// TODO - remove this setTimeout, figure out how to tell when an async app is booted
setTimeout(() => {
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPostReplay) {
driver.onPostReplay();
}
}
}, 500);
});
scheduler.start();
}, 1);
return newSourcesAndSinks;
}
module.exports = {
restart,
restartable
}
|
import {run} from '@cycle/core';
import Rx from 'rx';
import restartable from './restartable';
function restart (main, drivers, {sources, sinks}, isolate = {}, timeToTravelTo = null) {
sources.dispose();
sinks && sinks.dispose();
if (typeof isolate === 'function' && 'reset' in isolate) {
isolate.reset();
}
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPreReplay) {
driver.onPreReplay();
}
}
const newSourcesAndSinks = run(main, drivers);
setTimeout(() => {
const scheduler = new Rx.HistoricalScheduler();
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.replayLog) {
const log$ = sources[driverName].log$;
driver.replayLog(scheduler, log$, timeToTravelTo);
}
}
scheduler.scheduleAbsolute({}, new Date(), () => {
// TODO - remove this setTimeout, figure out how to tell when an async app is booted
setTimeout(() => {
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPostReplay) {
driver.onPostReplay();
}
}
}, 500);
});
scheduler.start();
});
return newSourcesAndSinks;
}
module.exports = {
restart,
restartable
}
|
chore(bundle): Remove named define in AMD
|
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
'browser-id3-writer': './src/browser-id3-writer.js',
'browser-id3-writer.min': './src/browser-id3-writer.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
library: 'ID3Writer',
libraryTarget: 'umd'
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min.js$/
})
]
};
|
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
'browser-id3-writer': './src/browser-id3-writer.js',
'browser-id3-writer.min': './src/browser-id3-writer.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
library: 'ID3Writer',
libraryTarget: 'umd',
umdNamedDefine: true
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min.js$/
})
]
};
|
Add rangeCondition to algorithm binding
|
package org.yamcs.algorithms;
import java.util.Calendar;
import java.util.Date;
import org.yamcs.parameter.ParameterValue;
import org.yamcs.protobuf.Pvalue.AcquisitionStatus;
import org.yamcs.protobuf.Pvalue.MonitoringResult;
import org.yamcs.protobuf.Pvalue.RangeCondition;
import org.yamcs.utils.TimeEncoding;
/**
* A ParameterValue as passed to an algorithm. Actual implementations are generated on-the-fly to walk around the issue
* of Rhino that maps boxed primitives to JavaScript Objects instead of Numbers
*/
public abstract class ValueBinding {
public Date acquisitionTime;
public long acquisitionTimeMs;
public Date generationTime;
public long generationTimeMs;
public AcquisitionStatus acquisitionStatus;
public MonitoringResult monitoringResult;
public RangeCondition rangeCondition;
public void updateValue(ParameterValue newValue) {
acquisitionStatus = newValue.getAcquisitionStatus();
monitoringResult = newValue.getMonitoringResult();
rangeCondition = newValue.getRangeCondition();
if (newValue.hasAcquisitionTime()) {
Calendar cal = TimeEncoding.toCalendar(newValue.getAcquisitionTime());
acquisitionTime = cal.getTime();
}
acquisitionTimeMs = newValue.getAcquisitionTime();
generationTime = TimeEncoding.toCalendar(newValue.getGenerationTime()).getTime();
generationTimeMs = newValue.getGenerationTime();
}
}
|
package org.yamcs.algorithms;
import java.util.Calendar;
import java.util.Date;
import org.yamcs.parameter.ParameterValue;
import org.yamcs.protobuf.Pvalue.AcquisitionStatus;
import org.yamcs.protobuf.Pvalue.MonitoringResult;
import org.yamcs.utils.TimeEncoding;
/**
* A ParameterValue as passed to an algorithm. Actual implementations are
* generated on-the-fly to walk around the issue of Rhino that maps
* boxed primitives to JavaScript Objects instead of Numbers
*/
public abstract class ValueBinding {
public Date acquisitionTime;
public long acquisitionTimeMs;
public Date generationTime;
public long generationTimeMs;
public AcquisitionStatus acquisitionStatus;
public MonitoringResult monitoringResult;
public void updateValue(ParameterValue newValue) {
acquisitionStatus = newValue.getAcquisitionStatus();
monitoringResult = newValue.getMonitoringResult();
if(newValue.hasAcquisitionTime()) {
Calendar cal = TimeEncoding.toCalendar(newValue.getAcquisitionTime());
acquisitionTime = cal.getTime();
}
acquisitionTimeMs = newValue.getAcquisitionTime();
generationTime = TimeEncoding.toCalendar(newValue.getGenerationTime()).getTime();
generationTimeMs = newValue.getGenerationTime();
}
}
|
Remove defect for building a string in a loop
|
package nl.eernie.jmoribus.model;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Step {
private StepType stepType;
private List<StepLine> stepLines = new ArrayList<>();
public Step(StepType stepType) {
this.stepType = stepType;
}
public StepType getStepType() {
return stepType;
}
public StepLine getFirstStepLine()
{
return stepLines.get(0);
}
public List<StepLine> getStepLines()
{
return stepLines;
}
public String getCombinedStepLines(){
StringBuffer buffer = new StringBuffer();
for(StepLine stepLine: stepLines){
if(StringUtils.isNotBlank(buffer.toString())){
buffer.append(" ");
}
if(stepLine instanceof Table){
int index = stepLines.indexOf(stepLine);
buffer.append("TABLE"+index);
}else{
buffer.append(stepLine.getText());
}
}
return buffer.toString();
}
}
|
package nl.eernie.jmoribus.model;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Step {
private StepType stepType;
private List<StepLine> stepLines = new ArrayList<>();
public Step(StepType stepType) {
this.stepType = stepType;
}
public StepType getStepType() {
return stepType;
}
public StepLine getFirstStepLine()
{
return stepLines.get(0);
}
public List<StepLine> getStepLines()
{
return stepLines;
}
public String getCombinedStepLines(){
String combined = "";
for(StepLine stepLine: stepLines){
if(StringUtils.isNotBlank(combined)){
combined = combined + " ";
}
if(stepLine instanceof Table){
int index = stepLines.indexOf(stepLine);
combined = combined + "TABLE"+index;
}else{
combined = combined + stepLine.getText();
}
}
return combined;
}
}
|
Add support for JSX *within* .vue files
|
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
},
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"vue/jsx-uses-vars": 2,
}
};
|
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
Add private constructor to prevent instantiation
------------------------------------------------------------------------
On behalf of the community, the JUnit Lambda Team thanks
msg systems ag (http://www.msg-systems.com) for supporting
the JUnit crowdfunding campaign!
------------------------------------------------------------------------
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
private CollectionUtils() {
/* no-op */
}
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
|
Change story index to use standard link for show action
|
@extends('layouts.admin')
@section('title') Stories @endsection
@section('content')
<table class="table table-striped">
<thead>
<tr>
<th style="width:10%">Action</th>
<th>Issue</th>
<th>Title</th>
<th>Author</th>
</tr>
</thead>
<tbody>
@foreach ($stories as $story)
<tr>
<td style="width:10%;white-space:nowrap">
<a href='{{ URL::route("sysop.stories.edit", [$story->id]) }}' title="Edit" class="btn"><i class="icon-edit"></i></a>
</td>
<td>{{ $story->number }}</td>
<td>{{ HTML::linkRoute('sysop.stories.show', $story->title, [$story->id]) }}</td>
<td>{{ HTML::mailto($story->email, $story->name) }}</td>
</tr>
@endforeach
</tbody>
</table>
<a href='{{ URL::route("sysop.stories.create") }}' class="btn btn-success" style="color:white"><i class="icon-plus icon-white"></i> New</a>
@endsection
|
@extends('layouts.admin')
@section('title') Stories @endsection
@section('content')
<table class="table table-striped">
<thead>
<tr>
<th style="width:10%">Action</th>
<th>Issue</th>
<th>Title</th>
<th>Author</th>
</tr>
</thead>
<tbody>
@foreach ($stories as $story)
<tr>
<td style="width:10%;white-space:nowrap">
<a href='{{ URL::route("sysop.stories.edit", [$story->id]) }}' title="Edit" class="btn"><i class="icon-edit"></i></a>
<a href='{{ URL::route("sysop.stories.show", [$story->id]) }}' title="Preview" class="btn"><i class="icon-eye-open"></i></a>
</td>
<td>{{ $story->number }}</td>
<td>{{ $story->title }}</td>
<td>{{ HTML::mailto($story->email, $story->name) }}</td>
</tr>
@endforeach
</tbody>
</table>
<a href='{{ URL::route("sysop.stories.create") }}' class="btn btn-success" style="color:white"><i class="icon-plus icon-white"></i> New</a>
@endsection
|
Remove temp directory just after the test (as well)
|
/* eslint no-console:0 */
var os = require('os');
var crypto = require('crypto');
var fse = require('fs-extra');
var originalCwd = process.cwd();
var createdDirectories = [];
process.on('exit', function () {
// In case something went wrong and some temp
// directories are still on the disk.
createdDirectories.forEach(function (path) {
fse.removeSync(path);
});
});
exports.setCleanTestCwd = function () {
var random = crypto.randomBytes(16).toString('hex');
var path = os.tmpdir() + '/fs-jetpack-test-' + random;
fse.mkdirSync(path);
createdDirectories.push(path);
process.chdir(path);
};
exports.switchBackToCorrectCwd = function () {
var path = createdDirectories.pop();
process.chdir(originalCwd);
fse.removeSync(path);
};
exports.parseMode = function (modeAsNumber) {
var mode = modeAsNumber.toString(8);
return mode.substring(mode.length - 3);
};
// Converts paths to windows or unix formats depending on platform running.
exports.osSep = function (path) {
if (Array.isArray(path)) {
return path.map(exports.osSep);
}
if (process.platform === 'win32') {
return path.replace(/\//g, '\\');
}
return path.replace(/\\/g, '/');
};
|
/* eslint no-console:0 */
var os = require('os');
var crypto = require('crypto');
var fse = require('fs-extra');
var originalCwd = process.cwd();
var createdDirectories = [];
process.on('exit', function () {
createdDirectories.forEach(function (path) {
try {
fse.removeSync(path);
} catch (err) {
console.error('Failed attempt to delete temp directory' + path);
console.error(err);
}
});
});
exports.setCleanTestCwd = function () {
var random = crypto.randomBytes(16).toString('hex');
var path = os.tmpdir() + '/fs-jetpack-test-' + random;
fse.mkdirSync(path);
createdDirectories.push(path);
process.chdir(path);
};
exports.switchBackToCorrectCwd = function () {
process.chdir(originalCwd);
};
exports.parseMode = function (modeAsNumber) {
var mode = modeAsNumber.toString(8);
return mode.substring(mode.length - 3);
};
// Converts paths to windows or unix formats depending on platform running.
exports.osSep = function (path) {
if (Array.isArray(path)) {
return path.map(exports.osSep);
}
if (process.platform === 'win32') {
return path.replace(/\//g, '\\');
}
return path.replace(/\\/g, '/');
};
|
Grunt/deploy: Use private ACL for S3
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
aws: grunt.file.readJSON('.aws-deploy.json'),
s3: {
options: {
accessKeyId: '<%= aws.accessKeyId %>',
secretAccessKey: '<%= aws.secretAccessKey %>',
bucket: 'gamekeller',
region: 'eu-central-1',
gzip: false,
overwrite: false,
access: 'private'
},
assets: {
cwd: 'public/',
src: ['assets/**', '!assets/manifest.json']
}
}
})
// Load local grunt tasks.
grunt.loadTasks('grunt')
// Load necessary plugins.
grunt.loadNpmTasks('grunt-aws')
// Production simulating task.
grunt.registerTask('prod', ['revupdate', 'precompile'])
// Database operation tasks.
grunt.registerTask('db', ['dropDB', 'seedDB'])
grunt.registerTask('db.drop', ['dropDB'])
grunt.registerTask('db.seed', ['seedDB'])
// Deploy task.
grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate'])
}
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
aws: grunt.file.readJSON('.aws-deploy.json'),
s3: {
options: {
accessKeyId: '<%= aws.accessKeyId %>',
secretAccessKey: '<%= aws.secretAccessKey %>',
bucket: 'gamekeller',
region: 'eu-central-1',
gzip: false,
overwrite: false
},
assets: {
cwd: 'public/',
src: ['assets/**', '!assets/manifest.json']
}
}
})
// Load local grunt tasks.
grunt.loadTasks('grunt')
// Load necessary plugins.
grunt.loadNpmTasks('grunt-aws')
// Production simulating task.
grunt.registerTask('prod', ['revupdate', 'precompile'])
// Database operation tasks.
grunt.registerTask('db', ['dropDB', 'seedDB'])
grunt.registerTask('db.drop', ['dropDB'])
grunt.registerTask('db.seed', ['seedDB'])
// Deploy task.
grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate'])
}
|
Use str and repr functions instead of magic methods
|
"""
NOTE: There are no tests that check for data validation at this point since
the interpreter doesn't have any data validation as a feature.
"""
import pytest
from calc import INTEGER, Token
def test_no_defaults():
# There's no valid defaults at the moment.
with pytest.raises(TypeError):
Token()
def test_known_type():
# There's no valid defaults at the moment.
token = Token(type=INTEGER, value=2)
assert token.value == 2
assert token.type == INTEGER
def test_str_non_string_value():
token = Token(type=INTEGER, value=2)
expected_result = "Token(type=INTEGER, value=2)"
assert str(token) == expected_result
def test_repr():
token = Token(type=INTEGER, value=2)
expected_result = "Token(type=INTEGER, value=2)"
assert repr(token) == expected_result
|
"""
NOTE: There are no tests that check for data validation at this point since
the interpreter doesn't have any data validation as a feature.
"""
import pytest
from calc import INTEGER, Token
def test_no_defaults():
# There's no valid defaults at the moment.
with pytest.raises(TypeError):
Token()
def test_known_type():
# There's no valid defaults at the moment.
token = Token(type=INTEGER, value=2)
assert token.value == 2
assert token.type == INTEGER
def test_str_non_string_value():
token = Token(type=INTEGER, value=2)
expected_result = "Token(type=INTEGER, value=2)"
assert token.__str__() == expected_result
def test_repr():
token = Token(type=INTEGER, value=2)
expected_result = "Token(type=INTEGER, value=2)"
assert token.__repr__() == expected_result
|
Add support to run inside Meteor.
When running this babel-plugin inside Meteor, it gives us
weird errors.
But, we don't need this to use inside Meteor.
Meteor do this for us automatically.
So, we simply turn off this when using inside Meteor.
|
import BabelRootImportHelper from './helper';
export default function({ types: t }) {
class BabelRootImport {
constructor() {
const that = this;
return {
visitor: {
ImportDeclaration(path, state) {
const givenPath = path.node.source.value;
var rootPathSuffix = state && state.opts && typeof state.opts.rootPathSuffix === 'string' ?
'/' + state.opts.rootPathSuffix.replace(/^(\/)|(\/)$/g, '') :
'';
if(BabelRootImportHelper().hasRoot(givenPath)) {
path.node.source.value = BabelRootImportHelper().transformRelativeToRootPath(givenPath, rootPathSuffix);
}
}
}
};
}
}
// Here's we detect the use of Meteor and send a dummy plugin.
// That's because, Meteor already do this for us.
// global.meteorBabelHelpers is something we can see when
// running inside Meteor.
if (global.meteorBabelHelpers) {
return {
visitor: {}
};
}
return new BabelRootImport();
}
|
import BabelRootImportHelper from './helper';
export default function({ types: t }) {
class BabelRootImport {
constructor() {
const that = this;
return {
visitor: {
ImportDeclaration(path, state) {
const givenPath = path.node.source.value;
var rootPathSuffix = state && state.opts && typeof state.opts.rootPathSuffix === 'string' ?
'/' + state.opts.rootPathSuffix.replace(/^(\/)|(\/)$/g, '') :
'';
if(BabelRootImportHelper().hasRoot(givenPath)) {
path.node.source.value = BabelRootImportHelper().transformRelativeToRootPath(givenPath, rootPathSuffix);
}
}
}
};
}
}
return new BabelRootImport();
}
|
Add LabeledImageDataset to datasets module
|
from chainer.datasets import cifar
from chainer.datasets import dict_dataset
from chainer.datasets import image_dataset
from chainer.datasets import mnist
from chainer.datasets import ptb
from chainer.datasets import sub_dataset
from chainer.datasets import tuple_dataset
DictDataset = dict_dataset.DictDataset
ImageDataset = image_dataset.ImageDataset
LabeledImageDataset = image_dataset.LabeledImageDataset
SubDataset = sub_dataset.SubDataset
TupleDataset = tuple_dataset.TupleDataset
get_cross_validation_datasets = sub_dataset.get_cross_validation_datasets
get_cross_validation_datasets_random = (
sub_dataset.get_cross_validation_datasets_random)
split_dataset = sub_dataset.split_dataset
split_dataset_random = sub_dataset.split_dataset_random
# examples
get_cifar10 = cifar.get_cifar10
get_cifar100 = cifar.get_cifar100
get_mnist = mnist.get_mnist
get_ptb_words = ptb.get_ptb_words
get_ptb_words_vocabulary = ptb.get_ptb_words_vocabulary
|
from chainer.datasets import cifar
from chainer.datasets import dict_dataset
from chainer.datasets import image_dataset
from chainer.datasets import mnist
from chainer.datasets import ptb
from chainer.datasets import sub_dataset
from chainer.datasets import tuple_dataset
DictDataset = dict_dataset.DictDataset
ImageDataset = image_dataset.ImageDataset
SubDataset = sub_dataset.SubDataset
TupleDataset = tuple_dataset.TupleDataset
get_cross_validation_datasets = sub_dataset.get_cross_validation_datasets
get_cross_validation_datasets_random = (
sub_dataset.get_cross_validation_datasets_random)
split_dataset = sub_dataset.split_dataset
split_dataset_random = sub_dataset.split_dataset_random
# examples
get_cifar10 = cifar.get_cifar10
get_cifar100 = cifar.get_cifar100
get_mnist = mnist.get_mnist
get_ptb_words = ptb.get_ptb_words
get_ptb_words_vocabulary = ptb.get_ptb_words_vocabulary
|
Extend SimpleStreamableObject so that we get a useful default toString().
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2321 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
//
// $Id: Cluster.java,v 1.3 2003/03/25 03:16:11 mdb Exp $
package com.threerings.whirled.spot.data;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet;
/**
* Contains information on clusters.
*/
public class Cluster extends SimpleStreamableObject
implements DSet.Entry
{
/** A unique identifier for this cluster (also the distributed object
* id of the cluster chat object). */
public int clusterOid;
/** The x-coordinate of the cluster in the scene. */
public int x;
/** The y-coordinate of the cluster in the scene. */
public int y;
/** The number of occupants in this cluster. */
public int occupants;
// documentation inherited
public Comparable getKey ()
{
if (_key == null) {
_key = new Integer(clusterOid);
}
return _key;
}
// documentation inherited
public boolean equals (Object other)
{
if (other instanceof Cluster) {
return ((Cluster)other).clusterOid == clusterOid;
} else {
return false;
}
}
// documentation inherited
public int hashCode ()
{
return clusterOid;
}
/** Used for {@link #geyKey}. */
protected transient Integer _key;
}
|
//
// $Id: Cluster.java,v 1.2 2003/02/13 23:01:35 mdb Exp $
package com.threerings.whirled.spot.data;
import com.threerings.presents.dobj.DSet;
/**
* Contains information on clusters.
*/
public class Cluster
implements DSet.Entry
{
/** A unique identifier for this cluster (also the distributed object
* id of the cluster chat object). */
public int clusterOid;
/** The x-coordinate of the cluster in the scene. */
public int x;
/** The y-coordinate of the cluster in the scene. */
public int y;
/** The number of occupants in this cluster. */
public int occupants;
// documentation inherited
public Comparable getKey ()
{
if (_key == null) {
_key = new Integer(clusterOid);
}
return _key;
}
// documentation inherited
public boolean equals (Object other)
{
if (other instanceof Cluster) {
return ((Cluster)other).clusterOid == clusterOid;
} else {
return false;
}
}
// documentation inherited
public int hashCode ()
{
return clusterOid;
}
/** Used for {@link #geyKey}. */
protected transient Integer _key;
}
|
Fix issue in Python 2
|
import venusian
class tween_config(object):
""" A decorator which allows developers to annotate tween factories. """
venusian = venusian
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, wrapped_tween_factory):
def do_the_thing(context, name, obj):
module_name = wrapped_tween_factory.__module__
callable_name = wrapped_tween_factory.__name__
factory_string = module_name + '.' + callable_name
context.config.with_package(info.module).add_tween(
factory_string,
*self.args,
**self.kwargs
)
info = self.venusian.attach(
wrapped_tween_factory,
do_the_thing,
category='opbeat_pyramid',
)
return wrapped_tween_factory
|
import venusian
class tween_config(object):
""" A decorator which allows developers to annotate tween factories. """
venusian = venusian
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, wrapped_tween_factory):
def do_the_thing(context, name, obj):
module_name = wrapped_tween_factory.__module__
callable_name = wrapped_tween_factory.__name__
factory_string = module_name + '.' + callable_name
context.config.with_package(info.module).add_tween(
factory_string,
*self.args,
**self.kwargs,
)
info = self.venusian.attach(
wrapped_tween_factory,
do_the_thing,
category='opbeat_pyramid',
)
return wrapped_tween_factory
|
Fix: Increase Height of 'About' window even more
|
const about = module.exports = {
init,
win: null
}
const config = require('../../config')
const electron = require('electron')
function init () {
if (about.win) {
return about.win.show()
}
const win = about.win = new electron.BrowserWindow({
backgroundColor: '#ECECEC',
center: true,
fullscreen: false,
height: 250,
icon: getIconPath(),
maximizable: false,
minimizable: false,
resizable: false,
show: false,
skipTaskbar: true,
title: 'About ' + config.APP_WINDOW_TITLE,
useContentSize: true,
webPreferences: {
nodeIntegration: true,
enableBlinkFeatures: 'AudioVideoTracks'
},
width: 300
})
win.loadURL(config.WINDOW_ABOUT)
// No menu on the About window
win.setMenu(null)
win.once('ready-to-show', function () {
win.show()
})
win.once('closed', function () {
about.win = null
})
}
function getIconPath () {
return process.platform === 'win32'
? config.APP_ICON + '.ico'
: config.APP_ICON + '.png'
}
|
const about = module.exports = {
init,
win: null
}
const config = require('../../config')
const electron = require('electron')
function init () {
if (about.win) {
return about.win.show()
}
const win = about.win = new electron.BrowserWindow({
backgroundColor: '#ECECEC',
center: true,
fullscreen: false,
height: 220,
icon: getIconPath(),
maximizable: false,
minimizable: false,
resizable: false,
show: false,
skipTaskbar: true,
title: 'About ' + config.APP_WINDOW_TITLE,
useContentSize: true,
webPreferences: {
nodeIntegration: true,
enableBlinkFeatures: 'AudioVideoTracks'
},
width: 300
})
win.loadURL(config.WINDOW_ABOUT)
// No menu on the About window
win.setMenu(null)
win.once('ready-to-show', function () {
win.show()
})
win.once('closed', function () {
about.win = null
})
}
function getIconPath () {
return process.platform === 'win32'
? config.APP_ICON + '.ico'
: config.APP_ICON + '.png'
}
|
Fix ajax for user update modal
|
$(document).ready(function() {
$("#profile").on('submit', '.edit-user', function(event) {
const $form = $('.edit-user');
let url = $form.attr('action');
let method = $form.attr('method');
let data = $form.serialize();
$.ajax({
url: url,
method: method,
data: data,
dataType: "json"
})
.success(function(response) {
console.log(response);
})
.fail(function(error) {
console.log(error);
})
});
$("#profile").on("click", ".edit-profile", function() {
const $modal = $('#userEditModal')[0];
console.log($modal);
$modal.style.display = "block";
$('#closeEditModal').on("click", function() {
$modal.style.display = "none";
});
});
});
|
$(document).ready(function() {
const $form = $('.edit_user');
$form.on('submit', function(event) {
let url = $form.attr('action');
let method = $form.attr('method');
let data = $form.serialize();
$.ajax({
url: url,
method: method,
data: data,
dataType: "json"
})
.success(function(response) {
console.log(response);
})
.fail(function(error) {
console.log(error);
})
});
$("#profile").on("click", ".edit-profile", function() {
const $modal = $('#userEditModal')[0];
console.log($modal);
$modal.style.display = "block";
$('#closeEditModal').on("click", function() {
$modal.style.display = "none";
});
});
});
|
Fix multivar for nodes with variable lenght stacks
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
def prepare(self, stack):
self.node_1.prepare(stack)
self.node_2.prepare(stack)
self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
rtn = self.node_2(stack[:self.node_2.args])
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
if len(stack) == 0:
self.add_arg(stack)
@Node.is_func
def apply(self, *stack):
self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
IMCMS-290: Add a "pin" icon to imCMS's panel:
- Refreshing elements length for displacing array.
|
/**
* Array with fixed max length and displacing first element on oversize.
*
* @author Serhii Maksymchuk from Ubrainians for imCode
* 10.05.18
*/
Imcms.define('imcms-displacing-array', [], function () {
var DisplacingArray = function (size) {
if (typeof size !== 'number') throw new Error("Size should be integer!");
if (size < 1) throw new Error("Size should be >= 1");
this.size = size;
this.elements = [];
};
DisplacingArray.prototype = {
push: function (content) {
if (this.elements.length > this.size) {
this.elements.splice(0, 1); // removes first element
}
this.elements.push(content);
this.length = this.elements.length;
},
forEach: function (doForEach) {
this.elements.forEach(doForEach);
}
};
return DisplacingArray;
});
|
/**
* Array with fixed max length and displacing first element on oversize.
*
* @author Serhii Maksymchuk from Ubrainians for imCode
* 10.05.18
*/
Imcms.define('imcms-displacing-array', [], function () {
var DisplacingArray = function (size) {
if (typeof size !== 'number') throw new Error("Size should be integer!");
if (size < 1) throw new Error("Size should be >= 1");
this.size = size;
this.elements = [];
};
DisplacingArray.prototype = {
push: function (content) {
if (this.elements.length > this.size) {
this.elements.splice(0, 1); // removes first element
}
this.elements.push(content);
},
forEach: function (doForEach) {
this.elements.forEach(doForEach);
}
};
return DisplacingArray;
});
|
Repair option if params not exists.
|
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor;
function WebService(currentUser) {
this._currentUser = currentUser;
this._dependencies = {};
this.runRef = undefined;
}
WebService.prototype.runWrapper = function () {
var self = this;
return function (name, allowedTypeAccount, params) {
params = params || {};
return function (req, res) {
params.req = req;
params.res = res;
self.runRef(name, allowedTypeAccount, params);
};
};
};
WebService.prototype.run = function (name, allowedTypeAccount, params) {
var self = this;
var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser);
var webServices = require('../ServiceDirectories/Web/Public');
params = params || {};
if (permissionsInit.check()) {
webServices[name].call(undefined, self._dependencies, params);
} else {
webServices['accessDenied'].call(undefined, self._dependencies, params);
}
};
WebService.prototype.addDependency = function (name, value) {
this._dependencies[name] = value;
};
module.exports.WebService = WebService;
|
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor;
function WebService(currentUser) {
this._currentUser = currentUser;
this._dependencies = {};
this.runRef = undefined;
}
WebService.prototype.runWrapper = function () {
var self = this;
return function (name, allowedTypeAccount, params) {
return function (req, res) {
params.req = req;
params.res = res;
self.runRef(name, allowedTypeAccount, params);
};
};
};
WebService.prototype.run = function (name, allowedTypeAccount, params) {
var self = this;
var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser);
var webServices = require('../ServiceDirectories/Web/Public');
params = params || {};
if (permissionsInit.check()) {
webServices[name].call(undefined, self._dependencies, params);
} else {
webServices['accessDenied'].call(undefined, self._dependencies, params);
}
};
WebService.prototype.addDependency = function (name, value) {
this._dependencies[name] = value;
};
module.exports.WebService = WebService;
|
Remove date todo
Add DRY todo
git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1452 e217846f-e12e-0410-a4e5-89ccaea66ff7
|
/*
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.usc.glidein.db;
import javax.naming.Context;
import javax.naming.InitialContext;
// TODO: Combine SQL DAOs and eliminate duplicate code
public abstract class Database
{
public static Database getDatabase() throws DatabaseException
{
String location = "java:comp/env/glidein/Database";
try {
Context initialContext = new InitialContext();
return (Database)initialContext.lookup(location);
} catch (Exception e) {
throw new DatabaseException("Unable to load database: "+location,e);
}
}
public abstract SiteDAO getSiteDAO();
public abstract GlideinDAO getGlideinDAO();
}
|
/*
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.usc.glidein.db;
import javax.naming.Context;
import javax.naming.InitialContext;
// TODO: Record event times in the database to match Condor event times
public abstract class Database
{
public static Database getDatabase() throws DatabaseException
{
String location = "java:comp/env/glidein/Database";
try {
Context initialContext = new InitialContext();
return (Database)initialContext.lookup(location);
} catch (Exception e) {
throw new DatabaseException("Unable to load database: "+location,e);
}
}
public abstract SiteDAO getSiteDAO();
public abstract GlideinDAO getGlideinDAO();
}
|
Update on suggestion of jezdez.
|
import os
from setuptools import setup, find_packages
from taggit import VERSION
f = open(os.path.join(os.path.dirname(__file__), 'README.txt'))
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagging.',
long_description=readme,
author='Alex Gaynor',
author_email='alex.gaynor@gmail.com',
url='http://github.com/alex/django-taggit/tree/master',
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
|
from setuptools import setup, find_packages
from taggit import VERSION
f = open('README.txt')
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagging.',
long_description=readme,
author='Alex Gaynor',
author_email='alex.gaynor@gmail.com',
url='http://github.com/alex/django-taggit/tree/master',
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
|
Add check for palindrome component of method
|
# Given a singly linked list of integers, determine whether or not it's a palindrome
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if l is None or l.next is None:
return True
# find center of list
fast = l
slow = l
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# reverse second half of list
p = slow.next
current_node = None
while p:
next = p.next
p.next = current_node
current_node = p
p = next
# check for palindrome
part_one = current_node
part_two = l
while part_one and part_one.value == part_two.value:
part_one = part_one.next
part_two = part_two.next
return part_one is None
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
print is_list_palindrome(create_nodes([1, 2, 3, 4]))
|
# Given a singly linked list of integers, determine whether or not it's a palindrome
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if l.value is None:
return True
# find center of list
fast = l
slow = l
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# reverse second half of list
p = slow.next
current_node = None
while p:
next = p.next
p.next = current_node
current_node = p
p = next
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
is_list_palindrome(create_nodes([1, 2, 3, 4]))
|
Add option parser and main method
|
#!/usr/bin/env python
from Crypto.Cipher import AES
import json
import os
import optparse
KEY_LENGTH = 256
BLOCK_LENGTH = 16
KEY_FILE = 'key'
ENCRYPTED_FILE = 'data'
DECRYPTED_FILE = 'tmp'
EOT_CHAR = '\x04'
def main(options, arguments):
pass
def get_cipher(iv):
try:
key = open(KEY_FILE, 'rb').read()
except IOError:
key = input("Please enter the decryption key: ")
return AES.new(key, AES.MODE_CBC, iv)
def encrypt():
bytes = multiple_of(open(DECRYPTED_FILE, 'rt').read().encode(), BLOCK_LENGTH)
iv = os.urandom(16)
c = get_cipher(iv)
return (iv, c.encrypt(bytes))
def decrypt():
bytes = open(ENCRYPTED_FILE, 'rb').read()
c = get_cipher(bytes[:16])
return c.decrypt(bytes).decode('utf-8')
def multiple_of(bytes, length):
if len(bytes) % length == 0:
return bytes
else:
return bytes + (EOT_CHAR * (length - (len(bytes) % length))).encode()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
main(options, arguments)
|
from Crypto.Cipher import AES
import json
import os
KEY_LENGTH = 256
BLOCK_LENGTH = 16
KEY_FILE = 'key'
ENCRYPTED_FILE = 'data'
DECRYPTED_FILE = 'tmp'
EOT_CHAR = '\x04'
def get_cipher(iv):
try:
key = open(KEY_FILE, 'rb').read()
except IOError:
key = input("Please enter the decryption key: ")
return AES.new(key, AES.MODE_CBC, iv)
def encrypt():
bytes = multiple_of(open(DECRYPTED_FILE, 'rt').read().encode(), BLOCK_LENGTH)
iv = os.urandom(16)
c = get_cipher(iv)
return (iv, c.encrypt(bytes))
def decrypt():
bytes = open(ENCRYPTED_FILE, 'rb').read()
c = get_cipher(bytes[:16])
return c.decrypt(bytes).decode('utf-8')
def multiple_of(bytes, length):
if len(bytes) % length == 0:
return bytes
else:
return bytes + (EOT_CHAR * (length - (len(bytes) % length))).encode()
|
Use an https URL rather than http.
Found by sphinx's linkcheck.
|
"""
RISC-V Target
-------------
`RISC-V <https://riscv.org/>`_ is an open instruction set architecture
originally developed at UC Berkeley. It is a RISC-style ISA with either a
32-bit (RV32I) or 64-bit (RV32I) base instruction set and a number of optional
extensions:
RV32M / RV64M
Integer multiplication and division.
RV32A / RV64A
Atomics.
RV32F / RV64F
Single-precision IEEE floating point.
RV32D / RV64D
Double-precision IEEE floating point.
RV32G / RV64G
General purpose instruction sets. This represents the union of the I, M, A,
F, and D instruction sets listed above.
"""
from __future__ import absolute_import
from . import defs
from . import encodings, settings, registers # noqa
# Re-export the primary target ISA definition.
ISA = defs.ISA.finish()
|
"""
RISC-V Target
-------------
`RISC-V <http://riscv.org/>`_ is an open instruction set architecture
originally developed at UC Berkeley. It is a RISC-style ISA with either a
32-bit (RV32I) or 64-bit (RV32I) base instruction set and a number of optional
extensions:
RV32M / RV64M
Integer multiplication and division.
RV32A / RV64A
Atomics.
RV32F / RV64F
Single-precision IEEE floating point.
RV32D / RV64D
Double-precision IEEE floating point.
RV32G / RV64G
General purpose instruction sets. This represents the union of the I, M, A,
F, and D instruction sets listed above.
"""
from __future__ import absolute_import
from . import defs
from . import encodings, settings, registers # noqa
# Re-export the primary target ISA definition.
ISA = defs.ISA.finish()
|
Fix fatal error in collection episodes listing
Add null as scope parameter to _items call
|
<?php
namespace VHX;
class Collections extends ApiResource {
public static function all($params = array(), $headers = null) {
return self::_list($params, $headers);
}
public static function retrieve($id = null, $headers = null) {
return self::_retrieve($id, null, $headers);
}
public static function create($params = array(), $headers = null) {
return self::_create($params, $headers);
}
public static function update($id = null, $params = array(), $headers = null) {
return self::_update($id, $params, null, $headers);
}
public static function items($id = null, $params = array(), $headers = null) {
if (is_array($id) && isset($id['collection'])) {
$params = $id;
$id = $id['collection'];
}
return self::_items($id, $params, null, $headers);
}
// deprecated (same as items)
public static function allItems($id = null, $params = array(), $headers = null) {
return self::_items($id, $params, $headers);
}
}
|
<?php
namespace VHX;
class Collections extends ApiResource {
public static function all($params = array(), $headers = null) {
return self::_list($params, $headers);
}
public static function retrieve($id = null, $headers = null) {
return self::_retrieve($id, null, $headers);
}
public static function create($params = array(), $headers = null) {
return self::_create($params, $headers);
}
public static function update($id = null, $params = array(), $headers = null) {
return self::_update($id, $params, null, $headers);
}
public static function items($id = null, $params = array(), $headers = null) {
if (is_array($id) && isset($id['collection'])) {
$params = $id;
$id = $id['collection'];
}
return self::_items($id, $params, $headers);
}
// deprecated (same as items)
public static function allItems($id = null, $params = array(), $headers = null) {
return self::_items($id, $params, $headers);
}
}
|
Add opacity to the drop shadow filter.
|
// Adapted from: http://bl.ocks.org/cpbotha/5200394
export function dropShadow (el, name, dx, dy, blur, opacity) {
let defs = el.select('defs');
if (defs.empty()) {
defs = el.append('defs');
}
// create filter with id #drop-shadow
// height = 130% so that the shadow is not clipped
const filter = defs.append('filter')
.attr('id', 'drop-shadow' + (name ? `-${name}` : ''))
.attr('height', '130%');
// SourceAlpha refers to opacity of graphic that this filter will be applied to
// convolve that with a Gaussian with standard deviation 3 and store result
// in blur
filter.append('feGaussianBlur')
.attr('in', 'SourceAlpha')
.attr('stdDeviation', blur);
// translate output of Gaussian blur to the right and downwards with 2px
// store result in offsetBlur
filter.append('feOffset')
.attr('dx', dx)
.attr('dy', dy)
.attr('result', 'offsetBlur');
filter.append('feComponentTransfer').append('feFuncA')
.attr('type', 'linear')
.attr('slope', opacity || 1);
// overlay original SourceGraphic over translated blurred opacity by using
// feMerge filter. Order of specifying inputs is important!
const feMerge = filter.append('feMerge');
feMerge.append('feMergeNode');
feMerge.append('feMergeNode').attr('in', 'SourceGraphic');
}
|
// Adapted from: http://bl.ocks.org/cpbotha/5200394
export function dropShadow (el, name, dx, dy, blur) {
let defs = el.select('defs');
if (defs.empty()) {
defs = el.append('defs');
}
// create filter with id #drop-shadow
// height = 130% so that the shadow is not clipped
const filter = defs.append('filter')
.attr('id', 'drop-shadow' + (name ? `-${name}` : ''))
.attr('height', '130%');
// SourceAlpha refers to opacity of graphic that this filter will be applied to
// convolve that with a Gaussian with standard deviation 3 and store result
// in blur
filter.append('feGaussianBlur')
.attr('in', 'SourceAlpha')
.attr('stdDeviation', blur);
// translate output of Gaussian blur to the right and downwards with 2px
// store result in offsetBlur
filter.append('feOffset')
.attr('dx', dx)
.attr('dy', dy)
.attr('result', 'offsetBlur');
// overlay original SourceGraphic over translated blurred opacity by using
// feMerge filter. Order of specifying inputs is important!
const feMerge = filter.append('feMerge');
feMerge.append('feMergeNode');
feMerge.append('feMergeNode').attr('in', 'SourceGraphic');
}
|
Add debug-menu manual triggers for Sentry
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
|
// @flow
import {Sentry, SentrySeverity} from 'react-native-sentry'
import * as React from 'react'
import {Section, PushButtonCell} from '@frogpond/tableview'
import {type NavigationScreenProp} from 'react-navigation'
type Props = {navigation: NavigationScreenProp<*>}
export class DeveloperSection extends React.Component<Props> {
onAPIButton = () => this.props.navigation.navigate('APITestView')
onBonAppButton = () => this.props.navigation.navigate('BonAppPickerView')
onDebugButton = () => this.props.navigation.navigate('DebugView')
sendSentryMessage = () => {
Sentry.captureMessage('A Sentry Message', {
level: SentrySeverity.Info,
})
}
sendSentryException = () => {
Sentry.captureException(new Error('Debug Exception'))
}
render() {
return (
<Section header="DEVELOPER">
<PushButtonCell onPress={this.onAPIButton} title="API Tester" />
<PushButtonCell
onPress={this.onBonAppButton}
title="Bon Appetit Picker"
/>
<PushButtonCell onPress={this.onDebugButton} title="Debug" />
<PushButtonCell
onPress={this.sendSentryMessage}
title="Send a Sentry Message"
/>
<PushButtonCell
onPress={this.sendSentryException}
title="Send a Sentry Exception"
/>
</Section>
)
}
}
|
// @flow
import * as React from 'react'
import {Section, PushButtonCell} from '@frogpond/tableview'
import {type NavigationScreenProp} from 'react-navigation'
type Props = {navigation: NavigationScreenProp<*>}
export class DeveloperSection extends React.Component<Props> {
onAPIButton = () => this.props.navigation.navigate('APITestView')
onBonAppButton = () => this.props.navigation.navigate('BonAppPickerView')
onDebugButton = () => this.props.navigation.navigate('DebugView')
render() {
return (
<Section header="DEVELOPER">
<PushButtonCell onPress={this.onAPIButton} title="API Tester" />
<PushButtonCell
onPress={this.onBonAppButton}
title="Bon Appetit Picker"
/>
<PushButtonCell onPress={this.onDebugButton} title="Debug" />
</Section>
)
}
}
|
Transform null values to empty string
|
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]==null ? "" : values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
|
package org.limeprotocol.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class StringUtils {
public static boolean isNullOrEmpty(String string){
return string == null || string.equals("");
}
public static boolean isNullOrWhiteSpace(String string){
return isNullOrEmpty(string) || string.trim().length() == 0;
}
public static String format(String pattern, Object... values){
Map<String, Object> tags = new LinkedHashMap<String, Object>();
for (int i=0; i<values.length; i++){
tags.put("\\{" + i + "\\}", values[i]);
}
String formatted = pattern;
for (Map.Entry<String, Object> tag : tags.entrySet()) {
// bottleneck, creating temporary String objects!
formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
}
return formatted;
}
public static String trimEnd(String string, String finalCharacter){
string.trim();
if(string.endsWith(finalCharacter)){
return string.substring(0, string.length()-1);
}
return string;
}
}
|
Handle exception and clean up during preview
|
/**
* (c) 2014 StreamSets, Inc. All rights reserved. May not
* be copied, modified, or distributed in whole or part without
* written consent of StreamSets, Inc.
*/
package com.streamsets.pipeline.runner.preview;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.runner.Pipeline;
import com.streamsets.pipeline.runner.PipelineRuntimeException;
import com.streamsets.pipeline.runner.StageOutput;
import com.streamsets.pipeline.validation.Issues;
import java.util.Collections;
import java.util.List;
public class PreviewPipeline {
private final Pipeline pipeline;
private final Issues issues;
public PreviewPipeline(Pipeline pipeline, Issues issues) {
this.issues = issues;
this.pipeline = pipeline;
}
@SuppressWarnings("unchecked")
public PreviewPipelineOutput run() throws StageException, PipelineRuntimeException{
return run(Collections.EMPTY_LIST);
}
public PreviewPipelineOutput run(List<StageOutput> stageOutputsToOverride)
throws StageException, PipelineRuntimeException{
pipeline.init();
try {
pipeline.run(stageOutputsToOverride);
} finally {
pipeline.destroy();
}
return new PreviewPipelineOutput(issues, pipeline.getRunner());
}
}
|
/**
* (c) 2014 StreamSets, Inc. All rights reserved. May not
* be copied, modified, or distributed in whole or part without
* written consent of StreamSets, Inc.
*/
package com.streamsets.pipeline.runner.preview;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.runner.Pipeline;
import com.streamsets.pipeline.runner.PipelineRuntimeException;
import com.streamsets.pipeline.runner.StageOutput;
import com.streamsets.pipeline.validation.Issues;
import java.util.Collections;
import java.util.List;
public class PreviewPipeline {
private final Pipeline pipeline;
private final Issues issues;
public PreviewPipeline(Pipeline pipeline, Issues issues) {
this.issues = issues;
this.pipeline = pipeline;
}
@SuppressWarnings("unchecked")
public PreviewPipelineOutput run() throws StageException, PipelineRuntimeException{
return run(Collections.EMPTY_LIST);
}
public PreviewPipelineOutput run(List<StageOutput> stageOutputsToOverride)
throws StageException, PipelineRuntimeException{
pipeline.init();
pipeline.run(stageOutputsToOverride);
pipeline.destroy();
return new PreviewPipelineOutput(issues, pipeline.getRunner());
}
}
|
Update method should use KConfig instead of ArrayObject as parameter.
|
<?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Event
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Class to handle events.
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Event
*/
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
/**
* Get the object identifier
*
* @return KIdentifier
* @see KObjectIdentifiable
*/
public function getIdentifier()
{
return $this->_identifier;
}
/**
* Method to trigger events
*
* @param object The event arguments
* @return mixed Routine return value
*/
public function update(KConfig $args)
{
if (in_array($args->event, $this->getMethods())) {
return $this->{$args->event}($args);
}
return null;
}
}
|
<?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Event
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Class to handle events.
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Event
*/
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
/**
* Get the object identifier
*
* @return KIdentifier
* @see KObjectIdentifiable
*/
public function getIdentifier()
{
return $this->_identifier;
}
/**
* Method to trigger events
*
* @param object The event arguments
* @return mixed Routine return value
*/
public function update(ArrayObject $args)
{
if (in_array($args['event'], $this->getMethods())) {
return $this->{$args['event']}($args);
}
return null;
}
}
|
Fix Landscape complaint "Method has no argument"
|
from django.test.runner import DiscoverRunner
from behave_django.environment import BehaveHooksMixin
from behave_django.testcase import (BehaviorDrivenTestCase,
ExistingDatabaseTestCase)
class BehaviorDrivenTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the BehaviorDrivenTestCase
"""
testcase_class = BehaviorDrivenTestCase
class ExistingDatabaseTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the ExistingDatabaseTestCase
This test runner nullifies Django's test database setup methods. Using this
test runner would make your tests run with the default configured database
in settings.py.
"""
testcase_class = ExistingDatabaseTestCase
def setup_databases(self, **kwargs):
pass
def teardown_databases(self, old_config, **kwargs):
pass
|
from django.test.runner import DiscoverRunner
from behave_django.environment import BehaveHooksMixin
from behave_django.testcase import (BehaviorDrivenTestCase,
ExistingDatabaseTestCase)
class BehaviorDrivenTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the BehaviorDrivenTestCase
"""
testcase_class = BehaviorDrivenTestCase
class ExistingDatabaseTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the ExistingDatabaseTestCase
This test runner nullifies Django's test database setup methods. Using this
test runner would make your tests run with the default configured database
in settings.py.
"""
testcase_class = ExistingDatabaseTestCase
def setup_databases(*args, **kwargs):
pass
def teardown_databases(*args, **kwargs):
pass
|
Fix to bracket ordering in tree representation
|
package upparse.corpus;
/**
* Data structure representing a bracket, not including a category label
* @author eponvert@utexas.edu (Elias Ponvert)
*/
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {
private final int first, last;
public UnlabeledBracket(final int _first, final int _last) {
first = _first;
last = _last;
}
@Override
public boolean equals(Object obj) {
final UnlabeledBracket b = (UnlabeledBracket) obj;
return first == b.first && last == b.last;
}
@Override
public int hashCode() {
return 37 * first + last;
}
public int getFirst() {
return first;
}
public int getLast() {
return last;
}
public int len() {
return last - first;
}
@Override
public int compareTo(UnlabeledBracket o) {
if (o == null) throw new NullPointerException();
else if (last < o.first) return -1;
else if (o.last < first) return 1;
else if (o.first == first && last == o.last) return 0;
else if (o.first <= first && last <= o.last) return -1;
else if (first <= o.first && o.last <= last) return 1;
else return 0;
}
public boolean contains(UnlabeledBracket b) {
return first <= b.first && b.last <= last;
}
@Override
public String toString() {
return String.format("[%d,%d]", first, last);
}
}
|
package upparse.corpus;
/**
* Data structure representing a bracket, not including a category label
* @author eponvert@utexas.edu (Elias Ponvert)
*/
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {
private final int first, last;
public UnlabeledBracket(final int _first, final int _last) {
first = _first;
last = _last;
}
@Override
public boolean equals(Object obj) {
final UnlabeledBracket b = (UnlabeledBracket) obj;
return first == b.first && last == b.last;
}
@Override
public int hashCode() {
return 37 * first + last;
}
public int getFirst() {
return first;
}
public int getLast() {
return last;
}
public int len() {
return last - first;
}
@Override
public int compareTo(UnlabeledBracket o) {
if (o == null) throw new NullPointerException();
else if (last < o.first) return -1;
else if (o.last < first) return 1;
else if (o.first <= first && last <= o.last) return -1;
else return 0;
}
public boolean contains(UnlabeledBracket b) {
return first <= b.first && b.last <= last;
}
@Override
public String toString() {
return String.format("[%d,%d]", first, last);
}
}
|
Add OPTIONS to CORS allowed methods
|
/**
* Adds CORS headers to the response
*
* ####Example:
*
* app.all('/api*', keystone.middleware.cors);
*
* @param {app.request} req
* @param {app.response} res
* @param {function} next
* @api public
*/
// The exported function returns a closure that retains
// a reference to the keystone instance, so it can be
// passed as middeware to the express app.
module.exports = function (keystone) {
return function cors (req, res, next) {
var origin = keystone.get('cors allow origin');
if (origin) {
res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin);
}
if (keystone.get('cors allow methods') !== false) {
res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE,OPTIONS');
}
if (keystone.get('cors allow headers') !== false) {
res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization');
}
next();
};
};
|
/**
* Adds CORS headers to the response
*
* ####Example:
*
* app.all('/api*', keystone.middleware.cors);
*
* @param {app.request} req
* @param {app.response} res
* @param {function} next
* @api public
*/
// The exported function returns a closure that retains
// a reference to the keystone instance, so it can be
// passed as middeware to the express app.
module.exports = function (keystone) {
return function cors (req, res, next) {
var origin = keystone.get('cors allow origin');
if (origin) {
res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin);
}
if (keystone.get('cors allow methods') !== false) {
res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE');
}
if (keystone.get('cors allow headers') !== false) {
res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization');
}
next();
};
};
|
Make sure to return python values, not lxml objects
Bump version to 0.4.0
|
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.4.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees.pyval
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees.pyval
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time.pyval
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters.pyval
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
"Simple parser for Garmin TCX files."
from lxml import objectify
__version__ = '0.3.0'
class TcxParser:
def __init__(self, tcx_file):
tree = objectify.parse(tcx_file)
self.root = tree.getroot()
self.activity = self.root.Activities.Activity
@property
def latitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LatitudeDegrees
@property
def longitude(self):
return self.activity.Lap.Track.Trackpoint.Position.LongitudeDegrees
@property
def activity_type(self):
return self.activity.attrib['Sport'].lower()
@property
def completed_at(self):
return self.activity.Lap[-1].Track.Trackpoint[-1].Time
@property
def distance(self):
return self.activity.Lap[-1].Track.Trackpoint[-2].DistanceMeters
@property
def distance_units(self):
return 'meters'
@property
def duration(self):
"""Returns duration of workout in seconds."""
return sum(lap.TotalTimeSeconds for lap in self.activity.Lap)
@property
def calories(self):
return sum(lap.Calories for lap in self.activity.Lap)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.