text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove field which was never accessed | package uk.ac.ebi.atlas.profiles.baseline;
import com.google.common.base.Joiner;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;
import java.util.List;
import java.util.Queue;
public class ExpressionsRowRawDeserializerBaseline extends ExpressionsRowRawDeserializer<BaselineExpression> {
private int expectedNumberOfValues;
public ExpressionsRowRawDeserializerBaseline(List<FactorGroup> orderedFactorGroups) {
expectedNumberOfValues = orderedFactorGroups.size();
}
@Override
public ExpressionsRowRawDeserializer<BaselineExpression> reload(BaselineExpression... values) {
if (values.length != expectedNumberOfValues) {
throw new IllegalArgumentException(String.format("Expected %s values but got [%s]", expectedNumberOfValues, Joiner.on(",").join(values)));
}
return super.reload(values);
}
@Override
public BaselineExpression nextExpression(Queue<BaselineExpression> rawValuesRow) {
return rawValuesRow.poll();
}
}
|
package uk.ac.ebi.atlas.profiles.baseline;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
public class ExpressionsRowRawDeserializerBaseline extends ExpressionsRowRawDeserializer<BaselineExpression> {
final int expectedNumberOfValues;
Iterator<FactorGroup> factorGroups;
public ExpressionsRowRawDeserializerBaseline(List<FactorGroup> orderedFactorGroups) {
expectedNumberOfValues = orderedFactorGroups.size();
factorGroups = Iterables.cycle(orderedFactorGroups).iterator();
}
@Override
public ExpressionsRowRawDeserializer<BaselineExpression> reload(BaselineExpression... values) {
if (values.length != expectedNumberOfValues) {
throw new IllegalArgumentException(String.format("Expected %s values but got [%s]", expectedNumberOfValues, Joiner.on(",").join(values)));
}
return super.reload(values);
}
@Override
public BaselineExpression nextExpression(Queue<BaselineExpression> rawValuesRow) {
return rawValuesRow.poll();
}
}
|
Update LoginForm to match reality | import logging
from django import forms
from django.contrib.auth import forms as authforms
from ..models import UserProfile
logger = logging.getLogger(__name__)
class LoginForm(forms.Form):
nick = forms.CharField(label="Nick", max_length=25)
password = forms.CharField(
label="Heslo", max_length=100, widget=forms.PasswordInput
)
class PasswordResetForm(authforms.PasswordResetForm):
def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This is overridem from original form to use UserProfile instead of standard
user model since that is normative for email storage.
"""
user_profiles = UserProfile.objects.filter(email_uzivatele__iexact=email)
users = tuple(
list(
up.user
for up in user_profiles
if up.user.has_usable_password() and up.user.is_active
)
)
logger.info(
"Selected users for password reset: %s"
% ", ".join([str(u.pk) for u in users])
)
return users
| import logging
from django import forms
from django.contrib.auth import forms as authforms
from ..models import UserProfile
logger = logging.getLogger(__name__)
class LoginForm(forms.Form):
nick = forms.CharField(label="Nick", max_length=20)
password = forms.CharField(label="Heslo", max_length=50, widget=forms.PasswordInput)
class PasswordResetForm(authforms.PasswordResetForm):
def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This is overridem from original form to use UserProfile instead of standard
user model since that is normative for email storage.
"""
user_profiles = UserProfile.objects.filter(email_uzivatele__iexact=email)
users = tuple(
list(
up.user
for up in user_profiles
if up.user.has_usable_password() and up.user.is_active
)
)
logger.info(
"Selected users for password reset: %s"
% ", ".join([str(u.pk) for u in users])
)
return users
|
Add a proper Riak health check | /**
* Copyright 2016 Smoke Turner, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.smoketurner.notification.application.health;
import java.util.Objects;
import javax.annotation.Nonnull;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.core.operations.PingOperation;
import com.codahale.metrics.health.HealthCheck;
public class RiakHealthCheck extends HealthCheck {
private final RiakClient client;
/**
* Constructor
*
* @param client
* Riak client
*/
public RiakHealthCheck(@Nonnull final RiakClient client) {
this.client = Objects.requireNonNull(client);
}
@Override
protected Result check() throws Exception {
final PingOperation ping = new PingOperation();
client.getRiakCluster().execute(ping);
ping.await();
if (ping.isSuccess()) {
return Result.healthy("Riak is healthly");
}
return Result.unhealthy("Riak is down");
}
}
| /**
* Copyright 2016 Smoke Turner, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.smoketurner.notification.application.health;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.core.RiakNode;
import com.codahale.metrics.health.HealthCheck;
public class RiakHealthCheck extends HealthCheck {
private final RiakClient client;
/**
* Constructor
*
* @param client
* Riak client
*/
public RiakHealthCheck(@Nonnull final RiakClient client) {
this.client = Objects.requireNonNull(client);
}
@Override
protected Result check() throws Exception {
final List<RiakNode> nodes = client.getRiakCluster().getNodes();
if (!nodes.isEmpty()) {
return Result.healthy();
}
return Result.unhealthy("No available Riak nodes");
}
}
|
Use blank string instead of None as default origin
Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com> | import logging
from fnmatch import fnmatch
from tornado import web
from qotr.config import config
L = logging.getLogger(__name__)
ALLOWED_ORIGINS = [o.strip() for o in config.allowed_origin.split(',')]
def set_cors_headers(handler):
'''
Given a handler, set the CORS headers on it.
'''
origin = handler.request.headers.get('Origin', '')
L.debug('Setting CORS headers for: %s based on %s', origin,
ALLOWED_ORIGINS)
if origin in ALLOWED_ORIGINS or any(fnmatch(origin, o)
for o in ALLOWED_ORIGINS):
handler.set_header("Access-Control-Allow-Origin", origin)
handler.set_header("Access-Control-Allow-Headers", "Content-Type")
# pylint: disable=W0223
class Base(web.RequestHandler):
'''
A base request handler.
'''
def prepare(self):
protocol = self.request.headers.get('x-forwarded-proto')
if config.redirect_to_https and \
self.request.method == 'GET' and \
protocol == 'http':
self.redirect('https://{}{}'.format(
self.request.host.split(':')[0], self.request.path
), permanent=True)
| import logging
from fnmatch import fnmatch
from tornado import web
from qotr.config import config
L = logging.getLogger(__name__)
ALLOWED_ORIGINS = [o.strip() for o in config.allowed_origin.split(',')]
def set_cors_headers(handler):
'''
Given a handler, set the CORS headers on it.
'''
origin = handler.request.headers.get('Origin')
L.debug('Setting CORS headers for: %s based on %s', origin,
ALLOWED_ORIGINS)
if origin in ALLOWED_ORIGINS or any(fnmatch(origin, o)
for o in ALLOWED_ORIGINS):
handler.set_header("Access-Control-Allow-Origin", origin)
handler.set_header("Access-Control-Allow-Headers", "Content-Type")
# pylint: disable=W0223
class Base(web.RequestHandler):
'''
A base request handler.
'''
def prepare(self):
protocol = self.request.headers.get('x-forwarded-proto')
if config.redirect_to_https and \
self.request.method == 'GET' and \
protocol == 'http':
self.redirect('https://{}{}'.format(
self.request.host.split(':')[0], self.request.path
), permanent=True)
|
Fix a few more lint issues | package org.gbif.nameparser.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Modified Executors DefaultThreadFactory to allow custom named thread pools.
* Otherwise, this factory yields the same semantics as the thread factory returned by
* {@link Executors#defaultThreadFactory()}.
*
* Optionally a priority or daemon flag can be provided.
*/
public class NamedThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private final int priority;
private final boolean daemon;
/**
* Creates a new named user thread factory using a normal priority.
* @param poolName the name prefix of the thread pool which will be appended -number for the individual thread
*/
public NamedThreadFactory(String poolName) {
this(poolName, Thread.NORM_PRIORITY, false);
}
/**
* Creates a new named thread factory using explicit priority and daemon settings.
*/
public NamedThreadFactory(String poolName, int priority, boolean daemon) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = poolName + "-";
this.priority = priority;
this.daemon = daemon;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setPriority(priority);
t.setDaemon(daemon);
return t;
}
}
| package org.gbif.nameparser.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Modified Executors DefaultThreadFactory to allow custom named thread pools.
* Otherwise, this factory yields the same semantics as the thread factory returned by
* {@link Executors#defaultThreadFactory()}.
*
* Optionally a priority or daemon flag can be provided.
*/
public class NamedThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private final int priority;
private final boolean daemon;
/**
* Creates a new named user thread factory using a normal priority.
* @param poolName the name prefix of the thread pool which will be appended -number for the individual thread
*/
public NamedThreadFactory(String poolName) {
this(poolName, Thread.NORM_PRIORITY, false);
}
/**
* Creates a new named thread factory using explicit priority and daemon settings.
*/
public NamedThreadFactory(String poolName, int priority, boolean daemon) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = poolName + "-";
this.priority = priority;
this.daemon = daemon;
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setPriority(priority);
t.setDaemon(daemon);
return t;
}
}
|
Improve comments and add breakpoint const | package wrap
import "strings"
const (
// breakpoints defines which characters should be able to break a line.
breakpoints = " "
)
// Line will wrap a single line of text at the given length.
// If limit is less than 1, the string remains unchanged.
//
// If a word is longer than the given limit, it will not be broken to fit.
// See the examples for this scenario.
func Line(s string, limit int) string {
if limit < 1 || len(s) < limit {
return s
}
// Find the index of the last breakpoint within the limit.
i := strings.LastIndexAny(s[:limit], breakpoints)
// Can't wrap within the limit, wrap at the next breakpoint instead.
if i < 0 {
i = strings.IndexAny(s, breakpoints)
// Nothing left to do!
if i < 0 {
return s
}
}
// Recurse until we have nothing left to do.
return s[:i] + "\n" + Line(s[i+1:], limit)
}
// LineWithPrefix will wrap a single line of text and prepend the given prefix,
// whilst staying within given limits.
func LineWithPrefix(s, prefix string, limit int) string {
var ret string
for _, str := range strings.Split(Line(s, limit-len(prefix)), "\n") {
ret += prefix + str + "\n"
}
return ret
}
| package wrap
import "strings"
// Line will wrap a single line of text at the given length.
// If limit is less than 1, the string remains unchanged.
//
// If a word is longer than the given limit, it will not be broken to fit.
// See the examples for this scenario.
func Line(s string, limit int) string {
if limit < 1 || len(s) < limit {
return s
}
// Find the index of the last space within the limit.
i := strings.LastIndex(s[:limit], " ")
// Can't wrap within the limit, wrap at the next space instead.
if i < 0 {
i = strings.Index(s, " ")
// Nothing left to do!
if i < 0 {
return s
}
}
return s[:i] + "\n" + Line(s[i+1:], limit)
}
// LineWithPrefix will wrap a single line of text and prepend the given prefix,
// whilst staying within given limits.
func LineWithPrefix(s, prefix string, limit int) string {
var ret string
for _, str := range strings.Split(Line(s, limit-len(prefix)), "\n") {
ret += prefix + str + "\n"
}
return ret
}
|
Fix disappearing contact entries after being renamed by another client.
This actually modified a cached roster entry of another random user that
happened to have the same JID in their roster. | <?php
namespace Moxl\Xec\Payload;
use App\Roster as DBRoster;
use App\User as DBUser;
class Roster extends Payload
{
public function handle($stanza, $parent = false)
{
if ((string)$parent->attributes()->type == 'set') {
$jid = current(explode('/', (string)$stanza->item->attributes()->jid));
$contact = DBUser::me()->session->contacts()->where('jid', $jid)->first();
if ($contact) $contact->delete();
if ((string)$stanza->item->attributes()->subscription != 'remove') {
$roster = DBRoster::firstOrNew(['jid' => $jid, 'session_id' => DBUser::me()->session->id]);
$roster->set($stanza->item);
$roster->save();
}
$this->deliver();
}
}
}
| <?php
namespace Moxl\Xec\Payload;
use App\Roster as DBRoster;
use App\User as DBUser;
class Roster extends Payload
{
public function handle($stanza, $parent = false)
{
if ((string)$parent->attributes()->type == 'set') {
$jid = current(explode('/', (string)$stanza->item->attributes()->jid));
$contact = DBUser::me()->session->contacts()->where('jid', $jid)->first();
if ($contact) $contact->delete();
if ((string)$stanza->item->attributes()->subscription != 'remove') {
$roster = DBRoster::firstOrNew(['jid' => $jid]);
$roster->set($stanza->item);
$roster->save();
}
$this->deliver();
}
}
}
|
Remove change set links from quick search as it will likely conflict with issues and builds too (on svn at least) | /*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.files;
import org.headsupdev.agile.api.LinkProvider;
import org.headsupdev.agile.api.Project;
/**
* Docs link format for a changeset in the scm browser
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class ChangeLinkProvider extends LinkProvider
{
@Override
public String getId()
{
return "change";
}
public String getPageName()
{
return "files/change";
}
public String getParamName()
{
return "id";
}
@Override
public boolean isLinkBroken( String params, Project project )
{
return !BrowseApplication.getChangeSetExists( project, params );
}
@Override
public boolean supportsQuickLink()
{
return false;
}
} | /*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.files;
import org.headsupdev.agile.api.LinkProvider;
import org.headsupdev.agile.api.Project;
/**
* Docs link format for a changeset in the scm browser
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class ChangeLinkProvider extends LinkProvider
{
@Override
public String getId()
{
return "change";
}
public String getPageName()
{
return "files/change";
}
public String getParamName()
{
return "id";
}
@Override
public boolean isLinkBroken( String params, Project project )
{
return !BrowseApplication.getChangeSetExists( project, params );
}
} |
Reformat code use golang standard format | package main
import (
"fmt"
"net"
"os"
"sync"
"time"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 10 * time.Second}
p := make(chan bool, 500) // make 500 parallel connection
wg := sync.WaitGroup{}
c := func(port int) {
conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
if err == nil {
conn.Close()
fmt.Printf("%d passed\n", port)
}
<-p
wg.Done()
}
wg.Add(65536)
for i := 0; i < 65536; i++ {
p <- true
go c(i)
}
wg.Wait()
}
| package main
import (
"fmt"
"os"
"net"
"time"
"sync"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 10 * time.Second}
p := make(chan bool, 500) // make 500 parallel connection
wg := sync.WaitGroup{}
c := func(port int) {
conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
if err == nil {
conn.Close()
fmt.Printf("%d passed\n", port)
}
<-p
wg.Done()
}
wg.Add(65536)
for i:=0; i < 65536; i++ {
p<-true
go c(i)
}
wg.Wait()
}
|
Use the correct host name | package com.example.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
public class OAuthConfigChecker implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (System.getenv("SFDC_OAUTH_CLIENT_ID") == null || System.getenv("SFDC_OAUTH_CLIENT_SECRET") == null) {
final String appName = servletRequest.getServerName().replace(".herokuapp.com", "");
((HttpServletResponse)servletResponse).sendRedirect("https://agi.herokuapp.com/oauthConfig?app=" + appName + "&callbackUrl=/_auth");
}
}
@Override
public void destroy() {}
}
| package com.example.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
public class OAuthConfigChecker implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (System.getenv("SFDC_OAUTH_CLIENT_ID") == null || System.getenv("SFDC_OAUTH_CLIENT_SECRET") == null) {
final String appName = servletRequest.getRemoteHost().replace(".herokuapp.com", "");
((HttpServletResponse)servletResponse).sendRedirect("https://agi.herokuapp.com/oauthConfig?app=" + URLEncoder.encode(appName, "UTF-8") + "&callbackUrl=/_auth");
}
}
@Override
public void destroy() {}
}
|
Clean up page metadata keys | <?php
namespace Site\Page;
class MetadataList {
public $error;
public $count = 0;
public function find($parameters = array()) {
$bind_params = array();
$get_object_query = "
SELECT id
FROM page_metadata
WHERE id = id
";
if (!empty($parameters['page_id'])) {
$get_object_query .= "
AND page_id = ?";
array_push($bind_params,$parameters['page_id']);
}
$rs = $GLOBALS['_database']->Execute($get_object_query,$bind_params);
if (! $rs) {
$this->error = "SQL Error in Site::Page::MetadataList::find(): ".$GLOBALS['_database']->ErrorMsg();
return null;
}
$metadatas = array();
while(list($id) = $rs->FetchRow()) {
$metadata = new \Site\Page\Metadata($id);
if (preg_match('/^[\w\_][\w\-\_\.]*$/',$metadata->key)) {
array_push($metadatas,$metadata);
$this->count ++;
}
}
return $metadatas;
}
public function error() {
return $this->error;
}
public function count() {
return $this->count();
}
}
| <?php
namespace Site\Page;
class MetadataList {
public $error;
public $count = 0;
public function find($parameters = array()) {
$bind_params = array();
$get_object_query = "
SELECT id
FROM page_metadata
WHERE id = id
";
if (!empty($parameters['page_id'])) {
$get_object_query .= "
AND page_id = ?";
array_push($bind_params,$parameters['page_id']);
}
$rs = $GLOBALS['_database']->Execute($get_object_query,$bind_params);
if (! $rs) {
$this->error = "SQL Error in Site::Page::MetadataList::find(): ".$GLOBALS['_database']->ErrorMsg();
return null;
}
$metadatas = array();
while(list($id) = $rs->FetchRow()) {
$metadata = new \Site\Page\Metadata($id);
array_push($metadatas,$metadata);
$this->count ++;
}
return $metadatas;
}
public function error() {
return $this->error;
}
public function count() {
return $this->count();
}
} |
Use print() for Python3. No global variables. Optimisations | from __future__ import print_function
import json
import optparse
def read_gene_info(gene_info):
transcript_species_dict = dict()
for gene_dict in gene_info.values():
for transcript in gene_dict['Transcript']:
transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "")
return transcript_species_dict
parser = optparse.OptionParser()
parser.add_option('-j', '--json', dest="input_gene_filename",
help='Gene feature information in JSON format')
parser.add_option('-f', '--fasta', dest="input_fasta_filename",
help='Sequences in FASTA format')
options, args = parser.parse_args()
if options.input_gene_filename is None:
raise Exception('-j option must be specified')
if options.input_fasta_filename is None:
raise Exception('-f option must be specified')
with open(options.input_gene_filename) as json_fh:
gene_info = json.load(json_fh)
transcript_species_dict = read_gene_info(gene_info)
with open(options.input_fasta_filename) as fasta_fh:
for line in fasta_fh:
line = line.rstrip()
if line.startswith(">"):
name = line[1:].lstrip()
print(">" + name + "_" + transcript_species_dict[name])
else:
print(line)
| import json
import optparse
transcript_species_dict = dict()
sequence_dict = dict()
def readgene(gene):
for transcript in gene['Transcript']:
transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "")
def read_fasta(fp):
for line in fp:
line = line.rstrip()
if line.startswith(">"):
name = line.replace(">", "")
print ">" + name + "_" + transcript_species_dict[name]
else:
print line
parser = optparse.OptionParser()
parser.add_option('-j', '--json', dest="input_gene_filename",
help='Gene Tree from Ensembl in JSON format')
parser.add_option('-f', '--fasta', dest="input_fasta_filename",
help='Gene Tree from Ensembl in JSON format')
options, args = parser.parse_args()
if options.input_gene_filename is None:
raise Exception('-j option must be specified')
if options.input_fasta_filename is None:
raise Exception('-f option must be specified')
with open(options.input_gene_filename) as data_file:
data = json.load(data_file)
for gene_dict in data.values():
readgene(gene_dict)
with open(options.input_fasta_filename) as fp:
read_fasta(fp)
|
Update contact to function on click | jQuery(document).ready(function() {
var loginToken = window.localStorage.getItem("token");
setTimeout(function() {
keepAliveTwo(loginToken);
}, 500);
displayAllUsersForCoach();
function displayAllUsersForCoach() {
// Get a list of users under the logged in job coach
var userList = JSON.parse(localStorage.getItem('userList'));
// Loop through list of users and create an accordion menu for each user
$.each(userList, function (key, item) {
console.log(item.userName);
$("<div data-role='collapsible'>" +
"<h4>" + item.userName + "</h4>" +
"<ul data-role='listview'>" +
// TODO: Have the jobs/contact button link correctly
"<li><a href='joblist.html'>Jobs</a></li>" +
"<li onclick='getUserInfo(\""+$userName+"\")'><a href='#'>Contact</a></li>" +
"</ul>" +
"</div>").appendTo($("#userList"));
$('#userList').collapsibleset('refresh');
});
}
});
| jQuery(document).ready(function() {
var loginToken = window.localStorage.getItem("token");
setTimeout(function() {
keepAliveTwo(loginToken);
}, 500);
displayAllUsersForCoach();
function displayAllUsersForCoach() {
// Get a list of users under the logged in job coach
var userList = JSON.parse(localStorage.getItem('userList'));
// Loop through list of users and create an accordion menu for each user
$.each(userList, function (key, item) {
console.log(item.userName);
$("<div data-role='collapsible'>" +
"<h4>" + item.userName + "</h4>" +
"<ul data-role='listview'>" +
// TODO: Have the jobs/contact button link correctly
"<li><a href='joblist.html'>Jobs</a></li>" +
"<li><a href='#'>Contact</a></li>" +
"</ul>" +
"</div>").appendTo($("#userList"));
$('#userList').collapsibleset('refresh');
});
}
}); |
Handle when container is undefined. | (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.posting = json.posting || "on";
json.project = json.project || (container && container.name) || "";
// prepopulate the sequence input dialog
$("input[name=post_activity]").val([json["posting"]]);
$("#project").val([json.project]);
$("#btn_submit").click( function() {
config.posting = $("input[name=post_activity]:checked").val();
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
| (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.posting = json.posting || "on";
json.project = json.project || container.name;
// prepopulate the sequence input dialog
$("input[name=post_activity]").val([json["posting"]]);
$("#project").val([json.project]);
$("#btn_submit").click( function() {
config.posting = $("input[name=post_activity]:checked").val();
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
|
Bugfix: Structure keyword get accepted now | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structure members"""
__defaults__ = {}
"""Default values for (a part of) the structure members.
__defaults__.keys() must be a (inproper) subset __slots__."""
def __init__(self, *args, **kwargs):
"""
@param *args: Positional arguments
@param **kwargs: Keyword arguments
"""
# Initialize all members with None
map(lambda k: self.__setattr__(k, self.__defaults__[k]() if k in self.__defaults__ else None), self.__slots__)
# Positional definition of members
for i,a in enumerate(args):
if len(self.__slots__) > i:
self.__setattr__(self.__slots__[i], a)
# Keyword definition of members
map(lambda k: self.__setattr__(k, kwargs[k]), filter(lambda k: k in self.__slots__, kwargs))
@property
def kind(self):
return self.__class__
| #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structure members"""
__defaults__ = {}
"""Default values for (a part of) the structure members.
__defaults__.keys() must be a (inproper) subset __slots__."""
def __init__(self, *args, **kwargs):
"""
@param *args: Positional arguments
@param **kwargs: Keyword arguments
"""
# Initialize all members with None
map(lambda k: self.__setattr__(k, self.__defaults__[k]() if k in self.__defaults__ else None), self.__slots__)
# Positional definition of members
for i,a in enumerate(args):
if len(self.__slots__) > i:
self.__setattr__(self.__slots__[i], a)
# Keyword definition of members
map(lambda k: self.__setattr__(k, None), filter(lambda k: k in self.__slots__, kwargs))
@property
def kind(self):
return self.__class |
Revert "commented out clear for now"
This reverts commit 1a03b1fc61f9c32e26dd146801127306736a86c3. | package guitests;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ClearCommandTest extends ToDoListGuiTest {
@Test
public void clear() {
/*
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
//verify other commands can work after a clear command
commandBox.runCommand(td.meetHoon.getAddCommand());
assertTrue(taskListPanel.isListMatching(td.meetHoon));
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {*/
commandBox.runCommand("clear");
assertListSize(0);
}
}
| package guitests;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ClearCommandTest extends ToDoListGuiTest {
/*
@Test
public void clear() {
/*
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
//verify other commands can work after a clear command
commandBox.runCommand(td.meetHoon.getAddCommand());
assertTrue(taskListPanel.isListMatching(td.meetHoon));
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("clear");
assertListSize(0);
}*/
}
|
Store session cookies as a dictionary | #!/usr/bin/env python
'''PyLibChorus -- Python Chorus API Library'''
import logging
from pylibchorus.chorus_api import login
from pylibchorus.chorus_api import logout
from pylibchorus.chorus_api import check_login_status
from pylibchorus.chorus_api import create_workfile
from pylibchorus.chorus_api import update_workfile_version
from pylibchorus.chorus_api import delete_workfile
LOG = logging.getLogger(__name__)
#pylint: disable=R0903
class ChorusSession(object):
'''Chorus User Session Object'''
def __init__(self, config):
self.config = config
self.sid = None
self.cookies = None
def __enter__(self):
'''create session and return sid and cookies'''
LOG.debug("Opening Chorus Session")
post = login(
self.config.get('alpine', 'username'),
self.config.get('alpine', 'password'),
self)
json = post.json()
self.sid = json['response']['session_id']
self.cookies = dict(post.cookies)
return self
def __exit__(self, _type, _value, _traceback):
'''Close chorus session'''
LOG.debug("Closing Chorus Session")
logout(self)
| #!/usr/bin/env python
'''PyLibChorus -- Python Chorus API Library'''
import logging
from pylibchorus.chorus_api import login
from pylibchorus.chorus_api import logout
from pylibchorus.chorus_api import check_login_status
from pylibchorus.chorus_api import create_workfile
from pylibchorus.chorus_api import update_workfile_version
from pylibchorus.chorus_api import delete_workfile
LOG = logging.getLogger(__name__)
#pylint: disable=R0903
class ChorusSession(object):
'''Chorus User Session Object'''
def __init__(self, config):
self.config = config
self.sid = None
self.cookies = None
def __enter__(self):
'''create session and return sid and cookies'''
LOG.debug("Opening Chorus Session")
post = login(
self.config.get('alpine', 'username'),
self.config.get('alpine', 'password'),
self)
json = post.json()
self.sid = json['response']['session_id']
self.cookies = post.cookies
return self
def __exit__(self, _type, _value, _traceback):
'''Close chorus session'''
LOG.debug("Closing Chorus Session")
logout(self)
|
Add missing border to messages box | package es.ucm.fdi.tp.views.swing;
import javax.swing.border.TitledBorder;
public class MessagesBox extends ScrollableTextarea {
private static final long serialVersionUID = 768586332299945974L;
public MessagesBox() {
super();
}
public MessagesBox(String text) {
super(text);
}
public MessagesBox(int rows, int cols) {
super(rows,cols);
}
public MessagesBox(String text, int rows, int cols) {
super(text,rows,cols);
}
@Override
protected void formatTextArea() {
super.formatTextArea();
this.textarea.setEditable(false);
this.textarea.setHighlighter(null);
this.setBorder(new TitledBorder("Status Messages"));
}
/**
* @throws UnsupportedOperationException when editable is set to true.
*/
@Override
public void setEditable(boolean b) {
if(b) throw new UnsupportedOperationException(
"This textarea object is read-only to users. ");
else this.textarea.setEditable(false);
}
/**
* Adds a new message to the box list. Does nothing if the model is null or
* the string is null or empty.
*/
@Override
public void append(String str) {
textarea.append("* " + str + "\n");
}
}
| package es.ucm.fdi.tp.views.swing;
public class MessagesBox extends ScrollableTextarea {
private static final long serialVersionUID = 768586332299945974L;
public MessagesBox() {
super();
}
public MessagesBox(String text) {
super(text);
}
public MessagesBox(int rows, int cols) {
super(rows,cols);
}
public MessagesBox(String text, int rows, int cols) {
super(text,rows,cols);
}
@Override
protected void formatTextArea() {
super.formatTextArea();
this.textarea.setEditable(false);
this.textarea.setHighlighter(null);
}
/**
* @throws UnsupportedOperationException when editable is set to true.
*/
@Override
public void setEditable(boolean b) {
if(b) throw new UnsupportedOperationException(
"This textarea object is read-only to users. ");
else this.textarea.setEditable(false);
}
/**
* Adds a new message to the box list. Does nothing if the model is null or
* the string is null or empty.
*/
@Override
public void append(String str) {
textarea.append("* " + str + "\n");
}
}
|
Change navigation after add category to list categories | package vu.de.npolke.myexpenses.servlets;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vu.de.npolke.myexpenses.backend.DatabaseConnection;
import vu.de.npolke.myexpenses.model.Category;
@WebServlet("/addcategory")
public class AddCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final DatabaseConnection DB_CONNECT = new DatabaseConnection();
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
final String name = request.getParameter("name");
Category category = new Category();
category.setName(name);
EntityManager dbConnection = DB_CONNECT.connect();
dbConnection.persist(category);
DB_CONNECT.commit();
DB_CONNECT.close();
response.sendRedirect("listcategories");
}
}
| package vu.de.npolke.myexpenses.servlets;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vu.de.npolke.myexpenses.backend.DatabaseConnection;
import vu.de.npolke.myexpenses.model.Category;
@WebServlet("/addcategory")
public class AddCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final DatabaseConnection DB_CONNECT = new DatabaseConnection();
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
final String name = request.getParameter("name");
Category category = new Category();
category.setName(name);
EntityManager dbConnection = DB_CONNECT.connect();
dbConnection.persist(category);
DB_CONNECT.commit();
DB_CONNECT.close();
response.sendRedirect("listexpenses");
}
}
|
Fix an issue in isEmulator | package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
} | package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDL built for")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
} |
Change custom stroke override method
Peeking into the fabric source, it looks like the `_stroke` method we're
overriding in the `highlighted_stroke` mixin has been renamed to
`_renderStroke`. Making sure we override the correct method, we start
seeing our customized stroke rendering. | module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_renderStroke: function (ctx) {
var myScale = this.scaleX;
var outline = this._outlineWidth();
function scale(x) {
return Math.round(x) / myScale;
}
ctx.lineWidth = scale(this.borderWidth + outline);
ctx.strokeStyle = this.outlineStyle;
ctx.stroke();
ctx.lineWidth = scale(this.borderWidth - outline);
ctx.strokeStyle = this.stroke;
ctx.stroke();
},
_outlineWidth: function () {
return Math.max(1, Math.round(this.borderWidth * this.outlineWidth));
},
/**
* This is primarily used to get a bounding rect for drawing borders and
* doing a hit-test for mouse events. We extend the size by the borderWidth
* cause rectangles and axis lines (horiz or vert) have half their
* borderWidth outside the actual bounding rect of the shape.
*/
_calculateCurrentDimensions: function (shouldTransform) {
var p = this.callParent(shouldTransform);
var b = this.borderWidth + this._outlineWidth();
return { x: p.x + b, y: p.y + b };
},
};
| module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_stroke: function (ctx) {
var myScale = this.scaleX;
var outline = this._outlineWidth();
function scale(x) {
return Math.round(x) / myScale;
}
ctx.lineWidth = scale(this.borderWidth + outline);
ctx.strokeStyle = this.outlineStyle;
ctx.stroke();
ctx.lineWidth = scale(this.borderWidth - outline);
ctx.strokeStyle = this.stroke;
ctx.stroke();
},
_outlineWidth: function () {
return Math.max(1, Math.round(this.borderWidth * this.outlineWidth));
},
/**
* This is primarily used to get a bounding rect for drawing borders and
* doing a hit-test for mouse events. We extend the size by the borderWidth
* cause rectangles and axis lines (horiz or vert) have half their
* borderWidth outside the actual bounding rect of the shape.
*/
_calculateCurrentDimensions: function (shouldTransform) {
var p = this.callParent(shouldTransform);
var b = this.borderWidth + this._outlineWidth();
return { x: p.x + b, y: p.y + b };
},
};
|
Add mutator generation to assemble command. | <?php
namespace R\Hive\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
class AssembleCommand extends Command
{
protected $name = 'hive:assemble';
protected $description = 'Create a new Hive resource collection for an instance.';
public function fire()
{
$name = $this->argument('name');
$this->call('hive:instance', ['name' => $name, '-e' => 'bar', '-m' => 'bar']);
$this->call('hive:factory', ['name' => $name, '-i' => 'bar']);
$this->call('hive:repo', ['name' => $name, '-o' => 'bar']);
$this->call('hive:mutator', ['name' => $name.'Request', '-r' => 'bar']);
$this->call('hive:controller', ['name' => $name]);
}
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the instance.'],
];
}
}
| <?php
namespace R\Hive\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
class AssembleCommand extends Command
{
protected $name = 'hive:assemble';
protected $description = 'Create a new Hive resource collection for an instance.';
public function fire()
{
$name = $this->argument('name');
$this->call('hive:instance', ['name' => $name, '-e' => 'bar', '-m' => 'bar']);
$this->call('hive:factory', ['name' => $name, '-i' => 'bar']);
$this->call('hive:repo', ['name' => $name, '-o' => 'bar']);
$this->call('hive:controller', ['name' => $name]);
}
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the instance.'],
];
}
}
|
Fix handling of non-error reponses from Graphite | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.ENV_NAME || "unknown";
var timer = null;
var graphite = null;
var data = Measured.createCollection('origami.polyfill.' + envName);
if (graphiteHost) {
graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort);
timer = setInterval(function() {
graphite.write(data.toJSON(), function(err) {
if (err) {
// Ignore timeouts
if (err.code === 'ETIMEDOUT') return;
console.error(err, err.stack);
console.warn('Disabling graphite reporting due to error');
clearTimeout(timer);
}
});
}, reportInterval);
timer.unref();
}
module.exports = data;
| var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.ENV_NAME || "unknown";
var timer = null;
var graphite = null;
var data = Measured.createCollection('origami.polyfill.' + envName);
if (graphiteHost) {
graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort);
timer = setInterval(function() {
graphite.write(data.toJSON(), function(err) {
// Ignore timeouts
if (err.code === 'ETIMEDOUT') return;
if (err) {
console.error(err, err.stack);
console.warn('Disabling graphite reporting due to error');
clearTimeout(timer);
}
});
}, reportInterval);
timer.unref();
}
module.exports = data;
|
Complete search functionality for models
* Add button functionality to search bar | const mongoose = require('mongoose')
const shortId = require('shortid')
const Schema = mongoose.Schema
const assetSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
tagId: String,
assignedTo: String
})
const specSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
key: String,
value: String
})
const categorySchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
name: String,
label: String,
description: String,
config: {
faIcon: String,
color: String,
api: String,
fallbackImage: String
},
models: [ { type: Schema.Types.ObjectId, ref: 'Model' } ]
})
const modelSchema = Schema({
_parent: {type: String, ref: 'Category'},
_shortId: {type: String, unique: true, default: shortId.generate},
category: String,
vendor: String,
name: String,
version: String,
image: String,
description: String,
active: Boolean,
specs: [ specSchema ],
assets: [ assetSchema ]
})
modelSchema.index({
vendor: 'text',
name: 'text',
version: 'text',
description: 'text'
})
module.exports = { assetSchema, modelSchema, categorySchema }
| const mongoose = require('mongoose')
const shortId = require('shortid')
const Schema = mongoose.Schema
const assetSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
tagId: { type: String, text: true },
assignedTo: { type: String, text: true }
})
const specSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
key: { type: String, text: true },
value: { type: String, text: true }
})
const categorySchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
name: String,
label: String,
description: String,
config: {
faIcon: String,
color: String,
api: String,
fallbackImage: String
},
models: [ { type: Schema.Types.ObjectId, ref: 'Model' } ]
})
const modelSchema = Schema({
_parent: {type: String, ref: 'Category'},
_shortId: {type: String, unique: true, default: shortId.generate},
category: { type: String, text: true },
vendor: { type: String, text: true },
name: { type: String, text: true },
version: { type: String, text: true },
image: String,
description: { type: String, text: true },
active: Boolean,
specs: [ specSchema ],
assets: [ assetSchema ]
})
modelSchema.index({
vendor: 'text',
name: 'text',
version: 'text',
description: 'text'
})
module.exports = { assetSchema, modelSchema, categorySchema }
|
Update parse() to grab the business URL | 'use strict';
var Backbone = require('backbone');
var BusinessModel = Backbone.Model.extend({
idAttribute: 'id',
parse: function(data) {
var hash = {};
hash.name = data.name;
hash.id = data.id;
hash.address = data.location.display_address.join(' ');
hash.rating = data.rating;
hash.url = data.url;
if (data.location.coordinate && data.location.coordinate !== 'undefined') {
hash.coordinates = {
lat: data.location.coordinate.latitude,
lng: data.location.coordinate.longitude
};
}
if (data.categories && data.categories !== 'undefined') {
hash.specificCategory = data.categories[0][0];
} else {
hash.specificCategory = '';
}
return hash;
}
});
module.exports = BusinessModel; | 'use strict';
var Backbone = require('backbone');
var BusinessModel = Backbone.Model.extend({
idAttribute: 'id',
parse: function(data) {
var hash = {};
hash.name = data.name;
hash.id = data.id;
hash.address = data.location.display_address.join(' ');
hash.rating = data.rating;
if (data.location.coordinate && data.location.coordinate !== 'undefined') {
hash.coordinates = {
lat: data.location.coordinate.latitude,
lng: data.location.coordinate.longitude
};
}
if (data.categories && data.categories !== 'undefined') {
hash.specificCategory = data.categories[0][0];
} else {
hash.specificCategory = '';
}
return hash;
}
});
module.exports = BusinessModel; |
[Feature] Add BucketListApi resource to api. | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource, BucketListApi
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
Use model injection for Pitch model | <?php
class PitchController extends BaseController {
protected $pitch;
function __construct(Pitch $pitch)
{
$this->pitch = $pitch;
}
/**
* Validator for pitches
*/
protected $rules = [
'email' => 'required|email',
'name' => 'required',
'blurb' => 'required'
];
public function getIndex()
{
return View::make('pitch')->with('pitch', $this->pitch);
}
public function postIndex()
{
$input = Input::all();
$validator = Validator::make($input, $this->rules);
if ($validator->fails()) {
Session::flashInput($input);
return Redirect::to('pitch')->with('error', $validator->messages());
}
$this->pitch->fill($input);
$author = Author::where('email', $this->pitch->email)->first();
if ($author) $this->pitch->author_id = $author->id;
$this->pitch->save();
Queue::push('PitchNotify', ['pitch' => $this->pitch->id]);
return View::make('gotpitch')->with('pitch', $this->pitch);
}
}
| <?php
class PitchController extends BaseController {
/**
* Validator for pitches
*/
protected $rules = [
'email' => 'required|email',
'name' => 'required',
'blurb' => 'required'
];
public function getIndex()
{
$pitch = new Pitch();
return View::make('pitch')->with('pitch', $pitch);
}
public function postIndex()
{
$input = Input::all();
$pitch = new Pitch();
$validator = Validator::make($input, $this->rules);
if ($validator->fails()) {
Session::flashInput($input);
return Redirect::to('pitch')->with('error', $validator->messages());
}
$pitch->fill($input);
$author = Author::where('email', $pitch->email)->first();
if ($author) $pitch->author_id = $author->id;
$pitch->save();
Queue::push('PitchNotify', ['pitch' => $pitch->id]);
return View::make('gotpitch')->with('pitch', $pitch);
}
}
|
Fix to use node path module to join path | var path = require('path');
var exec = require('child_process').exec;
var _ = require('lodash');
var Q = require('q');
function UrlToImage() {
var api = {};
api.render = function(url, file, opts) {
var def = Q.defer();
var args = [
path.join(__dirname, 'url-to-image.js'),
url,
file,
opts.width,
opts.height
];
var execOpts = {
maxBuffer: Infinity
};
exec('phantomjs ' + args.join(' '), execOpts, function(err, stdout) {
def.resolve(err);
});
return def;
};
return api;
}
module.exports = UrlToImage; | var exec = require('child_process').exec;
var _ = require('lodash');
var Q = require('q');
function UrlToImage() {
var api = {};
api.render = function(url, file, opts) {
var def = Q.defer();
var args = [
__dirname + 'url-to-image.js',
url,
file,
opts.width,
opts.height
];
var execOpts = {
maxBuffer: Infinity
};
exec('phantomjs ' + args.join(' '), execOpts, function(err, stdout) {
def.resolve(err);
});
return def;
};
return api;
}
module.exports = UrlToImage; |
Use plural names for resource types in URLs | from django.conf.urls.defaults import patterns, include, url
from boundaryservice.views import *
urlpatterns = patterns('',
url(r'^boundary-sets/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'),
url(r'^boundary-sets/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_set_detail'),
url(r'^boundaries/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'),
url(r'^boundaries/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()),
url(r'^boundaries/(?P<set_slug>[\w_-]+)/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'),
url(r'^boundaries/(?P<set_slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()),
url(r'^boundaries/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/$', BoundaryDetailView.as_view(), name='boundaryservice_boundary_detail'),
url(r'^boundaries/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryGeoDetailView.as_view()),
)
| from django.conf.urls.defaults import patterns, include, url
from boundaryservice.views import *
urlpatterns = patterns('',
url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'),
url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_set_detail'),
url(r'^boundary/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'),
url(r'^boundary/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()),
url(r'^boundary/(?P<set_slug>[\w_-]+)/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'),
url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()),
url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/$', BoundaryDetailView.as_view(), name='boundaryservice_boundary_detail'),
url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryGeoDetailView.as_view()),
)
|
Revert "Do not display quesitons in script."
This reverts commit 5c7286c1dc6348f2212266871876376df15592c0. | from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if t.type == 'missing':
return missing
if t.type == 'resource':
return str(t.value)
if t.type == 'triple':
_subject = string_of_triple(t.subject,missing,separator)
_predicate = string_of_triple(t.predicate,missing,separator)
_object = string_of_triple(t.object,missing,separator)
return "({1}{0}{2}{0}{3})".format(separator,_subject,_predicate,_object)
raise TripleError(t,"Wrong triple (new datamodel connectors?).")
def process_string(s,missing='?',separator=','):
return string_of_triple(get_answer(s),missing,separator)
if __name__ == "__main__":
while True:
try:
s = input("")
except EOFError:
break
print(s)
print(process_string(s))
| from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if t.type == 'missing':
return missing
if t.type == 'resource':
return str(t.value)
if t.type == 'triple':
_subject = string_of_triple(t.subject,missing,separator)
_predicate = string_of_triple(t.predicate,missing,separator)
_object = string_of_triple(t.object,missing,separator)
return "({1}{0}{2}{0}{3})".format(separator,_subject,_predicate,_object)
raise TripleError(t,"Wrong triple (new datamodel connectors?).")
def process_string(s,missing='?',separator=','):
return string_of_triple(get_answer(s),missing,separator)
if __name__ == "__main__":
while True:
try:
s = input("")
except EOFError:
break
print(process_string(s))
|
Fix attribute error in vsphere controller
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com> | from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc.name == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
| from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.client.get_datacenters():
if dc.name == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
|
ExpandURL: Move to group 'base' and enable "More at ..." | (function(env){
env.ddg_spice_expand_url = function(api_response) {
"use strict";
// Get the orignal query.
var query = DDG.get_query().replace(/expand\s*/i, "");
// Check if there are any errors.
if (!api_response["long-url"] || api_response["long-url"] === query) {
return Spice.failed('expand_url');
}
// Display the plug-in.
Spice.add({
id: "expand_url",
name: "Expand URL",
data: api_response,
meta: {
sourceUrl: "http://longurl.org/expand?url=" + encodeURIComponent(query),
sourceName: "LongURL"
},
templates: {
group: 'base',
options: {
content: Spice.expand_url.content,
moreAt: true
}
}
});
}
}(this));
| (function(env){
env.ddg_spice_expand_url = function(api_response) {
"use strict";
// Get the orignal query.
var query = DDG.get_query().replace(/expand\s*/i, "");
// Check if there are any errors.
if (!api_response["long-url"] || api_response["long-url"] === query) {
return Spice.failed('expand_url');
}
// Display the plug-in.
Spice.add({
id: "expand_url",
name: "Expand URL",
data: api_response,
meta: {
sourceUrl: "http://longurl.org/expand?url=" + encodeURIComponent(query),
sourceName: "LongURL"
},
templates: {
group: 'info',
options: {
content: Spice.expand_url.content
}
}
});
}
}(this)); |
Return graph object after ploting | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distribution of the sequences"""
short_name = 'length_dist'
def __init__(self, parent):
self.parent = parent
self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf')
def plot(self, x_log=False, y_log=False):
# Data #
counts = self.parent.lengths_counter
# Plot #
fig = pyplot.figure()
pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center')
axes = pyplot.gca()
# Information #
title = 'Distribution of sequence lengths'
axes.set_title(title)
axes.set_xlabel('Length of sequence in nucleotides')
axes.set_ylabel('Number of sequences with this length')
axes.xaxis.grid(False)
# Add logarithm to axes #
if x_log: axes.set_xscale('symlog')
if y_log: axes.set_yscale('symlog')
# Save it #
self.save_plot(fig, axes, sep=('x'))
# For convenience #
return self | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distribution of the sequences"""
short_name = 'length_dist'
def __init__(self, parent):
self.parent = parent
self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf')
def plot(self, x_log=False, y_log=False):
# Data #
counts = self.parent.lengths_counter
# Plot #
fig = pyplot.figure()
pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center')
axes = pyplot.gca()
# Information #
title = 'Distribution of sequence lengths'
axes.set_title(title)
axes.set_xlabel('Length of sequence in nucleotides')
axes.set_ylabel('Number of sequences with this length')
axes.xaxis.grid(False)
# Add logarithm to axes #
if x_log: axes.set_xscale('symlog')
if y_log: axes.set_yscale('symlog')
# Save it #
self.save_plot(fig, axes, sep=('x')) |
Fix format string for MessageFormat | package com.komanov.stringformat;
import org.slf4j.helpers.MessageFormatter;
import java.text.MessageFormat;
import java.util.Locale;
public class JavaFormats {
private static final MessageFormat messageFormatInstance = new MessageFormat("{0,number,#}a{1}b{2}{3}");
public static String concat(int value1, String value2, Object nullObject) {
return value1 + "a" + value2 + "b" + value2 + nullObject;
}
public static String stringFormat(int value1, String value2, Object nullObject) {
return String.format(Locale.ENGLISH, "%da%sb%s%s", value1, value2, value2, nullObject);
}
public static String messageFormat(int value1, String value2, Object nullObject) {
return MessageFormat.format("{0,number,#}a{1}b{2}{3}", value1, value2, value2, nullObject);
}
public static String messageFormatCached(int value1, String value2, Object nullObject) {
return messageFormatInstance.format(new Object[]{value1, value2, value2, nullObject});
}
public static String slf4j(int value1, String value2, Object nullObject) {
return MessageFormatter
.arrayFormat("{}a{}b{}{}", new Object[]{value1, value2, value2, nullObject})
.getMessage();
}
}
| package com.komanov.stringformat;
import org.slf4j.helpers.MessageFormatter;
import java.text.MessageFormat;
import java.util.Locale;
public class JavaFormats {
private static final MessageFormat messageFormatInstance = new MessageFormat("{0}a{1}b{2}{3}");
public static String concat(int value1, String value2, Object nullObject) {
return value1 + "a" + value2 + "b" + value2 + nullObject;
}
public static String stringFormat(int value1, String value2, Object nullObject) {
return String.format(Locale.ENGLISH, "%da%sb%s%s", value1, value2, value2, nullObject);
}
public static String messageFormat(int value1, String value2, Object nullObject) {
return MessageFormat.format("{0}a{1}b{2}{3}", value1, value2, value2, nullObject);
}
public static String messageFormatCached(int value1, String value2, Object nullObject) {
return messageFormatInstance.format(new Object[]{value1, value2, value2, nullObject});
}
public static String slf4j(int value1, String value2, Object nullObject) {
return MessageFormatter
.arrayFormat("{}a{}b{}{}", new Object[]{value1, value2, value2, nullObject})
.getMessage();
}
}
|
Bring US site shipping repo up-to-date
The repo internals had changed since the US site was born. | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')
class Repository(repository.Repository):
def get_available_shipping_methods(
self, basket, shipping_addr=None, **kwargs):
methods = [Standard(), Express()]
if shipping_addr:
item_methods = models.OrderAndItemCharges.objects.filter(
countries=shipping_addr.country)
methods.extend(list(item_methods))
return methods
| from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')
class Repository(repository.Repository):
methods = [Standard, Express]
def get_shipping_methods(self, basket, user=None, shipping_addr=None,
request=None, **kwargs):
methods = super(Repository, self).get_shipping_methods(
basket, user, shipping_addr, request, **kwargs)
if shipping_addr:
item_methods = models.OrderAndItemCharges.objects.filter(
countries=shipping_addr.country)
for method in item_methods:
methods.append(self.prime_method(basket, method))
return methods
|
Add support for scoped package | #!/usr/bin/env node
var program = require('commander'),
globalify = require('./globalify'),
packageJson = require('./package.json'),
fs = require('fs');
program
.version(packageJson.version)
.usage('<module> [options]')
.arguments('<module>')
.option('-o, --out <outputFileName>', 'the output path')
.option('-g, --globalVariable [globalVariable]', 'the name of the global variable to expose')
.parse(process.argv);
if (program.args.length !== 1) {
program.help();
}
var moduleArgument = program.args[0];
var moduleNodes, moduleName, version;
if (moduleArgument.indexOf('@') === 0) {
// scoped package
moduleNodes = moduleArgument.slice(1).split('@');
moduleName = '@' + moduleNodes[0];
}
else {
moduleNodes = moduleArgument.split('@');
moduleName = moduleNodes[0];
}
version = moduleNodes[1] || 'x.x.x';
var outStream = fs.createWriteStream(program.out || moduleName.replace('/', '-') + '.js');
globalify({
module: moduleName,
version: version,
globalVariable: program.globalVariable,
installDirectory: packageJson.installDirectory
},
function(error){
if(error){
console.log(error);
}
}
).pipe(outStream);
| #!/usr/bin/env node
var program = require('commander'),
globalify = require('./globalify'),
packageJson = require('./package.json'),
fs = require('fs');
program
.version(packageJson.version)
.usage('<module> [options]')
.arguments('<module>')
.option('-o, --out <outputFileName>', 'the output path')
.option('-g, --globalVariable [globalVariable]', 'the name of the global variable to expose')
.parse(process.argv);
if (program.args.length !== 1) {
program.help()
}
var moduleNameAndVersion = program.args[0].split('@'),
moduleName = moduleNameAndVersion[0],
version = moduleNameAndVersion[1] || 'x.x.x';
var outStream = fs.createWriteStream(program.out || moduleName + '.js');
globalify({
module: moduleName,
version: version,
globalVariable: program.globalVariable,
installDirectory: packageJson.installDirectory
},
function(error){
if(error){
console.log(error);
}
}
).pipe(outStream);
|
Add more detail to module docstring | # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
| # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
Make argv arguments optional, fixes pip installed script | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
import sys
def main(argv=None):
argv = argv or sys.argv
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = ZoneFilter(config['filter_rules']).filter
zone_updaters = [ZoneUpdater(**o).task for o in config['outputs']]
subsequent_tasks = [[zone_filter], zone_updaters]
work_manager = WorkManager()
for source in config['sources']:
for zone in source['zones']:
work_manager.submit_work(100, zone_xfer, (source['masters'], zone), subsequent_tasks)
work_manager.start()
work_manager.join()
if __name__ == '__main__':
main() | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
def main(argv):
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = ZoneFilter(config['filter_rules']).filter
zone_updaters = [ZoneUpdater(**o).task for o in config['outputs']]
subsequent_tasks = [[zone_filter], zone_updaters]
work_manager = WorkManager()
for source in config['sources']:
for zone in source['zones']:
work_manager.submit_work(100, zone_xfer, (source['masters'], zone), subsequent_tasks)
work_manager.start()
work_manager.join()
if __name__ == '__main__':
import sys
main(sys.argv) |
Add 'extraAllowedContent' to CKEditor config | (function(win, doc){
'use strict';
var
getRootPath = function(){
var parts = win.location.pathname.split('/');
parts.shift(); // remove first
parts.pop(); // remove last
parts.pop(); // yes, twice
var path = parts.join('/');
return '/' + path;
},
root_http = getRootPath(),
browser_plugin = 'filebrowser_upload',
plugin_dir = root_http + '/externs/ckeditor/plugins/',
openshift = 'http://filebrowser4openshift-jwalker.rhcloud.com',
browser = new FileBrowser({
root_http: openshift + '/server-side/writable',
server_http: openshift + '/server-side/filebrowser.php',
})
;
CKEDITOR.plugins.addExternal(browser_plugin, plugin_dir + browser_plugin + '/');
window.showUploadDialog = function(){
browser.show();
};
var ckeditor = CKEDITOR.replace('editor', {
extraPlugins: 'filebrowser_upload',
extraAllowedContent: 'img[src,alt,width,height]',
toolbarGroups: [
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'colors'] },
{ name: 'tools', groups: ['tools'] },
{ name: 'upload', groups: ['filebrowser'] }
]
});
browser.setEditor(ckeditor);
})(window, document);
| (function(win, doc){
'use strict';
var
getRootPath = function(){
var parts = win.location.pathname.split('/');
parts.shift(); // remove first
parts.pop(); // remove last
parts.pop(); // yes, twice
var path = parts.join('/');
return '/' + path;
},
root_http = getRootPath(),
browser_plugin = 'filebrowser_upload',
plugin_dir = root_http + '/externs/ckeditor/plugins/',
openshift = 'http://filebrowser4openshift-jwalker.rhcloud.com',
browser = new FileBrowser({
root_http: openshift + '/server-side/writable',
server_http: openshift + '/server-side/filebrowser.php',
})
;
CKEDITOR.plugins.addExternal(browser_plugin, plugin_dir + browser_plugin + '/');
window.showUploadDialog = function(){
browser.show();
};
var ckeditor = CKEDITOR.replace('editor', {
extraPlugins: 'filebrowser_upload',
toolbarGroups: [
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'colors'] },
{ name: 'tools', groups: ['tools'] },
{ name: 'upload', groups: ['filebrowser'] }
]
});
browser.setEditor(ckeditor);
})(window, document);
|
Add some more test coverage | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB)
sub_conn = sub.connect('inproc://foo')
sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '')
pub.send('FLUB')
poller = nnpy.PollSet((sub, nnpy.POLLIN))
self.assertEqual(poller.poll(), 1)
self.assertEqual(sub.recv(), 'FLUB')
self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1)
pub.close()
sub.shutdown(sub_conn)
def suite():
return unittest.makeSuite(Tests)
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB)
sub.connect('inproc://foo')
sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '')
pub.send('FLUB')
poller = nnpy.PollSet((sub, nnpy.POLLIN))
self.assertEqual(poller.poll(), 1)
self.assertEqual(sub.recv(), 'FLUB')
self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1)
def suite():
return unittest.makeSuite(Tests)
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
Fix large Input file generator | <?php
declare(strict_types=1);
require_once __DIR__.'/../__CondorcetAutoload.php';
///
$number_of_votes = 100_000_000;
$number_of_candidates = 8;
///
$candidateName = 'A';
$candidates = [];
for ($i=0; $i < $number_of_candidates ; $i++) :
$candidates[] = $candidateName++;
endfor;
$file = fopen(__DIR__.'/large.votes','w+');
$cache = '';
for ($i=0; $i < $number_of_votes; $i++) :
shuffle($candidates);
$cache .= implode('>',$candidates)."\n";
if (strlen($cache) > 5_000_000) :
fwrite($file,$cache);
$cache = '';
endif;
endfor;
fwrite($file,$cache);
fclose($file); | <?php
declare(strict_types=1);
require_once __DIR__.'/../__CondorcetAutoload.php';
///
$number_of_votes = 100_000_000;
$number_of_candidates = 8;
///
$candidateName = 'A';
$candidates = [];
for ($i=0; $i < $number_of_candidates ; $i++) :
$candidates[] = $candidateName++;
endfor;
$file = fopen(__DIR__.'/large.votes','w+');
$cache = '';
for ($i=0; $i < $number_of_votes; $i++) :
shuffle($candidates);
$cache .= implode('>',$candidates)."\n";
if (strlen($cache) > 5_000_000) :
fwrite($file,$cache);
$cache = '';
endif;
endfor;
fclose($file); |
Add "AnyOf" to public API. | from .compiler import ParseResult
from .expressions import (
Alt,
And,
Any,
AnyOf,
Backtrack,
Bind,
End,
Expect,
Fail,
ForwardRef,
Left,
List,
Literal,
Not,
Opt,
Or,
Require,
Return,
Right,
Some,
Start,
Struct,
Term,
Transform,
Where,
)
from .interpreter import (
ParseError,
parse,
parse_prefix,
tokenize,
tokenize_and_parse,
)
from .precedence import (
InfixLeft,
InfixRight,
LeftAssoc,
Operation,
OperatorPrecedence,
Postfix,
Prefix,
ReduceLeft,
ReduceRight,
RightAssoc,
)
from .tokens import (
AnyChar,
AnyString,
Content,
Pattern,
Regex,
Skip,
Token,
TokenSyntax,
Verbose,
)
| from .compiler import ParseResult
from .expressions import (
Alt,
And,
Any,
Backtrack,
Bind,
End,
Expect,
Fail,
ForwardRef,
Left,
List,
Literal,
Not,
Opt,
Or,
Require,
Return,
Right,
Some,
Start,
Struct,
Term,
Transform,
Where,
)
from .interpreter import (
ParseError,
parse,
parse_prefix,
tokenize,
tokenize_and_parse,
)
from .precedence import (
InfixLeft,
InfixRight,
LeftAssoc,
Operation,
OperatorPrecedence,
Postfix,
Prefix,
ReduceLeft,
ReduceRight,
RightAssoc,
)
from .tokens import (
AnyChar,
AnyString,
Content,
Pattern,
Regex,
Skip,
Token,
TokenSyntax,
Verbose,
)
|
Add function support to SVG as well | import { createElement } from './create-element.js';
import { parseArguments, isString, isNode } from './util.js';
const ns = 'http://www.w3.org/2000/svg';
const svgCache = {};
const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));
export const svg = (query, ...args) => {
let element;
if (isString(query)) {
element = memoizeSVG(query).cloneNode(false);
} else if (isNode(query)) {
element = query.cloneNode(false);
} else if (isFunction(query)) {
element = new query(...args);
} else {
throw new Error('At least one argument required');
}
parseArguments(element, args);
return element;
};
svg.extend = function (query) {
const clone = memoizeSVG(query);
return svg.bind(this, clone);
};
svg.ns = ns;
export const s = svg;
| import { createElement } from './create-element.js';
import { parseArguments, isString, isNode } from './util.js';
const ns = 'http://www.w3.org/2000/svg';
const svgCache = {};
const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));
export const svg = (query, ...args) => {
let element;
if (isString(query)) {
element = memoizeSVG(query).cloneNode(false);
} else if (isNode(query)) {
element = query.cloneNode(false);
} else {
throw new Error('At least one argument required');
}
parseArguments(element, args);
return element;
};
svg.extend = function (query) {
const clone = memoizeSVG(query);
return svg.bind(this, clone);
};
svg.ns = ns;
export const s = svg;
|
Add volume adjustment to sound script. | // This will not make any noise if the file
// ~/.arlobot/status/bequiet
// exists
var beQuietFile = process.env.HOME + '/.arlobot/status/bequiet';
var fs = require('fs');
fs.open(beQuietFile, 'r', function(err) {
if (err) {
var exec = require('child_process').exec;
// Set volume at max
exec('/usr/bin/amixer -D pulse sset Master 100% on');
var requestedSound = process.argv[2];
// This script can accept text to speak,
// or .wav files to play.
// We rely stricly on the extension to
// decide what it is!
var possibleExtension = requestedSound.slice(-4).toLowerCase();
if (possibleExtension === '.wav') {
exec('/usr/bin/aplay -q ' + requestedSound);
} else {
// https://github.com/marak/say.js/
var say = require('say');
// no callback, fire and forget
say.speak(null, process.argv[2]);
}
}
});
| // This will not make any noise if the file
// ~/.arlobot/status/bequiet
// exists
var beQuietFile = process.env.HOME + '/.arlobot/status/bequiet';
var fs = require('fs');
fs.open(beQuietFile, 'r', function(err) {
if (err) {
var requestedSound = process.argv[2];
// This script can accept text to speak,
// or .wav files to play.
// We rely stricly on the extension to
// decide what it is!
var possibleExtension = requestedSound.slice(-4).toLowerCase();
if (possibleExtension === '.wav') {
var exec = require('child_process').exec;
exec('/usr/bin/aplay -q ' + requestedSound);
} else {
// https://github.com/marak/say.js/
var say = require('say');
// no callback, fire and forget
say.speak(null, process.argv[2]);
}
}
});
|
Reorder to match PHPTAL interface. | <?php defined('SYSPATH') or die('No direct script access.');
/**
* Allows PHPTAL to take advantage of the Kohana i18n tranlator.
*
* @package KOtal
* @category Base
* @author Hanson Wong
* @author johanlindblad
* @copyright (c) 2010 Hanson Wong
* @license http://github.com/Dismounted/KOtal/blob/master/LICENSE
*/
require_once Kohana::find_file('vendor', 'phptal/PHPTAL/TranslationService');
class Kotal_TranslationService implements PHPTAL_TranslationService
{
private $vars = array();
// Not implemented and probably not needed
function setLanguage()
{
}
function setEncoding($encoding)
{
}
function useDomain($domain)
{
}
function setVar($key, $value)
{
$this->vars[':'.$key] = $value;
}
function translate($key, $htmlescape=true)
{
// Replace ${var} with :var and run through the translator
$text = __(preg_replace('/\$\{(.+?)\}/', ':$1', $key), $this->vars);
if ($htmlescape)
{
// Remove comment if you want to. Then you'll only be able to use
// <tal:block> for i18n:name attributes.
// return htmlentities($text);
}
return $text;
}
}
| <?php defined('SYSPATH') or die('No direct script access.');
/**
* Allows PHPTAL to take advantage of the Kohana i18n tranlator.
*
* @package KOtal
* @category Base
* @author Hanson Wong
* @author johanlindblad
* @copyright (c) 2010 Hanson Wong
* @license http://github.com/Dismounted/KOtal/blob/master/LICENSE
*/
require_once Kohana::find_file('vendor', 'phptal/PHPTAL/TranslationService');
class Kotal_TranslationService implements PHPTAL_TranslationService
{
private $vars = array();
function setVar($key, $value)
{
$this->vars[':'.$key] = $value;
}
function translate($key, $htmlescape=true)
{
// Replace ${var} with :var and run through the translator
$text = __(preg_replace('/\$\{(.+?)\}/', ':$1', $key), $this->vars);
if ($htmlescape)
{
// Remove comment if you want to. Then you'll only be able to use
// <tal:block> for i18n:name attributes.
// return htmlentities($text);
}
return $text;
}
// Not implemented and probably not needed
function setLanguage()
{
}
function setEncoding($encoding)
{
}
function useDomain($domain)
{
}
}
|
Increase intake motor value to 1.0. | package org.usfirst.frc.team3335.robot.subsystems;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.command.Subsystem;
public class Intake extends Subsystem implements LoggableSubsystem {
private CANTalon motor;
private double motorValue = 1.0; //0.5;
public Intake() {
motor = new CANTalon(RobotMap.INTAKE_MOTOR);
motor.set(0);
//motor.setControlMode();
}
public void turnOn(){
set(motorValue);
}
public void turnOff(){
set(0);
}
public void set(double value) {
motor.set(value);
}
@Override
protected void initDefaultCommand() {
// TODO Auto-generated method stub
}
@Override
public void log() {
SmartDashboard.putNumber("Intake Value",motor.get());
}
}
| package org.usfirst.frc.team3335.robot.subsystems;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.command.Subsystem;
public class Intake extends Subsystem implements LoggableSubsystem {
private CANTalon motor;
private double motorValue = 0.5;
public Intake() {
motor = new CANTalon(RobotMap.INTAKE_MOTOR);
motor.set(0);
//motor.setControlMode();
}
public void turnOn(){
set(motorValue);
}
public void turnOff(){
set(0);
}
public void set(double value) {
motor.set(value);
}
@Override
protected void initDefaultCommand() {
// TODO Auto-generated method stub
}
@Override
public void log() {
SmartDashboard.putNumber("Intake Value",motor.get());
}
}
|
Remove useless url from test urls | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.http.response import HttpResponse
admin.autodiscover()
def empty_view(request):
return HttpResponse()
urlpatterns = [
url(r'^home/', empty_view, name="home"),
url(r'^admin/', admin.site.urls),
url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")),
url(r'^testapp/', include('tests.apps.testapp.urls')),
url(
r'^testapp_namespaced/',
include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced")
),
# Represents protected content
url(r'^testapp_content/', include('tests.apps.testapp_content.urls')),
# For testing fnmatches
url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"),
# Default for DJSTRIPE_SUBSCRIPTION_REDIRECT
url(r"subscribe/$", empty_view, name="test_url_subscribe")
]
| # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.http.response import HttpResponse
admin.autodiscover()
def empty_view(request):
return HttpResponse()
urlpatterns = [
url(r'^home/', empty_view, name="home"),
url(r'^admin/', admin.site.urls),
url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")),
url(r'^testapp/', include('tests.apps.testapp.urls')),
url(r'^__debug__/', include('tests.apps.testapp.urls')),
url(
r'^testapp_namespaced/',
include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced")
),
# Represents protected content
url(r'^testapp_content/', include('tests.apps.testapp_content.urls')),
# For testing fnmatches
url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"),
# Default for DJSTRIPE_SUBSCRIPTION_REDIRECT
url(r"subscribe/$", empty_view, name="test_url_subscribe")
]
|
Fix link to example pipelines | import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
| import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a target="_blank" href="https://github.com/buildkite/sample-pipelines">sample pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
|
Set automatic releases as 'prerelease'. | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps({
'tag_name': 'v{0}'.format(version),
'name': 're:dash v{0}'.format(version),
'target_commitish': commit_sha,
'prerelease': True
})
response = requests.post('https://api.github.com/repos/everythingme/redash/releases',
data=params,
auth=auth)
upload_url = response.json()['upload_url']
upload_url = upload_url.replace('{?name}', '')
with open(filepath) as file_content:
headers = {'Content-Type': 'application/gzip'}
response = requests.post(upload_url, file_content, params={'name': filename}, auth=auth, headers=headers, verify=False)
| #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps({
'tag_name': 'v{0}'.format(version),
'name': 're:dash v{0}'.format(version),
'target_commitish': commit_sha
})
response = requests.post('https://api.github.com/repos/everythingme/redash/releases',
data=params,
auth=auth)
upload_url = response.json()['upload_url']
upload_url = upload_url.replace('{?name}', '')
with open(filepath) as file_content:
headers = {'Content-Type': 'application/gzip'}
response = requests.post(upload_url, file_content, params={'name': filename}, auth=auth, headers=headers, verify=False)
|
Install CMake in system dirs | #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None)
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
| #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None, install_dir='.')
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
|
Add tests for sending messages to "user" projects | from nose.tools import *
from lamson.testing import *
import os
from lamson import server
relay = relay(port=8823)
client = RouterConversation("queuetester@localhost", "requests_tests")
confirm_format = "testing-confirm-[0-9]+@"
noreply_format = "testing-noreply@"
host = "localhost"
def test_react_for_existing_project():
"""
Then make sure that project react messages for existing project queued properly.
"""
dest_addr = "docs.index@test.%s" % host
client.begin()
client.say(dest_addr, "Test project react messages for existing project queued properly")
def test_react_for_bad_project():
"""
Then make sure that project react messages for non-existing project dropped properly.
"""
dest_addr = "docs.index@badproject.%s" % host
client.begin()
client.say(dest_addr, "Test project react messages for non-existing project dropped properly")
def test_react_for_user_project():
"""
Then make sure that project react messages for existing user queued properly.
"""
dest_addr = "docs.index@test_user2.%s" % host
client.begin()
client.say(dest_addr, "Test project react messages for existing user queued properly")
| from nose.tools import *
from lamson.testing import *
import os
from lamson import server
relay = relay(port=8823)
client = RouterConversation("queuetester@localhost", "requests_tests")
confirm_format = "testing-confirm-[0-9]+@"
noreply_format = "testing-noreply@"
host = "localhost"
def test_react_for_existing_project():
"""
Then make sure that project react messages for existing project queued properly.
"""
dest_addr = "docs.index@test.%s" % host
client.begin()
client.say(dest_addr, "Test project react messages for existing project queued properly")
def test_react_for_bad_project():
"""
Then make sure that project react messages for non-existing project dropped properly.
"""
dest_addr = "docs.index@badproject.%s" % host
client.begin()
client.say(dest_addr, "Test project react messages for non-existing project dropped properly")
|
Remove superfluous parens; catch timeout | #!/usr/bin/env python
"""Collection of module netural utility functions"""
from sys import stderr
from ssl import SSLError
from socket import timeout
try:
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
from urllib2 import urlopen, HTTPError, URLError
class HTMLGetError(Exception):
pass
def get_html(url):
try:
html = urlopen(url)
except (HTTPError, URLError, SSLError, timeout) as err:
raise HTMLGetError(err)
return html.read().decode('utf-8')
def progress_msg(processed, total):
"""Update user on percent done"""
if total > 1:
percent = int((float(processed) / total) * 100)
stderr.write(
"\r[%d/%d] %d%%" % (processed, total, percent)
)
stderr.flush()
| #!/usr/bin/env python
"""Collection of module netural utility functions"""
from sys import stderr
from ssl import SSLError
try:
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
from urllib2 import urlopen, HTTPError, URLError
class HTMLGetError(Exception):
pass
def get_html(url):
try:
html = urlopen(url)
except (HTTPError, URLError, SSLError) as err:
raise(HTMLGetError(err))
return html.read().decode('utf-8')
def progress_msg(processed, total):
"""Update user on percent done"""
if total > 1:
percent = int((float(processed) / total) * 100)
stderr.write(
"\r[%d/%d] %d%%" % (processed, total, percent)
)
stderr.flush()
|
Use terminal md5 for perf | #coding:utf-8
import os
import cStringIO
import gzip
import hashlib
import subprocess
from cactus.utils.helpers import checksum
class FakeTime:
"""
Monkey-patch gzip.time to avoid changing files every time we deploy them.
"""
def time(self):
return 1111111111.111
def compressString(s):
"""Gzip a given string."""
gzip.time = FakeTime()
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)
zfile.write(s)
zfile.close()
return zbuf.getvalue()
def fileSize(num):
for x in ['b', 'kb', 'mb', 'gb', 'tb']:
if num < 1024.0:
return "%.0f%s" % (num, x)
num /= 1024.0
def calculate_file_checksum(path):
"""
Calculate the MD5 sum for a file (needs to fit in memory)
"""
# with open(path, 'rb') as f:
# return checksum(f.read())
output = subprocess.check_output(["md5", path])
md5 = output.split(" = ")[1].strip()
return md5
def file_changed_hash(path):
info = os.stat(path)
hashKey = str(info.st_mtime) + str(info.st_size)
return checksum(hashKey) | #coding:utf-8
import os
import cStringIO
import gzip
import hashlib
from cactus.utils.helpers import checksum
class FakeTime:
"""
Monkey-patch gzip.time to avoid changing files every time we deploy them.
"""
def time(self):
return 1111111111.111
def compressString(s):
"""Gzip a given string."""
gzip.time = FakeTime()
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)
zfile.write(s)
zfile.close()
return zbuf.getvalue()
def fileSize(num):
for x in ['b', 'kb', 'mb', 'gb', 'tb']:
if num < 1024.0:
return "%.0f%s" % (num, x)
num /= 1024.0
def calculate_file_checksum(path):
"""
Calculate the MD5 sum for a file (needs to fit in memory)
"""
with open(path, 'rb') as f:
return checksum(f.read())
def file_changed_hash(path):
info = os.stat(path)
hashKey = str(info.st_mtime) + str(info.st_size)
return checksum(hashKey) |
Add Google Analytics to each angular page viewed | 'use strict';
/**
* Main module of the application.
*/
angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate',
'ngResource',
'ui.bootstrap'
])
.run(['$rootScope', '$state', '$stateParams', '$location', function ($rootScope, $state, $stateParams, $location) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
/*// Hookup Google Analytics for sub pages when viewed.
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});*/
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
});
}]); | 'use strict';
/**
* Main module of the application.
*/
angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate',
'ngResource',
'ui.bootstrap'
])
.run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
});
}]); |
Fix warning assertion in credentials test
This commit fixes a warning assertion in a credentials test now that we
are stricter about warning message assertions. | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cloud.aws;
import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
public class EnvironmentCredentialsTests extends ESTestCase {
public void test() {
AWSCredentialsProvider provider =
InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
// NOTE: env vars are setup by the test runner in gradle
assertEquals("env_access", provider.getCredentials().getAWSAccessKeyId());
assertEquals("env_secret", provider.getCredentials().getAWSSecretKey());
assertWarnings("Supplying S3 credentials through environment variables is deprecated. "
+ "See the breaking changes lists in the documentation for details.");
}
}
| /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cloud.aws;
import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
public class EnvironmentCredentialsTests extends ESTestCase {
public void test() {
AWSCredentialsProvider provider =
InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
// NOTE: env vars are setup by the test runner in gradle
assertEquals("env_access", provider.getCredentials().getAWSAccessKeyId());
assertEquals("env_secret", provider.getCredentials().getAWSSecretKey());
assertWarnings("Supplying S3 credentials through environment variables is deprecated");
}
}
|
Add working_dir and copy_steps options | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
| from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
Fix queries and path to templates | from app import app
from app.models import Post
from flask import render_template
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
if posts:
pagination = posts.paginate(page=page, per_page=Post.PER_PAGE)
return render_template('blog.html', pagination=pagination)
@app.route('/archive')
def archive():
"""View an overview of all visible posts."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
return render_template('archive.html', posts=posts)
@app.route('/<path:slug>', methods=['GET', 'POST'])
def detail(slug):
"""View details of post with specified slug."""
post = Post.query.filter_by(visible=True, slug=slug) \
.first_or_404()
return render_template('detail.html', post=post)
| from app import app
from app.models import Post
from flask import render_template
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by_latest()
if posts:
pagination = posts.paginate(page=page, per_page=Post.PER_PAGE)
return render_template('frontend/blog.html', pagination=pagination)
@app.route('/archive')
def archive():
"""View an overview of all visible posts."""
posts = Post.query.filter_by_latest()
return render_template('frontend/archive.html', posts=posts)
@app.route('/<path:slug>', methods=['GET', 'POST'])
def detail(slug):
"""View details of post with specified slug."""
post = Post.query.slug_or_404(slug)
return render_template('frontend/detail.html', post=post)
|
Test whether Z3Java can be loaded in a simpler way. | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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.
*/
package org.sosy_lab.solver.z3java;
import org.junit.Test;
import org.sosy_lab.solver.SolverContextFactory;
import org.sosy_lab.solver.SolverContextFactory.Solvers;
public class Z3JavaLoadingTest {
@Test
@SuppressWarnings("CheckReturnValue")
public void testErrorHandling() throws Exception {
// Test that Z3Java can be loaded correctly.
SolverContextFactory.createSolverContext(Solvers.Z3JAVA);
}
}
| /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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.
*/
package org.sosy_lab.solver.z3java;
import org.junit.Test;
import org.sosy_lab.solver.SolverContextFactory.Solvers;
import org.sosy_lab.solver.test.SolverBasedTest0;
public class Z3JavaLoadingTest extends SolverBasedTest0 {
@Override
protected Solvers solverToUse() {
return Solvers.Z3JAVA;
}
@Test(expected = Exception.class)
@SuppressWarnings("CheckReturnValue")
public void testErrorHandling() throws Exception {
// Will exit(1) without an exception handler.
rmgr.makeNumber("not-a-number");
}
}
|
Set action rules kind to 'on_time' | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 HBEE (http://www.hbee.eu)
# @author: Paulius Sladkevičius <paulius@hbee.eu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
"UPDATE base_action_rule SET kind = 'on_create_or_write', "
"filter_pre_id = null, trg_date_id = null, trg_date_range = null, "
"trg_date_range_type = null where trg_date_id = null"
)
cr.exceute(
"UPDATE base_action_rule SET kind = 'on_time', "
"filter_pre_id = null where trg_date_id != null"
)
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 HBEE (http://www.hbee.eu)
# @author: Paulius Sladkevičius <paulius@hbee.eu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
"UPDATE base_action_rule SET kind = 'on_create_or_write', "
"filter_pre_id = null, trg_date_id = null, trg_date_range = null, "
"trg_date_range_type = null"
)
|
Use ->write() instead of echo | <?php
namespace Bendihossan\Pinfo\Command;
use Console_Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Bendihossan\Pinfo\Command\PinfoCommand;
class ExtensionsCommand extends PinfoCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('pinfo:exts')
->setDescription('Lists your PHP extensions.')
->setHelp('The <info>pinfo:env</info> lists your environment specific info')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->newSection("Loaded Extensions", $output);
$extensions = get_loaded_extensions();
// Sort an array using a case insensitive "natural order" algorithm
natcasesort($extensions);
$table = new Console_Table();
$table->setHeaders(array('Ext. Name'));
foreach ($extensions as $extension) {
$table->addRow(array($extension));
}
$output->write($table->getTable());
print "\n";
}
}
| <?php
namespace Bendihossan\Pinfo\Command;
use Console_Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Bendihossan\Pinfo\Command\PinfoCommand;
class ExtensionsCommand extends PinfoCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('pinfo:exts')
->setDescription('Lists your PHP extensions.')
->setHelp('The <info>pinfo:env</info> lists your environment specific info')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->newSection("Loaded Extensions", $output);
$extensions = get_loaded_extensions();
// Sort an array using a case insensitive "natural order" algorithm
natcasesort($extensions);
$table = new Console_Table();
$table->setHeaders(array('Ext. Name'));
foreach ($extensions as $extension) {
$table->addRow(array($extension));
}
echo $table->getTable();
print "\n";
}
}
|
Remove @override on createJSModules for latest RN version | package com.devfd.RNGeocoder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNGeocoderPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new RNGeocoderModule(reactContext)
);
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
| package com.devfd.RNGeocoder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNGeocoderPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new RNGeocoderModule(reactContext)
);
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Change type from text to UnicodeText | from sqlalchemy import ForeignKey, Column, UnicodeText
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
DeclarativeBase = declarative_base()
class MailModel(DeclarativeBase):
__tablename__ = 'mailtemplates_mail_models'
_id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(128), unique=True, nullable=False)
usage = Column(UnicodeText, nullable=False)
class TemplateTranslation(DeclarativeBase):
__tablename__ = 'mailtemplates_template_translations'
_id = Column(Integer, autoincrement=True, primary_key=True)
mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel)))
mail_model = relation(MailModel, backref=backref('template_translations'))
language = Column(Unicode(128), nullable=False)
subject = Column(Unicode(500))
body = Column(UnicodeText())
| from sqlalchemy import ForeignKey, Column
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
DeclarativeBase = declarative_base()
class MailModel(DeclarativeBase):
__tablename__ = 'mailtemplates_mail_models'
_id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(128), unique=True, nullable=False)
usage = Column(Text(), nullable=False)
class TemplateTranslation(DeclarativeBase):
__tablename__ = 'mailtemplates_template_translations'
_id = Column(Integer, autoincrement=True, primary_key=True)
mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel)))
mail_model = relation(MailModel, backref=backref('template_translations'))
language = Column(Unicode(128), nullable=False)
subject = Column(Unicode(500))
body = Column(Text())
|
Use option.text instead of option.label. | /**
* Patterns checkedflag - Add checked flag to checkbox labels
*
* Copyright 2013 Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"../registry",
"../utils"
], function($, patterns, utils) {
var select_option = {
name: "select-option",
trigger: "label select",
init: function($el) {
return $el
.on("change.pat-select-option", select_option._onChange)
.trigger("change");
},
destroy: function($el) {
return $el.off(".pat-select-option");
},
_onChange: function() {
var label = utils.findLabel(this);
if (label!==null) {
var title = (this.selectedIndex===-1) ? "" : this.options[this.selectedIndex].text;
label.setAttribute("data-option", title);
}
}
};
patterns.register(select_option);
return select_option;
});
| /**
* Patterns checkedflag - Add checked flag to checkbox labels
*
* Copyright 2013 Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"../registry",
"../utils"
], function($, patterns, utils) {
var select_option = {
name: "select-option",
trigger: "label select",
init: function($el) {
return $el
.on("change.pat-select-option", select_option._onChange)
.trigger("change");
},
destroy: function($el) {
return $el.off(".pat-select-option");
},
_onChange: function() {
var label = utils.findLabel(this);
if (label!==null) {
var title = (this.selectedIndex===-1) ? "" : this.options[this.selectedIndex].label;
label.setAttribute("data-option", title);
}
}
};
patterns.register(select_option);
return select_option;
});
|
Fix mutation not returning person | import { Likes } from '../collections';
import { swapiLoader, peopleUrl } from './swapi-loader';
import { pubsub } from './pubsub';
export const resolvers = {
Person: {
id: ({ url }) => url,
name: ({ name }) => name,
likes: ({ url }) => Likes.find({ personId: url }).count(),
films: ({ films }) => swapiLoader.loadMany(films),
},
Film: {
id: ({ url }) => url,
title: ({ title }) => title,
people: ({ characters }) => swapiLoader.loadMany(characters),
},
Query: {
person: (root, { id }) => swapiLoader.load(id),
people: () => swapiLoader.load(peopleUrl),
},
Mutation: {
likePerson: (root, { id }) => {
Likes.insert({ personId: id });
return swapiLoader.load(id).then((likePerson) => {
pubsub.publish('likePerson', { likePerson });
return likePerson;
});
},
},
};
| import { Likes } from '../collections';
import { swapiLoader, peopleUrl } from './swapi-loader';
import { pubsub } from './pubsub';
export const resolvers = {
Person: {
id: ({ url }) => url,
name: ({ name }) => name,
likes: ({ url }) => Likes.find({ personId: url }).count(),
films: ({ films }) => swapiLoader.loadMany(films),
},
Film: {
id: ({ url }) => url,
title: ({ title }) => title,
people: ({ characters }) => swapiLoader.loadMany(characters),
},
Query: {
person: (root, { id }) => swapiLoader.load(id),
people: () => swapiLoader.load(peopleUrl),
},
Mutation: {
likePerson: (root, { id }) => {
Likes.insert({ personId: id });
swapiLoader.load(id).then((person) => {
pubsub.publish('likePerson', { likePerson: person });
return person;
});
},
},
};
|
Make event type more explicit in examples | package eventstore.j.examples;
import eventstore.EventData;
import eventstore.j.EventDataBuilder;
import java.util.UUID;
public class EventDataBuilderExample {
final EventData empty = new EventDataBuilder("eventType").build();
final EventData binary = new EventDataBuilder("eventType")
.eventId(UUID.randomUUID())
.data(new byte[]{1, 2, 3, 4})
.metadata(new byte[]{5, 6, 7, 8})
.build();
final EventData string = new EventDataBuilder("eventType")
.eventId(UUID.randomUUID())
.data("data")
.metadata("metadata")
.build();
final EventData json = new EventDataBuilder("eventType")
.eventId(UUID.randomUUID())
.jsonData("{\"data\":\"data\"}")
.jsonMetadata("{\"metadata\":\"metadata\"}")
.build();
}
| package eventstore.j.examples;
import eventstore.EventData;
import eventstore.j.EventDataBuilder;
import java.util.UUID;
public class EventDataBuilderExample {
final EventData empty = new EventDataBuilder("empty").build();
final EventData binary = new EventDataBuilder("binary")
.eventId(UUID.randomUUID())
.data(new byte[]{1, 2, 3, 4})
.metadata(new byte[]{5, 6, 7, 8})
.build();
final EventData string = new EventDataBuilder("string")
.eventId(UUID.randomUUID())
.data("data")
.metadata("metadata")
.build();
final EventData json = new EventDataBuilder("json")
.eventId(UUID.randomUUID())
.jsonData("{\"data\":\"data\"}")
.jsonMetadata("{\"metadata\":\"metadata\"}")
.build();
} |
Add self instantiation, prevents possible reference conflicts | /**
* Module dependencies
*/
var assert = require('assert');
/**
* Expose 'foyer'
*/
module.exports = foyer;
/**
* Foyer
*
* @param {Function[]} tasks
* @param {Function} cb
* @api public
*/
function foyer(tasks, cb) {
if (!(this instanceof foyer)) return new foyer(tasks, cb);
assert('[object Array]' == Object.prototype.toString.call(tasks), 'Tasks must be an array of functions');
cb = cb || function(){};
var done = false;
var results = [];
var errors = [];
var index = 0;
function next() {
var i = index++;
var fn = tasks[i];
if (!fn) return;
try{
fn(callback)
} catch(err) {
callback(err)
}
function callback(err, res) {
if (done) return;
if (err) {
done = true;
return cb(err);
}
results[i] = res;
errors[i] = err;
if(index == tasks.length) cb(errors, results);
}
}
for (var i = 0; i < tasks.length; i++) {
next();
}
return this;
} | /**
* Module dependencies
*/
var assert = require('assert');
/**
* Expose 'foyer'
*/
module.exports = foyer;
/**
* Foyer
*
* @param {Function[]} tasks
* @param {Function} cb
* @api public
*/
function foyer(tasks, cb) {
assert('[object Array]' == Object.prototype.toString.call(tasks), 'Tasks must be an array of functions');
cb = cb || function(){};
var done = false;
var results = [];
var errors = [];
var index = 0;
function next() {
var i = index++;
var fn = tasks[i];
if (!fn) return;
try{
fn(callback)
} catch(err) {
callback(err)
}
function callback(err, res) {
if (done) return;
if (err) return done = true, cb(err);
results[i] = res;
errors[i] = err;
if(index == tasks.length) cb(errors, results);
}
}
for (var i = 0; i < tasks.length; i++) {
next();
}
return this;
} |
Change required privilege of DeleteJobAction (SERVER_OPERATION -> PROCESS_MANAGE) | <?php
class DeleteJobAction extends ApiActionBase
{
protected static $required_privileges = array(Auth::PROCESS_MANAGE);
protected static $rules = array(
'jobID' => array('type' => 'int', 'required' => true)
);
protected function execute($params)
{
$pdo = DBConnector::getConnection();
$pdo->beginTransaction();
$target = new Job($params['jobID']);
if (!isset($target->job_id))
throw new ApiOperationException('Target job not found (may be already deleted).');
if ($target->status == Job::JOB_NOT_ALLOCATED)
{
Job::delete($target->job_id);
CadResult::delete($target->job_id);
}
else
{
throw new ApiOperationException(
'The target job can not be deleted (status: ' . $target->status . ')');
}
$pdo->commit();
return null;
}
} | <?php
class DeleteJobAction extends ApiActionBase
{
protected static $required_privileges = array(Auth::SERVER_SETTINGS);
protected static $rules = array(
'jobID' => array('type' => 'int', 'required' => true)
);
protected function execute($params)
{
$pdo = DBConnector::getConnection();
$pdo->beginTransaction();
$target = new Job($params['jobID']);
if (!isset($target->job_id))
throw new ApiOperationException('Target job not found (may be already deleted).');
if ($target->status == Job::JOB_NOT_ALLOCATED)
{
Job::delete($target->job_id);
CadResult::delete($target->job_id);
}
else
{
throw new ApiOperationException(
'The target job can not be deleted (status: ' . $target->status . ')');
}
$pdo->commit();
return null;
}
} |
Send default_currency in Client init on client test | import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
'default_currency': 'GBP'
}
def setUp(self):
self.client = Client(env='live', **self.DUMMY_CREDENTIALS)
def test_env(self):
self.assertEqual(Client.ENDPOINTS.keys(), ['live', 'sandbox'])
for env, endpoint_url in Client.ENDPOINTS.iteritems():
client = Client(env=env, **self.DUMMY_CREDENTIALS)
self.assertEqual(client.endpoint_url, endpoint_url)
| import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
}
def setUp(self):
self.client = Client(env='live', **self.DUMMY_CREDENTIALS)
def test_env(self):
self.assertEqual(Client.ENDPOINTS.keys(), ['live', 'sandbox'])
for env, endpoint_url in Client.ENDPOINTS.iteritems():
client = Client(env=env, **self.DUMMY_CREDENTIALS)
self.assertEqual(client.endpoint_url, endpoint_url)
|
Revert "ACalc: Increased minimum and starting calculator size."
This reverts commit 1747c7b05b30630358a58603da0d1878cf9b2a57. | /**
* @license
* Copyright 2014 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.
*/
function launchCalc() {
chrome.app.window.create('AppCalc.html', {
id: 'Calculator',
innerBounds: {
minWidth: 330,
minHeight: 340,
width: 350,
height: 450
}
});
}
chrome.app.runtime.onLaunched.addListener(launchCalc);
| /**
* @license
* Copyright 2014 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.
*/
function launchCalc() {
chrome.app.window.create('AppCalc.html', {
id: 'Calculator',
innerBounds: {
minWidth: 510,
minHeight: 440,
width: 500,
height: 600
}
});
}
chrome.app.runtime.onLaunched.addListener(launchCalc);
|
Add comment describing url prefixes | import {has, type} from 'ramda';
/*
* requests_pathname_prefix is the new config parameter introduced in
* dash==0.18.0. The previous versions just had url_base_pathname
*/
export function urlBase(config) {
if (type(config) === "Null" ||
(type(config) === "Object") &&
!has('url_base_pathname', config) &&
!has('requests_pathname_prefix', config)) {
throw new Error(`
Trying to make an API request but "url_base_pathname" and
"requests_pathname_prefix"
is not in \`config\`. \`config\` is: `, config);
} else if (has('url_base_pathname', config) &&
!has('requests_pathname_prefix', config)) {
return config.url_base_pathname;
} else if (has('requests_pathname_prefix', config)) {
return config.requests_pathname_prefix;
} else {
throw new Error(
`Unhandled case trying to get url_base_pathname or
requests_pathname_prefix from config`, config);
}
}
| import {has, type} from 'ramda';
export function urlBase(config) {
if (type(config) === "Null" ||
(type(config) === "Object") &&
!has('url_base_pathname', config) &&
!has('requests_pathname_prefix', config)) {
throw new Error(`
Trying to make an API request but "url_base_pathname" and
"requests_pathname_prefix"
is not in \`config\`. \`config\` is: `, config);
} else if (has('url_base_pathname', config) &&
!has('requests_pathname_prefix', config)) {
return config.url_base_pathname;
} else if (has('requests_pathname_prefix', config)) {
return config.requests_pathname_prefix;
} else {
throw new Error(
`Unhandled case trying to get url_base_pathname or
requests_pathname_prefix from config`, config);
}
}
|
Add pytz as a dependency | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(
name='django-modelcluster',
version='0.5',
description="Django extension to allow working with 'clusters' of models as a single unit, independently of the database",
author='Matthew Westcott',
author_email='matthew.westcott@torchbox.com',
url='https://github.com/torchbox/django-modelcluster',
packages=['modelcluster', 'tests'],
license='BSD',
long_description=open('README.rst').read(),
install_requires=[
"six>=1.6.1",
"pytz>=2015.2",
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
],
)
| #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(
name='django-modelcluster',
version='0.5',
description="Django extension to allow working with 'clusters' of models as a single unit, independently of the database",
author='Matthew Westcott',
author_email='matthew.westcott@torchbox.com',
url='https://github.com/torchbox/django-modelcluster',
packages=['modelcluster', 'tests'],
license='BSD',
long_description=open('README.rst').read(),
install_requires=[
"six>=1.6.1",
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
],
)
|
Mark table cell by data-line | Object.prototype._is_nil = function (name) {
const obj = this; // e.g document
if (obj && obj.$attr) {
return obj.$attr(name)['$nil?']();
}
return true;
};
asciidoctor.Extensions.register(function () {
this.treeProcessor(function () {
const self = this;
const selector = JSON.stringify({
traverse_documents: true
});
self.process(function (parent, reader) {
if (parent._is_nil("apply-data-line"))
return parent;
parent.$find_by(selector).forEach(function (node) {
if (node && node.$source_location) {
if (node.$source_location().lineno) {
var nodeName = node.node_name;
var lineno = node.$source_location().lineno;
node['$add_role']("data-line-" + lineno);
}
}
});
return parent;
});
});
});
| Object.prototype._is_nil = function (name) {
const obj = this; // e.g document
if (obj && obj.$attr) {
return obj.$attr(name)['$nil?']();
}
return true;
};
asciidoctor.Extensions.register(function () {
this.treeProcessor(function () {
const self = this;
self.process(function (parent, reader) {
if (parent._is_nil("apply-data-line"))
return parent;
parent.$find_by().forEach(function (node) {
if (node && node.$source_location) {
if (node.$source_location().lineno) {
var nodeName = node.node_name;
var lineno = node.$source_location().lineno;
node['$add_role']("data-line-" + lineno);
}
}
});
return parent;
});
});
}); |
Raise an exception when request fails.
In general, I think that it is safer to raise an exception when an HTTP
request used to fetch a page fails. | import requests
class BasePage:
def __init__(self, data):
self.data = data
@classmethod
def from_file(cls, path):
with open(path) as f:
raw = f.read()
return cls(raw)
@classmethod
def from_url(cls, url):
res = requests.get(url)
res.raise_for_status()
return cls(res.text)
def int_or_none(blob):
try:
return int(blob)
except ValueError:
return None
def float_or_none(blob):
try:
return float(blob)
except TypeError:
return None
| import requests
class BasePage:
def __init__(self, data):
self.data = data
@classmethod
def from_file(cls, path):
with open(path) as f:
raw = f.read()
return cls(raw)
@classmethod
def from_url(cls, url):
res = requests.get(url)
return cls(res.text)
def int_or_none(blob):
try:
return int(blob)
except ValueError:
return None
def float_or_none(blob):
try:
return float(blob)
except TypeError:
return None
|
Append to log file instead of overwrite it | <?php
function debug_collectionInfoStart($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data\n";
}
}
function debug_collectionInfoEnd($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Finished collecting data\n";
}
}
function debug_collectionInterval($debug, $interval) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data every ".$interval." seconds\n\n";
}
}
function debug($echo, $log) {
if ($echo != "" && $echo !== NULL) {
echo $echo;
}
if ($log == TRUE) {
file_put_contents("logs/collect.log", $echo, FILE_APPEND);
}
}
?> | <?php
function debug_collectionInfoStart($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data\n";
}
}
function debug_collectionInfoEnd($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Finished collecting data\n";
}
}
function debug_collectionInterval($debug, $interval) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data every ".$interval." seconds\n\n";
}
}
function debug($echo, $log) {
if ($echo != "" && $echo !== NULL) {
echo $echo;
}
if ($log == TRUE) {
file_put_contents("logs/collect.log", $echo);
}
}
?> |
Add completion log message to the background task | from heltour.tournament.models import *
from heltour.tournament import lichessapi
from heltour.celery import app
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
# Disabled for now because of rate-limiting
lichess_teams = [] # ['lichess4545-league']
@app.task(bind=True)
def update_player_ratings(self):
players = Player.objects.all()
player_dict = {p.lichess_username: p for p in players}
# Query players from the bulk user endpoint based on our lichess teams
for team_name in lichess_teams:
for username, rating, games_played in lichessapi.enumerate_user_classical_rating_and_games_played(team_name, 0):
# Remove the player from the dict
p = player_dict.pop(username, None)
if p is not None:
p.rating, p.games_played = rating, games_played
p.save()
# Any players not found above will be queried individually
for username, p in player_dict.items():
try:
p.rating, p.games_played = lichessapi.get_user_classical_rating_and_games_played(username, 0)
p.save()
except Exception as e:
logger.warning('Error getting rating for %s: %s' % (username, e))
logger.info('Updated ratings for %d players', len(players))
| from heltour.tournament.models import *
from heltour.tournament import lichessapi
from heltour.celery import app
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
# Disabled for now because of rate-limiting
lichess_teams = [] # ['lichess4545-league']
@app.task(bind=True)
def update_player_ratings(self):
players = Player.objects.all()
player_dict = {p.lichess_username: p for p in players}
# Query players from the bulk user endpoint based on our lichess teams
for team_name in lichess_teams:
for username, rating, games_played in lichessapi.enumerate_user_classical_rating_and_games_played(team_name, 0):
# Remove the player from the dict
p = player_dict.pop(username, None)
if p is not None:
p.rating, p.games_played = rating, games_played
p.save()
# Any players not found above will be queried individually
for username, p in player_dict.items():
try:
p.rating, p.games_played = lichessapi.get_user_classical_rating_and_games_played(username, 0)
p.save()
except Exception as e:
logger.warning('Error getting rating for %s: %s' % (username, e))
return len(players)
|
Add greedSpread to Run Model | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var runSchema = new Schema({
time: Date,
participants: [ String ],
results: [{
season: Number,
fishStart: Number,
fishEnd: Number,
groupRestraint: Number,
groupEfficiency: Number,
fishers: [{
name: String,
type: {type: String},
fishTaken: Number,
profit: Number,
greed: Number,
greedSpread: Number,
individualRestraint: Number,
individualEfficiency: Number
}]
}],
log: [ String ],
microworld: {}
});
exports.Run = mongoose.model('Run', runSchema);
| 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var runSchema = new Schema({
time: Date,
participants: [ String ],
results: [{
season: Number,
fishStart: Number,
fishEnd: Number,
groupRestraint: Number,
groupEfficiency: Number,
fishers: [{
name: String,
type: {type: String},
fishTaken: Number,
profit: Number,
greed: Number,
individualRestraint: Number,
individualEfficiency: Number
}]
}],
log: [ String ],
microworld: {}
});
exports.Run = mongoose.model('Run', runSchema);
|
Add APL2 header and fix a typo. | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.lang;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation to hold the groovydoc for the annotated element at runtime, we call it "Runtime Groovydoc".
* Runtime Groovydoc is a bit like Python's Documentation Strings and will be useful for IDE and developers who set a high value on documentations.
*
* The usage is very simple, just place @Groovydoc at the beginning of the content of groovydoc, then the new parser Parrot will attach the annotation Groovydoc automatically
*
* @since 3.0.0
*/
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Groovydoc {
String value();
}
| package groovy.lang;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation to hold the groovydoc for the annotated element at runtime, we can it "Runtime Groovydoc".
* Runtime Groovydoc is a bit like Python's Documentation Strings and will be useful for IDE and developers who set a high value on documentations.
*
* The usage is very simple, just place @Groovydoc at the beginning of the content of groovydoc, then the new parser Parrot will attach the annotation Groovydoc automatically
*
* @since 3.0.0
*/
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Groovydoc {
String value();
}
|
Set properties to be public | <?php
namespace OAuth2\Client\Provider;
class User implements \IteratorAggregate {
public $uid = null;
public $nickname = null;
public $name = null;
public $firstName = null;
public $lastName = null;
public $email = null;
public $location = null;
public $description = null;
public $imageUrl = null;
public $urls = null;
public function __set($name, $value)
{
if (isset($this->{$name})) {
$this->{$name} = $value;
}
}
public function __get($name)
{
if (isset($this->{$name})) {
return $this->{$name};
} else {
return null;
}
}
public function getIterator()
{
return new \ArrayIterator($this);
}
}
| <?php
namespace OAuth2\Client\Provider;
class User implements \IteratorAggregate {
protected $uid = null;
protected $nickname = null;
protected $name = null;
protected $firstName = null;
protected $lastName = null;
protected $email = null;
protected $location = null;
protected $description = null;
protected $imageUrl = null;
protected $urls = null;
public function __set($name, $value)
{
if (isset($this->{$name})) {
$this->{$name} = $value;
}
}
public function __get($name)
{
if (isset($this->{$name})) {
return $this->{$name};
} else {
return null;
}
}
public function getIterator()
{
return new \ArrayIterator($this);
}
}
|
Update point to fix equality problems. | package com.censoredsoftware.library.schematic;
import java.util.Objects;
public class Point {
private final int X, Y, Z;
private final World world;
public Point(int X, int Y, int Z, World world) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.world = world;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public int getZ() {
return Z;
}
public World getWorld() {
return world;
}
public Point add(int X, int Y, int Z) {
return new Point(this.X + X, this.Y + Y, this.Z + Z, world);
}
@Override
public boolean equals(Object obj) {
return obj instanceof Point && ((Point) obj).X == X && ((Point) obj).Y == Y && ((Point) obj).Z == Z && ((Point) obj).world.getName().equals(world.getName());
}
@Override
public int hashCode() {
return Objects.hash(X, Y, Z, world.getName());
}
}
| package com.censoredsoftware.library.schematic;
public class Point {
private final int X, Y, Z;
private final World world;
public Point(int X, int Y, int Z, World world) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.world = world;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public int getZ() {
return Z;
}
public World getWorld() {
return world;
}
public Point add(int X, int Y, int Z) {
return new Point(this.X + X, this.Y + Y, this.Z + Z, world);
}
}
|
Make minor improvements to comments and formatting | #!/usr/bin/env python
import turtle
def draw_initials():
"""Draw the initials BC"""
# Set up screen, etc.
window = turtle.Screen()
window.bgcolor('gray')
letter = turtle.Turtle()
letter.shape('turtle')
letter.color('white', 'gray')
letter.speed(8)
# Move pen into place
letter.penup()
letter.left(180)
letter.forward(200)
letter.pendown()
# Draw the letter B
letter.right(90)
letter.forward(240)
letter.right(90)
letter.forward(65)
letter.circle(-55, 180)
letter.forward(65)
letter.left(180)
letter.forward(75)
letter.circle(-65, 180)
letter.forward(75)
# Move pen into place
letter.penup()
letter.right(180)
letter.forward(150)
letter.left(90)
letter.forward(240)
letter.right(90)
letter.forward(190)
letter.right(90)
letter.forward(80)
letter.pendown()
# Draw the letter C
letter.circle(-80, -180)
letter.right(180)
letter.forward(81)
letter.circle(80, 180)
# Hide turtle and exit drawing window
letter.hideturtle()
window.exitonclick()
draw_initials()
| import turtle
def draw_initials():
#Set up screen, etc.
window = turtle.Screen()
window.bgcolor('gray')
###THE LETTER B###
letter = turtle.Turtle()
letter.shape('turtle')
letter.color('white', 'gray')
letter.speed(8)
#Move pen into place
letter.penup()
letter.left(180)
letter.forward(200)
letter.pendown()
#Draw the letter B
letter.right(90)
letter.forward(240)
letter.right(90)
letter.forward(65)
letter.circle(-55,180)
letter.forward(65)
letter.left(180)
letter.forward(75)
letter.circle(-65, 180)
letter.forward(75)
#Move pen into place
letter.penup()
letter.right(180)
letter.forward(150)
letter.left(90)
letter.forward(240)
letter.right(90)
letter.forward(190)
letter.right(90)
letter.forward(80)
letter.pendown()
#Draw the letter C
letter.circle(-80,-180)
letter.right(180)
letter.forward(81)
letter.circle(80,180)
#Hide turtle and exit drawing window
letter.hideturtle()
window.exitonclick()
draw_initials()
|
cliedit: Fix the completion test case. | package cliedit
import (
"testing"
"github.com/elves/elvish/cli/el/codearea"
"github.com/elves/elvish/edit/ui"
"github.com/elves/elvish/eval"
"github.com/elves/elvish/styled"
"github.com/elves/elvish/util"
)
func TestCompletion(t *testing.T) {
_, cleanupDir := eval.InTempHome()
util.ApplyDir(util.Dir{"a": "", "b": ""})
defer cleanupDir()
ed, ttyCtrl, ev, _, cleanup := setupStarted()
defer cleanup()
ed.app.CodeArea().MutateState(func(s *codearea.State) {
s.CodeBuffer.InsertAtDot("echo ")
})
evalf(ev, "edit:completion:start")
wantBuf := ui.NewBufferBuilder(40).
WriteStyled(styled.MarkLines(
"~> echo a ", styles,
" gggg --",
"COMPLETING argument ", styles,
"mmmmmmmmmmmmmmmmmmm ")).
SetDotToCursor().
Newline().
WriteStyled(styled.MarkLines(
"a b", styles,
"# ",
)).
Buffer()
ttyCtrl.TestBuffer(t, wantBuf)
}
| package cliedit
import (
"testing"
"github.com/elves/elvish/cli/el/codearea"
"github.com/elves/elvish/edit/ui"
"github.com/elves/elvish/eval"
"github.com/elves/elvish/styled"
"github.com/elves/elvish/util"
)
func TestCompletion(t *testing.T) {
_, cleanupDir := eval.InTempHome()
util.ApplyDir(util.Dir{"a": "", "b": ""})
defer cleanupDir()
ed, ttyCtrl, ev, _, cleanup := setupStarted()
defer cleanup()
ed.app.CodeArea().MutateState(func(s *codearea.State) {
s.CodeBuffer.InsertAtDot("echo ")
})
evalf(ev, "edit:completion:start")
wantBuf := ui.NewBufferBuilder(40).
WriteStyled(styled.MarkLines(
"~> echo a ", styles,
" --",
"COMPLETING argument ", styles,
"mmmmmmmmmmmmmmmmmmm ")).
SetDotToCursor().
Newline().
WriteStyled(styled.MarkLines(
"a b", styles,
"# ",
)).
Buffer()
ttyCtrl.TestBuffer(t, wantBuf)
}
|
Make tab widgets look good on ElementaryOS.
Any other linux distribution will probably look bad because of this. In
the future a better solution must be found to styling the background of
a widget inside a scrollarea inside a tabwidget. | """
Style
Contains convenience functions for styling widgets.
:Authors:
Berend Klein Haneveld
"""
import sys
def styleWidgetForTab(widget):
"""
This function style a widget that can be used inside a QScrollArea that
is inside a QTabWidget. On OS X the background color inside a tab
widget is slightly darker than the default, so it has to be styled
otherwise it would stand out.
There is a bug in Qt where QComboBox will not render properly
on OS X when the background style of a parent is adjusted.
In order to solve this, the background style of such a widget
should only be set for that object, so by naming it and setting
the style only for objects with that name the bug can be worked
around.
Use this function whenever a (container) widget is needed inside a
QScrollArea in a QTabWidget.
:type widget: QWidget
"""
if sys.platform.startswith("darwin"):
widget.setObjectName("tabWidget")
widget.setStyleSheet("#tabWidget {background: rgb(229, 229, 229);}")
elif sys.platform.startswith("linux"):
# This makes it look pretty on Elementary theme
widget.setObjectName("tabWidget")
widget.setStyleSheet("#tabWidget {background: rgb(236, 236, 236);}")
| """
Style
Contains convenience functions for styling widgets.
:Authors:
Berend Klein Haneveld
"""
import sys
def styleWidgetForTab(widget):
"""
This function style a widget that can be used inside a QScrollArea that
is inside a QTabWidget. On OS X the background color inside a tab
widget is slightly darker than the default, so it has to be styled
otherwise it would stand out.
There is a bug in Qt where QComboBox will not render properly
on OS X when the background style of a parent is adjusted.
In order to solve this, the background style of such a widget
should only be set for that object, so by naming it and setting
the style only for objects with that name the bug can be worked
around.
Use this function whenever a (container) widget is needed inside a
QScrollArea in a QTabWidget.
:type widget: QWidget
"""
if sys.platform.startswith("darwin"):
widget.setObjectName("tabWidget")
widget.setStyleSheet("#tabWidget {background: rgb(229, 229, 229);}")
|
Remove check for "availability" command because this case is treated separately. | package rabbit;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "security":
switch (tokens[1]) {
case "tls":
return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
case "ecrypt2lvl":
return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
case "open_ports":
return "nmap " + tokens[2];
default :
return null;
}
default :
return null;
}
}
}
| package rabbit;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "availability":
return "nmap -sV " + tokens[1];
case "security":
switch (tokens[1]) {
case "tls":
return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
case "ecrypt2lvl":
return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
case "open_ports":
return "nmap " + tokens[2];
default :
return null;
}
default :
return null;
}
}
}
|
Fix deprecated usage of Ember.observer.
[Fixes #81] | import RecordArray from "./record-array";
/**
@module ember-orbit
*/
var get = Ember.get;
/**
@class FilteredRecordArray
@namespace EO
@extends EO.RecordArray
*/
export default RecordArray.extend({
/**
@method filterFunction
@param {EO.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
},
updateFilter: Ember.observer('filterFunction', function() {
Ember.run.once(this, this._updateFilter);
})
});
| import RecordArray from "./record-array";
/**
@module ember-orbit
*/
var get = Ember.get;
/**
@class FilteredRecordArray
@namespace EO
@extends EO.RecordArray
*/
var FilteredRecordArray = RecordArray.extend({
/**
@method filterFunction
@param {EO.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
},
updateFilter: Ember.observer(function() {
Ember.run.once(this, this._updateFilter);
}, 'filterFunction')
});
export default FilteredRecordArray;
|
Add message if transformer_hash already exists | from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
make_option('--row', action='store', dest='label_row', default=1,
help='Location of the row of labels, defaults to 1'),
)
def handle(self, filename, label_row=1, sheet=None, *args, **kwargs):
reader = transformer.convert_to_csv_reader(filename, sheet=sheet)
for i in range(1, int(label_row)):
reader.next()
labels = reader.next()
transformer_key = transformer.generate_key(labels)
if transformer_key in transformer.TRANSFORMERS.keys():
print transformer_key + ' (exists)'
else:
print transformer_key
| from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
make_option('--row', action='store', dest='label_row', default=1,
help='Location of the row of labels, defaults to 1'),
)
def handle(self, filename, label_row=1, sheet=None, *args, **kwargs):
reader = transformer.convert_to_csv_reader(filename, sheet=sheet)
for i in range(1, int(label_row)):
reader.next()
labels = reader.next()
print transformer.generate_key(labels)
|
Fix potential bug in parameter passing | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
results = self._execute_module(tmp=tmp, task_vars=task_vars)
# Remove special fields from the result, which can only be set
# internally by the executor engine. We do this only here in
# the 'normal' action, as other action plugins may set this.
for field in ('ansible_notify',):
if field in results:
results.pop(field)
return results
| # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
results = self._execute_module(tmp, task_vars=task_vars)
# Remove special fields from the result, which can only be set
# internally by the executor engine. We do this only here in
# the 'normal' action, as other action plugins may set this.
for field in ('ansible_notify',):
if field in results:
results.pop(field)
return results
|
Remove an unused method in FakeResourceTracker
Nothing calls _create and there is no _create in the super class for
this to be overriding.
Change-Id: Ic41f2d249b9aaffb2caaa18dd492924a4ceb3653 | # Copyright (c) 2012 OpenStack Foundation
# 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.
from nova.compute import resource_tracker
class FakeResourceTracker(resource_tracker.ResourceTracker):
"""Version without a DB requirement."""
def _update(self, context):
self._write_ext_resources(self.compute_node)
| # Copyright (c) 2012 OpenStack Foundation
# 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.
from nova.compute import resource_tracker
class FakeResourceTracker(resource_tracker.ResourceTracker):
"""Version without a DB requirement."""
def _create(self, context, values):
self._write_ext_resources(values)
self.compute_node = values
self.compute_node['id'] = 1
def _update(self, context):
self._write_ext_resources(self.compute_node)
|
Fix copy-paste-o in exception message. | from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(request, *args, **kwargs):
if not request.META.get("X_APPENGINE_QUEUENAME"):
return HttpResponseForbidden("Task queue requests only.")
return view_func(request, *args, **kwargs)
return new_view
def cron_only(view_func):
""" View decorator that only allows requests which originate from an App Engine cron.
"""
@wraps(view_func)
def new_view(request, *args, **kwargs):
if not request.META.get("X_APPENGINE_CRON"):
return HttpResponseForbidden("Cron requests only.")
return view_func(request, *args, **kwargs)
return new_view
def gae_admin_only(view_func):
""" View decorator that requires the user to be an administrator of the App Engine app. """
@wraps(view_func)
def new_view(*args, **kwargs):
if not is_current_user_admin():
return HttpResponseForbidden("Admin users only.")
return view_func(*args, **kwargs)
return new_view
| from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(request, *args, **kwargs):
if not request.META.get("X_APPENGINE_QUEUENAME"):
return HttpResponseForbidden("Task queue requests only.")
return view_func(request, *args, **kwargs)
return new_view
def cron_only(view_func):
""" View decorator that only allows requests which originate from an App Engine cron.
"""
@wraps(view_func)
def new_view(request, *args, **kwargs):
if not request.META.get("X_APPENGINE_CRON"):
return HttpResponseForbidden("Cron requests only.")
return view_func(request, *args, **kwargs)
return new_view
def gae_admin_only(view_func):
""" View decorator that requires the user to be an administrator of the App Engine app. """
@wraps(view_func)
def new_view(*args, **kwargs):
if not is_current_user_admin():
return HttpResponseForbidden("Cron requests only.")
return view_func(*args, **kwargs)
return new_view
|
Fix missing svg bug on chrome | var path = require('path');
// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Available modules --------------------------------//
// ---------------------------------------------------------------------------//
module.exports.hello = require('./hello');
// /////////////////////////////////////////////////////////////////////////////
// ----------------------- Node module settings ------------------------------//
// -------------------------- (Do not modify) --------------------------------//
module.exports.scssPath = path.join(__dirname, '../styles');
module.exports.graphicsPath = path.join(__dirname, '../graphics');
module.exports.graphicsMiddleware = function (fs) {
return function (req, res, next) {
var r = new RegExp('/?assets/graphics/(.+)');
var pieces = req.url.match(r);
if (!pieces) return next();
try {
if (pieces[1].match(/\.svgz?$/)) {
res.setHeader('Content-Type', 'image/svg+xml');
}
res.end(fs.readFileSync(path.join(__dirname, '../graphics', pieces[1])));
} catch (e) {
// Nothing to do there.
}
return next();
};
};
| var path = require('path');
// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Available modules --------------------------------//
// ---------------------------------------------------------------------------//
module.exports.hello = require('./hello');
// /////////////////////////////////////////////////////////////////////////////
// ----------------------- Node module settings ------------------------------//
// -------------------------- (Do not modify) --------------------------------//
module.exports.scssPath = path.join(__dirname, '../styles');
module.exports.graphicsPath = path.join(__dirname, '../graphics');
module.exports.graphicsMiddleware = function (fs) {
return function (req, res, next) {
var r = new RegExp('/?assets/graphics/(.+)');
var pieces = req.url.match(r);
if (!pieces) return next();
try {
res.end(fs.readFileSync(path.join(__dirname, '../graphics', pieces[1])));
} catch (e) {
// Nothing to do there.
}
return next();
};
};
|
Use the Accept-Encoding header for the cache key | var SyncCache = require('active-cache/sync');
var filesizeParser = require('filesize-parser');
function key(req) {
return req.z+','+req.x+','+req.y+','+req.layer+','+req.filename+','+req.headers['accept-encoding'];
}
module.exports = function(opts) {
opts = opts || {};
var lruopts = {max: 6};
if (typeof opts.size === 'string') {
lruopts.max = filesizeParser(opts.size);
lruopts.length = function(item){ return item.buffer.length; };
} else if (typeof opts.size === 'number') {
lruopts.max = opts.size;
}
lruopts.maxAge = (opts.ttl || 15) * 1000;
lruopts.interval = opts.clearInterval || 5000;
var cache = new SyncCache(lruopts);
return {
name: 'lru',
get: function(server, req, callback) {
var item = cache.get(key(req));
if (item) return callback(null, item.buffer, item.headers);
callback();
},
set: function(server, req, buffer, headers, callback) {
cache.set(key(req), {buffer: buffer, headers: headers});
callback();
}
};
};
| var SyncCache = require('active-cache/sync');
var filesizeParser = require('filesize-parser');
function key(req) {
return req.z+','+req.x+','+req.y+','+req.layer+','+req.filename;
}
module.exports = function(opts) {
opts = opts || {};
var lruopts = {max: 6};
if (typeof opts.size === 'string') {
lruopts.max = filesizeParser(opts.size);
lruopts.length = function(item){ return item.buffer.length; };
} else if (typeof opts.size === 'number') {
lruopts.max = opts.size;
}
lruopts.maxAge = (opts.ttl || 15) * 1000;
lruopts.interval = opts.clearInterval || 5000;
var cache = new SyncCache(lruopts);
return {
name: 'lru',
get: function(server, req, callback) {
var item = cache.get(key(req));
if (item) return callback(null, item.buffer, item.headers);
callback();
},
set: function(server, req, buffer, headers, callback) {
cache.set(key(req), {buffer: buffer, headers: headers});
callback();
}
};
};
|
Terminate the request after sending. | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simply call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have whipped up for them.
|
*/
$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
| <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simply call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have whipped up for them.
|
*/
$response = $app->make('Illuminate\Contracts\Http\Kernel')->handle(
Illuminate\Http\Request::capture()
);
$response->send();
|
Use parentheses even when constructor take no params | <?php
namespace YUti\OpChecker;
class ValueRepository
{
private $repository;
private static function initialize(ValueRepository $instance)
{
$instance->repository = array_fill_keys(TypeUtil::types(), array());
}
public static function newInstance()
{
$instance = new ValueRepository();
self::initialize($instance);
return $instance;
}
private function __construct()
{
$this->repository = array();
}
public function getByType($type)
{
if ($normalized = TypeUtil::normalize($type)) {
return $this->repository[$normalized];
}
return false;
}
public function put(NamedValue $value)
{
if ($type = $value->getType()) {
$this->repository[$type][$value->getName()] = $value;
}
return $this;
}
}
| <?php
namespace YUti\OpChecker;
class ValueRepository
{
private $repository;
private static function initialize(ValueRepository $instance)
{
$instance->repository = array_fill_keys(TypeUtil::types(), array());
}
public static function newInstance()
{
$instance = new ValueRepository;
self::initialize($instance);
return $instance;
}
private function __construct()
{
$this->repository = array();
}
public function getByType($type)
{
if ($normalized = TypeUtil::normalize($type)) {
return $this->repository[$normalized];
}
return false;
}
public function put(NamedValue $value)
{
if ($type = $value->getType()) {
$this->repository[$type][$value->getName()] = $value;
}
return $this;
}
}
|
Fix deprecated disableClick prop on Dropzone
Ref: https://github.com/react-dropzone/react-dropzone/commit/1402362dd16a349761187a29cca356628b23b798 | import React from "react";
import Dropzone from "react-dropzone";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
return (
<Dropzone
disabled={disabled}
onClick={evt => evt.preventDefault()}
multiple={false}
accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
activeClassName="isActive"
rejectClassName="isRejected"
onDropRejected={() => {
window.toastr.error("Error: Incorrect File Type");
}}
onDrop={this.handleDrop}
{...{ style, className }}
>
<DraggingMessage />
{children}
</Dropzone>
);
}
}
function DraggingMessage() {
return (
<div className="dropzone-dragging-message">
Drop Fasta or Genbank files to view them in the editor. The following
extensions are accepted: .gb .gbk .fasta .fa .gp .txt
</div>
);
}
| import React from "react";
import Dropzone from "react-dropzone";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
return (
<Dropzone
disabled={disabled}
disableClick
multiple={false}
accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
activeClassName="isActive"
rejectClassName="isRejected"
onDropRejected={() => {
window.toastr.error("Error: Incorrect File Type");
}}
onDrop={this.handleDrop}
{...{ style, className }}
>
<DraggingMessage />
{children}
</Dropzone>
);
}
}
function DraggingMessage() {
return (
<div className="dropzone-dragging-message">
Drop Fasta or Genbank files to view them in the editor. The following
extensions are accepted: .gb .gbk .fasta .fa .gp .txt
</div>
);
}
|
Fix bug with arguments handling in JSON API content decorator | from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
| from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
:recycle: Revert password route back to original broken state | <form class="keyboard-save" action="{{ url('auth/password') }}" method="POST" role="form" autocomplete="false" id="passwordUpdate">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="POST">
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">Current Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Current Password">
</div>
</div>
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">New Password</label>
<input type="password" class="form-control" name="new_password" id="new_password" placeholder="New Password">
</div>
</div>
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">Confirm New Password</label>
<input type="password" class="form-control" name="new_password_confirmation" id="new_password_confirmation" placeholder="Confirm New Password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-icon-text"><i class="zmdi zmdi-floppy"></i> Save</button>
<a href="{{ route('admin.profile.index') }}"><button type="button" class="btn btn-link">Cancel</button></a>
</div>
</form>
| <form class="keyboard-save" action="{!! route('canvas.auth.password') !!}" method="POST" role="form" autocomplete="false" id="passwordUpdate">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="POST">
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">Current Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Current Password">
</div>
</div>
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">New Password</label>
<input type="password" class="form-control" name="new_password" id="new_password" placeholder="New Password">
</div>
</div>
<br>
<div class="form-group">
<div class="fg-line">
<label class="fg-label">Confirm New Password</label>
<input type="password" class="form-control" name="new_password_confirmation" id="new_password_confirmation" placeholder="Confirm New Password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-icon-text"><i class="zmdi zmdi-floppy"></i> Save</button>
<a href="{{ route('admin.profile.index') }}"><button type="button" class="btn btn-link">Cancel</button></a>
</div>
</form>
|
Set standard state of wizard to one (so first step automatically starts) | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty
class ToolbarProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._state = 1
self._use_wizard = False
stateChanged = pyqtSignal()
wizardStateChanged = pyqtSignal()
@pyqtProperty(bool,notify = wizardStateChanged)
def wizardActive(self):
return self._use_wizard
@pyqtSlot(bool)
def setWizardState(self, state):
self._use_wizard = state
self.wizardStateChanged.emit()
@pyqtProperty(int,notify = stateChanged)
def state(self):
return self._state
@pyqtSlot(int)
def setState(self, state):
self._state = state
self.stateChanged.emit() | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty
class ToolbarProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._state = 0
self._use_wizard = False
stateChanged = pyqtSignal()
wizardStateChanged = pyqtSignal()
@pyqtProperty(bool,notify = wizardStateChanged)
def wizardActive(self):
return self._use_wizard
@pyqtSlot(bool)
def setWizardState(self, state):
self._use_wizard = state
self.wizardStateChanged.emit()
@pyqtProperty(int,notify = stateChanged)
def state(self):
return self._state
@pyqtSlot(int)
def setState(self, state):
self._state = state
self.stateChanged.emit() |
Correct warning print to only happen if the socket is not available. | import { consola } from './utils';
import initWebSocket from './initWebSocket';
import closeWebSocket from './closeWebSocket';
import * as types from './types';
export * from './types';
const createMiddleware = () => {
let websocket;
return store => next => (action) => {
switch (action.type) {
case types.WEBSOCKET_CONNECT:
websocket = closeWebSocket(websocket);
websocket = initWebSocket(store, action.payload);
return next(action);
case types.WEBSOCKET_SEND:
if (websocket) {
websocket.send(JSON.stringify(action.payload));
} else {
consola.warn('WebSocket is not open. To open, dispatch action WEBSOCKET_CONNECT.');
}
return next(action);
case types.WEBSOCKET_DISCONNECT:
websocket = closeWebSocket(websocket);
return next(action);
default:
return next(action);
}
};
};
export default createMiddleware();
| import { consola } from './utils';
import initWebSocket from './initWebSocket';
import closeWebSocket from './closeWebSocket';
import * as types from './types';
export * from './types';
const createMiddleware = () => {
let websocket;
return store => next => (action) => {
switch (action.type) {
case types.WEBSOCKET_CONNECT:
websocket = closeWebSocket(websocket);
websocket = initWebSocket(store, action.payload);
return next(action);
case types.WEBSOCKET_SEND:
if (websocket) {
websocket.send(JSON.stringify(action.payload));
}
consola.warn('WebSocket is not open. To open, dispatch action WEBSOCKET_CONNECT.');
return next(action);
case types.WEBSOCKET_DISCONNECT:
websocket = closeWebSocket(websocket);
return next(action);
default:
return next(action);
}
};
};
export default createMiddleware();
|
Remove all flowtypes for now | 'use strict'
/* eslint-disable no-param-reassign */
// Replace absolute file paths with <PROJECT_ROOT>
const cwd = process.cwd()
module.exports = {
print (val, serialize) {
if (isPath(val)) {
val = val.split(cwd).join('<PROJECT_ROOT>')
}
else if (val instanceof Error) {
val.message = val.message.split(cwd).join('<PROJECT_ROOT>')
}
else {
Object.keys(val).forEach(key => {
if (isPath(val[key])) {
val[key] = val[key].split(cwd).join('<PROJECT_ROOT>')
}
})
}
return serialize(val)
},
test (val) {
let has = false
if (val instanceof Error && isPath(val.message)) {
has = true
}
else if (val && typeof val === 'object') {
Object.keys(val).forEach(key => {
if (isPath(val[key])) {
has = true
}
})
}
else if (isPath(val)) {
has = true
}
return has
},
}
function isPath (value) {
return typeof value === 'string'
&& value.indexOf(cwd) !== -1
}
| 'use strict'
/* eslint-disable no-param-reassign */
// Replace absolute file paths with <PROJECT_ROOT>
const cwd = process.cwd()
/*::
type Val = string | Object
*/
module.exports = {
print (val/* : Val */, serialize/* : Function */) {
if (isPath(val)) {
val = val.split(cwd).join('<PROJECT_ROOT>')
}
else if (val instanceof Error) {
val.message = val.message.split(cwd).join('<PROJECT_ROOT>')
}
else {
Object.keys(val).forEach(key => {
if (isPath(val[key])) {
val[key] = val[key].split(cwd).join('<PROJECT_ROOT>')
}
})
}
return serialize(val)
},
test (val/* : Val */) {
let has = false
if (val instanceof Error && isPath(val.message)) {
has = true
}
else if (val && typeof val === 'object') {
Object.keys(val).forEach(key => {
if (isPath(val[key])) {
has = true
}
})
}
else if (isPath(val)) {
has = true
}
return has
},
}
function isPath (value) {
return typeof value === 'string'
&& value.indexOf(cwd) !== -1
}
|
Replace exact equality assert with isclose in bands cli | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli,
[
'bands',
'-o', out_file.name,
'-k', os.path.join(samples_dir, 'kpoints.hdf5'),
'-i', os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bs.io.load(out_file.name)
reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5'))
np.testing.assert_allclose(bs.compare.difference(res, reference), 0)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli,
[
'bands',
'-o', out_file.name,
'-k', os.path.join(samples_dir, 'kpoints.hdf5'),
'-i', os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bs.io.load(out_file.name)
reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5'))
assert bs.compare.difference(res, reference) == 0
|
Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3 | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
| # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.