text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add a basic test for client.NewRequest for no payload | package librariesio
import (
"testing"
"time"
)
const APIKey string = "1234"
func TestNewClient(t *testing.T) {
c := NewClient(APIKey)
if got, want := c.apiKey, APIKey; got != want {
t.Errorf("NewClient baseURL is %v, want %v", got, want)
}
if got, want := c.BaseURL.String(), "https://libraries.io/api/"; got != want {
t.Errorf("NewClient baseURL is %v, want %v", got, want)
}
if got, want := c.UserAgent, "go-librariesio/1"; got != want {
t.Errorf("NewClient userAgent is %v, want %v", got, want)
}
if got, want := c.client.Timeout, time.Second*10; got != want {
t.Errorf("NewClient timeout is %v, want %v", got, want)
}
}
func TestNewRequest_noPayload(t *testing.T) {
client := NewClient("")
req, err := client.NewRequest("GET", "pypi/cookiecutter", nil)
if err != nil {
t.Fatalf("NewRequest returned error: %v", err)
}
if req.Body != nil {
t.Fatalf("request contains a non-nil Body\n%v", req.Body)
}
}
| package librariesio
import (
"testing"
"time"
)
const APIKey string = "1234"
func TestNewClient(t *testing.T) {
c := NewClient(APIKey)
if got, want := c.apiKey, APIKey; got != want {
t.Errorf("NewClient baseURL is %v, want %v", got, want)
}
if got, want := c.BaseURL.String(), "https://libraries.io/api/"; got != want {
t.Errorf("NewClient baseURL is %v, want %v", got, want)
}
if got, want := c.UserAgent, "go-librariesio/1"; got != want {
t.Errorf("NewClient userAgent is %v, want %v", got, want)
}
if got, want := c.client.Timeout, time.Second*10; got != want {
t.Errorf("NewClient timeout is %v, want %v", got, want)
}
}
|
Test stable channel instead of testing channel for eigen | from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/stable"
def build(self):
cmake = CMake(self.settings)
self.run('cmake . %s' % cmake.command_line)
self.run("cmake --build . %s" % cmake.build_config)
def imports(self):
self.copy(pattern="*.dll", dst="bin", src="bin")
self.copy(pattern="*.dylib", dst="bin", src="lib")
def test(self):
self.run("cd bin && .%smytest" % os.sep)
| from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/testing"
def build(self):
cmake = CMake(self.settings)
self.run('cmake . %s' % cmake.command_line)
self.run("cmake --build . %s" % cmake.build_config)
def imports(self):
self.copy(pattern="*.dll", dst="bin", src="bin")
self.copy(pattern="*.dylib", dst="bin", src="lib")
def test(self):
self.run("cd bin && .%smytest" % os.sep)
|
Add query for getting sample by external identifier. | package ca.corefacility.bioinformatics.irida.repositories;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Sample;
/**
* A repository for storing Sample objects
*
* @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca>
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {
/**
* Get a {@link Sample} with the given string sample identifier from a
* specific project.
*
* @param project
* The {@link Project} that the {@link Sample} belongs to.
* @param externalSampleId
* The string sample identifier for a sample
* @return The {@link Sample} for this identifier
* @throws EntityNotFoundException
* if a sample with this identifier doesn't exist
*/
@Query("select j.sample from ProjectSampleJoin j where j.project = ?1 and j.sample.externalSampleId = ?2")
public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException;
}
| package ca.corefacility.bioinformatics.irida.repositories;
import org.springframework.data.repository.PagingAndSortingRepository;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Sample;
/**
* A repository for storing Sample objects
*
* @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca>
*/
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {
/**
* Get a {@link Sample} with the given string sample identifier from a
* specific project.
*
* @param project
* The {@link Project} that the {@link Sample} belongs to.
* @param externalSampleId
* The string sample identifier for a sample
* @return The {@link Sample} for this identifier
* @throws EntityNotFoundException
* if a sample with this identifier doesn't exist
*/
public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException;
}
|
fix(discord): Switch to new API domain | import requests
from allauth.socialaccount.providers.discord.provider import DiscordProvider
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class DiscordOAuth2Adapter(OAuth2Adapter):
provider_id = DiscordProvider.id
access_token_url = 'https://discord.com/api/oauth2/token'
authorize_url = 'https://discord.com/api/oauth2/authorize'
profile_url = 'https://discord.com/api/users/@me'
def complete_login(self, request, app, token, **kwargs):
headers = {
'Authorization': 'Bearer {0}'.format(token.token),
'Content-Type': 'application/json',
}
extra_data = requests.get(self.profile_url, headers=headers)
return self.get_provider().sociallogin_from_response(
request,
extra_data.json()
)
oauth2_login = OAuth2LoginView.adapter_view(DiscordOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DiscordOAuth2Adapter)
| import requests
from allauth.socialaccount.providers.discord.provider import DiscordProvider
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class DiscordOAuth2Adapter(OAuth2Adapter):
provider_id = DiscordProvider.id
access_token_url = 'https://discordapp.com/api/oauth2/token'
authorize_url = 'https://discordapp.com/api/oauth2/authorize'
profile_url = 'https://discordapp.com/api/users/@me'
def complete_login(self, request, app, token, **kwargs):
headers = {
'Authorization': 'Bearer {0}'.format(token.token),
'Content-Type': 'application/json',
}
extra_data = requests.get(self.profile_url, headers=headers)
return self.get_provider().sociallogin_from_response(
request,
extra_data.json()
)
oauth2_login = OAuth2LoginView.adapter_view(DiscordOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DiscordOAuth2Adapter)
|
Check that there are data files to import
It is possible for the pattern to match nothing leading to no files
being imported. This is an error case so we raise an exception if it
happens. | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 glob import glob
import luigi
from tasks.config import gtrnadb
from .json_to_csv import GtRNAdbJsonToCsv
class GtRNAdb(luigi.WrapperTask): # pylint: disable=R0904
"""
Imports all GtRNAdb data. This will generate a task for each separate file
to create the CSV files, but does not run the secondary structure
importing. That has to be trigger manually after this is complete.
"""
def requires(self):
config = gtrnadb()
files = glob(config.pattern)
if not files:
raise ValueError("No GtRNAdb data files file")
for filename in files:
yield GtRNAdbJsonToCsv(input_file=filename)
| # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 glob import iglob
import luigi
from tasks.config import gtrnadb
from .json_to_csv import GtRNAdbJsonToCsv
class GtRNAdb(luigi.WrapperTask): # pylint: disable=R0904
"""
Imports all GtRNAdb data. This will generate a task for each separate file to
create the CSV files, but does not run the secondary structure importing.
That has to be trigger manually after this is complete.
"""
def requires(self):
config = gtrnadb()
for filename in iglob(config.pattern):
yield GtRNAdbJsonToCsv(input_file=filename)
|
Fix typo in chunk linkset | <?php defined('SYSPATH') OR die('No direct script access.');
/**
* @package BoomCMS
* @category Chunks
* @author Rob Taylor
* @copyright Hoop Associates
*
*/
class Boom_Chunk_Linkset extends Chunk
{
protected $_default_template = 'quicklinks';
protected $_type = 'linkset';
protected function _show()
{
if ( ! Editor::instance()->state_is(Editor::DISABLED))
{
// Editor is enabled, show all the links.
$links = $this->_chunk->links();
}
else
{
// Editor is disabled - only show links where the target page is visible
$links = array();
foreach ($this->_chunk->links() as $link)
{
if ($link->is_external() OR $link->target->is_visible())
{
$links[] = $link;
}
}
}
return View::factory("site/slots/linkset/$this->_template", array(
'title' => $this->_chunk->title,
'links' => $links,
));
}
public function _show_default()
{
return View::factory("site/slots/default/linkset/$this->_template");
}
public function has_content()
{
return count($this->_chunk->links()) > 0;
}
} | <?php defined('SYSPATH') OR die('No direct script access.');
/**
* @package BoomCMS
* @category Chunks
* @author Rob Taylor
* @copyright Hoop Associates
*
*/
class Boom_Chunk_Linkset extends Chunk
{
protected $_default_template = 'quicklinks';
protected $_type = 'linkset';
protected function _show()
{
if ( ! Editor::instance()->state_is(Editor::DISABLED))
{
// Editor is enabled, show all the links.
$links = $this->_chunks->links();
}
else
{
// Editor is disabled - only show links where the target page is visible
$links = array();
foreach ($this->_chunk->links() as $link)
{
if ($link->is_external() OR $link->target->is_visible())
{
$links[] = $link;
}
}
}
return View::factory("site/slots/linkset/$this->_template", array(
'title' => $this->_chunk->title,
'links' => $links,
));
}
public function _show_default()
{
return View::factory("site/slots/default/linkset/$this->_template");
}
public function has_content()
{
return count($this->_chunk->links()) > 0;
}
} |
Fix bool setting dump issue. | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
| import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
|
Fix trove classifier for pypi | #!/usr/bin/env python
from setuptools import setup, find_packages
__author__ = "Nitrax <nitrax@lokisec.fr>"
__copyright__ = "Copyright 2017, Legobot"
description = 'Lego providing networking tools'
name = 'legos.nettools'
setup(
name=name,
version='0.1.0',
namespace_packages=name.split('.')[:-1],
license='MIT',
description=description,
author='Nitrax',
url='https://github.com/Legobot/' + name,
install_requires=['legobot>=1.1.4,<=2.0.0',
'python-whois',
'urllib3',
'bandit==1.3.0',
'flake8==3.2.1',
'pytest==3.0.5'
],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3'
],
packages=find_packages()
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
__author__ = "Nitrax <nitrax@lokisec.fr>"
__copyright__ = "Copyright 2017, Legobot"
description = 'Lego providing networking tools'
name = 'legos.nettools'
setup(
name=name,
version='0.1.0',
namespace_packages=name.split('.')[:-1],
license='MIT',
description=description,
author='Nitrax',
url='https://github.com/Legobot/' + name,
install_requires=['legobot>=1.1.4,<=2.0.0',
'python-whois',
'urllib3',
'bandit==1.3.0',
'flake8==3.2.1',
'pytest==3.0.5'
],
classifiers=[
'License :: MIT',
'Programming Language :: Python :: 3'
],
packages=find_packages()
)
|
Fix more broken-ness travis catches but local build does not | <?php
namespace Asana;
use Asana\Test\AsanaTest;
use Asana\Test\MockRequest;
use Asana\Dispatcher\OAuthDispatcher;
// Extend dispatcher to expose protected methods for testing.
class FakeOauthDispatcher extends OAuthDispatcher {
public function authenticate($request) {
return parent::authenticate($request);
}
};
class OAuthDispatcherTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->dispatcher = new FakeOAuthDispatcher(array(
'client_id' => 'fake_client_id'));
}
/**
* @expectedException Exception
* @expectedExceptionMessageRegExp #access token not set#
*/
public function testAuthenticateNoToken()
{
$request = new MockRequest($this->dispatcher);
$this->dispatcher->authenticate($request);
}
public function testAuthenticateUsesToken()
{
$this->dispatcher->accessToken = 'fake_token';
$request = new MockRequest($this->dispatcher);
$this->dispatcher->authenticate($request);
$this->assertEquals(
$request->headers, array('Authorization' => 'Bearer fake_token'));
}
}
| <?php
namespace Asana;
use Asana\Test\AsanaTest;
use Asana\Test\MockRequest;
use Asana\Dispatcher\OAuthDispatcher;
// Extend dispatcher to expose protected methods for testing.
class FakeOauthDispatcher extends OAuthDispatcher {
public function authenticate($request) {
return parent::authenticate($request);
}
};
class OAuthDispatcherTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->dispatcher = new FakeOAuthDispatcher(array());
}
/**
* @expectedException Exception
* @expectedExceptionMessageRegExp #access token not set#
*/
public function testAuthenticateNoToken()
{
$request = new MockRequest($this->dispatcher);
$this->dispatcher->authenticate($request);
}
public function testAuthenticateUsesToken()
{
$this->dispatcher->accessToken = 'fake_token';
$request = new MockRequest($this->dispatcher);
$this->dispatcher->authenticate($request);
$this->assertEquals(
$request->headers, array('Authorization' => 'Bearer fake_token'));
}
}
|
Remove unused set*(Collection) methods on models | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Model;
use Doctrine\Common\Collections\Collection;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrenciesAwareInterface
{
/**
* @return Collection|CurrencyInterface[]
*/
public function getCurrencies();
/**
* @param CurrencyInterface $currency
*
* @return bool
*/
public function hasCurrency(CurrencyInterface $currency);
/**
* @param CurrencyInterface $currency
*/
public function addCurrency(CurrencyInterface $currency);
/**
* @param CurrencyInterface $currency
*/
public function removeCurrency(CurrencyInterface $currency);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Model;
use Doctrine\Common\Collections\Collection;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrenciesAwareInterface
{
/**
* @return Collection|CurrencyInterface[]
*/
public function getCurrencies();
/**
* @param Collection $collection
*/
public function setCurrencies(Collection $collection);
/**
* @param CurrencyInterface $currency
*
* @return bool
*/
public function hasCurrency(CurrencyInterface $currency);
/**
* @param CurrencyInterface $currency
*/
public function addCurrency(CurrencyInterface $currency);
/**
* @param CurrencyInterface $currency
*/
public function removeCurrency(CurrencyInterface $currency);
}
|
Change all 1d to 24h | export const defaultRuleConfigs = {
deadman: {
period: '10m',
},
relative: {
change: 'change',
period: '1m',
shift: '1m',
operator: 'greater than',
value: '90',
},
threshold: {
operator: 'greater than',
value: '90',
relation: 'once',
percentile: '90',
period: '1m',
},
};
export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to'];
// export const RELATIONS = ['once', 'more than ', 'less than'];
export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h'];
export const CHANGES = ['change', '% change'];
export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h'];
export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops'];
export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
| export const defaultRuleConfigs = {
deadman: {
period: '10m',
},
relative: {
change: 'change',
period: '1m',
shift: '1m',
operator: 'greater than',
value: '90',
},
threshold: {
operator: 'greater than',
value: '90',
relation: 'once',
percentile: '90',
period: '1m',
},
};
export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to'];
// export const RELATIONS = ['once', 'more than ', 'less than'];
export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d'];
export const CHANGES = ['change', '% change'];
export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d'];
export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops'];
export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
|
Connect returnBook method to user | import React from 'react';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import Navbar from './Navbar';
import PageFooter from './PageFooter';
import Favorites from './Favorites';
import Profile from './Profile';
import getUserFavorites from '../actions/favorites';
import { getUserProfile, returnBook } from '../actions/profile';
const User = props => (
<div>
<Navbar />
<Switch>
<Route exact path={`${props.match.url}/:userId/favorites`} render= { () => (
<Favorites { ...props } />
)}/>
<Route exact path={`${props.match.url}/:userId/profile`} render= { () => (
<Profile { ...props } />
)}/>
</Switch>
<PageFooter />
</div>
);
const mapStateToProps = state => ({
...state.login,
...state.favorites,
...state.profile,
});
const mapDispatchToProps = dispatch => ({
getUserFavorites: (userId) => { dispatch(getUserFavorites(userId)); },
getUserProfile: (userId) => { dispatch(getUserProfile(userId)); },
returnBook: (userId, bookId) => {
dispatch(returnBook(userId, bookId));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(User);
| import React from 'react';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import Navbar from './Navbar';
import PageFooter from './PageFooter';
import Favorites from './Favorites';
import Profile from './Profile';
import getUserFavorites from '../actions/favorites';
import getUserProfile from '../actions/profile';
const User = props => (
<div>
<Navbar />
<Switch>
<Route exact path={`${props.match.url}/:userId/favorites`} render= { () => (
<Favorites { ...props } />
)}/>
<Route exact path={`${props.match.url}/:userId/profile`} render= { () => (
<Profile { ...props } />
)}/>
</Switch>
<PageFooter />
</div>
);
const mapStateToProps = state => ({
...state.login,
...state.favorites,
...state.profile,
});
const mapDispatchToProps = dispatch => ({
getUserFavorites: (userId) => { dispatch(getUserFavorites(userId)); },
getUserProfile: (userId) => { dispatch(getUserProfile(userId)); },
});
export default connect(mapStateToProps, mapDispatchToProps)(User);
|
Make state variables final, seeing as these are initialized in the constructor. | package uk.ac.ebi.quickgo.rest.search.filter;
import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.stream.Stream;
/**
* Data structure that holds the field name and values of a filter requested by a REST service endpoint.
*
* @author Tony Wardell
* Date: 03/05/2016
* Time: 10:25
*/
public class RequestFilter {
private final String field;
private final String[] values;
public RequestFilter(String field, String... values) {
Preconditions.checkArgument(field != null && !field.trim().isEmpty(), "Filter field cannot be null or empty");
Preconditions.checkArgument(values != null && values.length > 0, "Filter values cannot be null or empty");
this.field = field;
this.values = values;
}
/**
* Provides the field (column) the filter will be applied to.
*
* @return the field
*/
public String getField() {
return field;
}
/**
* Provides the field (column) the filter will be applied to.
*
* @return the field
*/
public Stream<String> getValues() {
return Arrays.stream(values);
}
} | package uk.ac.ebi.quickgo.rest.search.filter;
import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.stream.Stream;
/**
* Data structure that holds the field name and values of a filter requested by a REST service endpoint.
*
* @author Tony Wardell
* Date: 03/05/2016
* Time: 10:25
*/
public class RequestFilter {
private String field;
private String[] values;
public RequestFilter(String field, String... values) {
Preconditions.checkArgument(field != null && !field.trim().isEmpty(), "Filter field cannot be null or empty");
Preconditions.checkArgument(values != null && values.length > 0, "Filter values cannot be null or empty");
this.field = field;
this.values = values;
}
/**
* Provides the field (column) the filter will be applied to.
*
* @return the field
*/
public String getField() {
return field;
}
/**
* Provides the field (column) the filter will be applied to.
*
* @return the field
*/
public Stream<String> getValues() {
return Arrays.stream(values);
}
} |
fix(json): Remove class field from PluginContainer json serializer | package valandur.webapi.json.serializer.plugin;
import valandur.webapi.api.cache.plugin.ICachedPluginDependency;
import valandur.webapi.api.json.WebAPIBaseSerializer;
import valandur.webapi.cache.plugin.CachedPluginContainer;
import java.io.IOException;
public class CachedPluginContainerSerializer extends WebAPIBaseSerializer<CachedPluginContainer> {
@Override
public void serialize(CachedPluginContainer value) throws IOException {
writeStartObject();
writeField("id", value.getId());
writeField("name", value.getName());
writeField("version", value.getVersion());
if (shouldWriteDetails()) {
writeField("description", value.getDescription());
writeField("url", value.getUrl());
writeField("authors", value.getAuthors());
writeArrayFieldStart("dependencies");
for (ICachedPluginDependency dependency : value.getDependencies()) {
writeValue(dependency);
}
writeEndArray();
}
writeEndObject();
}
}
| package valandur.webapi.json.serializer.plugin;
import valandur.webapi.api.cache.plugin.ICachedPluginDependency;
import valandur.webapi.api.json.WebAPIBaseSerializer;
import valandur.webapi.cache.plugin.CachedPluginContainer;
import java.io.IOException;
public class CachedPluginContainerSerializer extends WebAPIBaseSerializer<CachedPluginContainer> {
@Override
public void serialize(CachedPluginContainer value) throws IOException {
writeStartObject();
writeField("id", value.getId());
writeField("name", value.getName());
writeField("version", value.getVersion());
if (shouldWriteDetails()) {
writeField("class", value.getClass());
writeField("description", value.getDescription());
writeField("url", value.getUrl());
writeField("authors", value.getAuthors());
writeArrayFieldStart("dependencies");
for (ICachedPluginDependency dependency : value.getDependencies()) {
writeValue(dependency);
}
writeEndArray();
}
writeEndObject();
}
}
|
Add 3.6 to trove classifiers [skipci] | from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Mark pudb post_mortem as debug-only, and optional. | # encoding: utf-8
from marrow.package.host import PluginManager
def indent(context, lines, padding='\t'):
return padding + ('\n' + padding).join(lines.split('\n'))
class ContentmentExtension:
needs = ('template', )
def __call__(self, context, app):
def protected_inner(environ, start_response=None):
try:
return app(environ, start_response)
except:
if __debug__:
try:
import pudb; pudb.post_mortem()
except:
pass
raise
return protected_inner
def start(self, context):
log = __import__('logging').getLogger(__name__)
log.info("Starting Contentment extension.")
context.namespace.indent = indent
for asset_type in PluginManager('web.component'):
log.info("Found asset type: " + repr(asset_type))
# registry.register(render_asset, Asset)
| # encoding: utf-8
from marrow.package.host import PluginManager
def indent(context, lines, padding='\t'):
return padding + ('\n' + padding).join(lines.split('\n'))
class ContentmentExtension:
needs = ('template', )
def __call__(self, context, app):
def protected_inner(environ, start_response=None):
try:
return app(environ, start_response)
except:
import pudb; pudb.post_mortem()
return protected_inner
def start(self, context):
log = __import__('logging').getLogger(__name__)
log.info("Starting Contentment extension.")
context.namespace.indent = indent
for asset_type in PluginManager('web.component'):
log.info("Found asset type: " + repr(asset_type))
# registry.register(render_asset, Asset)
|
Update (c) year and line | # -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../')
#needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('https://docs.python.org/3/',
'https://docs.python.org/3/objects.inv'),
'tornado': ('http://www.tornadoweb.org/en/stable/',
'http://www.tornadoweb.org/en/stable/objects.inv')}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'pika'
copyright = '2009-2017, Tony Garnock-Jones, Gavin M. Roy, Pivotal Software, Inc and contributors.'
import pika
release = pika.__version__
version = '.'.join(release.split('.')[0:1])
exclude_patterns = ['_build']
add_function_parentheses = True
add_module_names = True
show_authors = True
pygments_style = 'sphinx'
modindex_common_prefix = ['pika']
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'pikadoc'
| # -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../')
#needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('https://docs.python.org/3/',
'https://docs.python.org/3/objects.inv'),
'tornado': ('http://www.tornadoweb.org/en/stable/',
'http://www.tornadoweb.org/en/stable/objects.inv')}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'pika'
copyright = '2009-2015, Tony Garnock-Jones, Gavin M. Roy, Pivotal and others.'
import pika
release = pika.__version__
version = '.'.join(release.split('.')[0:1])
exclude_patterns = ['_build']
add_function_parentheses = True
add_module_names = True
show_authors = True
pygments_style = 'sphinx'
modindex_common_prefix = ['pika']
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'pikadoc'
|
Revert to debug=false for deployment | """Development settings and globals."""
from common import *
import dj_database_url
########## DEBUG CONFIGURATION
DEBUG = False
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': {
'ENGINE':'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*'] | """Development settings and globals."""
from common import *
import dj_database_url
########## DEBUG CONFIGURATION
DEBUG = True
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': {
'ENGINE':'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*'] |
Fix using LocalizedFieldsAdminMixin with inlines | from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
|
Rename ScraperWiki to Sensible Code in README | from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by The Sensible Code Company's Data Services team.",
long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="The Sensible Code Company Limited",
author_email='dataservices@sensiblecode.io',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
| from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
description="Provides some helper functions used by the ScraperWiki Data Services team.",
long_description="Provides some helper functions used by the ScraperWiki Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="ScraperWiki Limited",
author_email='dataservices@scraperwiki.com',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
|
Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=126825080 | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines the keys for the well known labels used by the cloud debugger.
*
* DO NOT EDIT - This file is auto-generated
*/
package com.google.devtools.clouddebugger.v2;
public final class Labels {
public static final class Breakpoint {
public static final String REQUEST_LOG_ID = "requestlogid";
private Breakpoint() {}
}
public static final class Debuggee {
public static final String DOMAIN = "domain";
public static final String PROJECT_ID = "projectid";
public static final String MODULE = "module";
public static final String VERSION = "version";
public static final String MINOR_VERSION = "minorversion";
private Debuggee() {}
}
private Labels() {}
}
| /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines the keys for the well known labels used by the cloud debugger.
*
* DO NOT EDIT - This file is auto-generated
*/
package com.google.devtools.clouddebugger.v2;
public final class Labels {
public static final class Debuggee {
public static final String DOMAIN = "domain";
public static final String PROJECT_ID = "projectid";
public static final String MODULE = "module";
public static final String MINOR_VERSION = "minorversion";
public static final String VERSION = "version";
private Debuggee() {}
}
public static final class Breakpoint {
public static final String REQUEST_LOG_ID = "requestlogid";
private Breakpoint() {}
}
private Labels() {}
}
|
Refactor: Move use statement to next line | <?php
namespace App\Bootstrap;
use App\Constants\Services;
use League\Fractal\Manager as FractalManager;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconUtils\Http\Response;
use PhalconUtils\Transformer\ResponseDataSerializer;
/**
* Class ApiServicesBootStrap
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Library\BootStrap
*/
class ApiServicesBootStrap extends BaseServicesBootStrap
{
public function run(Injectable $app, DiInterface $di, Config $config)
{
parent::run($app, $di, $config);
$di->set(Services::RESPONSE, function () {
return new Response();
});
/**
* Fractal
*/
$di->setShared(Services::FRACTAL_MANAGER, function () {
$fractal = new FractalManager();
$fractal->setSerializer(new ResponseDataSerializer());
return $fractal;
});
}
}
| <?php
namespace App\Bootstrap;
use App\Constants\Services;
use League\Fractal\Manager as FractalManager;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconUtils\Http\Response;use PhalconUtils\Transformer\ResponseDataSerializer;
/**
* Class ApiServicesBootStrap
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Library\BootStrap
*/
class ApiServicesBootStrap extends BaseServicesBootStrap
{
public function run(Injectable $app, DiInterface $di, Config $config)
{
parent::run($app, $di, $config);
$di->set(Services::RESPONSE, function () {
return new Response();
});
/**
* Fractal
*/
$di->setShared(Services::FRACTAL_MANAGER, function () {
$fractal = new FractalManager();
$fractal->setSerializer(new ResponseDataSerializer());
return $fractal;
});
}
}
|
Fix chart js copy/paste error | (function(root) {
var McasScaledChart = function initializeMcasScaledChart (series) {
this.title = 'MCAS score';
this.series = series;
};
McasScaledChart.fromChartData = function mcasScaledChartFromChartData(chartData) {
var datums = [];
var math_scaled_data = chartData.data('mcas-series-math-scaled');
var ela_scaled_data = chartData.data('mcas-series-ela-scaled')
if (math_scaled_data !== null) {
var math_scaled = new ProfileChartData("Math scale score", math_scaled_data).toDateChart();
datums.push(math_scaled);
}
if (ela_scaled_data !== null) {
var ela_scaled = new ProfileChartData("English scale score", ela_scaled_data).toDateChart();
datums.push(ela_scaled);
}
return new McasScaledChart(datums);
};
McasScaledChart.prototype.toHighChart = function mcasChartToHighChart () {
return $.extend({}, ChartSettings.base_options, {
xAxis: ChartSettings.x_axis_datetime,
yAxis: ChartSettings.default_yaxis,
series: this.series
});
};
McasScaledChart.prototype.render = function renderMcasScaledChart (controller) {
controller.renderChartOrEmptyView(this);
};
root.McasScaledChart = McasScaledChart;
})(window)
| (function(root) {
var McasScaledChart = function initializeMcasScaledChart (series) {
this.title = 'MCAS score';
this.series = series;
};
McasScaledChart.fromChartData = function mcasScaledChartFromChartData(chartData) {
var datums = [];
var math_scaled_data = chartData.data('mcas-series-math-scaled');
var ela_scaled_data = chartData.data('mcas-series-ela-scaled')
if (math_scaled_data !== null) {
var math_scaled = new ProfileChartData("Math scale score", math_scaled_data).toDateChart();
datums.push(math_scaled);
}
if (ela_scaled_data !== null) {
var ela_scaled = new ProfileChartData("English scale score", ela_scaled_data).toDateChart();
datums.push(math_scaled);
}
return new McasScaledChart(datums);
};
McasScaledChart.prototype.toHighChart = function mcasChartToHighChart () {
return $.extend({}, ChartSettings.base_options, {
xAxis: ChartSettings.x_axis_datetime,
yAxis: ChartSettings.default_yaxis,
series: this.series
});
};
McasScaledChart.prototype.render = function renderMcasScaledChart (controller) {
controller.renderChartOrEmptyView(this);
};
root.McasScaledChart = McasScaledChart;
})(window)
|
Remove newlines & old TODO | @extends('layout.layout')
@section('content')
<div class="row">
<div class="seven wide column centered">
<h2>{{ trans('general.titles.forgotten-link') }}</h2>
<p>{{ trans('general.texts.forgotten-link') }}</p>
<form class="ui form">
<div class="field">
<input type="text" name="email" placeholder="{{ trans('general.placeholders.forgotten-link-mail') }}">
</div>
<div class="align-center">
<button class="ui red submit button" type="submit">{{ trans('general.buttons.submit.send-short') }}</button>
</div>
</form>
</div>
</div>
@stop
| @extends('layout.layout')
@section('content')
<div class="row">
<div class="seven wide column centered">
<!-- TODO use trans()-->
<h2>{{ trans('general.titles.forgotten-link') }}</h2>
<p>
{{ trans('general.texts.forgotten-link') }}
</p>
<form class="ui form">
<div class="field">
<input type="text" name="email" placeholder="{{ trans('general.placeholders.forgotten-link-mail') }}">
</div>
<div class="align-center">
<button class="ui red submit button" type="submit">{{ trans('general.buttons.submit.send-short') }}</button>
</div>
</form>
</div>
</div>
@stop
|
Handle flow check error when React mount node is not found | // @flow
import React from 'react';
import ReactDOM from 'react-dom';
// AppContainer is a necessary wrapper component for HMR
import { AppContainer } from 'react-hot-loader';
import { BrowserRouter as Router } from 'react-router-dom';
import 'normalize.css';
import App from './app';
const rootElement = document.getElementById('react-root');
const renderApp = rootElement
? () => {
ReactDOM.render(
<AppContainer>
<Router>
<App />
</Router>
</AppContainer>,
rootElement
);
}
: () => {}; // set renderApp to a noop if we don't have `rootElement`
renderApp();
// Hot Module Replacement API
if (module.hot) {
// for Webpack 2, do not need to re-import module for HMR
// https://github.com/gaearon/react-hot-loader/tree/master/docs#webpack-2
// $FlowFixMe: how to annotate types for module, module.hot
module.hot.accept('./app', renderApp);
}
| // @flow
import React from 'react';
import ReactDOM from 'react-dom';
// AppContainer is a necessary wrapper component for HMR
import { AppContainer } from 'react-hot-loader';
import { BrowserRouter as Router } from 'react-router-dom';
import 'normalize.css';
import App from './app';
const rootElement = document.getElementById('react-root');
const renderApp = () => {
ReactDOM.render(
<AppContainer>
<Router>
<App />
</Router>
</AppContainer>,
rootElement
);
};
renderApp();
// Hot Module Replacement API
if (module.hot) {
// for Webpack 2, do not need to re-import module for HMR
// https://github.com/gaearon/react-hot-loader/tree/master/docs#webpack-2
// $FlowFixMe: how to annotate types for module, module.hot
module.hot.accept('./app', renderApp);
}
|
Convert ListSeparator into a string to use in Split. | // Copyright 2013 Chris McGee <sirnewton_01@yahoo.ca>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package gdblib
import (
"go/build"
"os"
"os/exec"
"path/filepath"
"strings"
)
var (
sendSignalPath string
)
func init() {
gopath := build.Default.GOPATH
gopaths := strings.Split(gopath, string(filepath.ListSeparator))
for _,path := range(gopaths) {
p := path + "\\src\\github.com\\sirnewton01\\gdblib\\SendSignal.exe"
_,err := os.Stat(p)
if err == nil {
sendSignalPath = p
break
}
}
}
func fixCmd(cmd *exec.Cmd) {
// No process group separation is required on Windows.
// Processes do not share signals like they can on Unix.
}
func interruptInferior(process *os.Process, pid string) {
// Invoke the included "sendsignal" program to send the
// Ctrl-break to the inferior process to interrupt it
initCommand := exec.Command("cmd", "/c", "start", sendSignalPath, pid)
initCommand.Run()
}
| // Copyright 2013 Chris McGee <sirnewton_01@yahoo.ca>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package gdblib
import (
"go/build"
"os"
"os/exec"
"path/filepath"
"strings"
)
var (
sendSignalPath string
)
func init() {
gopath := build.Default.GOPATH
gopaths := strings.Split(gopath, filepath.ListSeparator)
for _,path := range(gopaths) {
p := path + "\\src\\github.com\\sirnewton01\\gdblib\\SendSignal.exe"
_,err := os.Stat(p)
if err == nil {
sendSignalPath = p
break
}
}
}
func fixCmd(cmd *exec.Cmd) {
// No process group separation is required on Windows.
// Processes do not share signals like they can on Unix.
}
func interruptInferior(process *os.Process, pid string) {
// Invoke the included "sendsignal" program to send the
// Ctrl-break to the inferior process to interrupt it
initCommand := exec.Command("cmd", "/c", "start", sendSignalPath, pid)
initCommand.Run()
}
|
Add ImportError to exception instead of bare "except"
Fixes lint error on develop. | # -*- coding: utf-8 -*-
'''
Test the core grains
'''
# Import python libs
from __future__ import absolute_import
# Import Salt Testing libs
import tests.integration as integration
from tests.support.unit import skipIf
# Import salt libs
import salt.utils
if salt.utils.is_windows():
try:
import salt.modules.reg
except ImportError:
pass
class TestGrainsCore(integration.ModuleCase):
'''
Test the core grains grains
'''
@skipIf(not salt.utils.is_windows(), 'Only run on Windows')
def test_win_cpu_model(self):
'''
test grains['cpu_model']
'''
opts = self.minion_opts
cpu_model_text = salt.modules.reg.read_value(
"HKEY_LOCAL_MACHINE",
"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
"ProcessorNameString").get('vdata')
self.assertEqual(
self.run_function('grains.items')['cpu_model'],
cpu_model_text
)
| # -*- coding: utf-8 -*-
'''
Test the core grains
'''
# Import python libs
from __future__ import absolute_import
# Import Salt Testing libs
import tests.integration as integration
from tests.support.unit import skipIf
# Import salt libs
import salt.utils
if salt.utils.is_windows():
try:
import salt.modules.reg
except:
pass
class TestGrainsCore(integration.ModuleCase):
'''
Test the core grains grains
'''
@skipIf(not salt.utils.is_windows(), 'Only run on Windows')
def test_win_cpu_model(self):
'''
test grains['cpu_model']
'''
opts = self.minion_opts
cpu_model_text = salt.modules.reg.read_value(
"HKEY_LOCAL_MACHINE",
"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
"ProcessorNameString").get('vdata')
self.assertEqual(
self.run_function('grains.items')['cpu_model'],
cpu_model_text
)
|
Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client. | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
| """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
|
Change arguement of feed name | package main
import (
"log"
"os"
"github.com/timakin/ts/loader"
"github.com/codegangsta/cli"
)
var Commands = []cli.Command{
commandAll,
commandBiz,
commandHack,
}
var commandAll = cli.Command{
Name: "all",
Usage: "",
Description: `
`,
Action: doAll,
}
var commandBiz = cli.Command{
Name: "biz",
Usage: "",
Description: `
`,
Action: doBiz,
}
var commandHack = cli.Command{
Name: "hack",
Usage: "",
Description: `
`,
Action: doHack,
}
func debug(v ...interface{}) {
if os.Getenv("DEBUG") != "" {
log.Println(v...)
}
}
func assert(err error) {
if err != nil {
log.Fatal(err)
}
}
func doAll(c *cli.Context) {
hn := make(chan loader.ResultData)
go loader.GetHNFeed(hn)
phres := <- hn
var HNData loader.Feed = &phres
HNData.Display()
}
func doBiz(c *cli.Context) {
}
func doHack(c *cli.Context) {
}
| package main
import (
"log"
"os"
"github.com/timakin/ts/loader"
"github.com/codegangsta/cli"
)
var Commands = []cli.Command{
commandAll,
commandBiz,
commandHack,
}
var commandAll = cli.Command{
Name: "all",
Usage: "",
Description: `
`,
Action: doAll,
}
var commandBiz = cli.Command{
Name: "biz",
Usage: "",
Description: `
`,
Action: doBiz,
}
var commandHack = cli.Command{
Name: "hack",
Usage: "",
Description: `
`,
Action: doHack,
}
func debug(v ...interface{}) {
if os.Getenv("DEBUG") != "" {
log.Println(v...)
}
}
func assert(err error) {
if err != nil {
log.Fatal(err)
}
}
func doAll(c *cli.Context) {
hn := make(chan loader.ResultData)
go loader.GetHNFeed(hn)
phres := <- hn
var HNData loader.Feed = &phres
HNData.Display("Hacker News")
}
func doBiz(c *cli.Context) {
}
func doHack(c *cli.Context) {
}
|
Add missing param to DocBlock | <?php
namespace Laravel\Dusk;
use InvalidArgumentException;
class Dusk
{
/**
* Register the Dusk service provider.
*
* @param array $options
* @return void
*/
public static function register(array $options = [])
{
if (static::duskEnvironment($options)) {
app()->register(DuskServiceProvider::class);
}
}
/**
* Determine if Dusk may run in this environment.
*
* @param array $options
* @return bool
*/
protected static function duskEnvironment($options)
{
if (! isset($options['environments'])) {
return false;
}
if (is_string($options['environments'])) {
$options['environments'] = [$options['environments']];
}
if (! is_array($options['environments'])) {
throw new InvalidArgumentException("Dusk environments must be listed as an array.");
}
return app()->environment(...$options['environments']);
}
}
| <?php
namespace Laravel\Dusk;
use InvalidArgumentException;
class Dusk
{
/**
* Register the Dusk service provider.
*
* @return void
*/
public static function register(array $options = [])
{
if (static::duskEnvironment($options)) {
app()->register(DuskServiceProvider::class);
}
}
/**
* Determine if Dusk may run in this environment.
*
* @param array $options
* @return bool
*/
protected static function duskEnvironment($options)
{
if (! isset($options['environments'])) {
return false;
}
if (is_string($options['environments'])) {
$options['environments'] = [$options['environments']];
}
if (! is_array($options['environments'])) {
throw new InvalidArgumentException("Dusk environments must be listed as an array.");
}
return app()->environment(...$options['environments']);
}
}
|
Add timestamps to team_user intermediate table | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTeamUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('team_id');
$table->unsignedInteger('user_id');
$table->timestamps();
$table->foreign('team_id')->references('id')->on('teams');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('team_user');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTeamUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('team_id');
$table->unsignedInteger('user_id');
$table->foreign('team_id')->references('id')->on('teams');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('team_user');
}
}
|
Fix wrong HTTP redirection status code | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Http\Middleware;
use Closure;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (auth()->guard($guard)->guest()) {
return intend([
'url' => route('guestarea.auth.login'),
'with' => ['warning' => trans('cortex/foundation::messages.session_required')],
]);
}
return $next($request);
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Foundation\Http\Middleware;
use Closure;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (auth()->guard($guard)->guest()) {
return intend([
'url' => route('guestarea.auth.login'),
'with' => ['warning' => trans('cortex/foundation::messages.session_required')],
], 401);
}
return $next($request);
}
}
|
Fix api mobile only with geotrek flatpages trekking tourism | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import url, include
from rest_framework import routers
if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism':
from geotrek.api.mobile import views as api_mobile
router = routers.DefaultRouter()
urlpatterns = [
url(r'^$', api_mobile.SwaggerSchemaView.as_view(), name="schema"),
url(r'^', include(router.urls)),
]
urlpatterns += url(r'^settings/$', api_mobile.SettingsView.as_view(), name='settings'),
if 'geotrek.flatpages' in settings.INSTALLED_APPS:
router.register(r'flatpages', api_mobile.FlatPageViewSet, base_name='flatpage')
if 'geotrek.trekking' in settings.INSTALLED_APPS:
router.register(r'treks', api_mobile.TrekViewSet, base_name='treks')
| from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import url, include
from rest_framework import routers
from geotrek.api.mobile import views as api_mobile
router = routers.DefaultRouter()
if 'geotrek.flatpages' in settings.INSTALLED_APPS:
router.register(r'flatpages', api_mobile.FlatPageViewSet, base_name='flatpage')
if 'geotrek.trekking' in settings.INSTALLED_APPS:
router.register(r'treks', api_mobile.TrekViewSet, base_name='treks')
urlpatterns = [
url(r'^$', api_mobile.SwaggerSchemaView.as_view(), name="schema"),
url(r'^', include(router.urls)),
]
if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism':
urlpatterns += url(r'^settings/$', api_mobile.SettingsView.as_view(), name='settings'),
|
Fix unicode encoding of Slack message posts | #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.com/".format(self.slack_name)
url += "services/hooks/slackbot"
return url
def say(self, channel, statement):
"""
channel should not be preceded with '#'
"""
assert channel # not blank
if channel[0] == '#':
channel = channel[1:]
nurl = self.url + "?token={}&channel=%23{}".format(self.token, channel)
p = requests.post(nurl, data=statement.encode('utf-8'))
return p.status_code
| #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.com/".format(self.slack_name)
url += "services/hooks/slackbot"
return url
def say(self, channel, statement):
"""
channel should not be preceded with '#'
"""
assert channel # not blank
if channel[0] == '#':
channel = channel[1:]
nurl = self.url + "?token={}&channel=%23{}".format(self.token, channel)
p = requests.post(nurl, statement)
return p.status_code
|
Connect body parser doesn't work in union (and not necessary for session) | /**
* Auth cantina plugin.
*/
var connect = require('connect');
// Expose this service's package info.
require('pkginfo')(module);
// The plugin is being attached to an app.
exports.attach = function(options) {
options = options || {};
this.utils.defaults(options, {
secret: 'keyboard cat',
key: 'connect.sid'
});
this.session = {secret: options.secret, key: options.key};
if (options.redis) {
var RedisStore = require('connect-redis')(connect);
this.session.store = new RedisStore(typeof options.redis == 'object' ? options.redis : {});
}
else {
this.session.store = new connect.session.MemoryStore();
}
this.middleware([
connect.cookieParser(this.session.secret),
connect.session(this.session)
]);
this.session.fromSocket = require('./socket')(this.session);
};
| /**
* Auth cantina plugin.
*/
var connect = require('connect');
// Expose this service's package info.
require('pkginfo')(module);
// The plugin is being attached to an app.
exports.attach = function(options) {
options = options || {};
this.utils.defaults(options, {
secret: 'keyboard cat',
key: 'connect.sid'
});
this.session = {secret: options.secret, key: options.key};
if (options.redis) {
var RedisStore = require('connect-redis')(connect);
this.session.store = new RedisStore(typeof options.redis == 'object' ? options.redis : {});
}
else {
this.session.store = new connect.session.MemoryStore();
}
this.middleware([
connect.cookieParser(this.session.secret),
connect.bodyParser(),
connect.session(this.session)
]);
this.session.fromSocket = require('./socket')(this.session);
};
|
Fix bad request when retrieving creditnote detail
When retrieving a creditnote detail, the Teamleader API threw an error
400 (bad request) because the required option "creditnote_id" was
missing.
The RetrieveCreditnoteRequest class was using the "credit_id" option
intead of "creditnote_id".
Fixed! | <?php
namespace Nascom\TeamleaderApiClient\Request\Creditnote;
use Nascom\TeamleaderApiClient\Request\AbstractPostRequest;
/**
* Class RetrieveCreditnoteRequest
*
* @package Nascom\TeamleaderApiClient\Request\Creditnote
*/
class RetrieveCreditnoteRequest extends AbstractPostRequest
{
/**
* RetrieveCreditnoteRequest constructor.
*
* @param $credit_id
* @param array $options
*/
public function __construct($credit_id, array $options = [])
{
$this->options = $options;
$this->setCreditnoteId($credit_id);
}
/**
* @param $credit_id
*/
public function setCreditnoteId($credit_id)
{
$this->options['creditnote_id'] = $credit_id;
}
/**
* @return string
*/
public function getUri()
{
return 'getCreditnote.php';
}
}
| <?php
namespace Nascom\TeamleaderApiClient\Request\Creditnote;
use Nascom\TeamleaderApiClient\Request\AbstractPostRequest;
/**
* Class RetrieveCreditnoteRequest
*
* @package Nascom\TeamleaderApiClient\Request\Creditnote
*/
class RetrieveCreditnoteRequest extends AbstractPostRequest
{
/**
* RetrieveCreditnoteRequest constructor.
*
* @param $credit_id
* @param array $options
*/
public function __construct($credit_id, array $options = [])
{
$this->options = $options;
$this->setCreditnoteId($credit_id);
}
/**
* @param $credit_id
*/
public function setCreditnoteId($credit_id)
{
$this->options['credit_id'] = $credit_id;
}
/**
* @return string
*/
public function getUri()
{
return 'getCreditnote.php';
}
}
|
Update install dev domain name | <?php
namespace Soda\Cms\Foundation\Setup;
use Illuminate\Database\Seeder;
use Soda\Cms\Database\Models\Application;
use Soda\Cms\Database\Models\ApplicationUrl;
class SetupApplication extends Seeder
{
/**
* Auto generated seed file.
*
* @return void
*/
public function run()
{
$baseName = str_slug(basename(base_path()), '-');
if ($baseName == 'src') {
$baseName = str_slug(basename(dirname(base_path())), '-');
}
$application = Application::withoutGlobalScopes()->firstOrCreate([
'name' => ucwords(str_replace('-', ' ', $baseName)),
]);
ApplicationUrl::withoutGlobalScopes()->firstOrCreate([
'domain' => $baseName.'.test',
'application_id' => $application->getKey(),
]);
}
}
| <?php
namespace Soda\Cms\Foundation\Setup;
use Illuminate\Database\Seeder;
use Soda\Cms\Database\Models\Application;
use Soda\Cms\Database\Models\ApplicationUrl;
class SetupApplication extends Seeder
{
/**
* Auto generated seed file.
*
* @return void
*/
public function run()
{
$baseName = str_slug(basename(base_path()), '-');
if ($baseName == 'src') {
$baseName = str_slug(basename(dirname(base_path())), '-');
}
$application = Application::withoutGlobalScopes()->firstOrCreate([
'name' => ucwords(str_replace('-', '', $baseName)),
]);
ApplicationUrl::withoutGlobalScopes()->firstOrCreate([
'domain' => $baseName.'.dev',
'application_id' => $application->getKey(),
]);
}
}
|
Remove restriction on old BeautifulSoup | from setuptools import find_packages, setup
REQUIREMENTS = [
'beautifulsoup4']
PACKAGES = [
'pha']
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Testing',
'Topic :: Utilities']
setup(
name='python-html-assert',
version='0.2.1.1',
packages=find_packages(),
install_requires=REQUIREMENTS,
author='Robert Cox',
author_email='robjohncox@gmail.com',
description='partial matching of html using a tree-based specification',
license='MIT License',
url='https://github.com/robjohncox/python-html-assert',
classifiers=CLASSIFIERS)
| from setuptools import find_packages, setup
REQUIREMENTS = [
'beautifulsoup4<=4.3.2']
PACKAGES = [
'pha']
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Testing',
'Topic :: Utilities']
setup(
name='python-html-assert',
version='0.2.1.1',
packages=find_packages(),
install_requires=REQUIREMENTS,
author='Robert Cox',
author_email='robjohncox@gmail.com',
description='partial matching of html using a tree-based specification',
license='MIT License',
url='https://github.com/robjohncox/python-html-assert',
classifiers=CLASSIFIERS)
|
Add comment about disabled xss test. | // This causes a tus "source must be a valid file" error right now, but I do not know why.
// I have tested for xss manually and it works fine, meaning xss is not possible.
// @todo Figure this out and re-enable it again.
const numberOfPlannedTests = 7
casper.test.begin('test-xss', numberOfPlannedTests, (test) => {
casper.start(`http://${testhost}`, function () {
})
casper.then(function () {
const curr = this.getCurrentUrl()
const fixturePath = this.fetchText('#fixture_path')
this.fill('#entryForm', {
my_file : `${fixturePath}/><img src=x onerror=document.write((1338-1));>.png`,
width_field : '400',
height_field: '400',
})
this.evaluate(() => $('#entryForm').submit())
this.waitFor(function () {
return curr !== this.getCurrentUrl()
})
})
casper.then(function () {
this.test.assertTextDoesntExist('1337')
this.test.assertTextExists('{\\"width\\":400')
this.test.assertTextExists('\\"height\\":400')
})
casper.run(function () {
this.test.done()
})
})
| const numberOfPlannedTests = 7
casper.test.begin('test-xss', numberOfPlannedTests, (test) => {
casper.start(`http://${testhost}`, function () {
})
casper.then(function () {
const curr = this.getCurrentUrl()
const fixturePath = this.fetchText('#fixture_path')
this.fill('#entryForm', {
my_file : `${fixturePath}/><img src=x onerror=document.write((1338-1));>.png`,
width_field : '400',
height_field: '400',
})
this.evaluate(() => $('#entryForm').submit())
this.waitFor(function () {
return curr !== this.getCurrentUrl()
})
})
casper.then(function () {
this.test.assertTextDoesntExist('1337')
this.test.assertTextExists('{\\"width\\":400')
this.test.assertTextExists('\\"height\\":400')
})
casper.run(function () {
this.test.done()
})
})
|
Clean up for building blocks. | package com.nexmo.quickstart.voice;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import java.nio.file.FileSystems;
import static com.nexmo.quickstart.Util.configureLogging;
import static com.nexmo.quickstart.Util.envVar;
public class OutboundTextToSpeech {
public static void main(String[] args) throws Exception {
configureLogging();
String NEXMO_APPLICATION_ID = envVar("APPLICATION_ID");
String NEXMO_APPLICATION_PRIVATE_KEY = envVar("PRIVATE_KEY");
String NEXMO_NUMBER = envVar("NEXMO_NUMBER");
String TO_NUMBER = envVar("TO_NUMBER");
String ANSWER_URL = "https://developer.nexmo.com/ncco/tts.json";
AuthMethod auth = new JWTAuthMethod(
NEXMO_APPLICATION_ID,
FileSystems.getDefault().getPath(NEXMO_APPLICATION_PRIVATE_KEY)
);
NexmoClient client = new NexmoClient(auth);
client.getVoiceClient().createCall(
new Call(TO_NUMBER, NEXMO_NUMBER, ANSWER_URL)
);
}
}
| package com.nexmo.quickstart.voice;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import java.nio.file.FileSystems;
import static com.nexmo.quickstart.Util.*;
public class OutboundTextToSpeech {
public static void main(String[] args) throws Exception {
configureLogging();
String NEXMO_APPLICATION_ID = envVar("APPLICATION_ID");
String NEXMO_APPLICATION_PRIVATE_KEY = envVar("PRIVATE_KEY");
String NEXMO_NUMBER = envVar("NEXMO_NUMBER");
String TO_NUMBER = envVar("TO_NUMBER");
AuthMethod auth = new JWTAuthMethod(
NEXMO_APPLICATION_ID,
FileSystems.getDefault().getPath(NEXMO_APPLICATION_PRIVATE_KEY)
);
NexmoClient client = new NexmoClient(auth);
client.getVoiceClient().createCall(new Call(
TO_NUMBER,
NEXMO_NUMBER,
"https://developer.nexmo.com/ncco/tts.json"
));
}
}
|
Address review comments, remove zip_safe=True because GeoIP | __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0.17',
'python-dateutil==2.4.1',
'requests==2.5.0',
'sh==1.09',
'six==1.9.0',
'websocket-client==0.31.0',
'wsgiref==0.1.2',
'libpebble2==0.0.12',
'netaddr==0.7.18'
]
setup(name='pypkjs',
version='3.6',
description='PebbleKit JS in Python!',
url='https://github.com/pebble/pypkjs',
author='Pebble Technology Corporation',
author_email='katharine@pebble.com',
license='MIT',
packages=find_packages(),
install_requires=requires,
entry_points={
'console_scripts': [
'pypkjs=runner.websocket:run_tool'
],
})
| __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0.17',
'python-dateutil==2.4.1',
'requests==2.5.0',
'sh==1.09',
'six==1.9.0',
'websocket-client==0.31.0',
'wsgiref==0.1.2',
'libpebble2==0.0.12',
'netaddr==0.7.18'
]
packages = find_packages()
print packages
setup(name='pypkjs',
version='3.6',
description='PebbleKit JS in Python!',
url='https://github.com/pebble/pypkjs',
author='Pebble Technology Corporation',
author_email='katharine@pebble.com',
license='MIT',
packages=packages,
install_requires=requires,
entry_points={
'console_scripts': [
'pypkjs=runner.websocket:run_tool'
],
},
zip_safe=True)
|
Update dsub version to 0.3.5
PiperOrigin-RevId: 276119452 | # Copyright 2017 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.5'
| # Copyright 2017 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.5.dev0'
|
Fix jshint errors in transport | 'use strict';
var EventEmitter = require('events').EventEmitter;
var AbstractTransport = require('./abstract_transport.js');
var NetTransport = require('./net_transport.js');
var TlsTransport = require('./tls_transport.js');
function TransportProvider() {
this._transports = {};
}
TransportProvider.prototype.registerTransport = function(protocol, transport) {
// NOTE: if we only cared about internal modules, 'instanceof' would work, but
// since we're "duck typing" transports to avoid circular dependencies, we have to
// verify the transport prototype differently.
for(var member in AbstractTransport.prototype) {
if (AbstractTransport.prototype.hasOwnProperty(member))
if (typeof AbstractTransport.prototype[member] !== typeof transport[member]) {
throw new Error('transport should implement the \'' + member + '\' method.');
}
}
if (!(transport instanceof EventEmitter))
{
throw new Error('transport should inherit from EventEmitter');
}
this._transports[protocol] = transport;
};
TransportProvider.prototype.getTransportFor = function(protocol) {
if (!this._transports.hasOwnProperty(protocol))
throw new Error('invalid protocol: ', protocol);
return this._transports[protocol];
};
module.exports = function() {
var provider = new TransportProvider();
// pre-register our "known" transports
provider.registerTransport("amqp", new NetTransport());
provider.registerTransport("amqps", new TlsTransport());
return provider;
}; | 'use strict';
var EventEmitter = require('events').EventEmitter;
var AbstractTransport = require('./abstract_transport.js');
var NetTransport = require('./net_transport.js');
var TlsTransport = require('./tls_transport.js');
function TransportProvider() {
this._transports = {};
}
TransportProvider.prototype.registerTransport = function(protocol, transport) {
// NOTE: if we only cared about internal modules, 'instanceof' would work, but
// since we're "duck typing" transports to avoid circular dependencies, we have to
// verify the transport prototype differently.
for(var member in AbstractTransport.prototype) {
if (AbstractTransport.prototype.hasOwnProperty(member))
if (typeof AbstractTransport.prototype[member] != typeof transport[member]) {
throw new Error('transport should implement the \'' + member + '\' method.');
}
}
if (!(transport instanceof EventEmitter))
{
throw new Error('transport should inherit from EventEmitter')
}
this._transports[protocol] = transport;
};
TransportProvider.prototype.getTransportFor = function(protocol) {
if (!this._transports.hasOwnProperty(protocol))
throw new Error('invalid protocol: ', protocol);
return this._transports[protocol];
};
module.exports = function() {
var provider = new TransportProvider();
// pre-register our "known" transports
provider.registerTransport("amqp", new NetTransport());
provider.registerTransport("amqps", new TlsTransport());
return provider;
}; |
Use xcode theme instead of default for highlight.js | import React, { PropTypes } from 'react';
import LanguageLink from '../../components/LanguageLink/LanguageLink';
import './Guide.scss';
import 'highlight.js/styles/xcode.css';
const Guide = (props) => (
<div className="guide">
<div className="guide-header">
<h1>{props.title}</h1>
<div className="language-selector">
{props.languageOptions.map(({ language, url }) => (
<LanguageLink
key={language}
language={language}
url={url}
isActive={language === props.language}
isShowEmpty={false}
/>
))}
</div>
</div>
<div className="guide-content" dangerouslySetInnerHTML={{ __html: props.docHtml }} />
</div>
);
Guide.propTypes = {
title: PropTypes.string,
docHtml: PropTypes.string,
languageOptions: PropTypes.array,
language: PropTypes.string.isRequired,
};
export default Guide;
| import React, { PropTypes } from 'react';
import LanguageLink from '../../components/LanguageLink/LanguageLink';
import './Guide.scss';
import 'highlight.js/styles/default.css';
const Guide = (props) => (
<div className="guide">
<div className="guide-header">
<h1>{props.title}</h1>
<div className="language-selector">
{props.languageOptions.map(({ language, url }) => (
<LanguageLink
key={language}
language={language}
url={url}
isActive={language === props.language}
isShowEmpty={false}
/>
))}
</div>
</div>
<div className="guide-content" dangerouslySetInnerHTML={{ __html: props.docHtml }} />
</div>
);
Guide.propTypes = {
title: PropTypes.string,
docHtml: PropTypes.string,
languageOptions: PropTypes.array,
language: PropTypes.string.isRequired,
};
export default Guide;
|
Update route to serve correct json object | import {Router} from 'express'
import models from '../models';
import tasks from './tasks'
export default () => {
let app = Router({mergeParams: true})
app.use('/:userId/tasks', tasks())
app.get('/', (req, res) => {
models.User.findAll({
attributes: ['id', 'email']
}).then((users) => {
res.send(users)
})
})
app.get('/new', (req, res) => {
res.render('users/new')
})
app.get('/:id', (req, res) => {
models.User.find({
where: {
id: req.params.id
},
include: [models.Task]
}).then((user) => {
res.render('users/show', {user})
})
})
app.post('/', (req, res) => {
models.User.create(req.body).then((user) => {
req.session.userId = user.dataValues.id
req.app.locals.userId = user.dataValues.id
req.session.save()
// add validations and errors
res.send(user);
})
})
return app
} | import {Router} from 'express'
import models from '../models';
import tasks from './tasks'
export default () => {
let app = Router({mergeParams: true})
app.use('/:userId/tasks', tasks())
app.get('/', (req, res) => {
models.User.findAll({
attributes: ['id', 'email']
}).then((users) => {
console.log(users)
res.send(users)
})
})
app.get('/new', (req, res) => {
res.render('users/new')
})
app.get('/:id', (req, res) => {
models.User.find({
where: {
id: req.params.id
},
include: [models.Task]
}).then((user) => {
res.render('users/show', {user})
})
})
app.post('/', (req, res) => {
models.User.create(req.body.user).then((user) => {
req.session.userId = user.dataValues.id
req.app.locals.userId = user.dataValues.id
res.redirect('/');
})
})
return app
} |
Change mode of mconvert to be globaly executable | #!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite', 'matlab2cpp.inlines'],
package_dir={'': 'src'},
url='http://github.com/jonathf/matlab2cpp',
license='BSD',
author="Jonathan Feinberg",
author_email="jonathan@feinberg.no",
description='Matlab to C++ converter'
)
if system == "Windows":
print
print "Program now runnable through 'mconvert.py'"
print "To start:"
print "> python mconvert.py -h"
else:
mconvert = "cp mconvert.py /usr/local/bin/mconvert"
print mconvert
os.system(mconvert)
chmod = "chmod 755 /usr/local/bin/mconvert"
print chmod
os.system(chmod)
| #!/usr/bin/env python
# encoding: utf8
import platform
import os
system = platform.system()
from distutils.core import setup
setup(
name='matlab2cpp',
version='0.2',
packages=['matlab2cpp', 'matlab2cpp.translations',
'matlab2cpp.testsuite', 'matlab2cpp.inlines'],
package_dir={'': 'src'},
url='http://github.com/jonathf/matlab2cpp',
license='BSD',
author="Jonathan Feinberg",
author_email="jonathan@feinberg.no",
description='Matlab to C++ converter'
)
if system == "Windows":
print
print "Program now runnable through 'mconvert.py'"
print "To start:"
print "> python mconvert.py -h"
else:
mconvert = "cp mconvert.py /usr/local/bin/mconvert"
print mconvert
os.system(mconvert)
|
Fix modal when modal is open on mounting | import { useState, useRef, useEffect, useMemo } from 'react';
import invariant from 'fbjs/lib/invariant';
import useIdentifier from '../../hooks/useIdentifier';
import useModalEffects from './useModalEffects';
export default function useModal(visible, setVisible) {
const identifier = useIdentifier('modal');
const [mounted, setMounted] = useState(false);
const ref = useRef();
useEffect(() => {
setMounted(true);
}, []);
useModalEffects({
modalRef: ref,
active: mounted && visible,
});
return useMemo(
() => ({
identifier,
visible,
setVisible,
mounted,
ref,
trigger: ({ dismiss }) => {
invariant(
dismiss,
"Modal/ModalContext cannot be used with prop 'toggle'. Please use prop 'dismiss' instead.",
);
return {
props: {
onPress: () => {
setVisible(false);
},
},
};
},
}),
[visible, mounted],
);
}
| import { useState, useRef, useEffect, useMemo } from 'react';
import invariant from 'fbjs/lib/invariant';
import useIdentifier from '../../hooks/useIdentifier';
import useModalEffects from './useModalEffects';
export default function useModal(visible, setVisible) {
const identifier = useIdentifier('modal');
const [mounted, setMounted] = useState(false);
const ref = useRef();
useEffect(() => {
setMounted(true);
}, []);
useModalEffects({
modalRef: ref,
active: mounted && visible,
});
return useMemo(
() => ({
identifier,
visible,
setVisible,
mounted,
ref,
trigger: ({ dismiss }) => {
invariant(
dismiss,
"Modal/ModalContext cannot be used with prop 'toggle'. Please use prop 'dismiss' instead.",
);
return {
props: {
onPress: () => {
setVisible(false);
},
},
};
},
}),
[visible],
);
}
|
Disable unused test for now. | from __future__ import division
from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
from h2o.estimators import H2OGradientBoostingEstimator
def pyunit_make_metrics():
fr = h2o.import_file(pyunit_utils.locate("smalldata/logreg/prostate.csv"))
fr["CAPSULE"] = fr["CAPSULE"].asfactor()
fr["RACE"] = fr["RACE"].asfactor()
fr.describe()
response = "AGE"
predictors = range(1,fr.ncol)
# model = H2OGradientBoostingEstimator()
# model.train(x=predictors,y=response,training_frame=fr)
# p = model.model_performance(train=True)
# p = make_metrics(predicted,actual,"gaussian")
if __name__ == "__main__":
pyunit_utils.standalone_test(pyunit_make_metrics)
else:
pyunit_make_metrics()
| from __future__ import division
from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
from h2o.estimators import H2OGradientBoostingEstimator
def pyunit_make_metrics():
fr = h2o.import_file(pyunit_utils.locate("smalldata/logreg/prostate.csv"))
fr["CAPSULE"] = fr["CAPSULE"].asfactor()
fr["RACE"] = fr["RACE"].asfactor()
fr.describe()
response = "AGE"
predictors = range(1,fr.ncol)
model = H2OGradientBoostingEstimator()
model.train(x=predictors,y=response,training_frame=fr)
p = model.model_performance(train=True)
# p = make_metrics(predicted,actual,"gaussian")
if __name__ == "__main__":
pyunit_utils.standalone_test(pyunit_make_metrics)
else:
pyunit_make_metrics() |
Change comment to json key | 'use strict';
var _ = require('lodash');
/**
* Format where expression.
*
* @param {string[]|string} keys Array of keys to omit in query
* @param {string[]|string} query Array of parameter to use in where
* @param {string[]|string} jsonkeys Array of json keys to use in query
*/
module.exports = function (keys, query, jsonkeys) {
var where = _.omit(query, keys);
/**
* Omit all keys in 'where' who not value jonskeys[] + '.'
* Exemple:
* where = {id :5, data.team: 456}
* jsonkeys = [data]
* Result where = {data.team: 456} why data.team contains data.
*/
where = _.reduce(where, function(result, value, key) {
if (_.contains(jsonkeys, key.split('.')[0])) {
result[key] = value;
}
return result;
}, {});
var whereRaw = '';
_.each(where, function(value, key) {
var tab = key.split('.');
if (!whereRaw) {
whereRaw = tab[0] + '->>\'' + tab[1] + '\' = \'' + value + '\'';
} else {
whereRaw += ' AND ' + tab[0] + '->>\'' + tab[1] + '\' = \'' + value + '\'';
}
});
return whereRaw;
};
| 'use strict';
var _ = require('lodash');
/**
* Format where expression.
*
* @param {string[]|string} keys Array of keys to omit in query
* @param {string[]|string} query Array of parameter to use in where
* @param {string[]|string} jsonkeys Array of keys json to use in query
*/
module.exports = function (keys, query, jsonkeys) {
var where = _.omit(query, keys);
/**
* Omit all keys in 'where' who not value jonskeys[] + '.'
* Exemple:
* where = {id :5, data.team: 456}
* jsonkeys = [data]
* Result where = {data.team: 456} why data.team contains data.
*/
where = _.reduce(where, function(result, value, key) {
if (_.contains(jsonkeys, key.split('.')[0])) {
result[key] = value;
}
return result;
}, {});
var whereRaw = '';
_.each(where, function(value, key) {
var tab = key.split('.');
if (!whereRaw) {
whereRaw = tab[0] + '->>\'' + tab[1] + '\' = \'' + value + '\'';
} else {
whereRaw += ' AND ' + tab[0] + '->>\'' + tab[1] + '\' = \'' + value + '\'';
}
});
return whereRaw;
};
|
Load file content and set file base for proper destination | /**
* Created by Maurice on 6/13/2015.
*/
'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var mainBowerFiles = require('main-bower-files');
var fs = require('fs');
module.exports = function () {
return through.obj(function (file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError('gulp-main-bower-files', 'Streams are not supported!'));
return cb();
}
if (file.isBuffer()) {
var fileNames = mainBowerFiles();
fileNames.forEach(function (fileName) {
var newFile = file.clone();
newFile.path = fileName;
newFile.base += 'bower_components/';
newFile.contents = fs.readFileSync(newFile.path);
this.push(newFile);
}, this);
}
cb();
});
}; | /**
* Created by Maurice on 6/13/2015.
*/
'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var mainBowerFiles = require('main-bower-files');
module.exports = function () {
return through.obj(function (file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError('gulp-main-bower-files', 'Streams are not supported!'));
return cb();
}
if (file.isBuffer()) {
var fileNames = mainBowerFiles();
fileNames.forEach(function (fileName) {
var newFile = file.clone();
newFile.path = fileName;
this.push(newFile);
}, this);
}
cb();
});
}; |
Replace f_SimpleCache usage by f_DataCacheService | <?php
class uixul_InitializeAction extends f_action_BaseAction
{
/**
* @param Context $context
* @param Request $request
*/
public function _execute($context, $request)
{
f_persistentdocument_PersistentProvider::getInstance()->clearFrameworkCache();
//f_SimpleCache::clear();
f_DataCacheService::getInstance()->clearAll();
f_util_FileUtils::clearDir(f_util_FileUtils::buildCachePath('template'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('binding'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('css'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('js'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('htmlpreview'));
return $this->getSuccessView();
}
} | <?php
class uixul_InitializeAction extends f_action_BaseAction
{
/**
* @param Context $context
* @param Request $request
*/
public function _execute($context, $request)
{
f_persistentdocument_PersistentProvider::getInstance()->clearFrameworkCache();
f_SimpleCache::clear();
f_util_FileUtils::clearDir(f_util_FileUtils::buildCachePath('template'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('binding'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('css'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('js'));
f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('htmlpreview'));
return $this->getSuccessView();
}
} |
Prepare new package for PyPI publication | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='typogrified',
version='0.0.0',
packages=find_packages(),
author='Justin Mayer',
author_email='entroP@gmail.com',
license='BSD',
description='Filters to enhance web typography, including support for Django & Jinja templates',
long_description=open('README.rst').read(),
url='https://github.com/justinmayer/typogrify',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Framework :: Flask',
'Topic :: Utilities'
],
install_requires=['smartypants>=1.6']
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='typogrify',
version='2.0.0',
packages=find_packages(),
author='Christian Metts',
author_email='xian@mintchaos.com',
license='BSD',
description='Typography related template filters for Django & Jinja2 applications',
long_description=open('README.rst').read(),
url='https://github.com/mintchaos/typogrify',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Topic :: Utilities'
],
install_requires=['smartypants>=1.6']
)
|
Check if Image really is uploaded | <?php
class Kwf_Controller_Action_Welcome_ContentController extends Kwf_Controller_Action
{
public function indexAction()
{
$this->view->content = '';
try {
$t = new Kwf_Util_Model_Welcome();
$row = $t->getRow(1);
if ($row) {
$this->view->content = $row->content;
}
} catch (Zend_Db_Statement_Exception $e) {
//wenn tabelle nicht existiert fehler abfangen
$row = null;
}
if ($row && $row->getParentRow('WelcomeImage')) {
$this->view->image = Kwf_Media::getUrlByRow(
$row, 'WelcomeImage'
);
$this->view->imageSize = Kwf_Media::getDimensionsByRow($row, 'WelcomeImage');
} else {
$this->view->image = false;
}
$this->view->application = Zend_Registry::get('config')->application;
$this->_helper->viewRenderer->setRender('Welcome');
}
}
| <?php
class Kwf_Controller_Action_Welcome_ContentController extends Kwf_Controller_Action
{
public function indexAction()
{
$this->view->content = '';
try {
$t = new Kwf_Util_Model_Welcome();
$row = $t->getRow(1);
if ($row) {
$this->view->content = $row->content;
}
} catch (Zend_Db_Statement_Exception $e) {
//wenn tabelle nicht existiert fehler abfangen
$row = null;
}
if ($row) {
$this->view->image = Kwf_Media::getUrlByRow(
$row, 'WelcomeImage'
);
$this->view->imageSize = Kwf_Media::getDimensionsByRow($row, 'WelcomeImage');
} else {
$this->view->image = false;
}
$this->view->application = Zend_Registry::get('config')->application;
$this->_helper->viewRenderer->setRender('Welcome');
}
}
|
Improve naming of variable and message | // @flow
/* eslint-disable no-console */
import path from 'path';
import { green } from 'chalk';
import inquirer from 'inquirer';
import createConfig from '../createConfig';
import { fileExists } from '../util/fs';
import { printErrors } from '../printErrors';
import typeof Yargs from 'yargs';
import type { BaseArgs } from './index';
const name = 'init';
const description = 'Creates a .amazeeio.yml config in the current working directory';
export async function setup(yargs: Yargs): Promise<Object> {
return yargs.usage(`$0 ${name} - ${description}`).argv;
}
export async function run({ cwd, clog = console.log }: BaseArgs): Promise<number> {
const filepath = path.join(cwd, '.amazeeio.yml');
if (await fileExists(filepath)) {
const { overwrite } = await inquirer.prompt([
{
type: 'confirm',
name: 'overwrite',
message: `File '${filepath}' already exists! Overwrite?`,
default: false,
},
]);
if (!overwrite) return printErrors(clog, `Not overwriting existing file '${filepath}'.`);
}
try {
clog(`Creating file '${filepath}'...`);
await writeDefaultConfig(filepath);
clog(green('Configuration file created!'));
} catch (e) {
return printErrors(clog, `Error occurred while writing to ${filepath}:`, e);
}
return 0;
}
export default {
setup,
name,
description,
run,
};
| // @flow
/* eslint-disable no-console */
import path from 'path';
import { green } from 'chalk';
import inquirer from 'inquirer';
import createConfig from '../createConfig';
import { fileExists } from '../util/fs';
import { printErrors } from '../printErrors';
import typeof Yargs from 'yargs';
import type { BaseArgs } from './index';
const name = 'init';
const description = 'Creates a .amazeeio.yml config in the current working directory';
export async function setup(yargs: Yargs): Promise<Object> {
return yargs.usage(`$0 ${name} - ${description}`).argv;
}
export async function run({ cwd, clog = console.log }: BaseArgs): Promise<number> {
const filepath = path.join(cwd, '.amazeeio.yml');
if (await fileExists(filepath)) {
const { replace } = await inquirer.prompt([
{
type: 'confirm',
name: 'replace',
message: `File '${filepath}' already exists! Replace?`,
default: false,
},
]);
if (!replace) return printErrors(clog, `Not replacing existing file '${filepath}'.`);
}
try {
clog(`Creating file '${filepath}'...`);
await writeDefaultConfig(filepath);
clog(green('Configuration file created!'));
} catch (e) {
return printErrors(clog, `Error occurred while writing to ${filepath}:`, e);
}
return 0;
}
export default {
setup,
name,
description,
run,
};
|
Fix analogWrite API naming issue | from pygalileo.io.dio import Dio
from pygalileo.io.pwmio import Pwmio
'''
Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT
'''
INPUT = 'in'
OUTPUT = 'out'
'''
Defining Pin Levels: HIGH and LOW
'''
HIGH = 1
LOW = 0
_DIOS = {}
def pinMode(pin, mode):
if pin not in _DIOS:
dio = Dio(pin)
dio.direction(mode)
_DIOS[pin] = dio
else:
dio = _DIOS[pin]
dio.direction(mode)
def digitalWrite(pin, value):
dio = _DIOS[pin]
dio.value(value)
def digitalRead(pin):
dio = _DIOS[pin]
return dio.value()
def analogWrite(pin, value):
dio = _DIOS[pin]
return dio.pwm(value)
| from pygalileo.io.dio import Dio
from pygalileo.io.pwmio import Pwmio
'''
Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT
'''
INPUT = 'in'
OUTPUT = 'out'
'''
Defining Pin Levels: HIGH and LOW
'''
HIGH = 1
LOW = 0
_DIOS = {}
def pinMode(pin, mode):
if pin not in _DIOS:
dio = Dio(pin)
dio.direction(mode)
_DIOS[pin] = dio
else:
dio = _DIOS[pin]
dio.direction(mode)
def digitalWrite(pin, value):
dio = _DIOS[pin]
dio.value(value)
def digitalRead(pin):
dio = _DIOS[pin]
return dio.value()
def analogyWrite(pin, value):
dio = _DIOS[pin]
return dio.pwm(value) |
CLOUDSTACK-1148: Change URL from google as 503 returns from that site cause test to erroneously fail.
Signed-off-by: Simon Waterhouse <d0c6b5888fa60b3b8207dfa2bef2890dd742fceb@citrix.com>
Signed-off-by: Rohit Yadav <0fa72ca37c4b5fa62675187ce32ea6c9f842fd52@apache.org> | // 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 com.cloud.agent;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
public class TestAgentShell extends TestCase {
protected final static Logger s_logger = Logger.getLogger(TestAgentShell.class);
public void testWget() {
File file = null;
try {
file = File.createTempFile("wget", ".html");
AgentShell.wget("http://www.apache.org/", file);
if (s_logger.isDebugEnabled()) {
s_logger.debug("file saved to " + file.getAbsolutePath());
}
} catch (final IOException e) {
s_logger.warn("Exception while downloading agent update package, ", e);
}
}
}
| // 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 com.cloud.agent;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
public class TestAgentShell extends TestCase {
protected final static Logger s_logger = Logger.getLogger(TestAgentShell.class);
public void testWget() {
File file = null;
try {
file = File.createTempFile("wget", ".html");
AgentShell.wget("http://www.google.com/", file);
if (s_logger.isDebugEnabled()) {
s_logger.debug("file saved to " + file.getAbsolutePath());
}
} catch (final IOException e) {
s_logger.warn("Exception while downloading agent update package, ", e);
}
}
}
|
Update headers to allow file access origin | var exec = require('child_process').exec;
var express = require('express');
var fs = require('fs');
var socket = require('./socket').socket;
var serve = function () {
exec('mkdir -p test-project/gen/ && cat dasBoot/**.js > test-project/gen/dasBoot.js',
function(error, stdout, stderr){
var frontend = express();
frontend.use(express.static(__dirname + '/frontend'));
frontend.listen(8000);
var sockets = express();
var sockets_server = require('http').createServer(sockets);
socket.installHandlers(sockets_server, {prefix: '/socket'});
sockets_server.listen(1337, '0.0.0.0');
var files = express();
files.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
return next();
});
files.use(express.static(__dirname + '/test-project'));
files.listen(9999);
console.log('serving nin on http://localhost:8000');
});
}
module.exports = {serve: serve};
| var exec = require('child_process').exec;
var express = require('express');
var fs = require('fs');
var socket = require('./socket').socket;
var serve = function () {
exec('mkdir -p test-project/gen/ && cat dasBoot/**.js > test-project/gen/dasBoot.js',
function(error, stdout, stderr){
var frontend = express();
frontend.use(express.static(__dirname + '/frontend'));
frontend.listen(8000);
var sockets = express();
var sockets_server = require('http').createServer(sockets);
socket.installHandlers(sockets_server, {prefix: '/socket'});
sockets_server.listen(1337, '0.0.0.0');
var files = express();
files.use(express.static(__dirname + '/test-project'));
files.listen(9999);
console.log('serving nin on http://localhost:8000');
});
}
module.exports = {serve: serve};
|
Remove try/except block around CDLL | """
This module provides bindings to C functions defined by OpenMC shared library.
When the :mod:`openmc` package is imported, the OpenMC shared library is
automatically loaded. Calls to the OpenMC library can then be via functions or
objects in the :mod:`openmc.capi` subpackage, for example:
.. code-block:: python
openmc.capi.init()
openmc.capi.run()
openmc.capi.finalize()
"""
from ctypes import CDLL
import sys
from warnings import warn
import pkg_resources
# Determine shared-library suffix
if sys.platform == 'darwin':
_suffix = 'dylib'
else:
_suffix = 'so'
# Open shared library
_filename = pkg_resources.resource_filename(
__name__, '_libopenmc.{}'.format(_suffix))
_dll = CDLL(_filename)
from .error import *
from .core import *
from .nuclide import *
from .material import *
from .cell import *
from .tally import *
| """
This module provides bindings to C functions defined by OpenMC shared library.
When the :mod:`openmc` package is imported, the OpenMC shared library is
automatically loaded. Calls to the OpenMC library can then be via functions or
objects in the :mod:`openmc.capi` subpackage, for example:
.. code-block:: python
openmc.capi.init()
openmc.capi.run()
openmc.capi.finalize()
"""
from ctypes import CDLL
import sys
from warnings import warn
import pkg_resources
# Determine shared-library suffix
if sys.platform == 'darwin':
_suffix = 'dylib'
else:
_suffix = 'so'
# Open shared library
_filename = pkg_resources.resource_filename(
__name__, '_libopenmc.{}'.format(_suffix))
try:
_dll = CDLL(_filename)
except OSError:
warn("OpenMC shared library is not available from the Python API. This "
"means you will not be able to use openmc.capi to make in-memory "
"calls to OpenMC.")
else:
from .error import *
from .core import *
from .nuclide import *
from .material import *
from .cell import *
from .tally import *
|
Change delta to use 'change:delta' event | (function() {
'use strict';
var app = this.app
, _ = require('lodash')
, debug = require('debug')('signalk-server:interfaces:ws')
, Primus = require('primus')
, primus = new Primus(app.server, {
transformer: 'websockets',
pathname: '/signalk/stream' })
;
app.connections = {};
debug('Starting Primus/WS interface');
primus.on('connection', function(spark) {
debug(spark.id + " connected with params " + JSON.stringify(spark.query));
var onChange;
var event;
if (spark.query.stream === 'delta') {
event = 'change:delta';
onChange = function(data) {
spark.write(data);
}
} else {
event = 'change';
onChange = function(data) {
spark.write(app.signalk.retrieve());
};
spark.write(app.signalk.retrieve());//output tree after connect
}
app.signalk.on(event, function(data) {
onChange(data);
});
spark.onDisconnect = function() {
app.signalk.removeListener(event, onChange);
}
app.connections[spark.id] = spark;
});
primus.on('disconnection', function(spark) {
spark.onDisconnect();
debug(spark.id + " disconnected");
});
}).call(global); | (function() {
'use strict';
var app = this.app
, _ = require('lodash')
, debug = require('debug')('signalk-server:interfaces:ws')
, Primus = require('primus')
, primus = new Primus(app.server, {
transformer: 'websockets',
pathname: '/signalk/stream' })
;
app.connections = {};
debug('Starting Primus/WS interface');
primus.on('connection', function(spark) {
debug(spark.id + " connected with params " + JSON.stringify(spark.query));
var onChange;
if (spark.query.stream === 'delta') {
onChange = function(data) {
spark.write(data);
}
} else {
onChange = function(data) {
spark.write(app.signalk.retrieve());
};
spark.write(app.signalk.retrieve());//output tree after connect
}
app.signalk.on('change', function(data) {
onChange(data);
});
spark.onDisconnect = function() {
app.signalk.removeListener('change', onChange);
}
app.connections[spark.id] = spark;
});
primus.on('disconnection', function(spark) {
spark.onDisconnect();
debug(spark.id + " disconnected");
});
}).call(global); |
Update up to changes in es5-ext | 'use strict';
var customError = require('es5-ext/error/custom')
, logger = require('../lib/logger')();
module.exports = function (t, a) {
t = t(logger);
t(true, true, 'foo');
t.ok(false, 'bar');
t.not(false, true, 'not');
t.deep([1, 2], [1, 2], 'deep');
t.notDeep([1, 2], [2, 1], 'not deep');
t.throws(function () { throw customError('Test', 'TEST'); }, 'TEST',
'throws');
a.deep([logger[0].type, logger[0].data], ['pass', 'foo']);
a.deep([logger[1].type, logger[1].data.message], ['fail', 'bar']);
a.deep([logger[2].type, logger[2].data], ['pass', 'not'], "'not' support");
a.deep([logger[3].type, logger[3].data], ['pass', 'deep'], "'deep' support");
a.deep([logger[4].type, logger[4].data], ['pass', 'not deep'],
"'not deep' support");
a.deep([logger[5].type, logger[5].data], ['pass', 'throws'],
"custom trhows support");
};
| 'use strict';
var CustomError = require('es5-ext/error/custom')
, logger = require('../lib/logger')();
module.exports = function (t, a) {
t = t(logger);
t(true, true, 'foo');
t.ok(false, 'bar');
t.not(false, true, 'not');
t.deep([1, 2], [1, 2], 'deep');
t.notDeep([1, 2], [2, 1], 'not deep');
t.throws(function () { throw new CustomError('Test', 'TEST'); }, 'TEST',
'throws');
a.deep([logger[0].type, logger[0].data], ['pass', 'foo']);
a.deep([logger[1].type, logger[1].data.message], ['fail', 'bar']);
a.deep([logger[2].type, logger[2].data], ['pass', 'not'], "'not' support");
a.deep([logger[3].type, logger[3].data], ['pass', 'deep'], "'deep' support");
a.deep([logger[4].type, logger[4].data], ['pass', 'not deep'],
"'not deep' support");
a.deep([logger[5].type, logger[5].data], ['pass', 'throws'],
"custom trhows support");
};
|
Remove extra whitespace from imports | from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from hijack.helpers import login_user
from hijack.helpers import release_hijack as release_hijack_fx
from compat import get_user_model
@staff_member_required
def login_with_id(request, userId):
# input(userId) is unicode
try:
userId = int(userId)
except:
return HttpResponseBadRequest('userId must be an integer value.')
user = get_object_or_404(get_user_model(), pk=userId)
return login_user(request, user)
@staff_member_required
def login_with_email(request, email):
user = get_object_or_404(get_user_model(), email=email)
return login_user(request, user)
@staff_member_required
def login_with_username(request, username):
user = get_object_or_404(get_user_model(), username=username)
return login_user(request, user)
@login_required
def release_hijack(request):
return release_hijack_fx(request)
@login_required
def disable_hijack_warning(request):
request.session['is_hijacked_user']=False
return HttpResponseRedirect(request.GET.get('next','/'))
| from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from hijack.helpers import login_user
from hijack.helpers import release_hijack as release_hijack_fx
from compat import get_user_model
@staff_member_required
def login_with_id(request, userId):
# input(userId) is unicode
try:
userId = int(userId)
except:
return HttpResponseBadRequest('userId must be an integer value.')
user = get_object_or_404(get_user_model(), pk=userId)
return login_user(request, user)
@staff_member_required
def login_with_email(request, email):
user = get_object_or_404(get_user_model(), email=email)
return login_user(request, user)
@staff_member_required
def login_with_username(request, username):
user = get_object_or_404(get_user_model(), username=username)
return login_user(request, user)
@login_required
def release_hijack(request):
return release_hijack_fx(request)
@login_required
def disable_hijack_warning(request):
request.session['is_hijacked_user']=False
return HttpResponseRedirect(request.GET.get('next','/'))
|
Switch revision query to outer join | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload, contains_eager
from changes.api.base import APIView
from changes.models import Build, Project, Revision, Source
class ProjectCommitBuildsAPIView(APIView):
def get(self, project_id, commit_id):
project = Project.get(project_id)
if not project:
return '', 404
repo = project.repository
revision = Revision.query.filter(
Revision.repository_id == repo.id,
Revision.sha == commit_id,
).outerjoin(Revision.author).first()
if not revision:
return '', 404
build_query = Build.query.options(
joinedload('author'),
contains_eager('source').joinedload('revision'),
).join(
Source, Build.source_id == Source.id,
).filter(
Build.project_id == project.id,
Source.revision_sha == revision.sha,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc())
return self.paginate(build_query)
| from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload, contains_eager
from changes.api.base import APIView
from changes.models import Build, Project, Revision, Source
class ProjectCommitBuildsAPIView(APIView):
def get(self, project_id, commit_id):
project = Project.get(project_id)
if not project:
return '', 404
repo = project.repository
revision = Revision.query.filter(
Revision.repository_id == repo.id,
Revision.sha == commit_id,
).join(Revision.author).first()
if not revision:
return '', 404
build_query = Build.query.options(
joinedload('author'),
contains_eager('source').joinedload('revision'),
).join(
Source, Build.source_id == Source.id,
).filter(
Build.project_id == project.id,
Source.revision_sha == revision.sha,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc())
return self.paginate(build_query)
|
Use support address for author email | # -*- coding: UTF-8 -*-
from distutils.core import setup
from setuptools import find_packages
import time
_version = "2.9.dev%s" % int(time.time())
_packages = find_packages('.', exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
setup(
name='laterpay-client',
version=_version,
description="LaterPay API client",
long_description=open("README.rst").read(),
author="LaterPay GmbH",
author_email="support@laterpay.net",
url="https://github.com/laterpay/laterpay-client-python",
license='MIT',
keywords="LaterPay API client",
test_suite="test_client",
packages=_packages,
package_data={'laterpay.django': ['templates/laterpay/inclusion/*']},
classifiers=(
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules",
),
)
| # -*- coding: UTF-8 -*-
from distutils.core import setup
from setuptools import find_packages
import time
_version = "2.9.dev%s" % int(time.time())
_packages = find_packages('.', exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
setup(
name='laterpay-client',
version=_version,
description="LaterPay API client",
long_description=open("README.rst").read(),
author="LaterPay GmbH",
author_email="TODO",
url="https://github.com/laterpay/laterpay-client-python",
license='MIT',
keywords="LaterPay API client",
test_suite="test_client",
packages=_packages,
package_data={'laterpay.django': ['templates/laterpay/inclusion/*']},
classifiers=(
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules",
),
)
|
Normalize the issue blueprint's code base | from flask import (
Blueprint,
flash,
redirect,
url_for,
render_template)
from flask_login import current_user
from flask_babel import gettext as _
from catwatch.blueprints.issue.models import Issue
from catwatch.blueprints.issue.forms import SupportForm
issue = Blueprint('issue', __name__, template_folder='templates')
@issue.route('/support', methods=['GET', 'POST'])
def support():
form = SupportForm(obj=current_user)
if form.validate_on_submit():
i = Issue()
form.populate_obj(i)
i.save()
flash(_('Help is on the way, expect a response shortly.'), 'success')
return redirect(url_for('issue.support'))
return render_template('issue/support.jinja2', form=form)
| from flask import (
Blueprint,
flash,
redirect,
url_for,
render_template)
from flask_login import current_user
from flask_babel import gettext as _
from catwatch.blueprints.issue.models import Issue
from catwatch.blueprints.issue.forms import SupportForm
issue = Blueprint('issue', __name__, template_folder='templates')
@issue.route('/support', methods=['GET', 'POST'])
def support():
# Pre-populate the email field if the user is signed in.
form = SupportForm(obj=current_user)
if form.validate_on_submit():
i = Issue()
form.populate_obj(i)
i.save()
flash(_('Help is on the way, expect a response shortly.'), 'success')
return redirect(url_for('issue.support'))
return render_template('issue/support.jinja2', form=form)
|
Add support key for Travis LINT check | # -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Timesheet Activities Report',
'version': '8.0.1.1.0',
'category': 'Human Resources',
'depends': [
'project_timesheet',
'project_issue_sheet',
'business_requirement',
'business_requirement_deliverable_project',
'project_task_category'
],
'author': 'Elico Corp',
'support': 'support@elico-corp.com',
'license': 'AGPL-3',
'website': 'https://www.elico-corp.com',
'data': [
'report/timesheet_activity_report_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False
}
| # -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Timesheet Activities Report',
'version': '8.0.1.1.0',
'category': 'Human Resources',
'depends': [
'project_timesheet',
'project_issue_sheet',
'business_requirement',
'business_requirement_deliverable_project',
'project_task_category'
],
'author': 'Elico Corp',
'license': 'AGPL-3',
'website': 'https://www.elico-corp.com',
'data': [
'report/timesheet_activity_report_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False
}
|
Update file extension to use public dir instead of web dir | <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class FileExtension extends AbstractExtension
{
/**
* @var string
*/
private $projectDir;
public function __construct(string $projectDir)
{
$this->projectDir = $projectDir;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new TwigFunction('file', function ($file) {
return file_get_contents($this->projectDir.'/public/'.ltrim($file, '\\'));
}, ['is_safe' => ['css', 'html']]),
];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'solidinvoice_core.twig.file';
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class FileExtension extends AbstractExtension
{
/**
* @var string
*/
private $projectDir;
public function __construct(string $projectDir)
{
$this->projectDir = $projectDir;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new TwigFunction('file', function ($file) {
return file_get_contents($this->projectDir.'/web/'.ltrim($file, '\\'));
}, ['is_safe' => ['css', 'html']]),
];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'solidinvoice_core.twig.file';
}
}
|
Fix typo in bundle extension | <?php
namespace Becklyn\AssetsBundle\DependencyInjection;
use Becklyn\AssetsBundle\Asset\AssetGenerator;
use Becklyn\AssetsBundle\Finder\AssetsFinder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class BecklynAssetsExtension extends Extension
{
/**
* @inheritdoc
*/
public function load (array $configs, ContainerBuilder $container)
{
// process config
$config = $this->processConfiguration(new BecklynAssetsConfiguration(), $configs);
// load services
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__ . "/../Resources/config")
);
$loader->load("services.yaml");
// update services config with configuration values
$container->getDefinition(AssetGenerator::class)
->setArgument('$publicPath', rtrim($config["public_path"]))
->setArgument('$outputDir', $config["output_dir"]);
$container->getDefinition(AssetsFinder::class)
->setArgument('$publicPath', $config["public_path"]);
}
}
| <?php
namespace Becklyn\AssetsBundle\DependencyInjection;
use Becklyn\AssetsBundle\Asset\AssetGenerator;
use Becklyn\AssetsBundle\Finder\AssetsFinder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class BecklynAssetsExtension extends Extension
{
/**
* @inheritdoc
*/
public function load (array $configs, ContainerBuilder $container)
{
// process config
$config = $this->processConfiguration(new BecklynAssetsConfiguration(), $configs);
// load services
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__ . "/../Resources/config")
);
$loader->load("services.yaml");
// update services config with configuration values
$container->getDefinition(AssetGenerator::class)
->setArgument('$publicPath', rtrim($config["public_path"])
->setArgument('$outputDir', $config["output_dir"]);
$container->getDefinition(AssetsFinder::class)
->setArgument('$publicPath', $config["public_path"]);
}
}
|
Add test prompt message when no fixture is selected | const React = window.React;
import RangeInputFixtures from './range-inputs';
import TextInputFixtures from './text-inputs';
import SelectFixtures from './selects';
import TextAreaFixtures from './textareas/';
/**
* A simple routing component that renders the appropriate
* fixture based on the location pathname.
*/
const FixturesPage = React.createClass({
render() {
switch (window.location.pathname) {
case '/text-inputs':
return <TextInputFixtures />;
case '/range-inputs':
return <RangeInputFixtures />;
case '/selects':
return <SelectFixtures />;
case '/textareas':
return <TextAreaFixtures />;
default:
return <p>Please select a text fixture.</p>
}
},
});
module.exports = FixturesPage;
| const React = window.React;
import RangeInputFixtures from './range-inputs';
import TextInputFixtures from './text-inputs';
import SelectFixtures from './selects';
import TextAreaFixtures from './textareas/';
/**
* A simple routing component that renders the appropriate
* fixture based on the location pathname.
*/
const FixturesPage = React.createClass({
render() {
switch (window.location.pathname) {
case '/text-inputs':
return <TextInputFixtures />;
case '/range-inputs':
return <RangeInputFixtures />;
case '/selects':
return <SelectFixtures />;
case '/textareas':
return <TextAreaFixtures />;
default:
return <span />;
}
},
});
module.exports = FixturesPage;
|
Make cookies readable from frontend | import Cookies from 'cookies'
export function checkSession (req, res, next) {
const cookies = new Cookies(req, res)
const userId = cookies.get('user_id')
if (!userId) {
return res.redirect('/login')
}
return req
.core.users.show(userId)
.then(user => {
req.currentUser = user
next()
})
.catch(() => res.redirect('/login'))
}
export function login (req, res, next) {
if (!req.body) {
return res.render('index')
}
const cookies = new Cookies(req, res)
return req
.core.sessions.create({
email: req.body.email,
password: req.body.password
})
.then(session => {
cookies
.set('access_token', session.access_token, {httpOnly: false})
.set('user_id', session.user.id, {httpOnly: false})
req.user = session.user
next()
})
.catch(() => res.render('index'))
}
export const setLiqenCore = core => (req, res, next) => {
const cookies = new Cookies(req, res)
const accessToken = cookies.get('access_token')
if (accessToken) {
req.core = core(accessToken)
} else {
req.core = core()
}
next()
}
| import Cookies from 'cookies'
export function checkSession (req, res, next) {
const cookies = new Cookies(req, res)
const userId = cookies.get('user_id')
if (!userId) {
return res.redirect('/login')
}
return req
.core.users.show(userId)
.then(user => {
req.currentUser = user
next()
})
.catch(() => res.redirect('/login'))
}
export function login (req, res, next) {
if (!req.body) {
return res.render('index')
}
const cookies = new Cookies(req, res)
return req
.core.sessions.create({
email: req.body.email,
password: req.body.password
})
.then(session => {
cookies
.set('access_token', session.access_token)
.set('user_id', session.user.id)
req.user = session.user
next()
})
.catch(() => res.render('index'))
}
export const setLiqenCore = core => (req, res, next) => {
const cookies = new Cookies(req, res)
const accessToken = cookies.get('access_token')
if (accessToken) {
req.core = core(accessToken)
} else {
req.core = core()
}
next()
}
|
Print the returned error message. | const eg = require('../../eg');
module.exports = class extends eg.Generator {
constructor (args, opts) {
super(args, opts);
this.configureCommand({
command: 'create [options] <scope..>',
desc: 'Create a scope',
builder: yargs =>
yargs
.usage(`Usage: $0 ${process.argv[2]} create [options] <scope..>`)
.example(`$0 ${process.argv[2]} create scope_name`)
});
}
prompting () {
const argv = this.argv;
const scopes = Array.isArray(argv.scope)
? argv.scope
: [argv.scope];
return this.admin.scopes.create(scopes)
.then(res => {
if (argv.q) {
this.stdout(`${scopes}`);
} else {
this.log.ok(`Created ${scopes}`);
}
})
.catch(err => {
this.log.error(err.response.text);
});
};
};
| const eg = require('../../eg');
module.exports = class extends eg.Generator {
constructor (args, opts) {
super(args, opts);
this.configureCommand({
command: 'create [options] <scope..>',
desc: 'Create a scope',
builder: yargs =>
yargs
.usage(`Usage: $0 ${process.argv[2]} create [options] <scope..>`)
.example(`$0 ${process.argv[2]} create scope_name`)
});
}
prompting () {
const argv = this.argv;
const scopes = Array.isArray(argv.scope)
? argv.scope
: [argv.scope];
return this.admin.scopes.create(scopes)
.then(res => {
if (argv.q) {
this.stdout(`${scopes}`);
} else {
this.log.ok(`Created ${scopes}`);
}
})
.catch(err => {
this.log.error(err.message);
});
};
};
|
Add /flip and /flop commands | /*
* Copyright (c) 2015 Nick Jurgens <nicholas2010081@gmail.com>
*/
'use strict';
import Poller from './poller';
import api from './api';
let poller = new Poller();
poller.dispatcher
.register('ping', (text, message) => {
console.dir(message);
return 'pong';
})
.register('marco', (text, message) => {
return 'polo';
})
.register('me', (text, message) => {
console.dir(message);
if (!text.length) {
return null;
}
let {first_name, last_name} = message.from;
let name = last_name ? `${first_name} ${last_name}` : first_name;
return `${name} ${text}`;
})
.register('flip', (text, message) => {
return '(╯°□°)╯︵ ┻━┻';
})
.register('flop', (text, message) => {
return '┬─┬ノ( º _ ºノ)';
});
poller.start();
| /*
* Copyright (c) 2015 Nick Jurgens <nicholas2010081@gmail.com>
*/
'use strict';
import Poller from './poller';
import api from './api';
let poller = new Poller();
poller.dispatcher
.register('ping', (text, message) => {
console.dir(message);
return 'pong';
})
.register('marco', (text, message) => {
return 'polo';
})
.register('me', (text, message) => {
console.dir(message);
if (!text.length) {
return null;
}
let {first_name, last_name} = message.from;
let name = last_name ? `${first_name} ${last_name}` : first_name;
return `${name} ${text}`;
});
poller.start();
|
Correct newlines for gofmt comapt | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
var f = flag.String("f", "", "Output file, else stdout.")
var p = flag.String("p", "main", "Package.")
var fRE = regexp.MustCompile("[a-zA-Z0-9_]+")
func main() {
flag.Parse()
w := os.Stdout
var err error
if *f != "" {
if w, err = os.Create(*f); err != nil {
log.Fatal(err)
}
defer w.Close()
}
fmt.Fprintf(w, "package %s\n", *p)
for _, fname := range flag.Args() {
b, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatal(err)
}
v := strings.Join(fRE.FindAllString(fname, -1), "_")
fmt.Fprintf(w, "\nvar %s = []byte(%q)\n", v, b)
}
}
| package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
var f = flag.String("f", "", "Output file, else stdout.")
var p = flag.String("p", "main", "Package.")
var fRE = regexp.MustCompile("[a-zA-Z0-9_]+")
func main() {
flag.Parse()
w := os.Stdout
var err error
if *f != "" {
if w, err = os.Create(*f); err != nil {
log.Fatal(err)
}
defer w.Close()
}
fmt.Fprintf(w, "package %s", *p)
for _, fname := range flag.Args() {
b, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatal(err)
}
v := strings.Join(fRE.FindAllString(fname, -1), "_")
fmt.Fprintf(w, "\n\nvar %s = []byte(%q)", v, b)
}
}
|
Fix indentation of the C grammar | define(function() {
return function(Prism) {
Prism.languages.c = Prism.languages.extend('clike', {
'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g,
'operator': /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|={1,2}|\^|~|%|(&){1,2}|\|?\||\?|\*|\//g
});
Prism.languages.insertBefore('c', 'keyword', {
//property class reused for macro statements
'property': /#\s*[a-zA-Z]+/g
});
};
});
| define(function() {
// Export
return function(Prism) {
Prism.languages.c = Prism.languages.extend('clike', {
'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g,
'operator': /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|={1,2}|\^|~|%|(&){1,2}|\|?\||\?|\*|\//g
});
Prism.languages.insertBefore('c', 'keyword', {
//property class reused for macro statements
'property': /#\s*[a-zA-Z]+/g
});
};
});
|
Add time limit for worker threads | package cartel
import (
"sync"
"time"
)
type Pool struct {
Input chan Task
Output chan OutputValue
wg *sync.WaitGroup
}
func (p Pool) End() {
close(p.Input)
p.wg.Wait()
}
func (p Pool) Do(t Task) {
p.Input <- t
}
func (p Pool) GetOutput() []OutputValue {
values := []OutputValue{}
for {
select {
case r, ok := <-p.Output:
if ok {
values = append(values, r)
} else {
return values
}
default:
return values
}
}
}
func (p Pool) worker() {
t := time.Now()
for {
since := time.Since(t)
if since.Minutes() > 5 {
p.wg.Done()
p.addWorker()
break
}
t, ok := <-p.Input
if !ok {
p.wg.Done()
break
}
v := t.Execute()
p.Output <- v
}
}
func (p Pool) addWorker() {
p.wg.Add(1)
go p.worker()
}
func NewPool(numberOfWorkers int) Pool {
jobs := make(chan Task, 100)
results := make(chan OutputValue, 100)
var wg sync.WaitGroup
p := Pool{jobs, results, &wg}
for w := 1; w <= numberOfWorkers; w++ {
p.addWorker()
}
return p
}
| package cartel
import (
"sync"
)
type Pool struct {
Input chan Task
Output chan OutputValue
wg *sync.WaitGroup
}
func (p Pool) End() {
close(p.Input)
p.wg.Wait()
}
func (p Pool) Do(t Task) {
p.Input <- t
}
func (p Pool) GetOutput() []OutputValue {
values := []OutputValue{}
for {
select {
case r, ok := <-p.Output:
if ok {
values = append(values, r)
} else {
return values
}
default:
return values
}
}
}
func (p Pool) worker() {
for {
t, ok := <-p.Input
if !ok {
p.wg.Done()
break
}
v := t.Execute()
p.Output <- v
}
}
func NewPool(numberOfWorkers int) Pool {
jobs := make(chan Task, 100)
results := make(chan OutputValue, 100)
var wg sync.WaitGroup
p := Pool{jobs, results, &wg}
for w := 1; w <= numberOfWorkers; w++ {
wg.Add(1)
go p.worker()
}
return p
}
|
Add models (router currently failing) | /**
* Test dependencies.
*
* This file lists out all of the individual spec (test) files so that they
* are run by our infrastructure.
*/
// App configuration.
var appConfig = require("../../../../app/js/app/config"),
cfgId = !!window.__karma__ ? "karma" : "browser";
appConfig.storeName = "notes-browserify-" + cfgId + "-mocha";
// Require each module directly.
appConfig.useLocalStorage ?
require("./collections/notes.spec") :
require("./collections/notes-rest.spec");
require("./models/note.spec");
// TODO require("./routers/router.spec");
// require("./views/note.spec");
// require("./views/note-nav.spec");
// require("./views/note-view.spec");
// require("./views/notes.spec");
// require("./views/notes-filter.spec");
// require("./views/notes-item.spec");
| /**
* Test dependencies.
*
* This file lists out all of the individual spec (test) files so that they
* are run by our infrastructure.
*/
// App configuration.
var appConfig = require("../../../../app/js/app/config"),
cfgId = !!window.__karma__ ? "karma" : "browser";
appConfig.storeName = "notes-browserify-" + cfgId + "-mocha";
// Require each module directly.
appConfig.useLocalStorage ?
require("./collections/notes.spec") :
require("./collections/notes-rest.spec");
// require("./models/note.spec");
// require("./routers/router.spec");
// require("./views/note.spec");
// require("./views/note-nav.spec");
// require("./views/note-view.spec");
// require("./views/notes.spec");
// require("./views/notes-filter.spec");
// require("./views/notes-item.spec");
|
Remove extra new line from log | "use strict";
const fs = require("fs");
const prettyDate = function(date) {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return months[date.getUTCMonth()] + " " + date.getUTCDate() + ", " + date.getUTCFullYear();
};
const log = function(text) {
const message = prettyDate(new Date(Date.now())) + ": " + text;
console.log(message); // eslint-disable-line no-console
fs.appendFile("log.txt", message, function(err) {
if (err) {
return console.log(err); // eslint-disable-line no-console
}
});
};
const ip2Hex = function(address) {
return address.split(".").map(function(octet) {
let hex = parseInt(octet, 10).toString(16);
if (hex.length === 1) {
hex = "0" + hex;
}
return hex;
}).join("");
};
module.exports = {
log,
prettyDate,
ip2Hex,
};
| "use strict";
const fs = require("fs");
const prettyDate = function(date) {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return months[date.getUTCMonth()] + " " + date.getUTCDate() + ", " + date.getUTCFullYear();
};
const log = function(text) {
const message = prettyDate(new Date(Date.now())) + ": " + text + "\n";
console.log(message); // eslint-disable-line no-console
fs.appendFile("log.txt", message, function(err) {
if (err) {
return console.log(err); // eslint-disable-line no-console
}
});
};
const ip2Hex = function(address) {
return address.split(".").map(function(octet) {
let hex = parseInt(octet, 10).toString(16);
if (hex.length === 1) {
hex = "0" + hex;
}
return hex;
}).join("");
};
module.exports = {
log,
prettyDate,
ip2Hex,
};
|
Fix reverse date range migration for Mongo 3.2 | /**
* Swap reversed DateRange values
*/
var updated = 0;
// Match all Dataset having temporal_coverage.start > temporal_coverage.end
const pipeline = [
{$project: {
cmp: {$cmp: ['$temporal_coverage.start', '$temporal_coverage.end']},
dataset: '$$ROOT'
}},
{$match: {cmp: {$gt: 0}}}
];
db.dataset.aggregate(pipeline).forEach(row => {
db.dataset.update(
{_id: row.dataset._id},
{'$set': {
'temporal_coverage.start': row.dataset.temporal_coverage.end,
'temporal_coverage.end': row.dataset.temporal_coverage.start,
}}
);
updated++;
});
print(`Updated ${updated} datasets with reversed temporal coverage.`);
| /**
* Swap reversed DateRange values
*/
var updated = 0;
// Match all Dataset having temporal_coverage.start > temporal_coverage.end
const pipeline = [
{$project: {
cmp: {$cmp: ['$temporal_coverage.start', '$temporal_coverage.end']},
obj: '$$ROOT'
}},
{$match: {cmp: {$gt: 0}}},
{$replaceRoot: {newRoot: '$obj'}}
];
db.dataset.aggregate(pipeline).forEach(dataset => {
db.dataset.update(
{_id: dataset._id},
{'$set': {
'temporal_coverage.start': dataset.temporal_coverage.end,
'temporal_coverage.end': dataset.temporal_coverage.start,
}}
);
updated++;
});
print(`Updated ${updated} datasets with reversed temporal coverage.`);
|
Add listener for hardware back button | /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet
} from 'react-native';
import Router from 'react-native-simple-router';
import ContestListScreen from './ContestListScreen';
class JumuNordost extends Component {
render() {
return (
<Router
firstRoute={firstRoute}
headerStyle={styles.header}
handleBackAndroid={true}
/>
)
}
}
const firstRoute = {
name: 'Contests',
component: ContestListScreen
};
const styles = StyleSheet.create({
container: {
flex: 1
},
header: {
backgroundColor: '#a9a9a9',
},
});
AppRegistry.registerComponent('JumuNordost', () => JumuNordost);
| /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet
} from 'react-native';
import Router from 'react-native-simple-router';
import ContestListScreen from './ContestListScreen';
class JumuNordost extends Component {
render() {
return (
<Router
firstRoute={firstRoute}
headerStyle={styles.header}
/>
)
}
}
const firstRoute = {
name: 'Contests',
component: ContestListScreen
};
const styles = StyleSheet.create({
container: {
flex: 1
},
header: {
backgroundColor: '#a9a9a9',
},
});
AppRegistry.registerComponent('JumuNordost', () => JumuNordost);
|
Make second line in the example different | package main
import (
"../../../drawer"
"fmt"
"image"
"image/color"
"image/png"
"os"
)
func main() {
src := image.NewRGBA(image.Rect(0, 0, 100, 100))
drawer.Fill(src, color.RGBA{0, 255, 255, 255})
start := image.Pt(100, 100)
end := image.Pt(0, 0)
ld := drawer.NewLineDrawer(src, start, end, color.RGBA{255, 0, 0, 255}).Draw()
draw(ld, src, "negative.png")
start = image.Pt(0, 100)
end = image.Pt(100, 0)
ld.SetStart(end).SetEnd(start).Draw()
draw(ld, src, "positive.png")
}
func draw(drawer *drawer.LineDrawer, src image.Image, filename string) {
out, err := os.Create(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer out.Close()
fmt.Println("Writing output to:", filename)
err = png.Encode(out, src)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
| package main
import (
"../../../drawer"
"fmt"
"image"
"image/color"
"image/png"
"os"
)
func main() {
src := image.NewRGBA(image.Rect(0, 0, 100, 100))
drawer.Fill(src, color.RGBA{0, 255, 255, 255})
start := image.Pt(100, 100)
end := image.Pt(0, 0)
ld := drawer.NewLineDrawer(src, start, end, color.RGBA{255, 0, 0, 255}).Draw()
draw(ld, src, "positive.png")
ld.SetStart(end).SetEnd(start).Draw()
draw(ld, src, "negative.png")
}
func draw(drawer *drawer.LineDrawer, src image.Image, filename string) {
out, err := os.Create(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer out.Close()
fmt.Println("Writing output to:", filename)
err = png.Encode(out, src)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
Make sure that lib/lms_lib is included | <?php
require_once $CFG->dirroot."/lib/lms_lib.php"; // During transition
if ( ! defined('COOKIE_SESSION') ) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies',0);
ini_set('session.use_trans_sid',1);
}
if ( ! isset($CFG) ) die("Please configure this product using config.php");
if ( ! isset($CFG->staticroot) ) die('$CFG->staticroot not defined see https://github.com/csev/webauto/issues/2');
if ( ! isset($CFG->bootstrap) ) die('$CFG->bootstrap not defined in config.php');
if ( ! isset($CFG->timezone) ) die('$CFG->timezone not defined in config.php');
// Set this to the temporary folder if not set - dev only
if ( ! isset($CFG->dataroot) ) {
$tmp = sys_get_temp_dir();
if (strlen($tmp) > 1 && substr($tmp, -1) == '/') $tmp = substr($tmp,0,-1);
$CFG->dataroot = $tmp;
}
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);
date_default_timezone_set($CFG->timezone);
// No trailer
| <?php
if ( ! defined('COOKIE_SESSION') ) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies',0);
ini_set('session.use_trans_sid',1);
}
if ( ! isset($CFG) ) die("Please configure this product using config.php");
if ( ! isset($CFG->staticroot) ) die('$CFG->staticroot not defined see https://github.com/csev/webauto/issues/2');
if ( ! isset($CFG->bootstrap) ) die('$CFG->bootstrap not defined in config.php');
if ( ! isset($CFG->timezone) ) die('$CFG->timezone not defined in config.php');
// Set this to the temporary folder
if ( ! isset($CFG->dataroot) ) {
$tmp = sys_get_temp_dir();
if (strlen($tmp) > 1 && substr($tmp, -1) == '/') $tmp = substr($tmp,0,-1);
$CFG->dataroot = $tmp;
}
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);
date_default_timezone_set($CFG->timezone);
// No trailer
|
Make constructor public and member final | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
import java.nio.ByteBuffer;
/**
* Data value (a sequence of bytes)
**/
public class DataValue extends Value
{
private final byte[] value;
/**
* Create from a Java-type value
*
* @param value the value
**/
public DataValue(byte[] value) { this.value = value; }
/**
* Create by decoding the value from the given buffer
*
* @param src buffer where the value is stored
**/
public DataValue(ByteBuffer src) {
int size = src.getInt();
value = new byte[size];
src.get(value);
}
/**
* @return DATA
**/
public byte type() { return DATA; }
public int count() { return 1; }
int bytes() { return 4 + value.length; }
void encode(ByteBuffer dst) {
dst.putInt(value.length);
dst.put(value);
}
public byte[] asData() { return value; }
@Override
public String toString() {
return String.valueOf(value);
}
}
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
import java.nio.ByteBuffer;
/**
* Data value (a sequence of bytes)
**/
public class DataValue extends Value
{
private byte[] value;
/**
* Create from a Java-type value
*
* @param value the value
**/
public DataValue(byte[] value) { this.value = value; }
/**
* Create by decoding the value from the given buffer
*
* @param src buffer where the value is stored
**/
DataValue(ByteBuffer src) {
int size = src.getInt();
value = new byte[size];
src.get(value);
}
/**
* @return DATA
**/
public byte type() { return DATA; }
public int count() { return 1; }
int bytes() { return 4 + value.length; }
void encode(ByteBuffer dst) {
dst.putInt(value.length);
dst.put(value);
}
public byte[] asData() { return value; }
@Override
public String toString() {
return String.valueOf(value);
}
}
|
Fix click handler for Metrics Tab ticks. | <%page args="section_data"/>
$(function () {
// Click handler for x axis ticks
$('.metrics-container').on('click', '.stacked-bar-graph-axis .tick', function () {
var stackedBarElement;
var xValue;
var moduleId;
var tickIdentifier = d3.select(this).text();
var i;
var stackedBars;
var stackedBarElement;
var url;
stackedBars = $(this).parent().siblings();
for (i = 0; i < stackedBars.length; i++) {
stackedBarElement = stackedBars[i];
if (stackedBarElement.getAttribute('class') === 'stacked-bar') {
xValue = d3.select(stackedBarElement).data()[0].xValue;
if (xValue === tickIdentifier) {
moduleId = d3.select(stackedBarElement).data()[0].stackData[0].module_url;
break;
}
}
}
url = [
'/courses',
"${section_data['course_id']}",
'jump_to',
moduleId
].join('/');
window.location.href = url;
});
});
| <%page args="section_data"/>
$(function () {
// Click handler for x axis major ticks
$('.metrics-container').on('click', '.stacked-bar-graph-axis .tick.major', function () {
var stackedBarElement;
var xValue;
var moduleId;
var tickIdentifier = d3.select(this).text();
var i;
var stackedBars;
var stackedBarElement;
var url;
stackedBars = $(this).parent().siblings();
for (i = 0; i < stackedBars.length; i++) {
stackedBarElement = stackedBars[i];
if (stackedBarElement.getAttribute('class') === 'stacked-bar') {
xValue = d3.select(stackedBarElement).data()[0].xValue;
if (xValue === tickIdentifier) {
moduleId = d3.select(stackedBarElement).data()[0].stackData[0].module_url;
break;
}
}
}
url = [
'/courses',
"${section_data['course_id']}",
'jump_to',
moduleId
].join('/');
window.location.href = url;
});
});
|
Reset shield regen timer every time damage is taken, even if the shield isn't damaged | package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
public abstract class ShieldedEntity extends Entity {
protected final int maxShield;
protected int shield;
private long shieldRegenTime;
private long nextShieldRegen;
public ShieldedEntity(int maxHealth, int maxShield, long shieldRegenTime) {
super(maxHealth);
this.maxShield = maxShield;
shield = maxShield;
this.shieldRegenTime = shieldRegenTime;
}
public int getShield() {
return shield;
}
public void addShield(int shield) {
this.shield += shield;
if (this.shield > maxShield) {
this.shield = maxShield;
}
}
@Override
public final void update() {
if (shield < maxShield && System.currentTimeMillis() > nextShieldRegen) {
shield++;
nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
}
}
@Override
public void applyDamage(int damage, DamageType damageType,
Vector2 attackOrigin) {
if (shield > 0) {
shield--;
super.applyDamage(0, damageType, attackOrigin);
} else {
super.applyDamage(damage, damageType, attackOrigin);
}
nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
}
}
| package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
public abstract class ShieldedEntity extends Entity {
protected final int maxShield;
protected int shield;
private long shieldRegenTime;
private long nextShieldRegen;
public ShieldedEntity(int maxHealth, int maxShield, long shieldRegenTime) {
super(maxHealth);
this.maxShield = maxShield;
shield = maxShield;
this.shieldRegenTime = shieldRegenTime;
}
public int getShield() {
return shield;
}
public void addShield(int shield) {
this.shield += shield;
if (this.shield > maxShield) {
this.shield = maxShield;
}
}
@Override
public final void update() {
if (shield < maxShield && System.currentTimeMillis() > nextShieldRegen) {
shield++;
nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
}
}
@Override
public void applyDamage(int damage, DamageType damageType,
Vector2 attackOrigin) {
if (shield > 0) {
shield--;
nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
super.applyDamage(0, damageType, attackOrigin);
} else {
super.applyDamage(damage, damageType, attackOrigin);
}
}
}
|
feat: Add mdl-lite snackbar to notify user of required reload.
Reload required when user changes a settings | import Ember from 'ember';
export default Ember.Controller.extend({
init () {
Ember.run.schedule('afterRender', () => {
componentHandler.upgradeAllRegistered();
});
},
settingsSnackbar (message) {
const _this = this;
const snackbarContainer = document.querySelector('#snackbar-container');
const handler = function () {
_this.transitionToRoute('home');
Ember.run.later(() => {
window.location.reload(true);
}, 500);
};
const data = {
message,
timeout: 4000,
actionHandler: handler,
actionText: 'Reload'
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
},
currency: function () {
let currency = this.get('model').findBy('id', 'currency');
if (!currency) {
return {
id: false,
setting: 'Currency',
value: '£'
};
}
return currency;
}.property('model.@each.value'),
userName: function () {
let userName = this.get('model').findBy('id', 'user-name');
if (!userName) {
return {
id: false,
setting: 'Name',
value: 'Guest'
};
}
return userName;
}.property('model.@each.value')
});
| import Ember from 'ember';
export default Ember.Controller.extend({
init () {
Ember.run.schedule('afterRender', () => {
componentHandler.upgradeAllRegistered();
});
},
currency: function () {
let currency = this.get('model').findBy('id', 'currency');
if (!currency) {
return {
id: false,
setting: 'Currency',
value: '£'
};
}
return currency;
}.property('model.@each.value'),
userName: function () {
let userName = this.get('model').findBy('id', 'user-name');
if (!userName) {
return {
id: false,
setting: 'Name',
value: 'Guest'
};
}
return userName;
}.property('model.@each.value')
});
|
Add cache support for incremental builds |
var through = require('through2'),
gutil = require('gulp-util'),
Rollup = require('rollup');
var PluginError = gutil.PluginError;
module.exports = function(options, cache, cacheCallback) {
var cacheObj = Object.assign({}, cache);
var stream = through.obj(function(file, encoding, callback) {
if (file.isNull()) {
return callback();
}
var filePath = file.path;
options.entry = filePath;
if (cache) {
options.cache = cacheObj[filePath];
}
return Rollup.rollup(options).then(function (bundle) {
var proccessed = bundle.generate(options);
if (cache && cacheCallback) {
cacheCallback(bundle, filePath);
}
file.contents = new Buffer(proccessed.code);
if (options.sourceMap) {
var map = proccessed.map;
if (map) {
map.file = file.relative;
map.sources = map.sources.map(function(fileName) {
return fileName;
});
file.sourceMap = map;
}
}
callback(null, file);
}).catch(function (err) {
callback(new PluginError('gulp-rollup-mep', err));
});
});
return stream;
};
|
var through = require('through2'),
gutil = require('gulp-util'),
Rollup = require('rollup');
var PluginError = gutil.PluginError;
module.exports = function(options) {
var stream = through.obj(function(file, encoding, callback) {
if (file.isNull()) {
return callback();
}
var filePath = file.path;
options.entry = filePath;
return Rollup.rollup(options).then(function (bundle) {
var proccessed = bundle.generate(options);
file.contents = new Buffer(proccessed.code);
if (options.sourceMap) {
var map = proccessed.map;
if (map) {
map.file = file.relative;
map.sources = map.sources.map(function(fileName) {
return fileName;
});
file.sourceMap = map;
}
}
callback(null, file);
}).catch(function (err) {
callback(new PluginError('gulp-rollup-mep', err));
});
});
return stream;
};
|
Set default proxies allowed to all
If the media server is hosted behind a service like CloudFlare, Livewire will automatically make HTTP requests when attempting up upload files even if the connection is a HTTPS connection, setting the trusted proxies to `all` fixes this issue. | <?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies = '*';
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
| <?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
|
Replace the promise with async / await as its 10x cooler | import 'babel-core/register';
import React, { Component } from 'react';
import Loader from 'react-loader';
import Header from './Header';
import ImgurImageList from './ImgurImageList';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0, loaded: false};
}
async loadImages(page = 0) {
this.setState({loaded: false});
try {
let result = await searchGallery(undefined, undefined, page);
this.setState({images: result.data, page: page, loaded: true});
} catch (e) {
this.setState({loaded: true});
}
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<Loader loaded={this.state.loaded}>
<Header page={this.state.page} loadImages={this.loadImages.bind(this)} />
<ImgurImageList images={this.state.images} />
</Loader>
);
}
}
| import React, { Component } from 'react';
import Loader from 'react-loader';
import Header from './Header';
import ImgurImageList from './ImgurImageList';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0, loaded: false};
}
loadImages(page = 0) {
this.setState({loaded: false});
searchGallery(undefined, undefined, page).then((result) => {
this.setState({images: result.data, page: page, loaded: true});
}).catch(() => {
this.setState({loaded: true});
});
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<Loader loaded={this.state.loaded}>
<Header page={this.state.page} loadImages={this.loadImages.bind(this)} />
<ImgurImageList images={this.state.images} />
</Loader>
);
}
}
|
Use ~ instead of - | <?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
public function testFuncExists()
{
$this->assertTrue(function_exists('random_int'));
}
public function testOutput()
{
$integers = array(
random_int(0, 1000),
random_int(1001,2000),
random_int(-100, -10),
random_int(-1000, 1000),
random_int(-PHP_INT_MAX + 1, PHP_INT_MAX)
);
$this->assertFalse($integers[0] === $integers[1]);
$this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
$this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
$this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[4] >= ~PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
}
}
| <?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
public function testFuncExists()
{
$this->assertTrue(function_exists('random_int'));
}
public function testOutput()
{
$integers = array(
random_int(0, 1000),
random_int(1001,2000),
random_int(-100, -10),
random_int(-1000, 1000),
random_int(-PHP_INT_MAX + 1, PHP_INT_MAX)
);
$this->assertFalse($integers[0] === $integers[1]);
$this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
$this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
$this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[4] >= -PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
}
}
|
Add search feature to the Route API. | from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
| from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
|
Use null as default prop so it's not rendered | import React, { Component } from 'react'
import { string, oneOfType, arrayOf, node } from 'prop-types'
import { Helmet } from 'react-helmet'
import pick from '../utils/pick'
import commonPropTypes from './commonPropTypes'
class Sidebar extends Component {
static propTypes = {
...commonPropTypes,
id: string.isRequired,
side: string,
children: oneOfType([
arrayOf(node),
node
])
}
static defaultProps = {
side: null,
children: []
}
get properties() {
return pick(this.props, ...[
...Object.keys(commonPropTypes),
'id',
'side'
])
}
render() {
const { children } = this.props
return [
<Helmet key="helmet">
<script async="" custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js" />
</Helmet>,
<amp-sidebar {...{ ...this.properties }} key="sidebar">
{children}
</amp-sidebar>
]
}
}
export default Sidebar
| import React, { Component } from 'react'
import { string, oneOfType, arrayOf, node } from 'prop-types'
import { Helmet } from 'react-helmet'
import pick from '../utils/pick'
import commonPropTypes from './commonPropTypes'
class Sidebar extends Component {
static propTypes = {
...commonPropTypes,
id: string.isRequired,
side: string,
children: oneOfType([
arrayOf(node),
node
])
}
static defaultProps = {
side: '',
children: []
}
get properties() {
return pick(this.props, ...[
...Object.keys(commonPropTypes),
'id',
'side'
])
}
render() {
const { children } = this.props
return [
<Helmet key="helmet">
<script async="" custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js" />
</Helmet>,
<amp-sidebar {...{ ...this.properties }} key="sidebar">
{children}
</amp-sidebar>
]
}
}
export default Sidebar
|
Add alternative support for open in browser
Integrate SideBarEnhancements for ST3 for poplarity and browser detection | import sublime
import os.path as fs
if int(sublime.version()) < 3000:
from elm_project import ElmProject
from ViewInBrowserCommand import ViewInBrowserCommand as OpenInBrowserCommand
else:
from .elm_project import ElmProject
try:
from SideBarEnhancements.SideBar import SideBarOpenInBrowserCommand as OpenInBrowserCommand
except:
OpenInBrowserCommand = __import__('View In Browser').ViewInBrowserCommand.ViewInBrowserCommand
class ElmOpenInBrowserCommand(OpenInBrowserCommand):
def run(self, edit=None):
if edit: # ViewInBrowserCommand
super(ElmOpenInBrowserCommand, self).run(edit)
else: # SideBarOpenInBrowserCommand
super(ElmOpenInBrowserCommand, self).run([self.html_path()])
def is_enabled(self):
try: # ViewInBrowserCommand
self.project = ElmProject(self.view.file_name())
except: # SideBarOpenInBrowserCommand
self.project = ElmProject(self.window.active_view().file_name())
return self.project.exists
def normalizePath(self, fileToOpen): # ViewInBrowserCommand
return super(ElmOpenInBrowserCommand, self).normalizePath(self.html_path())
def html_path(self):
norm_path = fs.join(self.project.working_dir, fs.expanduser(self.project.html_path))
return fs.abspath(norm_path)
| import sublime
import os.path as fs
if int(sublime.version()) < 3000:
from elm_project import ElmProject
from ViewInBrowserCommand import ViewInBrowserCommand
else:
from .elm_project import ElmProject
ViewInBrowserCommand = __import__('View In Browser').ViewInBrowserCommand.ViewInBrowserCommand
class ElmOpenInBrowserCommand(ViewInBrowserCommand):
def run(self, edit):
super(ElmOpenInBrowserCommand, self).run(edit)
def is_enabled(self):
self.project = ElmProject(self.view.file_name())
return self.project.exists
def normalizePath(self, fileToOpen): # ViewInBrowserCommand
norm_path = fs.join(self.project.working_dir, fs.expanduser(self.project.html_path))
return super(ElmOpenInBrowserCommand, self).normalizePath(fs.abspath(norm_path))
|
Update gulp to change name of generated file | var gulp = require('gulp'),
rimraf = require('rimraf'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
insert = require('gulp-insert'),
p = require('./package.json')
;
//Folders and annotation
var src = 'src/',
dest = 'dist/',
annotation = '/* ' + p.name + ' v' + p.version + ' | Copyright (c) ' + new Date().getFullYear() + ' ' + p.homepage + ' | ' + p.license + ' license */\n';
gulp.task('clean', function(cb) {
rimraf(dest, cb);
});
gulp.task('scripts', ['clean'], function() {
return gulp.src(src + '*.js')
.pipe(jshint())
.pipe(jshint.reporter())
.pipe(uglify())
.pipe(rename('jquery.seslider.min.js'))
.pipe(insert.prepend(annotation))
.pipe(gulp.dest(dest));
;
});
gulp.task('default', ['scripts'], function() {
});
| var gulp = require('gulp'),
rimraf = require('rimraf'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
insert = require('gulp-insert'),
p = require('./package.json')
;
//Folders and annotation
var src = 'src/',
dest = 'dist/',
annotation = '/* ' + p.name + ' v' + p.version + ' | Copyright (c) ' + new Date().getFullYear() + ' ' + p.homepage + ' | ' + p.license + ' license */\n';
gulp.task('clean', function(cb) {
rimraf(dest, cb);
});
gulp.task('scripts', ['clean'], function() {
return gulp.src(src + '*.js')
.pipe(jshint())
.pipe(jshint.reporter())
.pipe(uglify())
.pipe(rename('jquery.seslider-' + p.version + '.min.js'))
.pipe(insert.prepend(annotation))
.pipe(gulp.dest(dest));
;
});
gulp.task('default', ['scripts'], function() {
});
|
Reset all attempts when ip not specified
When no ip address positional arguments are specified, reset all attempts, as with reset() and per documentation. | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs:
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
|
Add mode parameter for YEARWEEK | <?php
namespace DoctrineExtensions\Query\Mysql;
use Doctrine\ORM\Query\AST\Functions\FunctionNode,
Doctrine\ORM\Query\Lexer;
/**
* @author Michael Kimpton <mike@sketchthat.com>
*/
class YearWeek extends FunctionNode
{
public $date;
public $mode;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
$sql = "YEARWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date);
if ($this->mode != null) {
$sql .= ", " . $sqlWalker->walkLiteral($this->mode);
}
$sql .= ")";
return $sql;
}
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date = $parser->ArithmeticPrimary();
if (Lexer::T_COMMA === $parser->getLexer()->lookahead['type']) {
$parser->match(Lexer::T_COMMA);
$this->mode = $parser->Literal();
}
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
| <?php
namespace DoctrineExtensions\Query\Mysql;
use Doctrine\ORM\Query\AST\Functions\FunctionNode,
Doctrine\ORM\Query\Lexer;
/**
* @author Michael Kimpton <mike@sketchthat.com>
*/
class YearWeek extends FunctionNode
{
public $date;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return "YEARWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date) . ")";
}
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
|
Revert "Added script for cron job to load surveys to database."
This reverts commit 34e5560437348e5cfeab589b783c9cc524aa2abf. | from surveyextractor import QualtricsExtractor
import getopt, sys
# Script for scheduling regular EdxQualtrics updates
# Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses'])
for opt, arg in opts:
if opt in ('-a', '--reset'):
qe.resetMetadata()
qe.resetSurveys()
qe.resetResponses()
elif opt in ('-m', '--loadmeta'):
qe.loadSurveyMetadata()
elif opt in ('-s', '--loadsurvey'):
qe.resetSurveys()
qe.loadSurveyData()
elif opt in ('-r', '--loadresponses'):
qe.loadResponseData()
| from surveyextractor import QualtricsExtractor
import getopt
import sys
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses'])
for opt, arg in opts:
if opt in ('-a', '--reset'):
qe.resetMetadata()
qe.resetSurveys()
qe.resetResponses()
elif opt in ('-m', '--loadmeta'):
qe.loadSurveyMetadata()
elif opt in ('-s', '--loadsurvey'):
qe.resetSurveys()
qe.loadSurveyData()
elif opt in ('-r', '--loadresponses'):
qe.loadResponseData()
|
Remove curly quotes as well
I have a few of these in titles and they were showing up in CSS clases. | /**
* Simple pluralizer
*/
Handlebars.registerHelper('pluralize', function(n, thing) {
if (n === 1) {
return '1 ' + thing;
} else {
return n + ' ' + thing + 's';
}
});
/**
* Turn titles into CSS classes
*
* Remove puncuation
* Spaces to undescores
* Lowercase text
*/
Handlebars.registerHelper('lowerSpacesToDashes', function(input) {
if (input) {
return input.replace(/[\.,'-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase();
}
});
/**
* Strip HTML from a string
*
* This is obviously imperfect, but I trust the data source...me.
*/
Handlebars.registerHelper('brToSpace', function(input) {
if (input) {
return input.replace(/<br ?\/?>/g, " ")
}
});
| /**
* Simple pluralizer
*/
Handlebars.registerHelper('pluralize', function(n, thing) {
if (n === 1) {
return '1 ' + thing;
} else {
return n + ' ' + thing + 's';
}
});
/**
* Turn titles into CSS classes
*
* Remove puncuation
* Spaces to undescores
* Lowercase text
*/
Handlebars.registerHelper('lowerSpacesToDashes', function(input) {
if (input) {
return input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase();
}
});
/**
* Strip HTML from a string
*
* This is obviously imperfect, but I trust the data source...me.
*/
Handlebars.registerHelper('brToSpace', function(input) {
if (input) {
return input.replace(/<br ?\/?>/g, " ")
}
});
|
Add helper to change AMP mode. |
/**
* WordPress dependencies
*/
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';
/**
* The allow list of AMP modes.
*
*/
export const allowedAmpModes = {
standard: 'standard',
transitional: 'transitional',
reader: 'disabled',
};
/**
* Activate AMP and set it to the correct mode.
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const activateAmpAndSetMode = async ( mode ) => {
await activatePlugin( 'amp' );
await setAMPMode( mode );
};
/**
* Set AMP Mode
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const setAMPMode = async ( mode ) => {
// Test to be sure that the passed mode is known.
expect( Object.keys( allowedAmpModes ) ).toContain( mode );
// Set the AMP mode
await visitAdminPage( 'admin.php', 'page=amp-options' );
await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` );
await expect( page ).toClick( '#submit' );
await page.waitForSelector( '#setting-error-settings_updated' );
await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } );
};
|
/**
* WordPress dependencies
*/
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';
/**
* The allow list of AMP modes.
*
*/
export const allowedAmpModes = {
standard: 'standard',
transitional: 'transitional',
reader: 'disabled',
};
/**
* Activate AMP and set it to the correct mode.
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const activateAmpAndSetMode = async ( mode ) => {
// Test to be sure that the passed mode is known.
expect( Object.keys( allowedAmpModes ) ).toContain( mode );
// Active AMP and set the passed mode.
await activatePlugin( 'amp' );
await visitAdminPage( 'admin.php', 'page=amp-options' );
await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` );
await expect( page ).toClick( '#submit' );
await page.waitForSelector( '#setting-error-settings_updated' );
await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } );
};
|
Fix the JDBC resource's JDNI name
The leading slash works on Tomcat but fails on Payara.
If I remove it, it works on both. | package mx.nic.rdap.server.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DatabaseSession {
public static final String RDAP_DB = "rdap";
private static DataSource getEnvironmentDataSource(String name) {
try {
Context initContext = new InitialContext();
return (DataSource) initContext.lookup("java:comp/env/jdbc/" + name);
} catch (NamingException e) {
throw new IllegalArgumentException(e);
}
}
public static Connection getRdapConnection() throws SQLException {
return getEnvironmentDataSource(RDAP_DB).getConnection();
}
public static DataSource getDataSource() {
return getEnvironmentDataSource(RDAP_DB);
}
}
| package mx.nic.rdap.server.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DatabaseSession {
public static final String RDAP_DB = "rdap";
private static DataSource getEnvironmentDataSource(String name) {
try {
Context initContext = new InitialContext();
return (DataSource) initContext.lookup("java:/comp/env/jdbc/" + name);
} catch (NamingException e) {
throw new IllegalArgumentException(e);
}
}
public static Connection getRdapConnection() throws SQLException {
return getEnvironmentDataSource(RDAP_DB).getConnection();
}
public static DataSource getDataSource() {
return getEnvironmentDataSource(RDAP_DB);
}
}
|
Update 2 of Splash Activity | package com.implementist.treantreading;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
import com.implementist.treantreading.pref.AppPref;
/**
* Copyright © 2017 Implementist. All rights reserved.
*/
public class LogoSplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
//注意,这里没有setContentView,单纯只是用来跳转到相应的Activity
//目的是减少首屏渲染
if (AppPref.isFirstRunning(this)){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
finish();
}
}
| package com.implementist.treantreading;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.implementist.treantreading.pref.AppPref;
/**
* Copyright © 2017 Implementist. All rights reserved.
*/
public class LogoSplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//注意,这里没有setContentView,单纯只是用来跳转到相应的Activity
//目的是减少首屏渲染
if (AppPref.isFirstRunning(this)){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
finish();
}
}
|
Access Config through Service Container | <?php
namespace App\Http\Controllers;
class LanguageController extends Controller
{
/**
* Switch Language
*
* @param string $lang Language iso code
* @param Session $session Session Facade
* @return Redirect HTTP Redirect
*/
public function switchLang($lang)
{
$this->log->info("Language switch Request to $lang");
if (array_key_exists($lang, config()->get('languages'))) {
$this->log->info('Language Switched');
session()->set('applocale', $lang);
$locale = \Locale::parseLocale($lang);
session()->set('language', $locale['language']);
}
return redirect()->back();
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Config;
class LanguageController extends Controller
{
/**
* Switch Language
*
* @param string $lang Language iso code
* @param Session $session Session Facade
* @return Redirect HTTP Redirect
*/
public function switchLang($lang)
{
$this->log->info("Language switch Request to $lang");
if (array_key_exists($lang, Config::get('languages'))) {
$this->log->info('Language Switched');
session()->set('applocale', $lang);
$locale = \Locale::parseLocale($lang);
session()->set('language', $locale['language']);
}
return redirect()->back();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.