text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
[Core][Promotion] Return application result in promotion action command | <?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\Promotion\Action;
use Sylius\Component\Promotion\Model\PromotionInterface;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;
/**
* @author Saša Stamenković <umpirsky@gmail.com>
*/
interface PromotionActionCommandInterface
{
/**
* @param PromotionSubjectInterface $subject
* @param array $configuration
* @param PromotionInterface $promotion
*
* @return bool
*/
public function execute(PromotionSubjectInterface $subject, array $configuration, PromotionInterface $promotion);
/**
* @param PromotionSubjectInterface $subject
* @param array $configuration
* @param PromotionInterface $promotion
*
* @return mixed
*/
public function revert(PromotionSubjectInterface $subject, array $configuration, PromotionInterface $promotion);
/**
* @return string
*/
public function getConfigurationFormType();
}
| <?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\Promotion\Action;
use Sylius\Component\Promotion\Model\PromotionInterface;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;
/**
* @author Saša Stamenković <umpirsky@gmail.com>
*/
interface PromotionActionCommandInterface
{
/**
* @param PromotionSubjectInterface $subject
* @param array $configuration
* @param PromotionInterface $promotion
*
* @return mixed
*/
public function execute(PromotionSubjectInterface $subject, array $configuration, PromotionInterface $promotion);
/**
* @param PromotionSubjectInterface $subject
* @param array $configuration
* @param PromotionInterface $promotion
*
* @return mixed
*/
public function revert(PromotionSubjectInterface $subject, array $configuration, PromotionInterface $promotion);
/**
* @return string
*/
public function getConfigurationFormType();
}
|
Revert "Extra newline is superfluous."
This reverts commit 085b00a1aefc725e23718c5df573b9b357d9a087.
The new line isn't superfluous, the duplication I was seeing was caused elsehwere. | package net.hillsdon.reviki.plugins;
import java.net.*;
import java.io.*;
import net.hillsdon.reviki.vc.PageInfo;
import net.hillsdon.reviki.wiki.renderer.macro.Macro;
import net.hillsdon.reviki.wiki.renderer.macro.ResultFormat;
public class IncludeHtmlMacro implements Macro {
public String getName() {
return "include-html";
}
public ResultFormat getResultFormat() {
return ResultFormat.XHTML;
}
public String handle(final PageInfo page, final String remainder) throws Exception {
URL oracle = new URL(remainder);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
StringBuilder output = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
output.append(inputLine);
output.append('\n');
}
in.close();
return output.toString();
}
}
| package net.hillsdon.reviki.plugins;
import java.net.*;
import java.io.*;
import net.hillsdon.reviki.vc.PageInfo;
import net.hillsdon.reviki.wiki.renderer.macro.Macro;
import net.hillsdon.reviki.wiki.renderer.macro.ResultFormat;
public class IncludeHtmlMacro implements Macro {
public String getName() {
return "include-html";
}
public ResultFormat getResultFormat() {
return ResultFormat.XHTML;
}
public String handle(final PageInfo page, final String remainder) throws Exception {
URL oracle = new URL(remainder);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
StringBuilder output = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
output.append(inputLine);
}
in.close();
return output.toString();
}
}
|
Add return result in json. | package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/toomore/gogrs/tradingdays"
)
func Log(req *http.Request) {
log.Println(req.URL, req.UserAgent(), req.Form)
}
func Home(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello World"))
Log(req)
}
type tradeJSON struct {
Date time.Time `json:"date"`
Open bool `json:"open"`
}
func TradeOpen(w http.ResponseWriter, req *http.Request) {
data, err := strconv.ParseInt(req.FormValue("q"), 10, 64)
if err != nil {
w.Write([]byte("Wrong data format."))
} else {
date := time.Unix(data, 0)
json_str, _ := json.Marshal(&tradeJSON{
Date: date.UTC(),
Open: tradingdays.IsOpen(date.Year(), date.Month(), date.Day(), date.Location())})
w.Header().Set("Content-Type", "application/json")
w.Write(json_str)
}
Log(req)
}
func init() {
tradingdays.DownloadCSV(true)
}
func main() {
http.HandleFunc("/", Home)
http.HandleFunc("/open", TradeOpen)
log.Fatal(http.ListenAndServe(":59123", nil))
}
| package main
import (
"log"
"net/http"
"strconv"
"time"
)
func Log(req *http.Request) {
log.Println(req.URL, req.UserAgent(), req.Form)
}
func Home(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello World"))
Log(req)
}
func TradeOpen(w http.ResponseWriter, req *http.Request) {
data, err := strconv.ParseInt(req.FormValue("q"), 10, 64)
if err != nil {
w.Write([]byte("Wrong data format."))
} else {
date := time.Unix(data, 0)
w.Write([]byte(date.String()))
}
Log(req)
}
func main() {
http.HandleFunc("/", Home)
http.HandleFunc("/open", TradeOpen)
log.Fatal(http.ListenAndServe(":59123", nil))
}
|
Fix crash when no commandline args are passed
Regression from 3513da19363b8b4564f199b469d13486996ede57 | # Copyright 2017 Codethink Ltd.
#
# 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.
'''Utility functions.'''
import itertools
def ensure_list(string_or_list_or_none, separator=None):
if isinstance(string_or_list_or_none, str):
if separator:
return string_or_list_or_none.split(separator)
else:
return [string_or_list_or_none]
elif string_or_list_or_none is not None:
if separator:
return list(itertools.chain.from_iterable(
item.split(separator) for item in string_or_list_or_none))
else:
return string_or_list_or_none
else:
return []
| # Copyright 2017 Codethink Ltd.
#
# 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.
'''Utility functions.'''
import itertools
def ensure_list(string_or_list_or_none, separator=None):
if isinstance(string_or_list_or_none, str):
if separator:
return string_or_list_or_none.split(separator)
else:
return [string_or_list_or_none]
else:
if separator:
return list(itertools.chain.from_iterable(
item.split(separator) for item in string_or_list_or_none))
else:
return string_or_list_or_none or []
|
Fix paths to json files | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
|
Fix error handling for non-existent documents | <?php
namespace BNETDocs\Controllers\Document;
use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\Comment;
use \BNETDocs\Libraries\Document;
use \BNETDocs\Libraries\Exceptions\DocumentNotFoundException;
use \BNETDocs\Models\Document\View as DocumentViewModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Controller;
use \CarlBennett\MVC\Libraries\Router;
use \CarlBennett\MVC\Libraries\View as ViewLib;
use \DateTime;
use \DateTimeZone;
class View extends Controller {
public function &run(Router &$router, ViewLib &$view, array &$args) {
$model = new DocumentViewModel();
$model->active_user = Authentication::$user;
$model->document_id = array_shift($args);
try { $model->document = new Document($model->document_id); }
catch (DocumentNotFoundException $e) { $model->document = null; }
catch (InvalidArgumentException $e) { $model->document = null; }
if ($model->document) {
$model->comments = Comment::getAll(
Comment::PARENT_TYPE_DOCUMENT,
$model->document_id
);
}
$view->render($model);
$model->_responseCode = ($model->document ? 200 : 404);
return $model;
}
}
| <?php
namespace BNETDocs\Controllers\Document;
use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\Comment;
use \BNETDocs\Libraries\Document;
use \BNETDocs\Libraries\Exceptions\DocumentNotFoundException;
use \BNETDocs\Models\Document\View as DocumentViewModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Controller;
use \CarlBennett\MVC\Libraries\Router;
use \CarlBennett\MVC\Libraries\View as ViewLib;
use \DateTime;
use \DateTimeZone;
class View extends Controller {
public function &run(Router &$router, ViewLib &$view, array &$args) {
$model = new DocumentViewModel();
$model->active_user = Authentication::$user;
$model->document_id = array_shift($args);
try {
$model->document = new Document($model->document_id);
} catch (DocumentNotFoundException $e) {
$model->document = null;
}
if ($model->document) {
$model->comments = Comment::getAll(
Comment::PARENT_TYPE_DOCUMENT,
$model->document_id
);
}
$view->render($model);
$model->_responseCode = ($model->document ? 200 : 404);
return $model;
}
}
|
Use Ember.isEqual instead of direct equality | import Em from 'ember';
let get = Em.get;
let defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
let computed = Em.computed(function handler(key) {
let lastValueKey = `__changeGate${key}LastValue`;
let isFirstRun = !this.hasOwnProperty(lastValueKey);
if (isFirstRun) { //setup an observer which is responsible for notifying property changes
this[lastValueKey] = filter.call(this, get(this, dependentKey));
this.addObserver(dependentKey, function() {
let newValue = filter.call(this, get(this, dependentKey));
let lastValue = this[lastValueKey];
if(!Em.isEqual(newValue, lastValue)) {
this[lastValueKey] = newValue;
this.notifyPropertyChange(key);
}
});
}
return this[lastValueKey];
});
return computed;
}
| import Em from 'ember';
let get = Em.get;
let defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
let computed = Em.computed(function handler(key) {
let lastValueKey = `__changeGate${key}LastValue`;
let isFirstRun = !this.hasOwnProperty(lastValueKey);
if (isFirstRun) { //setup an observer which is responsible for notifying property changes
this[lastValueKey] = filter.call(this, get(this, dependentKey));
this.addObserver(dependentKey, function() {
let newValue = filter.call(this, get(this, dependentKey));
let lastValue = this[lastValueKey];
if(newValue !== lastValue) {
this[lastValueKey] = newValue;
this.notifyPropertyChange(key);
}
});
}
return this[lastValueKey];
});
return computed;
}
|
Move to using membership based CSV output | from collections import defaultdict
from compat import BufferDictWriter
from django.conf import settings
from popolo.models import Membership
from candidates.models import PersonRedirect
def list_to_csv(membership_list):
csv_fields = settings.CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
for row in membership_list:
writer.writerow(row)
return writer.output
def memberships_dicts_for_csv(election_slug=None, post_slug=None):
redirects = PersonRedirect.all_redirects_dict()
memberships = Membership.objects.joins_for_csv()
if election_slug:
memberships = memberships.filter(
post_election__election__slug=election_slug
)
if post_slug:
memberships = memberships.filter(post_election__post__slug=post_slug)
memberships_by_election = defaultdict(list)
elected_by_election = defaultdict(list)
for membership in memberships:
election_slug = membership.post_election.election.slug
line = membership.dict_for_csv(redirects=redirects)
memberships_by_election[election_slug].append(line)
if membership.elected:
elected_by_election[election_slug].append(line)
return (memberships_by_election, elected_by_election)
| from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row["name"].split()[-1],
row["name"].rsplit(None, 1)[0],
not row["election_current"],
row["election_date"],
row["election"],
row["post_label"],
)
def _candidate_sort_by_post_key(row):
return (
not row["election_current"],
row["election_date"],
row["election"],
row["post_label"],
row["name"].split()[-1],
row["name"].rsplit(None, 1)[0],
)
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
|
Store results under correct experiment key | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_opts = deepcopy(conf.storage.get('options', {}))
_opts.update(opts)
opts = _opts
if path in get_storage._cache:
return get_storage._cache[path]
Storage = utils.import_path(path)
get_storage._cache[path] = Storage(name, **opts)
return get_storage._cache[path]
get_storage._cache = {}
def store(result, storage=None):
storage = storage or get_storage(name=result.experiment.name)
key = simpleflake()
storage.set(key, result)
return key
def retrieve(key, storage=None):
storage = storage or get_storage()
return storage.get(key)
def retrieve_all(storage=None):
return (storage or get_storage()).list()
def remove(key, storage=None):
(storage or get_storage()).remove(key)
def clear(storage=None):
return (storage or get_storage()).clear()
| from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_opts = deepcopy(conf.storage.get('options', {}))
_opts.update(opts)
opts = _opts
if path in get_storage._cache:
return get_storage._cache[path]
Storage = utils.import_path(path)
get_storage._cache[path] = Storage(name, **opts)
return get_storage._cache[path]
get_storage._cache = {}
def store(result, storage=None):
storage = storage or get_storage()
key = simpleflake()
storage.set(key, result)
return key
def retrieve(key, storage=None):
storage = storage or get_storage()
return storage.get(key)
def retrieve_all(storage=None):
return (storage or get_storage()).list()
def remove(key, storage=None):
(storage or get_storage()).remove(key)
def clear(storage=None):
return (storage or get_storage()).clear()
|
Remove failing expectations for pixel tests.
R=kbr@chromium.org
BUG=252046, 371592
NOTRY=true
Review URL: https://codereview.chromium.org/282953002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270785 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
pass
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Pixel.Canvas2DRedBox', bug=371592)
self.Fail('Pixel.CSS3DBlueBox', bug=371592)
self.Fail('Pixel.WebGLGreenTriangle', bug=371592)
pass
|
Fix flake8 indentation issues with classifiers | #!/usr/bin/env python
# Copyright 2011 Andrew Ryrie (amr66)
from distutils.core import setup
setup(name='django-pyroven',
description='A Django authentication backend for Ucam-WebAuth / Raven',
long_description=open('README.md').read(),
url='https://github.com/pyroven/django-pyroven',
version='0.9',
license='MIT',
author='Andrew Ryrie',
author_email='smb314159@gmail.com',
maintainer='Kristian Glass',
maintainer_email='pyroven@doismellburning.co.uk',
packages=['pyroven'],
install_requires=[
'Django<1.7',
'pyOpenSSL',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| #!/usr/bin/env python
# Copyright 2011 Andrew Ryrie (amr66)
from distutils.core import setup
setup(name='django-pyroven',
description='A Django authentication backend for Ucam-WebAuth / Raven',
long_description=open('README.md').read(),
url='https://github.com/pyroven/django-pyroven',
version='0.9',
license='MIT',
author='Andrew Ryrie',
author_email='smb314159@gmail.com',
maintainer='Kristian Glass',
maintainer_email='pyroven@doismellburning.co.uk',
packages=['pyroven'],
install_requires=[
'Django<1.7',
'pyOpenSSL',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Fix compile error.
This is a workaround.Please fix correctly in the future. | //
// MessagePack for Java
//
// Copyright (C) 2009-2011 FURUHASHI Sadayuki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.msgpack.template;
public class TemplateClassWriter {
public static void write(Class<?> target, String directoryName) {
if(target.isEnum()) {
throw new UnsupportedOperationException("Not supported yet.");
} else {
//TemplateBuilder.writeClass(target, directoryName);
}
}
}
| //
// MessagePack for Java
//
// Copyright (C) 2009-2011 FURUHASHI Sadayuki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.msgpack.template;
public class TemplateClassWriter {
public static void write(Class<?> target, String directoryName) {
if(target.isEnum()) {
throw new UnsupportedOperationException("Not supported yet.");
} else {
TemplateBuilder.writeClass(target, directoryName);
}
}
}
|
Stop crashing when search doesn't have any matches | import json
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
search_template = ("http://api.openweathermap.org/data/2.5/" +
"find?q={}&type=like")
search_url = search_template.format(self.search_input.text)
request = UrlRequest(search_url, self.found_location)
def found_location(self, request, data):
data = json.loads(data.decode()) if not isinstance(data, dict) else data
if 'list' in data:
cities = ["{} ({})".format(d['name'], d['sys']['country'])
for d in data['list']]
else:
cities = []
self.search_results.item_strings = cities
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
| import json
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
search_template = ("http://api.openweathermap.org/data/2.5/" +
"find?q={}&type=like")
search_url = search_template.format(self.search_input.text)
request = UrlRequest(search_url, self.found_location)
def found_location(self, request, data):
data = json.loads(data.decode()) if not isinstance(data, dict) else data
cities = ["{} ({})".format(d['name'], d['sys']['country'])
for d in data['list']]
self.search_results.item_strings = cities
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
|
Update unnecessary "public static" modifiers. | package io.petros.posts.app.graph.modules;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.service.retrofit.RetrofitService;
import io.petros.posts.util.rx.RxSchedulers;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class NetModule {
private final String baseUrl;
public NetModule(final String baseUrl) {
this.baseUrl = baseUrl;
}
@Provides
@Singleton
RxSchedulers providesRxSchedulers() {
return new RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(),
AndroidSchedulers.mainThread());
}
@Provides
@Singleton
RetrofitService provideRetroService() {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
return retrofit.create(RetrofitService.class);
}
}
| package io.petros.posts.app.graph.modules;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.service.retrofit.RetrofitService;
import io.petros.posts.util.rx.RxSchedulers;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class NetModule {
private final String baseUrl;
public NetModule(final String baseUrl) {
this.baseUrl = baseUrl;
}
@Provides
@Singleton
public static RxSchedulers providesRxSchedulers() {
return new RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(),
AndroidSchedulers.mainThread());
}
@Provides
@Singleton
RetrofitService provideRetroService() {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
return retrofit.create(RetrofitService.class);
}
}
|
Add pygooglechart to the requirements | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
requirements=[
'pygooglechart',
'django-paging',
'django-indexer',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
) | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
requirements=[
'django-paging',
'django-indexer',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
) |
Use explicit dependency on 'check' lib | var both = ['client', 'server'];
Package.describe({
name: 'lookback:emoji',
summary: 'Easily render and manage emojis in Meteor.',
version: '0.2.0',
git: 'https://github.com/lookback/meteor-emoji'
});
Package.onUse(function(api) {
api.versionsFrom('1.0.4.2');
api.use(['mongo', 'coffeescript', 'check', 'underscore'], both);
api.use('templating', 'client');
api.addFiles('seed/emojis.json', 'server', {isAsset: true});
api.addFiles('emojis.coffee', both);
api.addFiles('template.coffee', 'client');
api.addFiles('seed/seed.coffee', 'server');
api.export('Emojis', both);
});
Package.onTest(function(api) {
api.use([
'coffeescript',
'mike:mocha-package',
'practicalmeteor:chai',
'practicalmeteor:sinon',
'respondly:test-reporter',
'lookback:emoji'
]);
api.addFiles('spec/emojis-spec.coffee');
api.addFiles('spec/emojis-server-spec.coffee', 'server');
});
| var both = ['client', 'server'];
Package.describe({
name: 'lookback:emoji',
summary: 'Easily render and manage emojis in Meteor.',
version: '0.2.0',
git: 'https://github.com/lookback/meteor-emoji'
});
Package.onUse(function(api) {
api.versionsFrom('1.0.4.2');
api.use(['mongo', 'coffeescript', 'underscore'], both);
api.use('templating', 'client');
api.addFiles('seed/emojis.json', 'server', {isAsset: true});
api.addFiles('emojis.coffee', both);
api.addFiles('template.coffee', 'client');
api.addFiles('seed/seed.coffee', 'server');
api.export('Emojis', both);
});
Package.onTest(function(api) {
api.use([
'coffeescript',
'mike:mocha-package',
'practicalmeteor:chai',
'practicalmeteor:sinon',
'respondly:test-reporter',
'lookback:emoji'
]);
api.addFiles('spec/emojis-spec.coffee');
api.addFiles('spec/emojis-server-spec.coffee', 'server');
});
|
Revert to some of the previous behavior for characters that shouldn't appear in identifiers. | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$.'\"])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$.'\"])|"
"_|\\s+")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s.lower() for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
| from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$])|"
"_")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
|
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False | from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
| from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
:bug: Remove login redirect for APIs | 'use strict';
/**
* @fileoverview Login check middleware
*/
const config = require('config');
/*
* Check authenticated status. Redirect to login page
*
* @param {object} req Express HTTP request
* @param {object} res Express HTTP response
* @param {object} next Express callback
*
*/
const authenticated = (req, res, next) => {
if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon') && !req.url.startsWith('/api')) {
res.redirect('/login');
}
else {
// consistent-return turned off because this doesn't return a value
next(); // eslint-disable-line callback-return
}
};
/**
* @param {object} app - Express app
*
* @returns {object} app - Modified Express app
*/
const authInit = (app) => {
return new Promise((res) => {
app.use(authenticated);
res(app);
});
};
module.exports = authInit;
| 'use strict';
/**
* @fileoverview Login check middleware
*/
const config = require('config');
/*
* Check authenticated status. Redirect to login page
*
* @param {object} req Express HTTP request
* @param {object} res Express HTTP response
* @param {object} next Express callback
*
*/
const authenticated = (req, res, next) => {
if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon')) {
res.redirect('/login');
}
else {
// consistent-return turned off because this doesn't return a value
next(); // eslint-disable-line callback-return
}
};
/**
* @param {object} app - Express app
*
* @returns {object} app - Modified Express app
*/
const authInit = (app) => {
return new Promise((res) => {
app.use(authenticated);
res(app);
});
};
module.exports = authInit;
|
Change format of parsed data. | module.exports = function crawler(callback) {
const request = require('request');
const cheerio = require('cheerio');
const URL = 'http://sarc.pucrs.br/Default/';
var data = [];
let requestHandler = (err, response, html) => {
if(err) return callback(err);
let $ = cheerio.load(html)('#ctl00_cphTitulo_UpdatePanel2 > div > table');
for (let i = 0, l = $.length; i < l; i++) {
let content = cheerio.load($.eq(i).html());
let time = content('span').html();
let table_data = content('.ms-btoolbar').children();
for (let j = 0, l = table_data.length; j < l; j+=3) {
let detail = {
'time' : formatTime(time),
'resource' : table_data.eq(j).text().trim(),
'course' : table_data.eq(j+1).text().trim(),
'owner' : table_data.eq(j+2).text().trim()
};
data.push(detail);
}
}
callback(null, data);
}
request(URL, requestHandler);
}
function formatTime(time) {
var weekday = new Date().getDay() + 1
return weekday + time
} | module.exports = function crawler(callback) {
const request = require('request');
const cheerio = require('cheerio');
const URL = 'http://sarc.pucrs.br/Default/';
var data = {};
let requestHandler = (err, response, html) => {
if(err) return callback(err);
let $ = cheerio.load(html)('#ctl00_cphTitulo_UpdatePanel2 > div > table');
for (let i = 0, l = $.length; i < l; i++) {
let content = cheerio.load($.eq(i).html());
let time = content('span').html();
let table_data = content('.ms-btoolbar').children();
let details = [];
for (let j = 0, l = table_data.length; j < l; j+=3) {
let detail = {
'resource' : table_data.eq(j).text().trim(),
'course' : table_data.eq(j+1).text().trim(),
'owner' : table_data.eq(j+2).text().trim()
};
details.push(detail);
}
time = formatTime(time);
if (details.length > 0) {
data[time] = details;
};
}
callback(null, data);
}
request(URL, requestHandler);
}
function formatTime(time) {
var weekday = new Date().getDay() + 1
return weekday + time
} |
Update error message to yml | package io.prometheus.cloudwatch;
import io.prometheus.client.exporter.MetricsServlet;
import java.io.FileReader;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class WebServer {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: WebServer <port> <yml configuration file>");
System.exit(1);
}
CloudWatchCollector cc = new CloudWatchCollector(new FileReader(args[1])).register();
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
context.addServlet(new ServletHolder(new HomePageServlet()), "/");
server.start();
server.join();
}
}
| package io.prometheus.cloudwatch;
import io.prometheus.client.exporter.MetricsServlet;
import java.io.FileReader;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class WebServer {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: WebServer <port> <json configuration file>");
System.exit(1);
}
CloudWatchCollector cc = new CloudWatchCollector(new FileReader(args[1])).register();
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
context.addServlet(new ServletHolder(new HomePageServlet()), "/");
server.start();
server.join();
}
}
|
Disable sourcemap generation for optimized static (sourcemap is 3mb) | module.exports = function(grunt) {
"use strict";
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
baseUrl: "js/",
mainConfigFile: "static/js/config.js",
appDir: "static/",
dir: "static-built/",
skipDirOptimize: true,
generateSourceMaps: false,
findNestedDependencies: true,
preserveLicenseComments: false,
uglify2: {
mangle: false
},
optimize: "uglify2",
optimizeCss: "none",
name: "main"
}
}
}
});
};
| module.exports = function(grunt) {
"use strict";
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
baseUrl: "js/",
mainConfigFile: "static/js/config.js",
appDir: "static/",
dir: "static-built/",
skipDirOptimize: true,
generateSourceMaps: true,
findNestedDependencies: true,
preserveLicenseComments: false,
uglify2: {
mangle: false
},
optimize: "uglify2",
optimizeCss: "none",
name: "main"
}
}
}
});
};
|
Add stem test for spanish stemmer | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.stem.snowball import SnowballStemmer
class SnowballTest(unittest.TestCase):
def test_russian(self):
# Russian words both consisting of Cyrillic
# and Roman letters can be stemmed.
stemmer_russian = SnowballStemmer("russian")
assert stemmer_russian.stem("авантненькая") == "авантненьк"
assert stemmer_russian.stem("avenantnen'kai^a") == "avenantnen'k"
def test_german(self):
stemmer_german = SnowballStemmer("german")
stemmer_german2 = SnowballStemmer("german", ignore_stopwords=True)
assert stemmer_german.stem("Schr\xe4nke") == 'schrank'
assert stemmer_german2.stem("Schr\xe4nke") == 'schrank'
assert stemmer_german.stem("keinen") == 'kein'
assert stemmer_german2.stem("keinen") == 'keinen'
def test_spanish(self):
stemmer = SnowballStemmer('spanish')
assert stemmer.stem("Visionado") == 'vision'
def test_short_strings_bug(self):
stemmer = SnowballStemmer('english')
assert stemmer.stem("y's") == 'y'
| # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.stem.snowball import SnowballStemmer
class SnowballTest(unittest.TestCase):
def test_russian(self):
# Russian words both consisting of Cyrillic
# and Roman letters can be stemmed.
stemmer_russian = SnowballStemmer("russian")
assert stemmer_russian.stem("авантненькая") == "авантненьк"
assert stemmer_russian.stem("avenantnen'kai^a") == "avenantnen'k"
def test_german(self):
stemmer_german = SnowballStemmer("german")
stemmer_german2 = SnowballStemmer("german", ignore_stopwords=True)
assert stemmer_german.stem("Schr\xe4nke") == 'schrank'
assert stemmer_german2.stem("Schr\xe4nke") == 'schrank'
assert stemmer_german.stem("keinen") == 'kein'
assert stemmer_german2.stem("keinen") == 'keinen'
def test_short_strings_bug(self):
stemmer = SnowballStemmer('english')
assert stemmer.stem("y's") == 'y'
|
Update properties and vectormath dependencies | #!/usr/bin/env python
"""omf: API Library for Open Mining Format"""
from distutils.core import setup
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS',
'Natural Language :: English',
]
with open('README.rst') as f:
LONG_DESCRIPTION = ''.join(f.readlines())
setup(
name='omf',
version='0.9.3',
packages=find_packages(exclude=('tests',)),
install_requires=[
'numpy>=1.7',
'properties>=0.5.5',
'pypng',
'six',
'vectormath>=0.2.0',
],
author='Global Mining Guidelines Group',
author_email='it@seequent.com',
description='API Library for Open Mining Format',
long_description=LONG_DESCRIPTION,
keywords='mining data interchange',
url='https://gmggroup.org',
download_url='https://github.com/gmggroup/omf',
classifiers=CLASSIFIERS,
platforms=['Windows', 'Linux', 'Solaris', 'Mac OS-X', 'Unix'],
license='MIT License',
use_2to3=False,
)
| #!/usr/bin/env python
"""omf: API Library for Open Mining Format"""
from distutils.core import setup
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS',
'Natural Language :: English',
]
with open('README.rst') as f:
LONG_DESCRIPTION = ''.join(f.readlines())
setup(
name='omf',
version='0.9.3',
packages=find_packages(exclude=('tests',)),
install_requires=[
'numpy>=1.7',
'properties==0.4.0',
'pypng',
'six',
'vectormath==0.2.0',
],
author='Global Mining Guidelines Group',
author_email='it@seequent.com',
description='API Library for Open Mining Format',
long_description=LONG_DESCRIPTION,
keywords='mining data interchange',
url='https://gmggroup.org',
download_url='https://github.com/gmggroup/omf',
classifiers=CLASSIFIERS,
platforms=['Windows', 'Linux', 'Solaris', 'Mac OS-X', 'Unix'],
license='MIT License',
use_2to3=False,
)
|
Fix the deprecation notice on the TreeBuilder added in Symfony 4.2
See https://symfony.com/blog/new-in-symfony-4-2-important-deprecations | <?php
namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder('sb_json_request');
$builder->getRootNode()
->children()
->arrayNode('listener')
->addDefaultsIfNotSet()
->children()
->scalarNode('request_transformer')
->defaultValue(RequestTransformerListener::class)
->end()
->end()
->end()
->end();
return $builder;
}
}
| <?php
namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$builder->root('sb_json_request')
->children()
->arrayNode('listener')
->addDefaultsIfNotSet()
->children()
->scalarNode('request_transformer')
->defaultValue(RequestTransformerListener::class)
->end()
->end()
->end()
->end();
return $builder;
}
}
|
Revert "client side redirect for unauth user"
This reverts commit 8577dc1dd2675aa06538954d299d1a47a40f9174. |
pjax_config_page("profit_table", function(){
return {
onLoad: function() {
BinarySocket.init({
onmessage: function(msg){
var response = JSON.parse(msg.data);
if (response) {
var type = response.msg_type;
if (type === 'profit_table'){
ProfitTableWS.profitTableHandler(response);
}
}
}
});
Content.populate();
ProfitTableWS.init();
},
onUnload: function(){
ProfitTableWS.clean();
}
};
}); |
pjax_config_page("profit_table", function(){
return {
onLoad: function() {
if (!getCookieItem("login")) {
window.location = window.location.host + "/login";
return;
}
BinarySocket.init({
onmessage: function(msg){
var response = JSON.parse(msg.data);
if (response) {
var type = response.msg_type;
if (type === 'profit_table'){
ProfitTableWS.profitTableHandler(response);
}
}
}
});
Content.populate();
ProfitTableWS.init();
},
onUnload: function(){
ProfitTableWS.clean();
}
};
}); |
Add --show option to key:generate. | <?php namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class KeyGenerateCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = "Set the application key";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
if ($this->option('show'))
{
return $this->line('<comment>'.$key.'</comment>');
}
foreach ([base_path('.env'), base_path('.env.example')] as $path)
{
if (file_exists($path))
{
file_put_contents($path, str_replace(
$this->laravel['config']['app.key'], $key, file_get_contents($path)
));
}
}
$this->laravel['config']['app.key'] = $key;
$this->info("Application key [$key] set successfully.");
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'),
);
}
}
| <?php namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
class KeyGenerateCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = "Set the application key";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
foreach ([base_path('.env'), base_path('.env.example')] as $path)
{
if (file_exists($path))
{
file_put_contents($path, str_replace(
$this->laravel['config']['app.key'], $key, file_get_contents($path)
));
}
}
$this->laravel['config']['app.key'] = $key;
$this->info("Application key [$key] set successfully.");
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
}
|
Save the observation if the form was valid. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from braces.views import LoginRequiredMixin
from .forms import ObservationForm, BatchUploadForm
class AddObservationView(FormView):
"""
Add a single observation.
"""
form_class = ObservationForm
template_name = "observations/add_observation.html"
success_url = reverse_lazy('observations:add_observation')
def form_valid(self, form):
observation = form.save(commit=False)
observation.observer = self.request.observer
observation.save()
return super(AddObservationView, self).form_valid(form)
class UploadObservationsView(LoginRequiredMixin, FormView):
"""
Upload a file of observations.
"""
form_class = BatchUploadForm
template_name = "observations/upload_observations.html"
success_url = reverse_lazy('observations:upload_observations')
def form_valid(self, form):
form.process_file()
messages.success(self.request, _("File uploaded successfully!"))
return super(UploadObservationsView, self).form_valid(form)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from braces.views import LoginRequiredMixin
from .forms import ObservationForm, BatchUploadForm
class AddObservationView(FormView):
"""
Add a single observation.
"""
form_class = ObservationForm
template_name = "observations/add_observation.html"
success_url = reverse_lazy('observations:add_observation')
class UploadObservationsView(LoginRequiredMixin, FormView):
"""
Upload a file of observations.
"""
form_class = BatchUploadForm
template_name = "observations/upload_observations.html"
success_url = reverse_lazy('observations:upload_observations')
def form_valid(self, form):
form.process_file()
messages.success(self.request, _("File uploaded successfully!"))
return super(UploadObservationsView, self).form_valid(form)
|
Set "public static String readFile()" :book: | public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(String...args){}
public static String readFile()
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
| public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(String...args){}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
fix: Create locale dir if doesn't exist | const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const program = require('commander')
const getConfig = require('lingui-conf').default
const plurals = require('make-plural')
const config = getConfig()
program.parse(process.argv)
function validateLocales (locales) {
const unknown = locales.filter(locale => !(locale in plurals))
if (unknown.length) {
console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`))
process.exit(1)
}
}
function addLocale (locales) {
if (!fs.existsSync(config.localeDir)) {
fs.mkdirSync(config.localeDir)
}
locales.forEach(locale => {
const localeDir = path.join(config.localeDir, locale)
if (fs.existsSync(localeDir)) {
console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`))
} else {
fs.mkdirSync(localeDir)
console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`))
}
})
}
validateLocales(program.args)
addLocale(program.args)
console.log()
console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
| const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const program = require('commander')
const getConfig = require('lingui-conf').default
const plurals = require('make-plural')
const config = getConfig()
program.parse(process.argv)
function validateLocales (locales) {
const unknown = locales.filter(locale => !(locale in plurals))
if (unknown.length) {
console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`))
process.exit(1)
}
}
function addLocale (locales) {
if (fs.existsSync(config.localeDir)) {
fs.mkdirSync(config.localeDir)
}
locales.forEach(locale => {
const localeDir = path.join(config.localeDir, locale)
if (fs.existsSync(localeDir)) {
console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`))
} else {
fs.mkdirSync(localeDir)
console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`))
}
})
}
validateLocales(program.args)
addLocale(program.args)
console.log()
console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
|
Remove origin and destination fields. They are not in Helsinki API | var moment = require('moment');
// Returned format from original API is a bit strange and very deeply nested.
// Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL
function transform(data) {
var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity;
return {
vehicles: vehicles.map(transformVehicle),
responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp
};
}
function transformVehicle(vehicle) {
var journey = vehicle.MonitoredVehicleJourney;
return {
id: journey.VehicleRef.value,
line: journey.LineRef.value,
latitude: journey.VehicleLocation.Latitude,
longitude: journey.VehicleLocation.Longitude,
rotation: journey.Bearing,
operator: journey.OperatorRef.value,
direction: journey.DirectionRef.value,
validUntil: moment(vehicle.ValidUntilTime).toISOString()
};
}
module.exports = transform;
| var moment = require('moment');
// Returned format from original API is a bit strange and very deeply nested.
// Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL
function transform(data) {
var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity;
return {
vehicles: vehicles.map(transformVehicle),
responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp
};
}
function transformVehicle(vehicle) {
var journey = vehicle.MonitoredVehicleJourney;
return {
id: journey.VehicleRef.value,
line: journey.LineRef.value,
latitude: journey.VehicleLocation.Latitude,
longitude: journey.VehicleLocation.Longitude,
rotation: journey.Bearing,
origin: journey.OriginName.value,
destination: journey.DestinationName.value,
operator: journey.OperatorRef.value,
direction: journey.DirectionRef.value,
validUntil: moment(vehicle.ValidUntilTime).toISOString()
};
}
module.exports = transform;
|
Use req.params[0] instead of req.param(0) | var express = require('express');
var router = express.Router();
var utils = require('./utils/firebase');
router.get(/^\/(.+)$/, (req, res, next) => {
const sectionPath = req.params[0];
Promise.all([
utils.loadDiff(sectionPath),
utils.loadFetchJSON()
]).then(([{ section, diffs }, time]) => {
// XXX
const topics = [];
const titles = [];
for (let node = section; node; node = node.parent) {
topics.unshift(node.headingText);
titles.push(node.headingText);
}
res.render('diff', {
title: 'Diff of ' + titles.join(' ← '),
time: time,
section: section,
topicPath: topics.join(' → '),
previousSection: section.previous,
nextSection: section.next,
diffs: diffs
});
}).catch((err) => {
next(err);
});
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var utils = require('./utils/firebase');
router.get(/^\/(.+)$/, (req, res, next) => {
const sectionPath = req.param(0);
Promise.all([
utils.loadDiff(sectionPath),
utils.loadFetchJSON()
]).then(([{ section, diffs }, time]) => {
// XXX
const topics = [];
const titles = [];
for (let node = section; node; node = node.parent) {
topics.unshift(node.headingText);
titles.push(node.headingText);
}
res.render('diff', {
title: 'Diff of ' + titles.join(' ← '),
time: time,
section: section,
topicPath: topics.join(' → '),
previousSection: section.previous,
nextSection: section.next,
diffs: diffs
});
}).catch((err) => {
next(err);
});
});
module.exports = router;
|
Add webob as a requirement. | from setuptools import setup
setup(
name='XBlock',
version='0.1',
description='XBlock Core Library',
packages=['xblock'],
requires=[
'webob',
],
entry_points={
'xblock.v1': [
'helloworld = xblock.content:HelloWorldBlock',
'html = xblock.content:HtmlBlock',
'sequence = xblock.structure:Sequence',
'vertical = xblock.structure:VerticalBlock',
'sidebar = xblock.structure:SidebarBlock',
'problem = xblock.problem:ProblemBlock',
'textinput = xblock.problem:TextInputBlock',
'equality = xblock.problem:EqualityCheckerBlock',
'attempts_scoreboard = xblock.problem:AttemptsScoreboardBlock',
'thumbs = xblock.thumbs:ThumbsBlock',
'slider = xblock.slider:Slider',
'progress_slider = xblock.slider:ProgressSlider',
]
}
)
| from setuptools import setup
setup(
name='XBlock',
version='0.1',
description='XBlock Core Library',
packages=['xblock'],
entry_points={
'xblock.v1': [
'helloworld = xblock.content:HelloWorldBlock',
'html = xblock.content:HtmlBlock',
'sequence = xblock.structure:Sequence',
'vertical = xblock.structure:VerticalBlock',
'sidebar = xblock.structure:SidebarBlock',
'problem = xblock.problem:ProblemBlock',
'textinput = xblock.problem:TextInputBlock',
'equality = xblock.problem:EqualityCheckerBlock',
'attempts_scoreboard = xblock.problem:AttemptsScoreboardBlock',
'thumbs = xblock.thumbs:ThumbsBlock',
'slider = xblock.slider:Slider',
'progress_slider = xblock.slider:ProgressSlider',
]
}
)
|
Update repo entrypoint and remote_update stub. | """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def update_repo(args):
"""
Main entrypoint for repo update operations.
"""
if args.repo_type == "local":
local_update(args.repository, args.package_paths)
else:
remote_update(args.repository, args.package_paths)
def remote_update(repo_ui, deb_paths=[]):
"""
Pushes packages to a remote deb repository.
Args:
repo_uri: location of the repository.
deb_paths: list of problem deb paths to copy.
"""
pass
def local_update(repo_path, deb_paths=[]):
"""
Updates a local deb repository by copying debs and running scanpackages.
Args:
repo_path: the path to the local repository.
dep_paths: list of problem deb paths to copy.
"""
[copy2(deb_path, repo_path) for deb_path in deb_paths]
shell = spur.LocalShell()
result = shell.run(["dpkg-scanpackages", ".", "/dev/null"], cwd=repo_path)
packages_path = join(repo_path, "Packages.gz")
with gzip.open(packages_path, "wb") as packages:
packages.write(result.output)
print("Updated problem repository.")
| """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def local_update(repo_path, deb_paths=[]):
"""
Updates a local deb repository by copying debs and running scanpackages.
Args:
repo_path: the path to the local repository.
dep_paths: list of problem deb paths to copy.
"""
[copy2(deb_path, repo_path) for deb_path in deb_paths]
shell = spur.LocalShell()
result = shell.run(["dpkg-scanpackages", ".", "/dev/null"], cwd=repo_path)
packages_path = join(repo_path, "Packages.gz")
with gzip.open(packages_path, "wb") as packages:
packages.write(result.output)
print("Updated problem repository.")
|
Add django setup for some initialization | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webview.settings")
import django
import logging
from api.webview.models import Document
from scrapi import events
from scrapi.processing.base import BaseProcessor
django.setup()
logger = logging.getLogger(__name__)
class PostgresProcessor(BaseProcessor):
NAME = 'postgres'
@events.logged(events.PROCESSING, 'raw.postgres')
def process_raw(self, raw_doc):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.raw = raw_doc.attributes
document.save()
@events.logged(events.PROCESSING, 'normalized.postgres')
def process_normalized(self, raw_doc, normalized):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.normalized = normalized.attributes
document.providerUpdatedDateTime = normalized['providerUpdatedDateTime']
document.save()
def _get_by_source_id(self, model, source, docID):
return Document.objects.filter(source=source, docID=docID)
| from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webview.settings")
import logging
from api.webview.models import Document
from scrapi import events
from scrapi.processing.base import BaseProcessor
logger = logging.getLogger(__name__)
class PostgresProcessor(BaseProcessor):
NAME = 'postgres'
@events.logged(events.PROCESSING, 'raw.postgres')
def process_raw(self, raw_doc):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.raw = raw_doc.attributes
document.save()
@events.logged(events.PROCESSING, 'normalized.postgres')
def process_normalized(self, raw_doc, normalized):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.normalized = normalized.attributes
document.providerUpdatedDateTime = normalized['providerUpdatedDateTime']
document.save()
def _get_by_source_id(self, model, source, docID):
return Document.objects.filter(source=source, docID=docID)
|
Fix component overriding for default case (no override) | define([], function() {
return {
load: function(id, require, callback) {
// actual module loading function
var loadImpl = function(id, require, callback) {
require([id], function() {
callback(require(id));
});
}
var appPattern = /^app\/js\//;
var overrideIdPrefix = 'app/js/app/_override/';
// check module id
var isAppModule = id.match(appPattern);
if (!isAppModule) {
// default
loadImpl(id, require, callback);
}
else {
// check if module is overridden
var overrideId = id.replace(appPattern, overrideIdPrefix);
console.debug('Check if component is overriden: '+overrideId);
require([overrideId], function(result) {
if (!(typeof result == 'function')) {
loadImpl(id, require, callback);
}
else {
callback(require(overrideId));
}
});
}
}
};
}); | define([], function() {
return {
load: function(id, require, callback) {
// actual module loading function
var loadImpl = function(id, require, callback) {
require([id], function() {
callback(require(id));
});
}
var appPattern = /^app\/js\//;
var overrideIdPrefix = 'app/js/app/_override/';
// check module id
var isAppModule = id.match(appPattern);
if (!isAppModule) {
// default
loadImpl(id, require, callback);
}
else {
// check if module is overridden
var overrideId = id.replace(appPattern, overrideIdPrefix);
require([overrideId], function(result) {
if (result == 'not-a-module') {
loadImpl(id, require, callback);
}
else {
callback(require(overrideId));
}
});
}
}
};
}); |
Use the same accept headers in browsers. | /*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/** Browser replacement for the request module using jQuery. */
var EventEmitter = require('events').EventEmitter,
SingleIterator = require('../../lib/iterators/Iterator').SingleIterator;
require('setimmediate');
// Requests the given resource as an iterator
function createRequest(settings) {
var request = new EventEmitter();
// Delegate the request to jQuery's AJAX module
var jqXHR = jQuery.ajax({
url: settings.url,
timeout: settings.timeout,
type: settings.method,
headers: { accept: settings.headers && settings.headers.accept || '*/*' },
})
// Emit the result as a readable response iterator
.always(function () {
if (jqXHR.failure) return;
var response = new SingleIterator(jqXHR.responseText || '');
response.statusCode = jqXHR.status;
response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') };
request.emit('response', response);
});
return request;
}
module.exports = createRequest;
| /*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/** Browser replacement for the request module using jQuery. */
var EventEmitter = require('events').EventEmitter,
SingleIterator = require('../../lib/iterators/Iterator').SingleIterator;
require('setimmediate');
// Requests the given resource as an iterator
function createRequest(settings) {
var request = new EventEmitter();
// Delegate the request to jQuery's AJAX module
var jqXHR = jQuery.ajax({
url: settings.url,
timeout: settings.timeout,
type: settings.method,
headers: { accept: 'text/turtle' },
})
// Emit the result as a readable response iterator
.always(function () {
if (jqXHR.failure) return;
var response = new SingleIterator(jqXHR.responseText || '');
response.statusCode = jqXHR.status;
response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') };
request.emit('response', response);
});
return request;
}
module.exports = createRequest;
|
Support non-string formats in `get_fields`.
This commit rewrites the `get_fields` function to be simpler and more general.
The previous implementation relied on ad hoc dict mocking and only supported
format strings involving string-valued formats ('%(name)s'). From this commit
other formats (e.g. '%(name)04d') are supported. The motivation for this is
upcoming changes to how the DMA pool frames are named. | #
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
'''Various helpers for doing advanced things with dictionaries.'''
import re
def get_fields(s):
'''Return a set of field names referenced as formatting keys in the given
string. I thought there would be an easier way to get this, but I can't
find one. E.g. get_fields('%(hello)s %(world)s') returns
set('hello', 'world').'''
return set(re.findall(r'%\(([^)]+)\)', s))
class Guard(object):
'''Representation of a condition required for some action. See usage in
Template.py.'''
def __init__(self, guard_fn):
self.guard_fn = guard_fn
def __call__(self, arg):
return self.guard_fn(arg)
| #
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
'''Various helpers for doing advanced things with dictionaries.'''
def get_fields(s):
'''Return a set of field names referenced as formatting keys in the given
string. I thought there would be an easier way to get this, but I can't
find one. E.g. get_fields('%(hello)s %(world)s') returns
set('hello', 'world').'''
class FakeDict(dict):
def __init__(self):
super(FakeDict, self).__init__()
self.referenced = set()
def __getitem__(self, key):
self.referenced.add(key)
return ''
f = FakeDict()
s % f # Value deliberately discarded
return f.referenced
class Guard(object):
'''Representation of a condition required for some action. See usage in
Template.py.'''
def __init__(self, guard_fn):
self.guard_fn = guard_fn
def __call__(self, arg):
return self.guard_fn(arg)
|
Add INTEGER type as alias of INT type | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0 # delete in the future
INTEGER = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
INTEGER: "INTEGER",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
|
Upgrade djsonb to fix syntax error | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
packages=find_packages(exclude=['tests']),
dependency_links=[
'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.4'
],
install_requires=[
'Django >=1.8',
'djangorestframework >=3.1.1',
'djangorestframework-gis >=0.8.1',
'django-filter >=0.9.2',
'djsonb >=0.1.4',
'jsonschema >=2.4.0',
'psycopg2 >=2.6',
'django-extensions >=1.5.2',
'python-dateutil >=2.4.2',
'PyYAML >=3.11'
],
extras_require={
'dev': [],
'test': tests_require
},
test_suite='tests',
tests_require=tests_require,
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
packages=find_packages(exclude=['tests']),
dependency_links=[
'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.3'
],
install_requires=[
'Django >=1.8',
'djangorestframework >=3.1.1',
'djangorestframework-gis >=0.8.1',
'django-filter >=0.9.2',
'djsonb >=0.1.3',
'jsonschema >=2.4.0',
'psycopg2 >=2.6',
'django-extensions >=1.5.2',
'python-dateutil >=2.4.2',
'PyYAML >=3.11'
],
extras_require={
'dev': [],
'test': tests_require
},
test_suite='tests',
tests_require=tests_require,
)
|
Allow using register_enum as a decorator
By returning the original class instance, it'd be possible to use `enum_wrapper.register_enum` as a decorator, making the usage cleaner while staying backwards compatible:
```python
@enum_wrapper.register_enum
class MyAwesomeClass:
pass
``` | import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
return enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__'])
def _json_dump_enum(self, enum_class):
return json.dumps(self._enum_to_dict(enum_class))
def get_json_formatted_enums(self):
data = {}
for identifier, enum_content in self.registered_enums.items():
data[identifier] = self._enum_to_dict(enum_content)
return json.dumps(data)
enum_wrapper = EnumWrapper()
| import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__'])
def _json_dump_enum(self, enum_class):
return json.dumps(self._enum_to_dict(enum_class))
def get_json_formatted_enums(self):
data = {}
for identifier, enum_content in self.registered_enums.items():
data[identifier] = self._enum_to_dict(enum_content)
return json.dumps(data)
enum_wrapper = EnumWrapper()
|
Change rate to 10 seconds. | // Status.js Front End
// Developed by @gaarb
var APIUrl = "https://api.garb.pw/status"; // Setting the APIUrl.
var Banner = document.getElementById('banner');
var BannerMsg = document.getElementById('banner-msg');
$(document).ready(function () {
setInterval(function () {
$.getJSON(APIUrl, function (data) {
if (data['login']) {
$('#login-color').removeClass("offline");
$('#login-color').addClass("online");
$('#login-text').text('ONLINE');
}
if (data['gameserver']) {
$('#game-color').removeClass("offline");
$('#game-color').addClass("online");
$('#game-text').text('ONLINE');
}
// Banner
if (data.banner) {
Banner.classList.remove('banner-disabled');
BannerMsg.innerHTML = data.banner;
} else {
Banner.classList.add('banner-disabled');
}
})
.fail(function() {
$('#login-color').addClass("offline");
$('#login-text').text('OFFLINE');
$('#game-color').addClass("offline");
$('#game-text').text('OFFLINE');
Banner.classList.add('banner-disabled');
});
}, 10000);
});
| // Status.js Front End
// Developed by @gaarb
var APIUrl = "https://api.garb.pw/status"; // Setting the APIUrl.
var Banner = document.getElementById('banner');
var BannerMsg = document.getElementById('banner-msg');
$(document).ready(function () {
setInterval(function () {
$.getJSON(APIUrl, function (data) {
if (data['login']) {
$('#login-color').removeClass("offline");
$('#login-color').addClass("online");
$('#login-text').text('ONLINE');
}
if (data['gameserver']) {
$('#game-color').removeClass("offline");
$('#game-color').addClass("online");
$('#game-text').text('ONLINE');
}
// Banner
if (data.banner) {
Banner.classList.remove('banner-disabled');
BannerMsg.innerHTML = data.banner;
} else {
Banner.classList.add('banner-disabled');
}
})
.fail(function() {
$('#login-color').addClass("offline");
$('#login-text').text('OFFLINE');
$('#game-color').addClass("offline");
$('#game-text').text('OFFLINE');
Banner.classList.add('banner-disabled');
});
}, 1000);
});
|
Fix regexp logic when installed into subfolder | <?php
/*
* This file is part of Slim JSON Web Token Authentication middleware
*
* Copyright (c) 2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
class RequestPathRule implements RuleInterface
{
protected $options = array(
"path" => "/",
"passthrough" => array()
);
public function __construct($options = array())
{
$this->options = array_merge($this->options, $options);
}
public function __invoke(\Slim\Slim $app)
{
/* If request path is matches passthrough should not authenticate. */
foreach ($this->options["passthrough"] as $passthrough) {
$passthrough = rtrim($passthrough, "/");
if (!!preg_match("@^{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
return false;
}
}
/* Otherwise check if path matches and we should authenticate. */
$path = rtrim($this->options["path"], "/");
return !!preg_match("@^{$path}(/.*)?$@", $app->request->getResourceUri());
}
}
| <?php
/*
* This file is part of Slim JSON Web Token Authentication middleware
*
* Copyright (c) 2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
class RequestPathRule implements RuleInterface
{
protected $options = array(
"path" => "/",
"passthrough" => array()
);
public function __construct($options = array())
{
$this->options = array_merge($this->options, $options);
}
public function __invoke(\Slim\Slim $app)
{
/* If request path is matches passthrough should not authenticate. */
foreach ($this->options["passthrough"] as $passthrough) {
$passthrough = rtrim($passthrough, "/");
if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
return false;
}
}
/* Otherwise check if path matches and we should authenticate. */
$path = rtrim($this->options["path"], "/");
return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
}
}
|
Add console input approximation point | package main;
import java.util.Scanner;
import approximation.Lagrange;
/**
* Main class
* @author Pavel_Verkhovtsov
*/
public class Main {
private static double[] y = {2.02, 1.98, 1.67, 1.65, 1.57, 1.42, 1.37, 1.07, 0.85, 0.48, 0.35, -0.30, -0.61, -1.2, -1.39, -1.76, -2.28, -2.81, -3.57, -4.06};
private static double[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
/**
* Main method.
* @param args console parameters
*/
@SuppressWarnings("resource")
public static void main(final String[] args){
Lagrange lagrange = new Lagrange(x, y);
System.out.print("Input approximation point: ");
double point = new Scanner(System.in).nextDouble();
System.out.println(lagrange.approximazeFunction(point));
}
}
| package main;
import approximation.Lagrange;
/**
* Main class
* @author Pavel_Verkhovtsov
*/
public class Main {
private static double[] y = {2.02, 1.98, 1.67, 1.65, 1.57, 1.42, 1.37, 1.07, 0.85, 0.48, 0.35, -0.30, -0.61, -1.2, -1.39, -1.76, -2.28, -2.81, -3.57, -4.06};
private static double[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
/**
* Main method.
* @param args console parameters
*/
public static void main(final String[] args){
Lagrange lagrange = new Lagrange(x, y);
System.out.println(lagrange.approximazeFunction(2));
}
}
|
Refactor part of 'ensureAuthenticated' into separate 'failNotSignedIn' | <?php
/*
* MovieContentFilter (https://www.moviecontentfilter.com/)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the GNU AGPL v3 (https://www.gnu.org/licenses/agpl-3.0.txt)
*/
namespace App;
use Delight\Foundation\App;
class Controller {
protected static function ensureAuthenticated(App $app, $targetPath = null) {
// if the user is not logged in
if (!$app->auth()->check()) {
// fail with a proper response for non-authenticated users
self::failNotSignedIn($app, $targetPath);
}
}
public static function failNotSignedIn(App $app, $targetPath = null) {
// if the requested target path has not been provided
if (empty($targetPath)) {
// use the current route as the default
$targetPath = $app->currentRoute();
}
// redirect back to the index and tell the user to sign in
$app->flash()->warning('Please sign in to view the requested page. If you don’t have an account yet, you may sign up for free.');
$app->redirect('/?continue=' . \urlencode($targetPath));
exit;
}
public static function failNotFound(App $app) {
// return the appropriate error code
$app->setStatus(404);
// return the view for the error page
echo $app->view('404.html');
}
}
| <?php
/*
* MovieContentFilter (https://www.moviecontentfilter.com/)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the GNU AGPL v3 (https://www.gnu.org/licenses/agpl-3.0.txt)
*/
namespace App;
use Delight\Foundation\App;
class Controller {
protected static function ensureAuthenticated(App $app, $targetPath = null) {
// if the user is not logged in
if (!$app->auth()->check()) {
// if the requested target path has not been provided
if (empty($targetPath)) {
// use the current route as the default
$targetPath = $app->currentRoute();
}
// redirect back to the index and tell the user to sign in
$app->flash()->warning('Please sign in to view the requested page. If you don’t have an account yet, you may sign up for free.');
$app->redirect('/?continue=' . \urlencode($targetPath));
exit;
}
}
public static function failNotFound(App $app) {
// return the appropriate error code
$app->setStatus(404);
// return the view for the error page
echo $app->view('404.html');
}
}
|
Remove console logs for PR | (function () {
'use strict';
angular.module('Tombola.Games.Bingo90.Core')
.service('LoginConverter', [
function () {
var me = this;
me.convertLoginData = function (response) {
var userData = {
username: response.payload.user.username,
balance: response.payload.user.balance,
token: response.payload.user.token
};
};
}]);
})(); | (function () {
'use strict';
angular.module('Tombola.Games.Bingo90.Core')
.service('LoginConverter', [
function () {
var me = this;
me.convertLoginData = function (response) {
var userData = {
username: response.payload.user.username,
balance: response.payload.user.balance,
token: response.payload.user.token
};
console.log(userData);
};
}]);
})(); |
doc: Use correct syntax for optional parameter in Console.put() | // Copyright © 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.
/**
* Console output interface.
* @constructor
* @protected
*/
function ConsoleIface() {}
/**
* Log error message.
* @param {String} message
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.error =
function(message) {
throw new Error("ConsoleIface.error() not implemented.");
};
/**
* Log message.
* @param {String} message
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.log =
function(message) {
throw new Error("ConsoleIface.log() not implemented.");
};
/**
* Output string without trailing newline.
* @param {String} message
* @param {Boolean} [toStderr] Optional, whether to write on stderr, default is stdout.
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.put =
function(message, toStderr) {
throw new Error("ConsoleIface.put() not implemented.");
};
module.exports = ConsoleIface;
| // Copyright © 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.
/**
* Console output interface.
* @constructor
* @protected
*/
function ConsoleIface() {}
/**
* Log error message.
* @param {String} message
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.error =
function(message) {
throw new Error("ConsoleIface.error() not implemented.");
};
/**
* Log message.
* @param {String} message
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.log =
function(message) {
throw new Error("ConsoleIface.log() not implemented.");
};
/**
* Output string without trailing newline.
* @param {String} message
* @param {Boolean|undefined} stderr Optional, whether to write on stderr, default is stdout.
* @memberOf ConsoleIface
*/
ConsoleIface.prototype.put =
function(message, stderr) {
throw new Error("ConsoleIface.put() not implemented.");
};
module.exports = ConsoleIface;
|
Fix public name displayment when logged in | <?php
namespace Calendar\View\Helper\Cell\Render;
use Square\Entity\Square;
use Zend\View\Helper\AbstractHelper;
class Occupied extends AbstractHelper
{
public function __invoke($user, $userBooking, array $reservations, array $cellLinkParams, Square $square)
{
$view = $this->getView();
if ($user && $user->can('calendar.see-data')) {
return $view->calendarCellRenderOccupiedForPrivileged($reservations, $cellLinkParams);
} else if ($user) {
if ($userBooking) {
$cellLabel = $view->t('Your Booking');
$cellGroup = ' cc-group-' . $userBooking->need('bid');
return $view->calendarCellLink($cellLabel, $view->url('square', [], $cellLinkParams), 'cc-own' . $cellGroup);
} else {
return $view->calendarCellRenderOccupiedForVisitors($reservations, $cellLinkParams, $square);
}
} else {
return $view->calendarCellRenderOccupiedForVisitors($reservations, $cellLinkParams, $square);
}
}
}
| <?php
namespace Calendar\View\Helper\Cell\Render;
use Square\Entity\Square;
use Zend\View\Helper\AbstractHelper;
class Occupied extends AbstractHelper
{
public function __invoke($user, $userBooking, array $reservations, array $cellLinkParams, Square $square)
{
$view = $this->getView();
if ($user && $user->can('calendar.see-data')) {
return $view->calendarCellRenderOccupiedForPrivileged($reservations, $cellLinkParams);
} else if ($user) {
if ($userBooking) {
$cellLabel = $view->t('Your Booking');
$cellGroup = ' cc-group-' . $userBooking->need('bid');
return $view->calendarCellLink($cellLabel, $view->url('square', [], $cellLinkParams), 'cc-own' . $cellGroup);
} else {
return $view->calendarCellRenderOccupiedForVisitors($reservations, $cellLinkParams);
}
} else {
return $view->calendarCellRenderOccupiedForVisitors($reservations, $cellLinkParams, $square);
}
}
}
|
Set default volumetype to hfs | <?php
// Adds media_type column and moves volumetype data to new column
use munkireport\lib\Schema;
class Migration_disk_report_add_media_type extends Model
{
/**
* Migrate up
*
* Migrates this table to the current version
*
**/
public function up()
{
Schema::table('diskreport', function ($table)
{
$table->string('media_type');
$table->index('media_type');
});
// Populate new column
$sql = "UPDATE diskreport
SET media_type = volumeType, volumeType = 'hfs'
WHERE volumeType IN ('hdd', 'ssd', 'fusion', 'raid')";
$this->exec($sql);
}// End function up()
/**
* Migrate down
*
* Migrates this table to the previous version
*
**/
public function down()
{
}
}
| <?php
// Adds media_type column and moves volumetype data to new column
use munkireport\lib\Schema;
class Migration_disk_report_add_media_type extends Model
{
/**
* Migrate up
*
* Migrates this table to the current version
*
**/
public function up()
{
Schema::table('diskreport', function ($table)
{
$table->string('media_type');
$table->index('media_type');
});
// Populate new column
$sql = "UPDATE diskreport
SET media_type = volumeType, volumeType = 'hfs+'
WHERE volumeType IN ('hdd', 'ssd', 'fusion', 'raid')";
$this->exec($sql);
}// End function up()
/**
* Migrate down
*
* Migrates this table to the previous version
*
**/
public function down()
{
// There is no down() as this is a bugfix and up() is idempotent
}
}
|
Remove try/except that should never be hit.
Increases code coverage. | # -*- coding: utf-8 -*-
"""Format adapter for the terminaltables module."""
import terminaltables
from cli_helpers.utils import filter_dict_by_key
from .preprocessors import (bytes_to_string, align_decimals,
override_missing_value)
supported_formats = ('ascii', 'double', 'github')
preprocessors = (bytes_to_string, override_missing_value, align_decimals)
def adapter(data, headers, table_format=None, **kwargs):
"""Wrap terminaltables inside a function for TabularOutputFormatter."""
keys = ('title', )
table_format_handler = {
'ascii': terminaltables.AsciiTable,
'double': terminaltables.DoubleTable,
'github': terminaltables.GithubFlavoredMarkdownTable,
}
table = table_format_handler[table_format]
t = table([headers] + data, **filter_dict_by_key(kwargs, keys))
return t.table
| # -*- coding: utf-8 -*-
"""Format adapter for the terminaltables module."""
import terminaltables
from cli_helpers.utils import filter_dict_by_key
from .preprocessors import (bytes_to_string, align_decimals,
override_missing_value)
supported_formats = ('ascii', 'double', 'github')
preprocessors = (bytes_to_string, override_missing_value, align_decimals)
def adapter(data, headers, table_format=None, **kwargs):
"""Wrap terminaltables inside a function for TabularOutputFormatter."""
keys = ('title', )
table_format_handler = {
'ascii': terminaltables.AsciiTable,
'double': terminaltables.DoubleTable,
'github': terminaltables.GithubFlavoredMarkdownTable,
}
try:
table = table_format_handler[table_format]
except KeyError:
raise ValueError('unrecognized table format: {}'.format(table_format))
t = table([headers] + data, **filter_dict_by_key(kwargs, keys))
return t.table
|
Make download script work with Python 3.
Closes #47. | from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
| from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
Add authorship in taxa name. Improve species "size" text description. Fix agent assignments.
git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1241 baf6b65b-9124-4dc3-b1c0-01155b4af546 | <?php
/* connector for Hydrothermal Vent Larvae
estimated execution time: 16-20 seconds
Connector screen scrapes the partner website.
*/
$timestart = microtime(1);
include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/HydrothermalVentLarvaeAPI');
$GLOBALS['ENV_DEBUG'] = false;
$taxa = HydrothermalVentLarvaeAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);
$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "121.xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);
//echo "time: ". Functions::time_elapsed() ."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");
?> | <?php
/* connector for Hydrothermal Vent Larvae
estimated execution time: 20-25 seconds
Connector screen scrapes the partner website.
*/
$timestart = microtime(1);
include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/HydrothermalVentLarvaeAPI');
$GLOBALS['ENV_DEBUG'] = false;
$taxa = HydrothermalVentLarvaeAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);
$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "121.xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);
//echo "time: ". Functions::time_elapsed() ."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");
?> |
Use if response since 'is not None' is unnecessary. |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, list):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response is not None:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, list):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
Connect to mongo here so we only do it once | "use strict";
var express = require('express'),
pages = require('./routes/pages.js'),
signup = require('./routes/signup.js'),
flash = require('connect-flash'),
auth = require('./modules/auth.js'),
api = require('./modules/api.js'),
mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var app = express();
// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(secret));
app.use(express.session({
secret: secret,
cookie: {
httpOnly: true
}
}));
app.use(auth);
app.use(flash());
if (app.get('env') === 'development') {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
} else {
app.use(express.errorHandler());
}
// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.get('/login', pages.login);
app.post('/signup', signup.sendToMailchimp);
app.use(express.static(__dirname + '/dist'));
// Go
app.listen(process.env.port || 3000);
console.log("Express server started"); | var express = require('express'),
pages = require('./routes/pages.js'),
signup = require('./routes/signup.js'),
flash = require('connect-flash'),
auth = require('./modules/auth.js');
var app = express();
// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(secret));
app.use(express.session({
secret: secret,
cookie: {
httpOnly: true
}
}));
app.use(auth);
app.use(flash());
if (app.get('env') === 'development') {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
} else {
app.use(express.errorHandler());
}
// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.get('/login', pages.login);
app.post('/signup', signup.sendToMailchimp);
app.use(express.static(__dirname + '/dist'));
// Go
app.listen(process.env.port || 3000);
console.log("Express server started"); |
Use Object.assign if no Ember.assign. And Ember.merge if no Object.assign | import Ember from 'ember'
const assign = Ember.assign || Object.assign || Ember.merge
import any from './any'
import array from './array'
import arrayOf from './array-of'
import bool from './bool'
import element from './element'
import emberObject from './ember-object'
import func from './func'
import instanceOf from './instance-of'
import nullFn from './null'
import number from './number'
import object from './object'
import oneOf from './one-of'
import oneOfType from './one-of-type'
import shape from './shape'
import string from './string'
import symbol from './symbol'
const validators = {
any,
array,
bool,
element,
EmberObject: emberObject,
func,
instanceOf,
null: nullFn,
number,
object,
oneOf,
string,
symbol
}
assign(validators, {
arrayOf: arrayOf.bind(this, validators),
oneOfType: oneOfType.bind(this, validators),
shape: shape.bind(this, validators)
})
export default validators
| import Ember from 'ember'
const {assign} = Ember
import any from './any'
import array from './array'
import arrayOf from './array-of'
import bool from './bool'
import element from './element'
import emberObject from './ember-object'
import func from './func'
import instanceOf from './instance-of'
import nullFn from './null'
import number from './number'
import object from './object'
import oneOf from './one-of'
import oneOfType from './one-of-type'
import shape from './shape'
import string from './string'
import symbol from './symbol'
const validators = {
any,
array,
bool,
element,
EmberObject: emberObject,
func,
instanceOf,
null: nullFn,
number,
object,
oneOf,
string,
symbol
}
assign(validators, {
arrayOf: arrayOf.bind(this, validators),
oneOfType: oneOfType.bind(this, validators),
shape: shape.bind(this, validators)
})
export default validators
|
Add searching for a project by id functionality | package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceContext
private EntityManager em;
public void addProject(Project project) {
Project foundProject = findProjectByName(project.getName());
if (foundProject != null) {
em.persist(project);
} else {
// TODO: Maybe update project title or users, or tasks?
}
}
public Project findProjectByName(String name) {
TypedQuery<Project> query = em
.createNamedQuery("findProjectByName", Project.class)
.setParameter("name", name);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public Project findProjectById(int projectId) {
String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
idQuery.setParameter("projectId", projectId);
try {
return idQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
| package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceContext
private EntityManager em;
public void addProject(Project project) {
Project foundProject = findProjectByName(project.getName());
if (foundProject != null) {
em.persist(project);
} else {
// TODO: Maybe update project title or users, or tasks?
}
}
public Project findProjectByName(String name) {
TypedQuery<Project> query = em
.createNamedQuery("findProjectByName", Project.class)
.setParameter("name", name);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
|
Create dir before data downloading | import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
| import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
Update skeleton for new updog | package org.pdxfinder.dataloaders.updog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;
public class Updog {
private String provider;
public Updog(String provider) {
this.provider = provider;
}
private static final Logger log = LoggerFactory.getLogger(Updog.class);
private Map<String, PdxDataTable> pdxDataTables;
private Map<String, Set<Object>> domainObjects;
private void readPdxDataTable() {
PdxDataTable pdxDataTables = new PdxDataTable(provider);
pdxDataTables.readData();
}
public boolean validateTemplate(){
//instantiate a validator class
TemplateValidator templateValidator = new TemplateValidator();
return true;
}
public void load(){
//create domain objects database nodes
DomainObjectCreator doc = new DomainObjectCreator(pdxDataTables);
//save db
}
}
| package org.pdxfinder.dataloaders.updog;
import com.ibm.icu.impl.LocaleDisplayNamesImpl;
import org.hibernate.sql.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class Updog {
private String provider;
public Updog(String provider) {
this.provider = provider;
}
private static final Logger log = LoggerFactory.getLogger(Updog.class);
private Map<String, PdxDataTable> pdxDataTables;
private Map<String, Object> domainObjects;
private void readPdxDataTable() {
PdxDataTable pdxDataTables = new PdxDataTable(provider);
pdxDataTables.readData();
}
public boolean validateTemplate(){
//instantiate a validator class
TemplateValidator templateValidator = new TemplateValidator();
return true;
}
public void load(){
//create domain objects database nodes
DomainObjectCreator doc = new DomainObjectCreator();
//save db
}
}
|
Make use of random_bytes for better uniqueness | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
/**
* Adds a unique identifier into records
*
* @author Simon Mönch <sm@webfactory.de>
*/
class UidProcessor
{
private $uid;
public function __construct(int $length = 7)
{
if (!is_int($length) || $length > 32 || $length < 1) {
throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
}
$this->uid = substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length);
}
public function __invoke(array $record): array
{
$record['extra']['uid'] = $this->uid;
return $record;
}
/**
* @return string
*/
public function getUid(): string
{
return $this->uid;
}
}
| <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
/**
* Adds a unique identifier into records
*
* @author Simon Mönch <sm@webfactory.de>
*/
class UidProcessor
{
private $uid;
public function __construct(int $length = 7)
{
if (!is_int($length) || $length > 32 || $length < 1) {
throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
}
$this->uid = substr(hash('md5', uniqid('', true)), 0, $length);
}
public function __invoke(array $record): array
{
$record['extra']['uid'] = $this->uid;
return $record;
}
/**
* @return string
*/
public function getUid(): string
{
return $this->uid;
}
}
|
Remove ALL powered by icons | <?php
class HitchwikiHooks {
/**
* Handler for BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function onBeforePageDisplay( &$out, &$skin ) {
// Ensure Hitchwiki skin runs only against Vector skin
// FIXME: See bug 62897
if ( $skin->getSkinName() !== 'vector' ) {
return true;
}
// Add our modules
$modules = array(
'skins.vector.hitchwiki'
);
$out->addModules( $modules );
return true;
}
/**
* Disable powered by footer icons
* Handled at hook BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function modifyFooterIcons( &$out, &$skin ) {
global $wgFooterIcons;
unset($wgFooterIcons["poweredby"]);
return true;
}
}
| <?php
class HitchwikiHooks {
/**
* Handler for BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function onBeforePageDisplay( &$out, &$skin ) {
// Ensure Hitchwiki skin runs only against Vector skin
// FIXME: See bug 62897
if ( $skin->getSkinName() !== 'vector' ) {
return true;
}
// Add our modules
$modules = array(
'skins.vector.hitchwiki'
);
$out->addModules( $modules );
return true;
}
/**
* Remove footer icons for MW and SMW
* Handler for BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function modifyFooterIcons( &$out, &$skin ) {
global $wgFooterIcons;
unset($wgFooterIcons["poweredby"]["mediawiki"]);
unset($wgFooterIcons["poweredby"]["semanticmediawiki"]);
return true;
}
}
|
Add authentication and modify response type for /test | package com.developi.wink.demo.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.ibm.domino.osgi.core.context.ContextInfo;
import lotus.domino.NotesException;
import lotus.domino.Session;
@Path("/test")
public class TestResource {
@GET
public Response test(){
try {
String userName = getUserSession().getEffectiveUserName();
if("Anonymous".equals(userName)) {
// If connected through a browser, this response will signal for authentication and redirected to the login form.
// However, be careful with 40x responses. If session authentication is enabled for the server,
// The consumer might receive the login form and 200-OK response. This would be a code-breaker.
return Response.status(Status.UNAUTHORIZED).build();
} else {
String message = "<b>Hello " + userName + "</b>";
return Response.ok().type(MediaType.TEXT_HTML).entity(message).build();
}
} catch (NotesException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
private Session getUserSession() {
return ContextInfo.getUserSession();
}
}
| package com.developi.wink.demo.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.osgi.core.context.ContextInfo;
import lotus.domino.NotesException;
import lotus.domino.Session;
@Path("/test")
public class TestResource {
@GET
public Response test(){
JsonJavaObject resp = new JsonJavaObject();
try {
resp.put("message", "Hello " + getUserSession().getEffectiveUserName());
return Response.ok().type(MediaType.APPLICATION_JSON).entity(resp.toString()).build();
} catch (NotesException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
private Session getUserSession() {
return ContextInfo.getUserSession();
}
}
|
Add cache expiration on class metadata | <?php
namespace JPC\Test\MongoDB\ODM\Factory;
use JPC\MongoDB\ODM\Factory\ClassMetadataFactory;
use JPC\Test\MongoDB\ODM\Framework\TestCase;
class ClassMetadataFactoryTest extends TestCase
{
/**
* @var ClassMetadataFactory
*/
private $classMetadataFactory;
public function setUp()
{
$this->classMetadataFactory = new ClassMetadataFactory();
}
public function testGetMetadataForClassInexisting()
{
$this->expectException(\Exception::class);
$this->classMetadataFactory->getMetadataForClass("Inexisting");
}
public function testGetMetadataForClass()
{
$classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass");
$this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta);
$this->assertCount(1, $this->getPropertyValue($this->classMetadataFactory, "loadedMetadata"));
}
}
| <?php
namespace JPC\Test\MongoDB\ODM\Factory;
use JPC\MongoDB\ODM\Factory\ClassMetadataFactory;
use JPC\Test\MongoDB\ODM\Framework\TestCase;
class ClassMetadataFactoryTest extends TestCase
{
/**
* @var ClassMetadataFactory
*/
private $classMetadataFactory;
public function setUp()
{
$this->classMetadataFactory = new ClassMetadataFactory();
}
public function testGetMetadataForClassInexisting()
{
$this->expectException(\Exception::class);
$this->classMetadataFactory->getMetadataForClass("Inexisting");
}
public function testGetMetadataForClass()
{
$classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass");
$this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta);
$this->assertCount(1, $this->getPropertyValue($this->classMetadataFactory, "loadedMetadatas"));
}
}
|
Change memcache expiration timing to 1 week | __author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'
from BaseHandler import *
import logging
from XMLAnalyser import XMLAnalyser
from google.appengine.api import memcache
class StudentsListHandler(BaseHandler):
def __init__(self, request=None, response=None):
self.initialize(request, response)
self.pageName = "students_list"
def get(self):
self.render("groupchoice.html")
def post(self):
group_to_find = self.request.get("group_name")
groups = memcache.get("group_list")
if groups is None:
logging.error("CACHE MISS StudentsListHandler l. 24")
parser = XMLAnalyser()
groups = parser.get_members()
memcache.set("group_list", groups, time=604800);
to_display = dict()
for key in groups:
if group_to_find in key:
to_display[key] = groups[key]
if len(to_display) > 0:
self.render("groupdisplay.html", group_name=group_to_find, groups=to_display)
else:
self.render("message.html", title="No such group", subtitle="", argument=group_to_find)
| __author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'
from BaseHandler import *
import logging
from XMLAnalyser import XMLAnalyser
from google.appengine.api import memcache
class StudentsListHandler(BaseHandler):
def __init__(self, request=None, response=None):
self.initialize(request, response)
self.pageName = "students_list"
def get(self):
self.render("groupchoice.html")
def post(self):
group_to_find = self.request.get("group_name")
groups = memcache.get("group_list")
if groups is None:
logging.error("CACHE MISS StudentsListHandler l. 24")
parser = XMLAnalyser()
groups = parser.get_members()
memcache.set("group_list", groups, time=7200);
to_display = dict()
for key in groups:
if group_to_find in key:
to_display[key] = groups[key]
if len(to_display) > 0:
self.render("groupdisplay.html", group_name=group_to_find, groups=to_display)
else:
self.render("message.html", title="No such group", subtitle="", argument=group_to_find)
|
Remove incorrect check for LCL | package me.nallar.modpatcher;
import me.nallar.javatransformer.api.JavaTransformer;
class ModPatcherLoadHook {
private static final int API_VERSION = 0; //Keep in sync with version in ModPatcher.java
private static final String VERSION = "@VERSION@".replace("-SNAPSHOT", "");
static void loadHook(ModPatcher.Version requiredVersion, String modPatcherRelease, int apiVersion) {
PatcherLog.trace("Loaded ModPatcher", new Throwable());
if (API_VERSION != apiVersion) {
PatcherLog.warn("API version mismatch. Expected " + API_VERSION + ", got " + apiVersion);
PatcherLog.warn("API was loaded from: " + JavaTransformer.pathFromClass(ModPatcher.class));
}
ModPatcher.Version current = ModPatcher.Version.of(VERSION);
if (current.compareTo(requiredVersion) < 0) {
String autoUpdate = "\nWill auto-update on next start.";
if (ModPatcher.neverUpdate())
autoUpdate = "";
else
JavaTransformer.pathFromClass(ModPatcherTransformer.class).toFile().deleteOnExit();
throw new RuntimeException("ModPatcher outdated. Have version: " + VERSION + ", requested version: " + requiredVersion + autoUpdate);
}
}
}
| package me.nallar.modpatcher;
import me.nallar.javatransformer.api.JavaTransformer;
class ModPatcherLoadHook {
private static final int API_VERSION = 0; //Keep in sync with version in ModPatcher.java
private static final String VERSION = "@VERSION@".replace("-SNAPSHOT", "");
static void loadHook(ModPatcher.Version requiredVersion, String modPatcherRelease, int apiVersion) {
PatcherLog.trace("Loaded ModPatcher", new Throwable());
if (ModPatcherLoadHook.class.getClassLoader().getClass().getName().contains("LaunchClassLoader")) {
throw new Error("ModPatcher should not be loaded under LaunchClassLoader");
}
if (API_VERSION != apiVersion) {
PatcherLog.warn("API version mismatch. Expected " + API_VERSION + ", got " + apiVersion);
PatcherLog.warn("API was loaded from: " + JavaTransformer.pathFromClass(ModPatcher.class));
}
ModPatcher.Version current = ModPatcher.Version.of(VERSION);
if (current.compareTo(requiredVersion) < 0) {
String autoUpdate = "\nWill auto-update on next start.";
if (ModPatcher.neverUpdate())
autoUpdate = "";
else
JavaTransformer.pathFromClass(ModPatcherTransformer.class).toFile().deleteOnExit();
throw new RuntimeException("ModPatcher outdated. Have version: " + VERSION + ", requested version: " + requiredVersion + autoUpdate);
}
}
}
|
Make queues list output consistent with git status | package gitmedia
import (
".."
"../queuedir"
"os"
"path/filepath"
"strings"
)
type QueuesCommand struct {
*Command
}
func (c *QueuesCommand) Run() {
err := gitmedia.WalkQueues(func(name string, queue *queuedir.Queue) error {
wd, _ := os.Getwd()
gitmedia.Print(name)
return queue.Walk(func(id string, body []byte) error {
parts := strings.Split(string(body), ":")
if len(parts) == 2 {
absPath := filepath.Join(gitmedia.LocalWorkingDir, parts[1])
relPath, _ := filepath.Rel(wd, absPath)
gitmedia.Print(" " + relPath)
} else {
gitmedia.Print(" " + parts[0])
}
return nil
})
})
if err != nil {
gitmedia.Panic(err, "Error walking queues")
}
}
func init() {
registerCommand("queues", func(c *Command) RunnableCommand {
return &QueuesCommand{Command: c}
})
}
| package gitmedia
import (
".."
"../queuedir"
"strings"
)
type QueuesCommand struct {
*Command
}
func (c *QueuesCommand) Run() {
err := gitmedia.WalkQueues(func(name string, queue *queuedir.Queue) error {
gitmedia.Print(name)
return queue.Walk(func(id string, body []byte) error {
parts := strings.Split(string(body), ":")
if len(parts) == 2 {
gitmedia.Print(" " + parts[1])
} else {
gitmedia.Print(" " + parts[0])
}
return nil
})
})
if err != nil {
gitmedia.Panic(err, "Error walking queues")
}
}
func init() {
registerCommand("queues", func(c *Command) RunnableCommand {
return &QueuesCommand{Command: c}
})
}
|
Use jQuery.scrollTop to support IE. | $(function () {
$('.frilinks .fri').each(function (n, e) {
e = $(e);
var hr = e.find('a').attr('href');
if (!hr)
return;
e.css({cursor: 'pointer'});
e.click(function (e) {
window.open(hr);
e.preventDefault();
});
});
var header = $('.header');
var headbg = header.find('.background');
var bhc = header.find('.big-header-content');
var tsy = 250;
var bhch;
function find_bhch () {
bhc.css({"height": ""});
bhch = (bhc.length ? bhc.height() : 0)
tsy = header.height();
}
function am () {
requestAnimationFrame(am);
find_bhch();
var t = Math.min($(window).scrollTop() / tsy, 1);
headbg.css({opacity: 1 - t});
if (bhch > 0) {
bhc.css({height: (bhch * (1 - t)) + "px", opacity: 1 - t});
bhc.css("pointer-events", (t>=0.5?"none":""));
}
}
am();
});
| $(function () {
$('.frilinks .fri').each(function (n, e) {
e = $(e);
var hr = e.find('a').attr('href');
if (!hr)
return;
e.css({cursor: 'pointer'});
e.click(function (e) {
window.open(hr);
e.preventDefault();
});
});
var header = $('.header');
var headbg = header.find('.background');
var bhc = header.find('.big-header-content');
var tsy = 250;
var bhch;
function find_bhch () {
bhc.css({"height": ""});
bhch = (bhc.length ? bhc.height() : 0)
tsy = header.height();
}
function am () {
requestAnimationFrame(am);
find_bhch();
var t = Math.min(window.scrollY / tsy, 1);
headbg.css({opacity: 1 - t});
if (bhch > 0) {
bhc.css({height: (bhch * (1 - t)) + "px", opacity: 1 - t});
bhc.css("pointer-events", (t>=0.5?"none":""));
}
}
am();
});
|
Change issues to sending categories | import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* Displays all knowledge base (KB) articles and a search bar
*/
public class KB_IndexController extends BaseController {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
Category_DBWrapper categoryWrapper = this.getPortalBean().getCategories();
categoryWrapper.reset();
List<Category> categories = Arrays.asList(categoryWrapper.getCategories());
request.setAttribute("categories", categories);
request.getRequestDispatcher("/WEB-INF/jsp/kb/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
}
}
| import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* Displays all knowledge base (KB) articles and a search bar
*/
public class KB_IndexController extends BaseController {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
Issue_DBWrapper issueWrapper = this.getPortalBean().getIssues();
issueWrapper.reset();
List<Issue> issues = Arrays.asList(issueWrapper.getIssues());
request.setAttribute("issues", issues);
request.getRequestDispatcher("/WEB-INF/jsp/kb/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
}
}
|
Return 400 status for incomplete API queries | """
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the flask application
"""
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'}), 400
| """
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the flask application
"""
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def home():
"""Returns static home page"""
return app.send_static_file('html/home.html')
@app.route('/about')
def about():
"""Returns static about page"""
return app.send_static_file('html/about.html')
@app.route('/contact')
def contact():
"""Returns static contact page"""
return app.send_static_file('html/contact.html')
@app.route('/documentation')
def documentation():
"""Returns static documentation page"""
return app.send_static_file('html/documentation.html')
@app.route('/updates')
def updates():
"""Returns static updates page"""
return app.send_static_file('html/updates.html')
##-------------------------------------------------------##
# API Routing Errors
@app.route('/api')
def no_report():
"""Returns no report msg"""
return jsonify({'Error': 'No report type given'})
@app.route('/api/metar')
@app.route('/api/taf')
def no_station():
"""Returns no station msg"""
return jsonify({'Error': 'No station given'})
|
Make sure options is an object. | module.exports.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
var utils = {};
utils.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
utils.toRadians = function(degrees) {
return degrees * Math.PI / 180;
};
utils.toDegrees = function(radians) {
return radians * 180 / Math.PI;
};
utils.options = function(options, object) {
if (typeof options !== 'object') {
options = {};
}
if (options.value !== undefined) {
throw new TypeError('Could not create options object.');
}
options.value = function (name, value) {
if (options[name] === undefined) {
if (object) {
object[name] = value;
}
return value;
}
if (object) {
object[name] = options[name];
}
return options[name];
};
return options;
};
module.exports.Utils = utils; | module.exports.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
var utils = {};
utils.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
utils.toRadians = function(degrees) {
return degrees * Math.PI / 180;
};
utils.toDegrees = function(radians) {
return radians * 180 / Math.PI;
};
utils.options = function(options, object) {
options = options || {};
if (options.value !== undefined) {
throw new TypeError('Could not create options object.');
}
options.value = function (name, value) {
if (options[name] === undefined) {
if (object) {
object[name] = value;
}
return value;
}
if (object) {
object[name] = options[name];
}
return options[name];
};
return options;
};
module.exports.Utils = utils; |
Fix package in AOP pointcut
See gh-18558 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 smoketest.aop.monitor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceMonitor {
@AfterReturning("execution(* smoketest..*Service.*(..))")
public void logServiceAccess(JoinPoint joinPoint) {
System.out.println("Completed: " + joinPoint);
}
}
| /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 smoketest.aop.monitor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceMonitor {
@AfterReturning("execution(* sample..*Service.*(..))")
public void logServiceAccess(JoinPoint joinPoint) {
System.out.println("Completed: " + joinPoint);
}
}
|
Add 'entityManager' as possible annotation value
Reason for this change is that the IDE parses the private attributes of the annotation and provides those as autocomplete.
So this is simply a convenience change. | <?php
declare(strict_types=1);
namespace Reinfi\DependencyInjection\Annotation;
use Psr\Container\ContainerInterface;
/**
* @package Reinfi\DependencyInjection\Annotation
*
* @Annotation
* @Target({"PROPERTY", "METHOD"})
*/
final class InjectDoctrineRepository extends AbstractAnnotation
{
/**
* @var string
*/
private $entityManager = 'Doctrine\ORM\EntityManager';
/**
* @var string
*/
private $entity;
/**
* @param array $values
*/
public function __construct(array $values)
{
if (!isset($values['value'])) {
if (isset($values['em']) || isset($values['entityManager'])) {
$this->entityManager = $values['entityManager'] ?? $values['em'];
}
$this->entity = $values['entity'];
return;
}
$this->entity = $values['value'];
}
/**
* @inheritDoc
*/
public function __invoke(ContainerInterface $container)
{
$container = $this->determineContainer($container);
return $container->get($this->entityManager)->getRepository($this->entity);
}
}
| <?php
declare(strict_types=1);
namespace Reinfi\DependencyInjection\Annotation;
use Psr\Container\ContainerInterface;
/**
* @package Reinfi\DependencyInjection\Annotation
*
* @Annotation
* @Target({"PROPERTY", "METHOD"})
*/
final class InjectDoctrineRepository extends AbstractAnnotation
{
/**
* @var string
*/
private $entityManager = 'Doctrine\ORM\EntityManager';
/**
* @var string
*/
private $entity;
/**
* @param array $values
*/
public function __construct(array $values)
{
if (!isset($values['value'])) {
if (isset($values['em'])) {
$this->entityManager = $values['em'];
}
$this->entity = $values['entity'];
return;
}
$this->entity = $values['value'];
}
/**
* @inheritDoc
*/
public function __invoke(ContainerInterface $container)
{
$container = $this->determineContainer($container);
return $container->get($this->entityManager)->getRepository($this->entity);
}
}
|
[Android] Return the correct context for external extensions
The previous implementation returns the context of runtime side which is
a context for library package. This is true for internal extensions. However,
for external extensions, the context should be the same as the activity
because they're inside of runtime client. This is to fix the issue to return
the activity as the context for external extensions.
BUG=#777 | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.runtime.extension;
import android.app.Activity;
import android.content.Context;
/**
* This is a public class to provide context for extensions.
* It'll be shared by all external extensions.
*/
public class XWalkExtensionContextWrapper extends XWalkExtensionContext {
private XWalkExtensionContext mOriginContext;
public XWalkExtensionContextWrapper(XWalkExtensionContext context) {
mOriginContext = context;
}
public Object registerExtension(XWalkExtension extension) {
return mOriginContext.registerExtension(extension);
}
public void unregisterExtension(XWalkExtension extension) {
mOriginContext.unregisterExtension(extension);
}
public void postMessage(XWalkExtension extension, String message) {
mOriginContext.postMessage(extension, message);
}
public Context getContext() {
// This is very tricky because for external extensions, we should
// use Activity which contains the context for runtime client side.
// mOriginContext.getContext() returns the context of library package,
// e.g., the package context of runtime side.
return mOriginContext.getActivity();
}
public Activity getActivity() {
return mOriginContext.getActivity();
}
}
| // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.runtime.extension;
import android.app.Activity;
import android.content.Context;
/**
* This is a public class to provide context for extensions.
* It'll be shared by all extensions.
*/
public class XWalkExtensionContextWrapper extends XWalkExtensionContext {
private XWalkExtensionContext mOriginContext;
public XWalkExtensionContextWrapper(XWalkExtensionContext context) {
mOriginContext = context;
}
public Object registerExtension(XWalkExtension extension) {
return mOriginContext.registerExtension(extension);
}
public void unregisterExtension(XWalkExtension extension) {
mOriginContext.unregisterExtension(extension);
}
public void postMessage(XWalkExtension extension, String message) {
mOriginContext.postMessage(extension, message);
}
public Context getContext() {
return mOriginContext.getContext();
}
public Activity getActivity() {
return mOriginContext.getActivity();
}
}
|
Make the image data date aware
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@959 b4e469a2-07ce-4b26-9273-4d7d95a670c7 | package org.helioviewer.viewmodel.imagedata;
import org.helioviewer.viewmodel.imageformat.ImageFormat;
import org.helioviewer.viewmodel.imagetransport.ImageTransport;
/**
* Basic representation of an image handled by the view chain.
*
* <p>
* Within the view chain, the image data is given from view to view as an
* ImageData object. The object provides only methods to read informations, such
* as dimensions and pixel data. To write data, a new ImageData object has to be
* created.
*
* @author Ludwig Schmidt
* @author Markus Langenberg
*
*/
public interface ImageData {
/**
* Returns the width of the image
*
* @return width of the image
*/
public int getWidth();
/**
* Returns the height of the image
*
* @return height of the image
*/
public int getHeight();
/**
* Returns an object to read the pixel data
*
* @return object to read pixels
*/
public ImageTransport getImageTransport();
/**
* Returns an object to get informations about the image format
*
* @return object containing informations about the image format
*/
public ImageFormat getImageFormat();
/**
* Returns the color mask which should be used when drawing the image.
*
* @return the color mask which should be used when drawing the image.
*/
public ColorMask getColorMask();
public long getDateMillis();
public void setDateMillis(long dateMillis);
}
| package org.helioviewer.viewmodel.imagedata;
import org.helioviewer.viewmodel.imageformat.ImageFormat;
import org.helioviewer.viewmodel.imagetransport.ImageTransport;
/**
* Basic representation of an image handled by the view chain.
*
* <p>
* Within the view chain, the image data is given from view to view as an
* ImageData object. The object provides only methods to read informations, such
* as dimensions and pixel data. To write data, a new ImageData object has to be
* created.
*
* @author Ludwig Schmidt
* @author Markus Langenberg
*
*/
public interface ImageData {
/**
* Returns the width of the image
*
* @return width of the image
*/
public int getWidth();
/**
* Returns the height of the image
*
* @return height of the image
*/
public int getHeight();
/**
* Returns an object to read the pixel data
*
* @return object to read pixels
*/
public ImageTransport getImageTransport();
/**
* Returns an object to get informations about the image format
*
* @return object containing informations about the image format
*/
public ImageFormat getImageFormat();
/**
* Returns the color mask which should be used when drawing the image.
*
* @return the color mask which should be used when drawing the image.
*/
public ColorMask getColorMask();
}
|
Rename funtion reportIfMissing to reportIfAbsolute
The old name seems wrong. Probably copied from no-extraneuous-dependencies | import isStaticRequire from '../core/staticRequire'
function reportIfAbsolute(context, node, name) {
if (isAbsolute(name)) {
context.report(node, 'Do not import modules using an absolute path')
}
}
function isAbsolute(name) {
return name.indexOf('/') === 0
}
module.exports = {
meta: {
docs: {},
},
create: function (context) {
return {
ImportDeclaration: function handleImports(node) {
reportIfAbsolute(context, node, node.source.value)
},
CallExpression: function handleRequires(node) {
if (isStaticRequire(node)) {
reportIfAbsolute(context, node, node.arguments[0].value)
}
},
}
},
}
| import isStaticRequire from '../core/staticRequire'
function reportIfMissing(context, node, name) {
if (isAbsolute(name)) {
context.report(node, 'Do not import modules using an absolute path')
}
}
function isAbsolute(name) {
return name.indexOf('/') === 0
}
module.exports = {
meta: {
docs: {},
},
create: function (context) {
return {
ImportDeclaration: function handleImports(node) {
reportIfMissing(context, node, node.source.value)
},
CallExpression: function handleRequires(node) {
if (isStaticRequire(node)) {
reportIfMissing(context, node, node.arguments[0].value)
}
},
}
},
}
|
Use icons and titles in formSelector | 'use strict';
angular.module('arethusa.morph').directive('formSelector', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var id = scope.id;
function action(event) {
event.stopPropagation();
scope.$apply(function() {
if (scope.form.selected) {
scope.plugin.unsetState(id);
} else {
scope.plugin.setState(id, scope.form);
}
});
}
scope.$watch('form.selected', function(newVal, oldVal) {
scope.iconClass = newVal ? 'minus' : 'plus';
scope.title = newVal ? 'deselect' : 'select';
});
element.bind('click', action);
},
template: '\
<span\
class="button micro radius"\
title="{{ title }}"\
ng-class="{ success: form.selected }">\
<i class="fi-{{ iconClass }}"></i>\
</span>\
'
};
});
| 'use strict';
angular.module('arethusa.morph').directive('formSelector', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var id = scope.id;
function action(event) {
event.stopPropagation();
scope.$apply(function() {
if (scope.form.selected) {
scope.plugin.unsetState(id);
} else {
scope.plugin.setState(id, scope.form);
}
});
}
scope.$watch('form.selected', function(newVal, oldVal) {
scope.text = newVal ? 'D' : 'S';
});
element.bind('click', action);
},
template: '\
<span\
class="button micro radius"\
ng-class="{ success: form.selected }">\
{{ text }}\
</span>\
'
};
});
|
Add type field to edit channel perms request | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request.channel;
import co.phoenixlab.discord.api.entities.guild.DiscordPermissionSet;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class EditChannelPermissionsRequest {
public enum Type {
MEMBER,
ROLE
}
private DiscordPermissionSet allow;
private DiscordPermissionSet deny;
private Type type;
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request.channel;
import co.phoenixlab.discord.api.entities.guild.DiscordPermissionSet;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class EditChannelPermissionsRequest {
private DiscordPermissionSet allow;
private DiscordPermissionSet deny;
}
|
Increment version to 0.0.6 for release | <?php
define("BEYONIC_CLIENT_VERSION", "0.0.6");
if (!function_exists('curl_init')) {
throw new Exception('Beyonic requires the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Beyonic requires the JSON PHP extension.');
}
// Beyonic Primary Interface
require_once(dirname(__FILE__) . '/Beyonic/Beyonic.php');
// Beyonic API endpoints
require_once(dirname(__FILE__) . '/Beyonic/Endpoint_Wrapper.php');
require_once(dirname(__FILE__) . '/Beyonic/Webhook.php');
require_once(dirname(__FILE__) . '/Beyonic/Payment.php');
require_once(dirname(__FILE__) . '/Beyonic/Collection.php');
require_once(dirname(__FILE__) . '/Beyonic/Collection_Request.php');
require_once(dirname(__FILE__) . '/Beyonic/Contact.php');
require_once(dirname(__FILE__) . '/Beyonic/Account.php');
require_once(dirname(__FILE__) . '/Beyonic/Transaction.php');
require_once(dirname(__FILE__) . '/Beyonic/Beyonic_Exception.php');
| <?php
define("BEYONIC_CLIENT_VERSION", "0.0.5");
if (!function_exists('curl_init')) {
throw new Exception('Beyonic requires the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Beyonic requires the JSON PHP extension.');
}
// Beyonic Primary Interface
require_once(dirname(__FILE__) . '/Beyonic/Beyonic.php');
// Beyonic API endpoints
require_once(dirname(__FILE__) . '/Beyonic/Endpoint_Wrapper.php');
require_once(dirname(__FILE__) . '/Beyonic/Webhook.php');
require_once(dirname(__FILE__) . '/Beyonic/Payment.php');
require_once(dirname(__FILE__) . '/Beyonic/Collection.php');
require_once(dirname(__FILE__) . '/Beyonic/Collection_Request.php');
require_once(dirname(__FILE__) . '/Beyonic/Contact.php');
require_once(dirname(__FILE__) . '/Beyonic/Account.php');
require_once(dirname(__FILE__) . '/Beyonic/Transaction.php');
require_once(dirname(__FILE__) . '/Beyonic/Beyonic_Exception.php');
|
Check undefined with _.isUndefined in DropdownOverlayView | var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
/*
* Dropdown overlay to disable all interactions between elements
* beneath the dropdown
*/
module.exports = CoreView.extend({
className: 'CDB-Box-modalOverlay',
events: {
'click': '_onOverlayClicked'
},
initialize: function (opts) {
this.container = opts && opts.container;
this.onClickAction = opts && opts.onClickAction;
this.model = new Backbone.Model({
visible: _.isUndefined(opts && opts.visible) ? true : opts.visible
});
this._initBinds();
this.render();
},
_initBinds: function () {
this.listenTo(this.model, 'change:visible', this._onVisibilityChange);
},
render: function () {
(this.container || $(document.body)).append(this.$el);
this.$el.toggle(this.isVisible());
return this;
},
_onOverlayClicked: function () {
this.onClickAction && this.onClickAction();
this.hide();
},
show: function () {
this.model.set('visible', true);
},
hide: function () {
this.model.set('visible', false);
},
toggle: function () {
this.model.set('visible', !this.model.get('visible'));
},
isVisible: function () {
return this.model.get('visible');
},
_onVisibilityChange: function () {
this.$el.toggle(this.isVisible());
}
});
| var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
/*
* Dropdown overlay to disable all interactions between elements
* beneath the dropdown
*/
module.exports = CoreView.extend({
className: 'CDB-Box-modalOverlay',
events: {
'click': '_onOverlayClicked'
},
initialize: function (opts) {
this.container = opts && opts.container;
this.onClickAction = opts && opts.onClickAction;
this.model = new Backbone.Model({
visible: opts && typeof opts.visible !== 'undefined' ? opts.visible : true
});
this._initBinds();
this.render();
},
_initBinds: function () {
this.listenTo(this.model, 'change:visible', this._onVisibilityChange);
},
render: function () {
(this.container || $(document.body)).append(this.$el);
this.$el.toggle(this.isVisible());
return this;
},
_onOverlayClicked: function () {
this.onClickAction && this.onClickAction();
this.hide();
},
show: function () {
this.model.set('visible', true);
},
hide: function () {
this.model.set('visible', false);
},
toggle: function () {
this.model.set('visible', !this.model.get('visible'));
},
isVisible: function () {
return this.model.get('visible');
},
_onVisibilityChange: function () {
this.$el.toggle(this.isVisible());
}
});
|
Make tests pass on v0.8
Can't pass file open flags to writeFileSync in 0.8.
Close #79 | var fs = require('fs')
var mkdirp = require('mkdirp')
module.exports = function () {
fill(4, 10, 2, __dirname + '/target')
}
if (module === require.main) {
require('tap').pass('yes')
return
}
function fill (depth, files, folders, target) {
mkdirp.sync(target)
var o = { flag: 'wx' }
if (process.version.match(/^v0\.8/))
o = 'utf8'
for (var f = files; f > 0; f--) {
fs.writeFileSync(target + '/f-' + depth + '-' + f, '', o)
}
// valid symlink
fs.symlinkSync('f-' + depth + '-1', target + '/link-' + depth + '-good', 'file')
// invalid symlink
fs.symlinkSync('does-not-exist', target + '/link-' + depth + '-bad', 'file')
// file with a name that looks like a glob
fs.writeFileSync(target + '/[a-z0-9].txt', '', o)
depth--
if (depth <= 0)
return
for (f = folders; f > 0; f--) {
mkdirp.sync(target + '/folder-' + depth + '-' + f)
fill(depth, files, folders, target + '/d-' + depth + '-' + f)
}
}
| var fs = require('fs')
var mkdirp = require('mkdirp')
module.exports = function () {
fill(4, 10, 2, __dirname + '/target')
}
if (module === require.main) {
require('tap').pass('yes')
return
}
function fill (depth, files, folders, target) {
mkdirp.sync(target)
var o = { flag: 'wx' }
for (var f = files; f > 0; f--) {
fs.writeFileSync(target + '/f-' + depth + '-' + f, '', o)
}
// valid symlink
fs.symlinkSync('f-' + depth + '-1', target + '/link-' + depth + '-good', 'file')
// invalid symlink
fs.symlinkSync('does-not-exist', target + '/link-' + depth + '-bad', 'file')
// file with a name that looks like a glob
fs.writeFileSync(target + '/[a-z0-9].txt', '', o)
depth--
if (depth <= 0)
return
for (f = folders; f > 0; f--) {
mkdirp.sync(target + '/folder-' + depth + '-' + f)
fill(depth, files, folders, target + '/d-' + depth + '-' + f)
}
}
|
Fix typo with class name |
package fr.neamar.kiss;
import fr.neamar.R;
import android.support.test.rule.ActivityTestRule;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.action.ViewActions.typeText;
@LargeTest
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void testActivityShouldHaveText() {
onView(withId(R.id.searchEditText)).perform(typeText("Test"));
onView(withId(R.id.searchEditText)).check(matches(withText("Test")));
}
} |
package fr.neamar.kiss;
import fr.neamar.R;
import android.support.test.rule.ActivityTestRule;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.action.ViewActions.typeText;
@LargeTest
public class DeckardEspressoTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void testActivityShouldHaveText() {
onView(withId(R.id.searchEditText)).perform(typeText("Test"));
onView(withId(R.id.searchEditText)).check(matches(withText("Test")));
}
} |
Add dynamic changable brainfuck arraylength | package dk.dtu.brainfuckcomp;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
if (args.length == 0) {
System.out.println("Length of Brainfuck array not specified. Defaulting to 8.");
n = 8;
} else {
n = Integer.parseInt(args[0]);
}
Brainfuck bf = new Brainfuck(n);
Scanner sc = new Scanner(System.in);
System.out.println("Enter Brainfuck (Leave blank for \"Hello World!\"):");
String str = sc.nextLine();
if (str.equals("")) {
str = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
}
sc.close();
try {
bf.parse(str);
} catch (UnknownSymbolExeption e) {
e.printStackTrace();
}
System.out.println(bf.toString());
}
}
| package dk.dtu.brainfuckcomp;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Brainfuck bf = new Brainfuck(7);
String str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Brainfuck (Leave blank for \"Hello World!\"):");
str = sc.nextLine();
if (str.equals("")) {
str = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
}
sc.close();
try {
bf.parse(str);
} catch (UnknownSymbolExeption e) {
e.printStackTrace();
}
System.out.println(bf.toString());
}
}
|
Revert explicit type in unrelated test class | <?php
namespace Doctrine\Tests\Common\Proxy;
use BadMethodCallException;
/**
* Test asset class
*/
class MagicSetClassWithScalarTypeAndRenamedParameters
{
/** @var string */
public $id = 'id';
/** @var string */
public $publicField = 'publicField';
/** @var string|null */
public $testAttribute;
/**
* @param string $n
* @param mixed $val
*
* @throws BadMethodCallException
*/
public function __set($n, $val)
{
if ($n === 'test') {
$this->testAttribute = $val;
}
if ($n === 'publicField' || $n === 'id') {
throw new BadMethodCallException('Should never be called for "publicField" or "id"');
}
$this->testAttribute = $val;
}
}
| <?php
namespace Doctrine\Tests\Common\Proxy;
use BadMethodCallException;
/**
* Test asset class
*/
class MagicSetClassWithScalarTypeAndRenamedParameters
{
/** @var string */
public $id = 'id';
/** @var string */
public $publicField = 'publicField';
/** @var string|null */
public $testAttribute;
/**
* @param string $n
* @param mixed $val
*
* @throws BadMethodCallException
*/
public function __set(string $n, $val)
{
if ($n === 'test') {
$this->testAttribute = $val;
}
if ($n === 'publicField' || $n === 'id') {
throw new BadMethodCallException('Should never be called for "publicField" or "id"');
}
$this->testAttribute = $val;
}
}
|
Make getting back to dashboard instantaneous
By using an updated version of store.filter with forceReload turned on
for accounts, we can avoid waiting for any load when a user navigates
away from the dashboard and then returns. A query to refresh data will
be still send in the background, but the promise will resolve
immediately.
This commit also removes a limit on repos so we get the default from the
API. | import Ember from 'ember';
import TravisRoute from 'travis/routes/basic';
export default TravisRoute.extend({
queryParams: {
filter: {
replace: true
},
offset: {
refreshModel: true
}
},
redirect() {
if (!this.get('features.dashboard')) {
return this.transitionTo('index');
}
},
model(params) {
return Ember.RSVP.hash({
starredRepos: this.store.filter('repo', {
active: true,
sort_by: 'current_build:desc',
starred: true
}, (repo) => repo.get('starred'), ['starred'], true),
repos: this.store.paginated('repo', {
active: true,
sort_by: 'current_build:desc',
offset: params.offset
}, {
filter: (repo) => repo.get('active') && repo.get('isCurrentUserACollaborator'),
sort: 'currentBuildId:desc',
dependencies: ['active', 'isCurrentUserACollaborator'],
forceReload: true
}),
accounts: this.store.filter('account', {
all: true
}, () => true, [], true)
});
}
});
| import Ember from 'ember';
import TravisRoute from 'travis/routes/basic';
export default TravisRoute.extend({
queryParams: {
filter: {
replace: true
},
offset: {
refreshModel: true
}
},
redirect() {
if (!this.get('features.dashboard')) {
return this.transitionTo('index');
}
},
model(params) {
return Ember.RSVP.hash({
starredRepos: this.store.filter('repo', {
active: true,
sort_by: 'current_build:desc',
starred: true
}, (repo) => repo.get('starred'), ['starred']),
repos: this.store.paginated('repo', {
active: true,
sort_by: 'current_build:desc',
offset: params.offset,
limit: 10
}, {
filter: (repo) => repo.get('active') && repo.get('isCurrentUserACollaborator'),
sort: 'currentBuildId:desc',
dependencies: ['active', 'isCurrentUserACollaborator'],
forceReload: true
}),
accounts: this.store.query('account', {
all: true
})
});
}
});
|
:+1: Change initial state value to prevent fire didMount 2-times | // @flow
import * as React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import AppFooter from './App/AppFooter'
import AppHeader from './App/AppHeader'
import type { ReducersStateT } from '../ducks'
import * as SessionAction from '../ducks/session'
import type { SessionT } from '../ducks/session'
const App = ({
children,
session
}: {
children: React.Node,
session: ?SessionT
}) => (
<div>
<AppHeader session={session} />
{children}
<AppFooter />
</div>
)
export default App
export const AppContainer = withRouter(
connect<_, _, *, _, *, _>(({ session }: ReducersStateT) => ({
session
}))(
class $App extends React.Component<*, { isLoading: boolean }> {
state = { isLoading: true }
async componentDidMount() {
const { dispatch } = this.props
this.setState({ isLoading: true })
dispatch(await SessionAction.getCurrentUser())
this.setState({ isLoading: false })
}
render() {
return this.state.isLoading ? (
<div>Loading...</div>
) : (
<App {...this.props} />
)
}
}
)
)
| // @flow
import * as React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import AppFooter from './App/AppFooter'
import AppHeader from './App/AppHeader'
import type { ReducersStateT } from '../ducks'
import * as SessionAction from '../ducks/session'
import type { SessionT } from '../ducks/session'
const App = ({
children,
session
}: {
children: React.Node,
session: ?SessionT
}) => (
<div>
<AppHeader session={session} />
{children}
<AppFooter />
</div>
)
export default App
export const AppContainer = withRouter(
connect<_, _, *, _, *, _>(({ session }: ReducersStateT) => ({
session
}))(
class $App extends React.Component<*, { isLoading: boolean }> {
state = { isLoading: false }
async componentDidMount() {
const { dispatch } = this.props
this.setState({ isLoading: true })
dispatch(await SessionAction.getCurrentUser())
this.setState({ isLoading: false })
}
render() {
return this.state.isLoading ? (
<div>Loading...</div>
) : (
<App {...this.props} />
)
}
}
)
)
|
Create and clean the test root directory when starting test cases | 'use strict';
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const root = path.join(__dirname, '../temp');
function filePath(p) {
return path.join(root, p);
}
const helper = {
createFile(p, initialContent) {
fs.writeFileSync(filePath(p), initialContent);
},
makeDirectory(p) {
try {
fs.mkdirSync(filePath(p));
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
},
path(p) {
return path.join(root, p);
},
createRootDirectory() {
try {
fs.mkdirSync(root);
} catch (e) {
// do nothing
}
},
clean() {
rimraf.sync(path.join(root, '*'));
},
previewRegExp(pathname) {
let basename = path.basename(pathname);
let regexStr = `^<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${basename}<\/title><style>(.|\n)*<\/style><\/head><body><div id="app"><\/div><script>(.|\n)*<\/script><\/body><\/html>$`;
return new RegExp(regexStr);
}
};
helper.createRootDirectory();
helper.clean();
module.exports = helper;
| 'use strict';
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const root = path.join(__dirname, '../temp');
function filePath(p) {
return path.join(root, p);
}
try {
fs.mkdirSync(root);
} catch (e) {
// do nothing
}
module.exports = {
createFile(p, initialContent) {
fs.writeFileSync(filePath(p), initialContent);
},
makeDirectory(p) {
fs.mkdirSync(filePath(p));
},
path(p) {
return path.join(root, p);
},
clean() {
rimraf.sync(path.join(root, '*'));
},
previewRegExp(pathname) {
let basename = path.basename(pathname);
let regexStr = `^<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${basename}<\/title><style>(.|\n)*<\/style><\/head><body><div id="app"><\/div><script>(.|\n)*<\/script><\/body><\/html>$`;
return new RegExp(regexStr);
}
};
|
Adjust signature of test class fully | <?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load(string $pathAndFilename, bool $allowSplitSource = false): array
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
| <?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load($pathAndFilename, $allowSplitSource = false): array
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
|
Reduce initial size of Stack | package main
import (
"bytes"
)
// Stack is a stack of matrices
type Stack struct {
stack []*Matrix
}
// NewStack returns a new stack
func NewStack() *Stack {
return &Stack{
stack: make([]*Matrix, 0, 10),
}
}
// Pop returns and removes the top matrix in the stack
func (s *Stack) Pop() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
ret := s.stack[length-1]
s.stack = s.stack[:length-1]
return ret
}
// Push pushes a new matrix onto the stack
func (s *Stack) Push(m *Matrix) {
s.stack = append(s.stack, m)
}
// Peek returns the top matrix in the stack
func (s *Stack) Peek() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
return s.stack[length-1]
}
// IsEmpty returns true if the stack is empty, false otherwise
func (s *Stack) IsEmpty() bool {
return len(s.stack) == 0
}
func (s *Stack) String() string {
var buffer bytes.Buffer
length := len(s.stack)
for i := length - 1; i >= 0; i-- {
buffer.WriteString(s.stack[i].String())
}
return buffer.String()
}
| package main
import (
"bytes"
)
// Stack is a stack of matrices
type Stack struct {
stack []*Matrix
}
// NewStack returns a new stack
func NewStack() *Stack {
return &Stack{
stack: make([]*Matrix, 0, 100),
}
}
// Pop returns and removes the top matrix in the stack
func (s *Stack) Pop() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
ret := s.stack[length-1]
s.stack = s.stack[:length-1]
return ret
}
// Push pushes a new matrix onto the stack
func (s *Stack) Push(m *Matrix) {
s.stack = append(s.stack, m)
}
// Peek returns the top matrix in the stack
func (s *Stack) Peek() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
return s.stack[length-1]
}
// IsEmpty returns true if the stack is empty, false otherwise
func (s *Stack) IsEmpty() bool {
return len(s.stack) == 0
}
func (s *Stack) String() string {
var buffer bytes.Buffer
length := len(s.stack)
for i := length - 1; i >= 0; i-- {
buffer.WriteString(s.stack[i].String())
}
return buffer.String()
}
|
Implement localization and fix existing localization to match changes | /* This file is part of RentalRooms for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.bukkit.rental;
import com.jcwhatever.bukkit.generic.language.Localized;
public class Lang {
private Lang() {}
@Localized
public static String get(String text, Object... params) {
return RentalRooms.getInstance().getLanguageManager().get(text, params);
}
}
| /* This file is part of RentalRooms for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.bukkit.rental;
import com.jcwhatever.bukkit.generic.language.LanguageManager;
import com.jcwhatever.bukkit.generic.language.Localized;
public class Lang {
private Lang() {}
private static LanguageManager _languageManager = new LanguageManager();
@Localized
public static String get(String text, Object... params) {
return _languageManager.get(RentalRooms.getInstance(), text, params);
}
}
|
Fix `assert_called` usage for Python 3.5 build
The `assert_called` method seems to invoke a bug caused by a type in the
unittest mock module. (The bug was ultimately tracked and fix here:
https://bugs.python.org/issue24656) | # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.headers["key"] = "value"
# Verify
assert uplink_builder_mock.add_hook.called
assert sess.headers == {"key": "value"}
def test_params(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.params["key"] = "value"
# Verify
assert uplink_builder_mock.add_hook.called
assert sess.params == {"key": "value"}
def test_auth(uplink_builder_mock):
# Setup
uplink_builder_mock.auth = ("username", "password")
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.auth == sess.auth
def test_auth_set(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.auth = ("username", "password")
# Verify
assert ("username", "password") == uplink_builder_mock.auth
| # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.headers["key"] = "value"
# Verify
assert uplink_builder_mock.add_hook.called
assert sess.headers == {"key": "value"}
def test_params(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.params["key"] = "value"
# Verify
uplink_builder_mock.add_hook.assert_called()
assert sess.params == {"key": "value"}
def test_auth(uplink_builder_mock):
# Setup
uplink_builder_mock.auth = ("username", "password")
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.auth == sess.auth
def test_auth_set(uplink_builder_mock):
# Setup
sess = session.Session(uplink_builder_mock)
# Run
sess.auth = ("username", "password")
# Verify
assert ("username", "password") == uplink_builder_mock.auth
|
Remove failing test on Windows | import path from 'path';
import test from 'ava';
import clintonRuleTester from './fixtures/rule-tester';
const opts = {
cwd: 'test/fixtures/editorconfig',
rules: {
editorconfig: 'error'
}
};
const ruleTester = clintonRuleTester(opts);
test('no editorconfig', async t => {
await ruleTester(t, 'false',
[
{
ruleId: 'editorconfig',
severity: 'error',
message: 'Use `.editorconfig` to define and maintain consistent coding styles between editors',
file: path.resolve(opts.cwd, 'false/.editorconfig')
}
]
);
});
test('editorconfig', async t => {
await ruleTester(t, 'true', []);
});
test('do not validate binary files', async t => {
await ruleTester(t, 'binary', []);
});
if (process.platform !== 'win32') {
// TODO https://github.com/SamVerschueren/clinton/issues/80
test('invalid editorconfig', async t => {
await ruleTester(t, 'invalid',
[
{
ruleId: 'editorconfig',
severity: 'error',
message: 'Unexpected spaces found at line 2',
file: path.resolve(opts.cwd, 'invalid/package.json')
}
]
);
});
}
| import path from 'path';
import test from 'ava';
import clintonRuleTester from './fixtures/rule-tester';
const opts = {
cwd: 'test/fixtures/editorconfig',
rules: {
editorconfig: 'error'
}
};
const ruleTester = clintonRuleTester(opts);
test('no editorconfig', async t => {
await ruleTester(t, 'false',
[
{
ruleId: 'editorconfig',
severity: 'error',
message: 'Use `.editorconfig` to define and maintain consistent coding styles between editors',
file: path.resolve(opts.cwd, 'false/.editorconfig')
}
]
);
});
test('editorconfig', async t => {
await ruleTester(t, 'true', []);
});
test('do not validate binary files', async t => {
await ruleTester(t, 'binary', []);
});
test('invalid editorconfig', async t => {
await ruleTester(t, 'invalid',
[
{
ruleId: 'editorconfig',
severity: 'error',
message: 'Unexpected spaces found at line 2',
file: path.resolve(opts.cwd, 'invalid/package.json')
}
]
);
});
|
Support mysql2: prefixed database url's | from os import getenv, \
path
from time import time
from datetime import timedelta
class Config(object):
AWS_ACCESS_KEY_ID = getenv('AWS_ACCESS_KEY_ID')
AWS_REGION = getenv('AWS_REGION')
AWS_S3_BUCKET = getenv('AWS_S3_BUCKET')
AWS_SECRET_ACCESS_KEY = getenv('AWS_SECRET_ACCESS_KEY')
CACHE_BUSTER = int(path.getmtime(__file__))
GOOGLE_ANALYTICS_ID = getenv('GOOGLE_ANALYTICS_ID', False)
MAX_UPLOAD_SIZE = getenv('MAX_UPLOAD_SIZE')
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
REMEMBER_COOKIE_DURATION = timedelta(days=30)
SECRET_KEY = getenv('SECRET_KEY')
SITE_NAME = getenv('SITE_NAME', 'Aflutter')
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL').replace('mysql2:', 'mysql:')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', False)
FILES_PROTECTED = getenv('FILES_PROTECTED', False)
class ProductionConfig(Config):
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
CACHE_BUSTER = int(time())
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + path.dirname(__file__) + '/app/app.db'
class TestingConfig(Config):
TESTING = True
| from os import getenv, \
path
from time import time
from datetime import timedelta
class Config(object):
AWS_ACCESS_KEY_ID = getenv('AWS_ACCESS_KEY_ID')
AWS_REGION = getenv('AWS_REGION')
AWS_S3_BUCKET = getenv('AWS_S3_BUCKET')
AWS_SECRET_ACCESS_KEY = getenv('AWS_SECRET_ACCESS_KEY')
CACHE_BUSTER = int(path.getmtime(__file__))
GOOGLE_ANALYTICS_ID = getenv('GOOGLE_ANALYTICS_ID', False)
MAX_UPLOAD_SIZE = getenv('MAX_UPLOAD_SIZE')
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
REMEMBER_COOKIE_DURATION = timedelta(days=30)
SECRET_KEY = getenv('SECRET_KEY')
SITE_NAME = getenv('SITE_NAME', 'Aflutter')
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', False)
FILES_PROTECTED = getenv('FILES_PROTECTED', False)
class ProductionConfig(Config):
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
CACHE_BUSTER = int(time())
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + path.dirname(__file__) + '/app/app.db'
class TestingConfig(Config):
TESTING = True
|
Replace LDAP displayName only enum with Database | /*
* oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.model;
import java.util.HashMap;
import java.util.Map;
import org.gluu.persist.annotation.AttributeEnum;
/**
* Specify type of script location
*
* @author Yuriy Movchan Date: 10/07/2015
*/
public enum ScriptLocationType implements AttributeEnum {
LDAP("ldap", "Database"), FILE("file", "File");
private String value;
private String displayName;
private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>();
static {
for (ScriptLocationType enumType : values()) {
MAP_BY_VALUES.put(enumType.getValue(), enumType);
}
}
ScriptLocationType(String value, String displayName) {
this.value = value;
this.displayName = displayName;
}
public String getValue() {
return value;
}
public String getDisplayName() {
return displayName;
}
public static ScriptLocationType getByValue(String value) {
return MAP_BY_VALUES.get(value);
}
public Enum<? extends AttributeEnum> resolveByValue(String value) {
return getByValue(value);
}
@Override
public String toString() {
return value;
}
}
| /*
* oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.model;
import java.util.HashMap;
import java.util.Map;
import org.gluu.persist.annotation.AttributeEnum;
/**
* Specify type of script location
*
* @author Yuriy Movchan Date: 10/07/2015
*/
public enum ScriptLocationType implements AttributeEnum {
DB("db", "Database"), FILE("file", "File");
private String value;
private String displayName;
private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>();
static {
for (ScriptLocationType enumType : values()) {
MAP_BY_VALUES.put(enumType.getValue(), enumType);
}
}
ScriptLocationType(String value, String displayName) {
this.value = value;
this.displayName = displayName;
}
public String getValue() {
return value;
}
public String getDisplayName() {
return displayName;
}
public static ScriptLocationType getByValue(String value) {
return MAP_BY_VALUES.get(value);
}
public Enum<? extends AttributeEnum> resolveByValue(String value) {
return getByValue(value);
}
@Override
public String toString() {
return value;
}
}
|
Add some data into the request context.
Better handling of missing Schema objects when logging in (should we raise an error?). | """
Middleware to automatically set the schema (namespace).
if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that.
Otherwise, set the schema to the one associated with the logged in user.
"""
from django.core.exceptions import ObjectDoesNotExist
from models import Schema
class SchemaMiddleware:
def process_request(self, request):
if request.user.is_anonymous():
return None
if request.user.is_superuser:
if '__schema' in request.GET:
request.session['schema'] = request.GET['__schema']
if 'schema' in request.session:
Schema.objects.get(pk=request.session['schema']).activate()
else:
try:
request.user.schema.schema.activate()
except ObjectDoesNotExist:
pass
def process_template_response(self, request, response):
if request.user.is_superuser:
response.context_data['schemata'] = Schema.objects.all()
response.context_data['selected_schema'] = request.session['schema']
return response | """
Middleware to automatically set the schema (namespace).
if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that.
Otherwise, set the schema to the one associated with the logged in user.
"""
from models import Schema
class SchemaMiddleware:
def process_request(self, request):
if request.user.is_anonymous():
return None
if request.user.is_superuser and '__schema' in request.GET:
request.session['schema'] = request.GET['__schema']
if request.user.is_superuser and 'schema' in request.session:
Schema.objects.get(pk=request.session['schema']).activate()
else:
request.user.schema.schema.activate()
def process_response(self, request):
pass |
Remove unnessacary check and format | package stream.flarebot.flarebot.commands.secret;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import stream.flarebot.flarebot.commands.Command;
import stream.flarebot.flarebot.commands.CommandType;
import stream.flarebot.flarebot.objects.GuildWrapper;
import java.io.File;
public class LogsCommand implements Command {
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
channel.sendFile(new File("latest.log"), new MessageBuilder().append('\u200B').build()).queue();
}
@Override
public String getCommand() {
return "logs";
}
@Override
public String getDescription() {
return "Gets the logs";
}
@Override
public String getUsage() {
return "{%}logs";
}
@Override
public CommandType getType() {
return CommandType.SECRET;
}
@Override
public boolean isDefaultPermission() {
return false;
}
}
| package stream.flarebot.flarebot.commands.secret;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import stream.flarebot.flarebot.commands.Command;
import stream.flarebot.flarebot.commands.CommandType;
import stream.flarebot.flarebot.objects.GuildWrapper;
import java.io.File;
public class LogsCommand implements Command {
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
if (getPermissions(channel).isCreator(sender)) {
channel.sendFile(new File("latest.log"), new MessageBuilder().append('\u200B').build()).queue();
}
}
@Override
public String getCommand() {
return "logs";
}
@Override
public String getDescription() {
return "Gets the logs";
}
@Override
public String getUsage() {
return "{%}logs";
}
@Override
public CommandType getType() {
return CommandType.SECRET;
}
@Override
public boolean isDefaultPermission() {
return false;
}
}
|
Add access log for logserver container | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
addDefaultSearchAccessLog();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
| // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
|
Change parameter type to match psr15 interface | <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected $middleware;
/**
* @var Message\ResponseInterface
*/
protected $response;
/**
* MiddlewareDelegate constructor.
*
* @param ServerMiddlewareInterface[] $middleware Middleware of the frame
*/
public function __construct(array $middleware, Message\ResponseInterface $response = null)
{
$this->middleware = $middleware;
$this->response = $response;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\ServerRequestInterface $request): Message\ResponseInterface
{
if ($this->middleware !== []) {
$middleware = array_shift($this->middleware);
return $middleware->process($request, $this);
}
return $this->response;
}
}
| <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected $middleware;
/**
* @var Message\ResponseInterface
*/
protected $response;
/**
* MiddlewareDelegate constructor.
*
* @param ServerMiddlewareInterface[] $middleware Middleware of the frame
*/
public function __construct(array $middleware, Message\ResponseInterface $response = null)
{
$this->middleware = $middleware;
$this->response = $response;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\RequestInterface $request): Message\ResponseInterface
{
if ($this->middleware !== []) {
$middleware = array_shift($this->middleware);
return $middleware->process($request, $this);
}
return $this->response;
}
}
|
Change treff home to the journal home | <?php
session_start();
if (isset($_SESSION['userId']) && $_SESSION['userId'] != 0) {
header("Location: " . $_POST["redirectUrl"]);
}
include_once 'functions.php';
createHeader(array("style.css"), array("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js#sthash.J5zZTqH1.dpuf", "validate.js"));
echo '
<div class="main_body">
<div class="login">
<div class="create">
<a href="login.php">Make a Journal Entry</a>
</div>
<div class="join">
<a href="search_treff.php">Look at Your Past</a>
</div>
</div> <!--// End of login -->
</div><!--// End of main_body -->';
include 'footer.php';
| <?php
session_start();
include_once 'functions.php';
createHeader(array("style.css"), array());
?>
<div class="main_body">
<div class="info">
<h1>Need a half-way meeting point?</h1>
<p>
Treff is a service for creating meeting points for people.<br /><br />
Treff will ask for your location and the phone numbers or emails of the people
you would like to meet up with. Then it will find a meeting point and automatically
send out personalized directions to everyone.
</p>
</div>
<div class="login">
<div class="create">
<a href="create1.php">Create a Treff</a>
</div>
<div class="join">
<a href="search_treff.php">Join a Treff</a>
</div>
</div> <!--// End of login -->
</div> <!--// End of main_body -->
<?php include 'footer.php'; ?>
|
Use os.sep for splitting directories
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com> | import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split(os.sep):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
| import os
from git import *
from django.conf import settings
def get_repos():
repos = [get_repo(dir) for dir in os.listdir(settings.REPOS_ROOT)]
return [r for r in repos if not (r is None)]
def get_repo(name):
repo_path = os.path.join(settings.REPOS_ROOT, name)
if os.path.isdir(repo_path):
try:
return Repo(repo_path)
except Exception:
pass
return None
def get_commit(name, commit):
repo = get_repo(name)
commit = repo.commit(commit)
return commit
def get_blob(repo, commit, file):
repo = get_repo(repo)
commit = repo.commit(commit)
tree = commit.tree
for path_seg in file.split('/'):
t = tree.get(path_seg)
if isinstance(t, Tree):
tree = t
else:
blob = t
return blob
|
Raise exception is EMAIL_RECIPIENT not set | from contextlib import contextmanager
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from settings import Settings
@contextmanager
def smtp_server():
s = smtplib.SMTP(Settings.SMTP_HOST, Settings.SMTP_PORT)
s.starttls()
s.login(Settings.SMTP_USERNAME, Settings.SMTP_PASSWORD)
yield s
s.quit()
def send_email(s, sender, msg_subject, html_content):
if Settings.EMAIL_RECIPIENT is None:
raise Exception('EMAIL_RECIPIENT env variable must be set')
recipients = [Settings.EMAIL_RECIPIENT]
msg = MIMEMultipart()
msg['Subject'] = msg_subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
part_html = MIMEText(html_content, 'html', 'utf-8')
msg.attach(part_html)
try:
if not Settings.DRY_RUN:
s.sendmail(msg['From'], recipients, msg.as_string())
logging.info('sent email to "%s" about "%s"' % (recipients, msg_subject))
except Exception as e:
logging.error('An error occurred while sending email: %s - %s' % (e.__class__, e))
logging.debug(u'email:\n%s' % html_content)
raise
| from contextlib import contextmanager
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from settings import Settings
@contextmanager
def smtp_server():
s = smtplib.SMTP(Settings.SMTP_HOST, Settings.SMTP_PORT)
s.starttls()
s.login(Settings.SMTP_USERNAME, Settings.SMTP_PASSWORD)
yield s
s.quit()
def send_email(s, sender, msg_subject, html_content):
msg = MIMEMultipart()
recipients = [Settings.EMAIL_RECIPIENT]
msg['Subject'] = msg_subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
part_html = MIMEText(html_content, 'html', 'utf-8')
msg.attach(part_html)
try:
if not Settings.DRY_RUN:
s.sendmail(msg['From'], recipients, msg.as_string())
logging.info('sent email to "%s" about "%s"' % (recipients, msg_subject))
except Exception as e:
logging.error('An error occurred while sending email: %s - %s' % (e.__class__, e))
logging.debug(u'email:\n%s' % html_content)
raise
|
Fix configured paths for partials | var path = require("path");
// Export function to create new config (builder is passed in from outside)
module.exports = function(builder) {
var bootstrapLess = require.resolve("bootstrap/less/bootstrap.less");
return builder.merge({
template: require.resolve("./handlebars/template.hbs"),
partials: path.resolve(__dirname,"handlebars"),
helpers: require("./src/handlebars-helper.js"),
less: {
main: [
bootstrapLess,
require.resolve("./less/main.less")
],
paths: [
path.dirname(bootstrapLess)
]
},
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function(obj) { return obj; }
})
};
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require("./package");
| var path = require("path");
// Export function to create new config (builder is passed in from outside)
module.exports = function(builder) {
var bootstrapLess = require.resolve("bootstrap/less/bootstrap.less");
return builder.merge({
template: require.resolve("./template/template.hbs"),
partials: path.resolve(__dirname,"template"),
helpers: require("./src/handlebars-helper.js"),
less: {
main: [
bootstrapLess,
require.resolve("./less/main.less")
],
paths: [
path.dirname(bootstrapLess)
]
},
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function(obj) { return obj; }
})
};
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require("./package");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.