text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove inefficient boxing of int.
// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.testsystems.fit; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class SocketDealer { private Map<Integer, SocketSeeker> waitingList = new HashMap<Integer, SocketSeeker>(17); private int ticketCounter = 1; public int seekingSocket(SocketSeeker seeker) { int ticket = ticketCounter++; waitingList.put(ticket, seeker); return ticket; } public Collection<SocketSeeker> getWaitingList() { return waitingList.values(); } public void dealSocketTo(int ticket, SocketDoner doner) throws Exception { SocketSeeker seeker = waitingList.get(ticket); seeker.acceptSocketFrom(doner); waitingList.remove(ticket); } public boolean isWaiting(int ticket) { return waitingList.containsKey(ticket); } }
// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.testsystems.fit; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class SocketDealer { private Map<Integer, SocketSeeker> waitingList = new HashMap<Integer, SocketSeeker>(17); private int ticketCounter = 1; public int seekingSocket(SocketSeeker seeker) { int ticket = ticketCounter++; waitingList.put(new Integer(ticket), seeker); return ticket; } public Collection<SocketSeeker> getWaitingList() { return waitingList.values(); } public void dealSocketTo(int ticket, SocketDoner doner) throws Exception { Integer key = new Integer(ticket); SocketSeeker seeker = waitingList.get(key); seeker.acceptSocketFrom(doner); waitingList.remove(key); } public boolean isWaiting(int ticket) { return waitingList.containsKey(new Integer(ticket)); } }
Adjust login width on xl screens
@extends('layouts.base') @section('body') <div class="flex items-center justify-center my-8 md:my-20"> <div class="w-full md:w-1/2 lg:w-1/3 xl:w-1/4"> <h1 class="text-4xl text-gray-700 text-center mb-2 font-bold">{{ $title }}</h1> <div class="p-8 md:border-2 md:rounded md:bg-gray-100"> @include('layouts._alerts') @yield('small-content') @yield('small-content-after') </div> </div> </div> @endsection
@extends('layouts.base') @section('body') <div class="flex items-center justify-center my-8 md:my-20"> <div class="w-full md:w-1/2 lg:w-1/3"> <h1 class="text-4xl text-gray-700 text-center mb-2 font-bold">{{ $title }}</h1> <div class="p-8 md:border-2 md:rounded md:bg-gray-100"> @include('layouts._alerts') @yield('small-content') @yield('small-content-after') </div> </div> </div> @endsection
Fix text typo in javadoc
/* * Copyright (C) 2015 Index Data * * 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 okapi.bean; /** * Tells how a module is to be deployed. Either by exec'ing a command (and * killing the process afterwards), or by using command lines to start and * stop it. */ public class ProcessDeploymentDescriptor { private String cmdlineStart; private String cmdlineStop; private String exec; public ProcessDeploymentDescriptor() { } public String getCmdlineStart() { return cmdlineStart; } public void setCmdlineStart(String cmdlineStart) { this.cmdlineStart = cmdlineStart; } public String getCmdlineStop() { return cmdlineStop; } public void setCmdlineStop(String cmdlineStop) { this.cmdlineStop = cmdlineStop; } public String getExec() { return exec; } public void setExec(String exec) { this.exec = exec; } }
/* * Copyright (C) 2015 Index Data * * 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 okapi.bean; /** * Tells how a module is to be deployed. Either my exec'ing a command (and * killing the process afterwards), or by using command lines to start and * stop it. */ public class ProcessDeploymentDescriptor { private String cmdlineStart; private String cmdlineStop; private String exec; public ProcessDeploymentDescriptor() { } public String getCmdlineStart() { return cmdlineStart; } public void setCmdlineStart(String cmdlineStart) { this.cmdlineStart = cmdlineStart; } public String getCmdlineStop() { return cmdlineStop; } public void setCmdlineStop(String cmdlineStop) { this.cmdlineStop = cmdlineStop; } public String getExec() { return exec; } public void setExec(String exec) { this.exec = exec; } }
Update the default language for the media generator
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create('it_IT') for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
Fix use of AWS library
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. See the AUTHORS file // for names of contributors. // // Author: Marc Berhault (marc@cockroachlabs.com) package amazon import "github.com/awslabs/aws-sdk-go/aws" // LoadAWSCredentials loads the credentials using the AWS api. This automatically // loads from ENV, or from the .aws/credentials file. // Returns the key-id and secret-key. func LoadAWSCredentials() (string, string, error) { creds, err := aws.DefaultChainCredentials.Get() if err != nil { return "", "", err } return creds.AccessKeyID, creds.SecretAccessKey, nil }
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. See the AUTHORS file // for names of contributors. // // Author: Marc Berhault (marc@cockroachlabs.com) package amazon import "github.com/awslabs/aws-sdk-go/aws" // LoadAWSCredentials loads the credentials using the AWS api. This automatically // loads from ENV, or from the .aws/credentials file. // Returns the key-id and secret-key. func LoadAWSCredentials() (string, string, error) { creds, err := aws.DefaultCreds().Credentials() if err != nil { return "", "", err } return creds.AccessKeyID, creds.SecretAccessKey, nil }
Add order by to individual capacity query
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id, fromDate, toDate) { return knex('workload_points_calculations') .join('workload', 'workload_points_calculations.workload_id', '=', 'workload.id') .join('workload_report', 'workload_points_calculations.workload_report_id', '=', 'workload_report.id') .where('workload_report.effective_from', '>=', fromDate) .where('workload_report.effective_from', '<=', toDate) .where('workload.workload_owner_id', id) .select('workload_report.effective_from', 'workload_points_calculations.total_points', 'workload_points_calculations.sdr_points', 'workload_points_calculations.sdr_conversion_points', 'workload_points_calculations.paroms_points', 'workload_points_calculations.available_points', 'workload_points_calculations.reduction_hours') .orderBy('workload_report.effective_from') .then(function (workloadReports) { return workloadReports }) }
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id, fromDate, toDate) { return knex('workload_points_calculations') .join('workload', 'workload_points_calculations.workload_id', '=', 'workload.id') .join('workload_report', 'workload_points_calculations.workload_report_id', '=', 'workload_report.id') .where('workload_report.effective_from', '>=', fromDate) .where('workload_report.effective_from', '<=', toDate) .where('workload.workload_owner_id', id) .select('workload_report.effective_from', 'workload_points_calculations.total_points', 'workload_points_calculations.sdr_points', 'workload_points_calculations.sdr_conversion_points', 'workload_points_calculations.paroms_points', 'workload_points_calculations.available_points', 'workload_points_calculations.reduction_hours') .then(function (workloadReports) { return workloadReports }) }
Add debug code to test login post
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): # idNumber = IntField() # serialNumber = CharField() # typeCategory = CharField() # description = TextField() # issues = TextField() # photo = CharField() # quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': #session['username'] = request.form['username'] return "success"#redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): # idNumber = IntField() # serialNumber = CharField() # typeCategory = CharField() # description = TextField() # issues = TextField() # photo = CharField() # quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
Revise docstring and add space line
"""Leetcode 461. Hamming Distance Medium URL: https://leetcode.com/problems/hamming-distance/description/ The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 โ‰ค x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) โ†‘ โ†‘ The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int Time complexity: O(1). Space complexity: O(1). """ return bin(x ^ y).count('1') def main(): print Solution().hammingDistance(1, 4) if __name__ == '__main__': main()
"""Leetcode 461. Hamming Distance Medium URL: https://leetcode.com/problems/hamming-distance/description/ The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 โ‰ค x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) โ†‘ โ†‘ The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int Time complexity: O(1). Space complexity: O(1). """ return bin(x ^ y).count('1') def main(): print Solution().hammingDistance(1, 4) if __name__ == '__main__': main()
Add reorder data type exports
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class Address extends Realm.Object {} export { Item } from './Item'; export { ItemBatch } from './ItemBatch'; export class ItemDepartment extends Realm.Object {} export class ItemCategory extends Realm.Object {} export { ItemStoreJoin } from './ItemStoreJoin'; export { Transaction } from './Transaction'; export class TransactionCategory extends Realm.Object {} export { TransactionItem } from './TransactionItem'; export { TransactionBatch } from './TransactionBatch'; export { MasterList } from './MasterList'; export { MasterListItem } from './MasterListItem'; export { MasterListNameJoin } from './MasterListNameJoin'; export { Name } from './Name'; export { NameStoreJoin } from './NameStoreJoin'; export { NumberSequence } from './NumberSequence'; export { NumberToReuse } from './NumberToReuse'; export { Options } from './Options'; export { Period } from './Period'; export { PeriodSchedule } from './PeriodSchedule'; export { Requisition } from './Requisition'; export { RequisitionItem } from './RequisitionItem'; export class Setting extends Realm.Object {} export class SyncOut extends Realm.Object {} export { Stocktake } from './Stocktake'; export { StocktakeItem } from './StocktakeItem'; export { StocktakeBatch } from './StocktakeBatch'; export class User extends Realm.Object {}
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class Address extends Realm.Object {} export { Item } from './Item'; export { ItemBatch } from './ItemBatch'; export class ItemDepartment extends Realm.Object {} export class ItemCategory extends Realm.Object {} export { ItemStoreJoin } from './ItemStoreJoin'; export { Transaction } from './Transaction'; export class TransactionCategory extends Realm.Object {} export { TransactionItem } from './TransactionItem'; export { TransactionBatch } from './TransactionBatch'; export { MasterList } from './MasterList'; export { MasterListItem } from './MasterListItem'; export { MasterListNameJoin } from './MasterListNameJoin'; export { Name } from './Name'; export { NameStoreJoin } from './NameStoreJoin'; export { NumberSequence } from './NumberSequence'; export { NumberToReuse } from './NumberToReuse'; export { Requisition } from './Requisition'; export { RequisitionItem } from './RequisitionItem'; export class Setting extends Realm.Object {} export class SyncOut extends Realm.Object {} export { Stocktake } from './Stocktake'; export { StocktakeItem } from './StocktakeItem'; export { StocktakeBatch } from './StocktakeBatch'; export { Period } from './Period'; export { PeriodSchedule } from './PeriodSchedule'; export { Options } from './Options'; export class User extends Realm.Object {}
Add better error handling for non-200 responses
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
Use @ResponseBody to write exception message.
package org.talend.dataprep.exception; import java.io.StringWriter; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class TDPExceptionController { public static final Logger LOGGER = LoggerFactory.getLogger(TDPExceptionController.class); @ExceptionHandler(InternalException.class) public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); final StringWriter message = new StringWriter(); e.writeTo(message); return message.toString(); } @ExceptionHandler(UserException.class) public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final StringWriter message = new StringWriter(); e.writeTo(message); return message.toString(); } }
package org.talend.dataprep.exception; import java.io.StringWriter; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class TDPExceptionController { private static HttpEntity<String> buildHttpEntity(TDPException e) { StringWriter writer = new StringWriter(); e.writeTo(writer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(writer.toString(), headers); } @ExceptionHandler(InternalException.class) public HttpEntity<String> handleInternalError(HttpServletResponse response, InternalException e) { HttpEntity<String> entity = buildHttpEntity(e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return entity; } @ExceptionHandler(UserException.class) public HttpEntity<String> handleUserError(HttpServletResponse response, UserException e) { HttpEntity<String> entity = buildHttpEntity(e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return entity; } }
Use new invocations pytest helper
from invoke import task, Collection from invocations.packaging import release from invocations import pytest as pytests @task def coverage(c, html=True): """ Run coverage with coverage.py. """ # NOTE: this MUST use coverage itself, and not pytest-cov, because the # latter is apparently unable to prevent pytest plugins from being loaded # before pytest-cov itself is able to start up coverage.py! The result is # that coverage _always_ skips over all module level code, i.e. constants, # 'def' lines, etc. Running coverage as the "outer" layer avoids this # problem, thus no need for pytest-cov. # NOTE: this does NOT hold true for NON-PYTEST code, so # pytest-relaxed-USING modules can happily use pytest-cov. c.run("coverage run --source=pytest_relaxed -m pytest") if html: c.run("coverage html") c.run("open htmlcov/index.html") ns = Collection( coverage, pytests.test, packaging=release, )
from invoke import task, Collection from invocations.packaging import release # TODO: once this stuff is stable and I start switching my other projects to be # pytest-oriented, move this into invocations somehow. @task def test(c): """ Run verbose pytests. """ c.run("pytest --verbose --color=yes") @task def coverage(c, html=True): """ Run coverage with coverage.py. """ # NOTE: this MUST use coverage itself, and not pytest-cov, because the # latter is apparently unable to prevent pytest plugins from being loaded # before pytest-cov itself is able to start up coverage.py! The result is # that coverage _always_ skips over all module level code, i.e. constants, # 'def' lines, etc. Running coverage as the "outer" layer avoids this # problem, thus no need for pytest-cov. # NOTE: this does NOT hold true for NON-PYTEST code, so # pytest-relaxed-USING modules can happily use pytest-cov. c.run("coverage run --source=pytest_relaxed -m pytest") if html: c.run("coverage html") c.run("open htmlcov/index.html") ns = Collection( coverage, test, packaging=release, ) ns.configure({ })
Add Py 2 and Py 3 classifiers
from setuptools import setup, find_packages setup( name='dataset', version='0.3.14', description="Toolkit for Python-based data processing.", long_description="", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3' ], keywords='sql sqlalchemy etl loading utility', author='Friedrich Lindenberg, Gregor Aisch', author_email='info@okfn.org', url='http://github.com/pudo/dataset', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=[], include_package_data=False, zip_safe=False, install_requires=[ 'sqlalchemy >= 0.8.1', 'alembic >= 0.6.1', "argparse >= 1.2.1", 'python-slugify >= 0.0.6', "PyYAML >= 3.10" ], tests_require=[], entry_points={ 'console_scripts': [ 'datafreeze = dataset.freeze.app:main', ] } )
from setuptools import setup, find_packages setup( name='dataset', version='0.3.14', description="Toolkit for Python-based data processing.", long_description="", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", ], keywords='sql sqlalchemy etl loading utility', author='Friedrich Lindenberg, Gregor Aisch', author_email='info@okfn.org', url='http://github.com/pudo/dataset', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=[], include_package_data=False, zip_safe=False, install_requires=[ 'sqlalchemy >= 0.8.1', 'alembic >= 0.6.1', "argparse >= 1.2.1", 'python-slugify >= 0.0.6', "PyYAML >= 3.10" ], tests_require=[], entry_points={ 'console_scripts': [ 'datafreeze = dataset.freeze.app:main', ] } )
Fix index for title without geo abr
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### # create new unique index to include geometry_application_ref op.execute("DROP INDEX title_abr_idx") op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (case when (record->'data'->>'geometry_application_reference') IS NULL then 'NULL' else (record->'data'->>'geometry_application_reference') end))") ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.execute("DROP INDEX title_abr_geo_idx") op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))") ### end Alembic commands ###
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### # create new unique index to include geometry_application_ref op.execute("DROP INDEX title_abr_idx") op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (record->'data'->>'geometry_application_reference'))") ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.execute("DROP INDEX title_abr_geo_idx") op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))") ### end Alembic commands ###
Change the left and right subtree when recurring findLCA
// Copyright (c) 2015, Peter Mrekaj. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE.txt file. package btrees // findLCA walks the binary tree t and returns lowest common // ancestor for the nodes n0 and n1. The cnt is 0, 1, or 2 // depending on nodes (n0, n1) presented in the tree. func findLCA(t, n0, n1 *BTree) (cnt int, ancestor *BTree) { if t == nil { return 0, nil // Base case. } // Postorder walk. lc, la := findLCA(t.left, n0, n1) if lc == 2 { return lc, la } rc, ra := findLCA(t.right, n0, n1) if rc == 2 { return rc, ra } cnt = lc + rc if t == n0 { cnt++ } if t == n1 { cnt++ } if cnt == 2 { ancestor = t } return cnt, ancestor } // LCA returns the lowest common ancestor in // the binary tree t for the nodes n0, n1. func LCA(t, n0, n1 *BTree) *BTree { _, a := findLCA(t, n0, n1) return a }
// Copyright (c) 2015, Peter Mrekaj. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE.txt file. package btrees // findLCA walks the binary tree t and returns lowest common // ancestor for the nodes n0 and n1. The cnt is 0, 1, or 2 // depending on nodes (n0, n1) presented in the tree. func findLCA(t, n0, n1 *BTree) (cnt int, ancestor *BTree) { if t == nil { return 0, nil // Base case. } // Postorder walk. lc, la := findLCA(t.right, n0, n1) if lc == 2 { return lc, la } rc, ra := findLCA(t.left, n0, n1) if rc == 2 { return rc, ra } cnt = lc + rc if t == n0 { cnt++ } if t == n1 { cnt++ } if cnt == 2 { ancestor = t } return cnt, ancestor } // LCA returns the lowest common ancestor in // the binary tree t for the nodes n0, n1. func LCA(t, n0, n1 *BTree) *BTree { _, a := findLCA(t, n0, n1) return a }
Use sqlalchemy reflection in migration 080 Change-Id: If2a0e59461d108d59c6e9907d3db053ba2b44f57
# Copyright 2012 OpenStack, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from sqlalchemy import Column, MetaData, String, Table def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine compute_nodes = Table("compute_nodes", meta, autoload=True) hypervisor_hostname = Column("hypervisor_hostname", String(255)) compute_nodes.create_column(hypervisor_hostname) def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine compute_nodes = Table("compute_nodes", meta, autoload=True) compute_nodes.drop_column('hypervisor_hostname')
# Copyright 2012 OpenStack, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from sqlalchemy import * meta = MetaData() compute_nodes = Table("compute_nodes", meta, Column("id", Integer(), primary_key=True, nullable=False)) hypervisor_hostname = Column("hypervisor_hostname", String(255)) def upgrade(migrate_engine): meta.bind = migrate_engine compute_nodes.create_column(hypervisor_hostname) def downgrade(migrate_engine): meta.bind = migrate_engine compute_nodes.drop_column(hypervisor_hostname)
Set page title for editor
#encoding: utf-8 """Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web from ..base.handlers import IPythonHandler, path_regex from ..utils import url_escape class EditorHandler(IPythonHandler): """Render the text editor interface.""" @web.authenticated def get(self, path): path = path.strip('/') if not self.contents_manager.file_exists(path): raise web.HTTPError(404, u'File does not exist: %s' % path) self.write(self.render_template('texteditor.html', file_path=url_escape(path), page_title=path.rsplit('/', 1)[-1] + " (editing)", ) ) default_handlers = [ (r"/texteditor%s" % path_regex, EditorHandler), ]
#encoding: utf-8 """Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web from ..base.handlers import IPythonHandler, path_regex from ..utils import url_escape class EditorHandler(IPythonHandler): """Render the text editor interface.""" @web.authenticated def get(self, path): path = path.strip('/') if not self.contents_manager.file_exists(path): raise web.HTTPError(404, u'File does not exist: %s' % path) self.write(self.render_template('texteditor.html', file_path=url_escape(path), ) ) default_handlers = [ (r"/texteditor%s" % path_regex, EditorHandler), ]
Add button for PlayDates view
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Navigator, TouchableHighlight } from 'react-native'; import MapScene from "./MapScene"; import PlayDates from "./PlayDates"; class TestPage extends Component { componentDidMount(){ this.props.navigator.pop(); } makeButtonLink(text, component) { return ( <TouchableHighlight style={styles.button} onPress={() => this.props.navigator.push({ component: component, }) } > <Text>{text}</Text> </TouchableHighlight> ); } render() { return ( <View style={styles.container}> <Text>This is a test page</Text> {this.makeButtonLink("MapScene", MapScene)} {this.makeButtonLink("PlayDates", PlayDates)} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, button: { borderWidth: 2, borderRadius: 12, padding: 10, backgroundColor: 'antiquewhite' }, }); module.exports = TestPage;
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Navigator, TouchableHighlight } from 'react-native'; import MapScene from "./MapScene"; class TestPage extends Component { componentDidMount(){ this.props.navigator.pop(); } render() { return ( <View> <Text>This is a test page</Text> <TouchableHighlight onPress={() => this.props.navigator.push({ component: MapScene, }) }> <Text>Hola</Text> </TouchableHighlight> </View> ); } } module.exports = TestPage;
Use the id of the channel and unquote all of the text first.
from flask import Flask, request import requests from urllib import unquote app = Flask(__name__) @app.route("/") def meme(): domain = request.args["team_domain"] slackbot = request.args["slackbot"] text = request.args["text"] channel = request.args["channel_id"] text = unquote(text) text = text[:-1] if text[-1] == ";" else text params = text.split(";") params = [x.strip().replace(" ", "-") for x in params] if not len(params) == 3: response = "Your syntax should be in the form: /meme template; top; bottom;" else: template = params[0] top = params[1] bottom = params[2] response = "http://memegen.link/{0}/{1}/{2}.jpg".format(template, top, bottom) url = "https://{0}.slack.com/services/hooks/slackbot?token={1}&channel={2}".format(domain, slackbot, channel) requests.post(url, data=response) return "ok", 200
from flask import Flask, request import requests from urllib import unquote app = Flask(__name__) @app.route("/") def meme(): domain = request.args["team_domain"] slackbot = request.args["slackbot"] text = request.args["text"] channel = request.args["channel_name"] text = text[:-1] if text[-1] == ";" else text params = text.split(";") params = [x.strip().replace(" ", "-") for x in params] params = [unquote(x) for x in params] if not len(params) == 3: response = "Your syntax should be in the form: /meme template; top; bottom;" else: template = params[0] top = params[1] bottom = params[2] response = "http://memegen.link/{0}/{1}/{2}.jpg".format(template, top, bottom) url = "https://{0}.slack.com/services/hooks/slackbot?token={1}&channel=%23{2}".format(domain, slackbot, channel) requests.post(url, data=response) return "ok", 200
Add correct room_history_entry in UserFactory
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
Update description. Module needs testing.
# -*- coding: utf-8 -*- """ File Name: Description: s2s sets up sending files to servers via public SSH keys. Author: S. Hutchins Date Created: Tue Apr 11 12:31:17 2017 Project Name: Orthologs Project """ #import os #import logging as log #import pandas as pd #from datetime import datetime as d ##import zipfile #import pexpect import subprocess #------------------------------------------------------------------------------ class S2S(object): """S2S (Send 2 Server) is designed for use with a public ssh key.""" def __init__(username, server_address): address = server_address user = username sendto = user + "@" + address + ":" return sendto def scpto(self, file, destpath): cmd = "scp " + file + " " + self.sendto + destpath status = subprocess.call([cmd], shell=True) if status == 0: # Command was successful. print("%s file sent." % file) pass # Continue else: # Unsuccessful. Stdout will be '1'. print("%s file not sent." % file)
# -*- coding: utf-8 -*- """ File Name: Description: s2s sets up sending files to servers via public SSH keys. Author: S. Hutchins Date Created: Tue Apr 11 12:31:17 2017 Project Name: Orthologs Project """ #import os #import logging as log #import pandas as pd #from datetime import datetime as d ##import zipfile #import pexpect import subprocess #------------------------------------------------------------------------------ class S2S(object): """S2S (Send 2 Server)""" def __init__(username, server_address): address = server_address user = username sendto = user + "@" + address + ":" return sendto def scpto(self, file, destpath): cmd = "scp " + file + " " + self.sendto + destpath status = subprocess.call([cmd], shell=True) if status == 0: # Command was successful. print("%s file sent." % file) pass # Continue else: # Unsuccessful. Stdout will be '1'. print("%s file not sent." % file)
Change to address instead of port
// Copyright 2013 Landon Wainwright. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Starts up the blog system using the default values package main import ( "flag" "github.com/landonia/simplegoblog/blog" "log" "os" ) // Starts a new simple go blog server func main() { // Define flags var postsdir, templatesdir, assetsdir, address string flag.StringVar(&postsdir, "pdir", "../posts", "the directory for storing the posts") flag.StringVar(&templatesdir, "tdir", "../templates", "the directory containing the templates") flag.StringVar(&assetsdir, "adir", "../assets", "the directory containing the assets") flag.StringVar(&address, "address", ":8080", "the host:port to run the blog on") flag.Parse() // Create a new configuration containing the info config := &blog.Configuration{Title: "Life thru a Lando", DevelopmentMode: true, Postsdir: postsdir, Templatesdir: templatesdir, Assetsdir: assetsdir} // Create a new data structure for storing the data b := blog.New(config) // Start the blog server err := b.Start(address) if err != nil { log.Println(err) os.Exit(1) } }
// Copyright 2013 Landon Wainwright. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Starts up the blog system using the default values package main import ( "flag" "github.com/landonia/simplegoblog/blog" "log" "os" ) // Starts a new simple go blog server func main() { // Define flags var postsdir, templatesdir, assetsdir, port string flag.StringVar(&postsdir, "pdir", "../posts", "the directory for storing the posts") flag.StringVar(&templatesdir, "tdir", "../templates", "the directory containing the templates") flag.StringVar(&assetsdir, "adir", "../assets", "the directory containing the assets") flag.StringVar(&port, "port", "8080", "the port to run the blog on") flag.Parse() // Create a new configuration containing the info config := &blog.Configuration{Title: "Life thru a Lando", DevelopmentMode: true, Postsdir: postsdir, Templatesdir: templatesdir, Assetsdir: assetsdir} // Create a new data structure for storing the data b := blog.New(config) // Start the blog server err := b.Start(port) if err != nil { log.Println(err) os.Exit(1) } }
Fix wrong ascii character in comments of base service
from sqlalchemy.exc import StatementError from zou.app.utils import events def get_instance(model, instance_id, exception): """ Get instance of any model from its ID and raise given exception if not found. """ if instance_id is None: raise exception() try: instance = model.get(instance_id) except StatementError: raise exception() if instance is None: raise exception() return instance def get_or_create_instance_by_name(model, **kwargs): """ Get instance of any model by name. If it doesn't exist it creates a new instance of this model from positional arguments dict. """ instance = model.get_by(name=kwargs["name"]) if instance is None: instance = model.create(**kwargs) events.emit("%s:new" % model.__tablename__, { "%s_id" % model.__tablename__: instance.id }) return instance.serialize() def get_model_map_from_array(models): """ Return a map matching based on given model list. The maps keys are the model IDs and the values are the models. It's convenient to check find a model by its ID. """ return {model["id"]: model for model in models}
from sqlalchemy.exc import StatementError from zou.app.utils import events def get_instance(model, instance_id, exception): """ Get instance of any model from its ID and raise given exception if not found. """ if instance_id is None: raise exception() try: instance = model.get(instance_id) except StatementError: raise exception() if instance is None: raise exception() return instance def get_or_create_instance_by_name(model, **kwargs): """ Get instance of any model by name. If it doesn't exist it creates a new instance of this model from positional arguments dict. """ instance = model.get_by(name=kwargs["name"]) if instance is None: instance = model.create(**kwargs) events.emit("%s:new" % model.__tablename__, { "%s_id" % model.__tablename__: instance.id }) return instance.serialize() def get_model_map_from_array(models): """ Return a map matching based on given model list. The maps keys are the model IDs and the values are the models.ย It's convenient to check find a model by its ID. """ return {model["id"]: model for model in models}
Fix indentation on comments block
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _s * @since _s 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content .site-content --> </div><!-- #primary .content-area --> <?php get_sidebar(); ?> <?php get_footer(); ?>
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _s * @since _s 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content .site-content --> </div><!-- #primary .content-area --> <?php get_sidebar(); ?> <?php get_footer(); ?>
chore(parser-getter-setter): Remove hello from the karma output
var fs = require('fs'); var sys = require('sys'); var exec = require('child_process').exec; var generateParser = function(logger) { var log = logger.create('generate-parser'); return function(content, file, done) { log.info('Generating parser for parser test: %s', file.originalPath); fs.readFile(file.originalPath, function(err, data) { if (err) throw err; exec( 'dart --checked bin/parser_generator_for_spec.dart getter-setter', function(err, stdout, stderr) { if (err) throw err; done(data + '\n\n' + stdout); }); }); } } module.exports = generateParser;
var fs = require('fs'); var sys = require('sys'); var exec = require('child_process').exec; var generateParser = function(logger) { var log = logger.create('generate-parser'); log.info('hello'); return function(content, file, done) { log.info('Generating parser for parser test: %s', file.originalPath); fs.readFile(file.originalPath, function(err, data) { if (err) throw err; exec( 'dart --checked bin/parser_generator_for_spec.dart getter-setter', function(err, stdout, stderr) { if (err) throw err; done(data + '\n\n' + stdout); }); }); } } module.exports = generateParser;
Revert "No bug - Add more debugging information" This reverts commit 0d149d368a52e4ca44a8b38ba4a80a9e40cf3ea7.
function renderError( err, res ) { res.format({ "text/html": function() { res.render( 'error.html', err ); }, "application/json": function() { res.json( { status: err.status, message: err.message } ); }, "default": function() { res.send( err.message ); } }); } module.exports.errorHandler = function(err, req, res, next) { if (!err.status) { err.status = 500; } res.status(err.status); renderError(err, res); }; module.exports.pageNotFoundHandler = function(req, res, next) { var err = { message: req.gettext("You found a loose thread!"), status: 404 }; res.status(err.status); renderError(err, res); };
Error.stackTraceLimit = Infinity; function renderError( err, res ) { res.format({ "text/html": function() { res.render( 'error.html', err ); }, "application/json": function() { res.json( { status: err.status, message: err.message } ); }, "default": function() { res.send( err.message ); } }); } module.exports.errorHandler = function(err, req, res, next) { console.log(err); if (!err.status) { err.status = 500; } res.status(err.status); renderError(err, res); }; module.exports.pageNotFoundHandler = function(req, res, next) { var err = { message: req.gettext("You found a loose thread!"), status: 404 }; res.status(err.status); renderError(err, res); };
Update extension stub with new APIs
<?php namespace {{namespace}}; use Flarum\Support\ServiceProvider; use Flarum\Extend; class {{classPrefix}}ServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->extend([ (new Extend\Locale('en'))->translations(__DIR__.'/../locale/en.yml'), (new Extend\ForumClient()) ->assets([ __DIR__.'/../js/dist/extension.js', __DIR__.'/../less/extension.less' ]) ->translations([ // Add the keys of translations you would like to be available // for use by the JS client application. ]) ]); } /** * Register the service provider. * * @return void */ public function register() { // } }
<?php namespace {{namespace}}; use Flarum\Support\ServiceProvider; use Flarum\Extend\ForumAssets; use Flarum\Extend\Locale; use Flarum\Extend\ForumTranslations; class {{classPrefix}}ServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->extend( new ForumAssets([ __DIR__.'/../js/dist/extension.js', __DIR__.'/../less/extension.less' ]), (new Locale('en'))->translations(__DIR__.'/../locale/en.yml'), new ForumTranslations([ // Add the keys of translations you would like to be available // for use by the JS client application. ]), ); } /** * Register the service provider. * * @return void */ public function register() { // } }
Allow HTML/React elements in message content More information about PropTypes.node here: https://facebook.github.io/react/docs/typechecking-with-proptypes.html ATM passing HTML/React produces validation error in console. Regardless that everything seems working smoothly.
import React from 'react'; const Notif = ({ kind, componentClassName, actionLabel, onActionClick, id, message }) => { const handleActionClick = (ev) => { ev.preventDefault(); if (!onActionClick) { return; } onActionClick(id); }; return ( <div className={`${componentClassName} ${componentClassName}--${kind}`}> <div className={`${componentClassName}__icon`} /> <div className={`${componentClassName}__content`}> <span className={`${componentClassName}__message`}>{message}</span> </div> {actionLabel && <span className={`${componentClassName}__action`}> <button onClick={handleActionClick}>{actionLabel}</button> </span> } <div className={`${componentClassName}__close`} /> </div> ); }; Notif.defaultProps = { kind: 'info', }; Notif.propTypes = { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]).isRequired, message: React.PropTypes.node.isRequired, kind: React.PropTypes.oneOf([ 'success', 'info', 'warning', 'danger', ]).isRequired, componentClassName: React.PropTypes.string, onActionClick: React.PropTypes.func, actionLabel: React.PropTypes.string, }; export default Notif;
import React from 'react'; const Notif = ({ kind, componentClassName, actionLabel, onActionClick, id, message }) => { const handleActionClick = (ev) => { ev.preventDefault(); if (!onActionClick) { return; } onActionClick(id); }; return ( <div className={`${componentClassName} ${componentClassName}--${kind}`}> <div className={`${componentClassName}__icon`} /> <div className={`${componentClassName}__content`}> <span className={`${componentClassName}__message`}>{message}</span> </div> {actionLabel && <span className={`${componentClassName}__action`}> <button onClick={handleActionClick}>{actionLabel}</button> </span> } <div className={`${componentClassName}__close`} /> </div> ); }; Notif.defaultProps = { kind: 'info', }; Notif.propTypes = { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]).isRequired, message: React.PropTypes.string.isRequired, kind: React.PropTypes.oneOf([ 'success', 'info', 'warning', 'danger', ]).isRequired, componentClassName: React.PropTypes.string, onActionClick: React.PropTypes.func, actionLabel: React.PropTypes.string, }; export default Notif;
Add version and distinguish linter error from faulty witness.
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP
Remove fmt import since no more use, need to add git hooks :-/
package crypto import ( "testing" "github.com/stretchr/testify/assert" ) func TestEncrypt(t *testing.T) { authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71") expected := map[string]interface{}{"entity": "something2"} res, _ := Encrypt(expected, authKey, authKey) r, _ := Decrypt(res, authKey, authKey) assert.Equal(t, expected, r) } func TestDecrypt(t *testing.T) { authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71") input := "WmtlMxl4d_VTfUYnl-A0Uycpr2e3VswKDwoPd03XtoY=.JZMk6FZloYh5BL0K7dHGSyTqB4lTgd9annrFEgLTELnxR3bHweL2" expected := map[string]interface{}{"entity": "something2"} r, _ := Decrypt(input, authKey, authKey) assert.Equal(t, expected, r) }
package crypto import ( "testing" "fmt" "github.com/stretchr/testify/assert" ) func TestEncrypt(t *testing.T) { authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71") expected := map[string]interface{}{"entity": "something2"} res, _ := Encrypt(expected, authKey, authKey) r, _ := Decrypt(res, authKey, authKey) assert.Equal(t, expected, r) } func TestDecrypt(t *testing.T) { authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71") input := "WmtlMxl4d_VTfUYnl-A0Uycpr2e3VswKDwoPd03XtoY=.JZMk6FZloYh5BL0K7dHGSyTqB4lTgd9annrFEgLTELnxR3bHweL2" expected := map[string]interface{}{"entity": "something2"} r, _ := Decrypt(input, authKey, authKey) assert.Equal(t, expected, r) }
Fix HTML5 Video plugin JSHint errors
/* * CSS Modal Plugin for HTML5 Video (play/pause) * Author: Anselm Hannemann * Date: 2014-02-04 */ (function (global) { 'use strict'; var CSSModal = global.CSSModal; var videos; // If CSS Modal is still undefined, throw an error if (!CSSModal) { throw new Error('Error: CSSModal is not loaded.'); } // Enables Auto-Play when calling modal CSSModal.on('cssmodal:show', document, function () { // Fetch all video elements in active modal videos = CSSModal.activeElement.querySelectorAll('video'); // Play first video in modal if (videos.length > 0) { videos[0].play(); } }); // If modal is closed, pause all videos CSSModal.on('cssmodal:hide', document, function () { var i = 0; // Pause all videos in active modal if (videos.length > 0) { for (; i < videos.length; i++) { videos[i].pause(); } } }); }(window));
/* * CSS Modal Plugin for HTML5 Video (play/pause) * Author: Anselm Hannemann * Date: 2014-02-04 */ (function (global) { 'use strict'; var CSSModal = global.CSSModal; // If CSS Modal is still undefined, throw an error if (!CSSModal) { throw new Error('Error: CSSModal is not loaded.'); } var videos; // Enables Auto-Play when calling modal CSSModal.on('cssmodal:show', document, function (event) { // Fetch all video elements in active modal videos = CSSModal.activeElement.querySelectorAll('video'); if (videos.length > 0) { // Play first video in modal videos[0].play(); } }); // If modal is closed, pause all videos CSSModal.on('cssmodal:hide', document, function (event) { var i = 0; if (videos.length > 0) { // Pause all videos in active modal for (; i < videos.length; i++) { videos[i].pause(); } } }); }(window));
Remove unused constant for topics While reading the code, I found "L3_AGENT" topic is defined but never be used. Change-Id: I9b6da61f9fe5224d2c25bbe7cc55fd508b4e240f
# Copyright 2015 Cisco Systems, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. FIREWALL = 'FIREWALL' FIREWALL_V2 = 'FIREWALL_V2' # Constants for "topics" FIREWALL_PLUGIN = 'q-firewall-plugin' FW_AGENT = 'firewall_agent' FIREWALL_RULE_LIST = 'firewall_rule_list'
# Copyright 2015 Cisco Systems, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. FIREWALL = 'FIREWALL' FIREWALL_V2 = 'FIREWALL_V2' # Constants for "topics" FIREWALL_PLUGIN = 'q-firewall-plugin' L3_AGENT = 'l3_agent' FW_AGENT = 'firewall_agent' FIREWALL_RULE_LIST = 'firewall_rule_list'
Correct spelling mistake in 'generic_error'
<?php /** * Messages for Registration * * @author Ushahidi Team <team@ushahidi.com> * @package Ushahidi\Application\Messages * @copyright Ushahidi - http://www.ushahidi.com * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License Version 3 (GPLv3) */ return array ( 'crowdmapid' => array( 'email_collision' => 'That email address already has an account registered.', 'username_collision' => 'That username is already in use. Pleae try another.', 'password_collision' => 'You must use your existing CrowdmapID password.', 'generic_error' => 'Please try again later.' ), 'token' => array( 'not_empty' => 'invalid submission', 'Security::check' => 'invalid submission' ) );
<?php /** * Messages for Registration * * @author Ushahidi Team <team@ushahidi.com> * @package Ushahidi\Application\Messages * @copyright Ushahidi - http://www.ushahidi.com * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License Version 3 (GPLv3) */ return array ( 'crowdmapid' => array( 'email_collision' => 'That email address already has an account registered.', 'username_collision' => 'That username is already in use. Pleae try another.', 'password_collision' => 'You must use your existing CrowdmapID password.', 'generic_error' => 'Pleae try again later.' ), 'token' => array( 'not_empty' => 'invalid submission', 'Security::check' => 'invalid submission' ) );
Fix regexp extracting `repositoryId` for GitHub if it contains dot
import { parse as parseUrl } from 'url'; import _ from 'lodash'; const KNOWN_REPOSITORIES = { 'github.com': parsedRepositoryUrl => { const repositoryId = /^(.+?\/.+?)(?:\/|\.git$|$)/.exec(parsedRepositoryUrl.pathname.slice(1))[1]; const rootUrl = `https://github.com/${repositoryId}`; return { repositoryId, fileUrlBuilder: filename => `${rootUrl}/blob/master/${filename}`, releasesPageUrl: `${rootUrl}/releases` }; } }; export function getRepositoryInfo(repositoryUrl) { const parsedUrl = parseUrl(repositoryUrl); const { hostname } = parsedUrl; return _.has(KNOWN_REPOSITORIES, hostname) ? KNOWN_REPOSITORIES[hostname](parsedUrl) : null; }
import { parse as parseUrl } from 'url'; import _ from 'lodash'; const KNOWN_REPOSITORIES = { 'github.com': parsedRepositoryUrl => { const repositoryId = /^(.+?\/.+?)(?:\/|\.|$)/.exec(parsedRepositoryUrl.pathname.slice(1))[1]; const rootUrl = `https://github.com/${repositoryId}`; return { repositoryId, fileUrlBuilder: filename => `${rootUrl}/blob/master/${filename}`, releasesPageUrl: `${rootUrl}/releases` }; } }; export function getRepositoryInfo(repositoryUrl) { const parsedUrl = parseUrl(repositoryUrl); const { hostname } = parsedUrl; return _.has(KNOWN_REPOSITORIES, hostname) ? KNOWN_REPOSITORIES[hostname](parsedUrl) : null; }
Add receent activity to dashboard
#_*_ coding: UTF-8 _*_ from flask import render_template from application import app import db import data_models import views import properties import renderers import funds import projects import grants import pledges import suppliers import supplier_funds import internal_transfers import purchases import users import roles import partners import foreign_transfer import committees audit_fields = [ properties.DateProperty('timestamp'), properties.KeyProperty('entity', title_of=lambda e: e.key.kind()), properties.StringProperty('message'), properties.KeyProperty('user') ] @app.route('/') def home(): model = data_models.Model(None) links = views.view_links(None, ('Committee', 'Show Committees'), ('Supplier', 'Show Suppliers'), ('User', 'Show Users')) audit_list = db.AuditRecord.query().order(-db.AuditRecord.timestamp).iter(limit = 10) sub_heading = renderers.sub_heading('Recent Activity') table = views.view_entity_list(audit_list, audit_fields, selectable=False) content = renderers.render_div(sub_heading, table) return render_template('layout.html', title='DashBoard', user=views.view_user_controls(model), links=links, content=content) projects.add_rules(app) pledges.add_rules(app) supplier_funds.add_rules(app) users.add_rules(app) partners.add_rules(app)
#_*_ coding: UTF-8 _*_ from flask import render_template from application import app import data_models import views import funds import projects import grants import pledges import suppliers import supplier_funds import internal_transfers import purchases import users import roles import partners import foreign_transfer import committees @app.route('/') def home(): model = data_models.Model(None) links = views.view_links(None, ('Committee', 'Show Committees'), ('Supplier', 'Show Suppliers'), ('User', 'Show Users')) return render_template('layout.html', title='DashBoard', user=views.view_user_controls(model), links=links) projects.add_rules(app) pledges.add_rules(app) supplier_funds.add_rules(app) users.add_rules(app) partners.add_rules(app)
Remove cleanup ids - for possibility to use svg gradients
import SVGOptim from 'svgo'; const svgo = new SVGOptim({ plugins: [ 'removeDoctype', 'removeXMLProcInst', 'removeComments', 'removeMetadata', 'removeEditorsNSData', 'cleanupAttrs', 'convertStyleToAttrs', {'cleanupIDs': false}, 'removeRasterImages', 'removeUselessDefs', 'cleanupNumericValues', 'cleanupListOfValues', 'convertColors', 'removeUnknownsAndDefaults', 'removeNonInheritableGroupAttrs', 'removeUselessStrokeAndFill', 'removeViewBox', 'cleanupEnableBackground', 'removeHiddenElems', 'removeEmptyText', 'convertShapeToPath', 'moveElemsAttrsToGroup', 'moveGroupAttrsToElems', 'collapseGroups', 'convertPathData', 'convertTransform', 'removeEmptyAttrs', 'removeEmptyContainers', 'mergePaths', 'removeUnusedNS', 'transformsWithOnePath', 'sortAttrs', 'removeTitle', 'removeDesc', 'removeDimensions', 'addClassesToSVGElement', 'removeStyleElement', { removeAttrs: { attrs: 'class', }, }, ], }); export default svgo;
import SVGOptim from 'svgo'; const svgo = new SVGOptim({ plugins: [ 'removeDoctype', 'removeXMLProcInst', 'removeComments', 'removeMetadata', 'removeEditorsNSData', 'cleanupAttrs', 'convertStyleToAttrs', 'cleanupIDs', 'removeRasterImages', 'removeUselessDefs', 'cleanupNumericValues', 'cleanupListOfValues', 'convertColors', 'removeUnknownsAndDefaults', 'removeNonInheritableGroupAttrs', 'removeUselessStrokeAndFill', 'removeViewBox', 'cleanupEnableBackground', 'removeHiddenElems', 'removeEmptyText', 'convertShapeToPath', 'moveElemsAttrsToGroup', 'moveGroupAttrsToElems', 'collapseGroups', 'convertPathData', 'convertTransform', 'removeEmptyAttrs', 'removeEmptyContainers', 'mergePaths', 'removeUnusedNS', 'transformsWithOnePath', 'sortAttrs', 'removeTitle', 'removeDesc', 'removeDimensions', 'addClassesToSVGElement', 'removeStyleElement', { removeAttrs: { attrs: 'class', }, }, ], }); export default svgo;
Increment version number for release
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.5", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "GNU Lesser General Public License (LGPL), Version 3", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.4", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "GNU Lesser General Public License (LGPL), Version 3", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
Update TwG Base store to reflect owned keys changes.
/** * `modules/thank-with-google` base data store * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Internal dependencies */ import Modules from 'googlesitekit-modules'; import { MODULES_THANK_WITH_GOOGLE } from './constants'; import { submitChanges, validateCanSubmitChanges } from './settings'; export default Modules.createModuleStore( 'thank-with-google', { ownedSettingsSlugs: [ 'publicationID' ], storeName: MODULES_THANK_WITH_GOOGLE, settingSlugs: [ 'publicationID', 'colorTheme', 'buttonPlacement', 'buttonPostTypes', 'ownerID', ], submitChanges, validateCanSubmitChanges, } );
/** * `modules/thank-with-google` base data store * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * Internal dependencies */ import Modules from 'googlesitekit-modules'; import { MODULES_THANK_WITH_GOOGLE } from './constants'; import { submitChanges, validateCanSubmitChanges } from './settings'; export default Modules.createModuleStore( 'thank-with-google', { ownedSettingsSlugs: [ 'publicationID', 'colorTheme', 'buttonPlacement', 'buttonPostTypes', ], storeName: MODULES_THANK_WITH_GOOGLE, settingSlugs: [ 'publicationID', 'colorTheme', 'buttonPlacement', 'buttonPostTypes', ], submitChanges, validateCanSubmitChanges, } );
Check if the result from Bugzilla has an error when trying to get a token
import requests from bug import Bug class BugsyException(Exception): """If trying to do something to a Bug this will be thrown""" def __init__(self, msg): self.msg = msg def __str__(self): return "Message: %s" % self.msg class Bugsy(object): """docstring for Bugsy""" def __init__(self, username=None, password=None, bugzilla_url='https://bugzilla.mozilla.org/rest'): self.username = username self.password = password self.token = None self.bugzilla_url = bugzilla_url if self.username and self.password: result = requests.get(bugzilla_url + '/login?login=%s&password=%s' % (self.username, self.password)).json() if not result.get('error', True): self.token = result['token'] def get(self, bug_number): bug = requests.get(self.bugzilla_url + "/bug/%s" % bug_number).json() return Bug(**bug['bugs'][0]) def put(self, bug): if not self.username or not self.password: raise BugsyException("Unfortunately you can't put bugs in Bugzilla without credentials") if not isinstance(bug, Bug): raise BugsyException("Please pass in a Bug object when posting to Bugzilla")
import requests from bug import Bug class BugsyException(Exception): """If trying to do something to a Bug this will be thrown""" def __init__(self, msg): self.msg = msg def __str__(self): return "Message: %s" % self.msg class Bugsy(object): """docstring for Bugsy""" def __init__(self, username=None, password=None, bugzilla_url='https://bugzilla.mozilla.org/rest'): self.username = username self.password = password self.token = None self.bugzilla_url = bugzilla_url if self.username and self.password: result = requests.get(bugzilla_url + '/login?login=%s&password=%s' % (self.username, self.password)).json() self.token = result['token'] def get(self, bug_number): bug = requests.get(self.bugzilla_url + "/bug/%s" % bug_number).json() return Bug(**bug['bugs'][0]) def put(self, bug): if not self.username or not self.password: raise BugsyException("Unfortunately you can't put bugs in Bugzilla without credentials") if not isinstance(bug, Bug): raise BugsyException("Please pass in a Bug object when posting to Bugzilla")
Fix typo cleanInput => cleanDump
// Requires var Q = require('q'); var _ = require('underscore'); var qClass = require('qpatch').qClass; // Etcd client var Etcd = qClass(require('node-etcd'), ['watcher']); // Since etcd create the dir keys automatically // transform the tree of keys // to contain only a flat array of leaves function cleanDump(obj) { // Is a leaf if(!_.has(obj, 'kvs')) { // We don't want the modifiedIndex attr in our dumps/restores return _.pick(obj, 'key', 'value'); } return _.flatten(_.map(obj.kvs, cleanDump)); } function Dumper(etcd) { // ETCD client this.store = new Etcd(); _.bindAll(this); } // Get a JS object of the DB Dumper.prototype.dump = function() { return this.store.get('', { recusrive: true }) .then(cleanDump); }; // Restore a list of keys Dumper.prototype.restore = function(entries) { var self = this; return Q.all(_.map(entries, function(entry) { return this.store.set(entry.key, entry.value); })); }; // Restore the database from input data function createDumper() { return new Dumper(); } // Exports module.exports = createDumper;
// Requires var Q = require('q'); var _ = require('underscore'); var qClass = require('qpatch').qClass; // Etcd client var Etcd = qClass(require('node-etcd'), ['watcher']); // Since etcd create the dir keys automatically // transform the tree of keys // to contain only a flat array of leaves function cleanDump(obj) { // Is a leaf if(!_.has(obj, 'kvs')) { // We don't want the modifiedIndex attr in our dumps/restores return _.pick(obj, 'key', 'value'); } return _.flatten(_.map(obj.kvs, cleanInput)); } function Dumper(etcd) { // ETCD client this.store = new Etcd(); _.bindAll(this); } // Get a JS object of the DB Dumper.prototype.dump = function() { return this.store.get('', { recusrive: true }) .then(cleanDump); }; // Restore a list of keys Dumper.prototype.restore = function(entries) { var self = this; return Q.all(_.map(entries, function(entry) { return this.store.set(entry.key, entry.value); })); }; // Restore the database from input data function createDumper() { return new Dumper(); } // Exports module.exports = createDumper;
FIX dependency on aeroo rpoert
# -*- coding: utf-8 -*- { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Remove spacing between static and non static variables
package vooga.request.forwarder; import vooga.request.IRequest; /** * An exception capturing when an error occurred during delivery of an request * to a known receiver */ public class DeliveryException extends Exception { private static final long serialVersionUID = 7788838511248429280L; private IRequest myRequest; private String myReason; /** * Create a new delivery exception * * @param request The request that failed to deliver * @param reason The reason the delivery failed */ public DeliveryException(IRequest request, String reason){ super("Delivery of " + request + " failed, because: " + reason); myRequest = request; myReason = reason; } /** * Get the request * * @return The request that failed to deliver */ public IRequest request(){ return myRequest; } /** * Get the reason * * @return The reason the delivery failed */ public String reason(){ return myReason; } }
package vooga.request.forwarder; import vooga.request.IRequest; /** * An exception capturing when an error occurred during delivery of an request * to a known receiver */ public class DeliveryException extends Exception { private static final long serialVersionUID = 7788838511248429280L; private IRequest myRequest; private String myReason; /** * Create a new delivery exception * * @param request The request that failed to deliver * @param reason The reason the delivery failed */ public DeliveryException(IRequest request, String reason){ super("Delivery of " + request + " failed, because: " + reason); myRequest = request; myReason = reason; } /** * Get the request * * @return The request that failed to deliver */ public IRequest request(){ return myRequest; } /** * Get the reason * * @return The reason the delivery failed */ public String reason(){ return myReason; } }
Include Package Data was missing.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'django-helpline-faq', version = '1.1', description = 'A simple FAQ application for Django sites.', long_description = read('README.rst'), license = "BSD", author ='Kevin Fricovsky', author_email = 'kfricovsky@gmail.com', url = 'http://django-fack.rtfd.org/', packages = find_packages(exclude=['example']), include_package_data=True, zip_safe = False, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires = ['Django >= 1.3'], test_suite = "faq._testrunner.runtests", tests_require = ["mock"], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'django-helpline-faq', version = '1.1', description = 'A simple FAQ application for Django sites.', long_description = read('README.rst'), license = "BSD", author ='Kevin Fricovsky', author_email = 'kfricovsky@gmail.com', url = 'http://django-fack.rtfd.org/', packages = find_packages(exclude=['example']), zip_safe = False, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires = ['Django >= 1.3'], test_suite = "faq._testrunner.runtests", tests_require = ["mock"], )
Read the info from stream instead of NIO
package org.utplsql.cli; import org.utplsql.api.JavaApiVersionInfo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; /** This class is getting updated automatically by the build process. * Please do not update its constants manually cause they will be overwritten. * * @author pesse */ public class CliVersionInfo { private static final String MAVEN_PROJECT_NAME = "utPLSL-cli"; private static String MAVEN_PROJECT_VERSION = "unknown"; static { try { try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-cli.version")) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); MAVEN_PROJECT_VERSION = reader.readLine(); reader.close(); } } catch ( IOException e ) { System.out.println("WARNING: Could not get Version information!"); } } public static String getVersion() { return MAVEN_PROJECT_VERSION; } public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); } }
package org.utplsql.cli; import org.utplsql.api.JavaApiVersionInfo; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; /** This class is getting updated automatically by the build process. * Please do not update its constants manually cause they will be overwritten. * * @author pesse */ public class CliVersionInfo { private static final String MAVEN_PROJECT_NAME = "utPLSL-cli"; private static String MAVEN_PROJECT_VERSION = "unknown"; static { try { MAVEN_PROJECT_VERSION = Files.readAllLines( Paths.get(CliVersionInfo.class.getClassLoader().getResource("utplsql-cli.version").toURI()) , Charset.defaultCharset()) .get(0); } catch ( IOException | URISyntaxException e ) { System.out.println("WARNING: Could not get Version information!"); } } public static String getVersion() { return MAVEN_PROJECT_VERSION; } public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); } }
Remove code field from API /auth/test response
# Copyright (C) 2016 University of Zurich. All rights reserved. # # This file is part of MSRegistry Backend. # # MSRegistry Backend is free software: you can redistribute it and/or # modify it under the terms of the version 3 of the GNU Affero General # Public License as published by the Free Software Foundation, or any # other later version. # # MSRegistry Backend is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the version # 3 of the GNU Affero General Public License for more details. # # You should have received a copy of the version 3 of the GNU Affero # General Public License along with MSRegistry Backend. If not, see # <http://www.gnu.org/licenses/>. __author__ = "Filippo Panessa <filippo.panessa@uzh.ch>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
# Copyright (C) 2016 University of Zurich. All rights reserved. # # This file is part of MSRegistry Backend. # # MSRegistry Backend is free software: you can redistribute it and/or # modify it under the terms of the version 3 of the GNU Affero General # Public License as published by the Free Software Foundation, or any # other later version. # # MSRegistry Backend is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the version # 3 of the GNU Affero General Public License for more details. # # You should have received a copy of the version 3 of the GNU Affero # General Public License along with MSRegistry Backend. If not, see # <http://www.gnu.org/licenses/>. __author__ = "Filippo Panessa <filippo.panessa@uzh.ch>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'status': 200, 'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
Add a test for the sector generator in builder mode
import sectorGenerator from '../sector-generator'; import { testSystems } from '../generator-data'; describe('SectorGenerator', () => { let config; beforeEach(() => { config = { columns: 8, rows: 10, seed: 'asdfghjkl', isBuilder: false, }; }); it('should have a randomly generated name', () => { const { name } = sectorGenerator(config); expect(name).toEqual('Edena Omega'); }); it('should pass the seed, rows, and columns through to the result', () => { const testSeed = 'lkjhgfdsa'; const { seed, rows, columns } = sectorGenerator({ ...config, seed: testSeed, }); expect(seed).toEqual(testSeed); expect(rows).toEqual(10); expect(columns).toEqual(8); }); it('should generate a sector full of systems from a seed', () => { const { systems } = sectorGenerator(config); expect(systems).toMatchObject(testSystems); }); it('should generate a sector with no systems if it is initialized in builder mode', () => { const { systems } = sectorGenerator({ ...config, isBuilder: true }); expect(systems).toEqual({}); }); });
import sectorGenerator from '../sector-generator'; import { testSystems } from '../generator-data'; describe('SectorGenerator', () => { let config; beforeEach(() => { config = { columns: 8, rows: 10, seed: 'asdfghjkl', }; }); it('should have a randomly generated name', () => { const { name } = sectorGenerator(config); expect(name).toEqual('Edena Omega'); }); it('should pass the seed, rows, and columns through to the result', () => { const testSeed = 'lkjhgfdsa'; const { seed, rows, columns } = sectorGenerator({ ...config, seed: testSeed, }); expect(seed).toEqual(testSeed); expect(rows).toEqual(10); expect(columns).toEqual(8); }); it('should generate a sector full of systems from a seed', () => { const { systems } = sectorGenerator(config); expect(systems).toMatchObject(testSystems); }); });
Load only the active collections instead of all accessible collections
import logging from flask import Blueprint, request from aleph.model import Collection from aleph.queues import get_active_collection_status from aleph.views.util import jsonify from aleph.views.util import require log = logging.getLogger(__name__) blueprint = Blueprint('status_api', __name__) @blueprint.route('/api/2/status', methods=['GET']) def status(): require(request.authz.logged_in) status = get_active_collection_status() active_collections = status.pop('datasets') active_foreign_ids = set(active_collections.keys()) collections = request.authz.collections(request.authz.READ) results = [] for fid in active_foreign_ids: collection = Collection.by_foreign_id(fid) if collection is None: continue if collection.id in collections: result = active_collections[fid] result['collection'] = collection.to_dict() result['id'] = fid results.append(result) status['results'] = results return jsonify(status)
import logging from flask import Blueprint, request from aleph.model import Collection from aleph.queues import get_active_collection_status from aleph.views.util import jsonify from aleph.logic import resolver from aleph.views.util import require log = logging.getLogger(__name__) blueprint = Blueprint('status_api', __name__) @blueprint.route('/api/2/status', methods=['GET']) def status(): require(request.authz.logged_in) status = get_active_collection_status() active_collections = status.pop('datasets') active_foreign_ids = set(active_collections.keys()) collections = request.authz.collections(request.authz.READ) for collection_id in collections: resolver.queue(request, Collection, collection_id) resolver.resolve(request) results = [] for collection_id in collections: data = resolver.get(request, Collection, collection_id) if data is None: continue fid = data['foreign_id'] if fid in active_foreign_ids: result = active_collections[fid] result['collection'] = data result['id'] = fid results.append(result) status['results'] = results return jsonify(status)
Maintain a single whitespace between elements in templates Removing all whitespace in templates can have side effects for how the content is presented when it comes to inline elements, eg. ```html <p>My name is <em>Fredrik</em></p> ``` is compiled into ```html <p>My name is<em>Fredrik</em></p> ``` Even though this does increase the filesize slightly, I think it definitely is expected behavior for this kind of inline space to be preserved all the way in to the browser.
/** * Created by netanel on 01/01/15. */ var minify = Npm.require('html-minifier').minify; Plugin.registerSourceHandler('ng.html', { isTemplate: true, archMatching: "web" }, function(compileStep) { var contents = compileStep.read().toString('utf8'); var results = 'angular.module(\'angular-meteor\').run([\'$templateCache\', function($templateCache) {' + // Since compileStep.inputPath uses backslashes on Windows, we need replace them // with forward slashes to be able to consistently include templates across platforms. // Ticket here: https://github.com/Urigo/angular-meteor/issues/169 // A standardized solution to this problem might be on its way, see this ticket: // https://github.com/meteor/windows-preview/issues/47 '$templateCache.put(\'' + compileStep.inputPath.replace(/\\/g, "/") + '\', \'' + minify(contents.replace(/'/g, "\\'"), { collapseWhitespace : true, conservativeCollapse: true, removeComments : true, minifyJS : true, minifyCSS: true, processScripts : ['text/ng-template'] }) + '\');' + '}]);'; compileStep.addJavaScript({ path : compileStep.inputPath, data : results, sourcePath : compileStep.inputPath }); });
/** * Created by netanel on 01/01/15. */ var minify = Npm.require('html-minifier').minify; Plugin.registerSourceHandler('ng.html', { isTemplate: true, archMatching: "web" }, function(compileStep) { var contents = compileStep.read().toString('utf8'); var results = 'angular.module(\'angular-meteor\').run([\'$templateCache\', function($templateCache) {' + // Since compileStep.inputPath uses backslashes on Windows, we need replace them // with forward slashes to be able to consistently include templates across platforms. // Ticket here: https://github.com/Urigo/angular-meteor/issues/169 // A standardized solution to this problem might be on its way, see this ticket: // https://github.com/meteor/windows-preview/issues/47 '$templateCache.put(\'' + compileStep.inputPath.replace(/\\/g, "/") + '\', \'' + minify(contents.replace(/'/g, "\\'"), { collapseWhitespace : true, removeComments : true, minifyJS : true, minifyCSS: true, processScripts : ['text/ng-template'] }) + '\');' + '}]);'; compileStep.addJavaScript({ path : compileStep.inputPath, data : results, sourcePath : compileStep.inputPath }); });
Revert code that broke changing language.
// We save the user language preference in the user profile, and use that to set // the language reactively. If the user is not connected we use the language // information provided by the browser, and default to english. Meteor.startup(() => { Tracker.autorun(() => { const currentUser = Meteor.user(); let language; if (currentUser) { language = currentUser.profile && currentUser.profile.language; } if (!language) { if(navigator.languages) { language = navigator.languages[0]; } else { language = navigator.language || navigator.userLanguage; } } if (language) { TAPi18n.setLanguage(language); T9n.setLanguage(language); } }); });
// We save the user language preference in the user profile, and use that to set // the language reactively. If the user is not connected we use the language // information provided by the browser, and default to english. Meteor.startup(() => { Tracker.autorun(() => { const currentUser = Meteor.user(); let language; if (currentUser) { language = currentUser.profile && currentUser.profile.language; } if (!language) { if(navigator.languages) { language = navigator.languages[0]; } else { language = navigator.language || navigator.userLanguage; } } if (language) { TAPi18n.setLanguage(language); T9n.setLanguage(language); } if (language === 'zh') { TAPi18n.setLanguage('zh_CN'); T9n.setLanguage('zh_CN'); } }); });
Return only alphabetic words from sentence
# -*- coding: utf8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals import re from itertools import chain from .._compat import to_unicode, to_string, unicode_compatible _WORD_PATTERN = re.compile(r"^[^\W_]+$", re.UNICODE) @unicode_compatible class Sentence(object): __slots__ = ("_words", "_is_heading",) def __init__(self, words, is_heading=False): self._words = tuple(map(to_unicode, words)) self._is_heading = bool(is_heading) @property def words(self): return tuple(filter(self._is_word, self._words)) @property def is_heading(self): return self._is_heading def _is_word(self, word): return bool(_WORD_PATTERN.search(word)) def __unicode__(self): return " ".join(self._words) def __repr__(self): return to_string("<Sentence: %s>") % self.__str__()
# -*- coding: utf8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from itertools import chain from .._compat import to_unicode, to_string, unicode_compatible @unicode_compatible class Sentence(object): __slots__ = ("_words", "_is_heading",) def __init__(self, words, is_heading=False): self._words = tuple(map(to_unicode, words)) self._is_heading = bool(is_heading) @property def words(self): return self._words @property def is_heading(self): return self._is_heading def __unicode__(self): return " ".join(self._words) def __repr__(self): return to_string("<Sentence: %s>") % self.__str__()
Revert "cleaning up a few unnecessary modules" This reverts commit 6b6911ca54a8bb61a1715c19be71729a55497278.
""" setup script """ from setuptools import setup, find_packages _VERSION = '0.7' setup( name='jut-tools', version=_VERSION, author='Rodney Gomes', author_email='rodney@jut.io', url='https://github.com/jut-io/jut-python-tools', download_url='https://github.com/jut-io/jut-python-tools/tarball/%s' % _VERSION, install_requires=[ 'requests==2.7.0', 'websocket-client==0.32.0', 'memoized==0.2', 'tabulate==0.7.5' ], test_suite='tests', tests_install=[ 'sh==1.11' ], keywords=[''], packages=find_packages(exclude=['tests']), license='MIT License', description='jut command line tools', # pypi doesn't support markdown so we can't push the README.md as is long_description='https://github.com/jut-io/jut-python-tools/blob/master/README.md', include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'jut = jut.cli:main' ] }, )
""" setup script """ from setuptools import setup, find_packages _VERSION = '0.7' setup( name='jut-tools', version=_VERSION, author='Rodney Gomes', author_email='rodney@jut.io', url='https://github.com/jut-io/jut-python-tools', download_url='https://github.com/jut-io/jut-python-tools/tarball/%s' % _VERSION, install_requires=[ 'requests==2.7.0', 'websocket-client==0.32.0', 'memoized==0.2', 'tabulate==0.7.5' ], test_suite='tests', keywords=[''], packages=find_packages(exclude=['tests']), license='MIT License', description='jut command line tools', # pypi doesn't support markdown so we can't push the README.md as is long_description='https://github.com/jut-io/jut-python-tools/blob/master/README.md', include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'jut = jut.cli:main' ] }, )
Mark as deprecated to discourage usage for new tests Change-Id: I87d417da5b6b8cf9753604944dff74f8f39c321a
/* * Copyright 2000-2013 Vaadin 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. */ /** * */ package com.vaadin.tests.tb3; import org.junit.Test; /** * A simple version of {@link MultiBrowserTest} which allows only one test * method ({@link #test()}). Uses only the enclosing class name as test * identifier (i.e. excludes "-test"). * * This class is only provided as a helper for converting existing TB2 tests * without renaming all screenshots. All new TB3+ tests should extend * {@link MultiBrowserTest} directly instead of this. * * @author Vaadin Ltd */ @Deprecated public abstract class SimpleMultiBrowserTest extends MultiBrowserTest { @Test public abstract void test() throws Exception; /* * (non-Javadoc) * * @see com.vaadin.tests.tb3.ScreenshotTB3Test#getScreenshotBaseName() */ @Override public String getScreenshotBaseName() { return super.getScreenshotBaseName().replaceFirst("-test$", ""); } }
/* * Copyright 2000-2013 Vaadin 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. */ /** * */ package com.vaadin.tests.tb3; import org.junit.Test; /** * A simple version of {@link MultiBrowserTest} which allows only one test * method ({@link #test()}). Uses only the enclosing class name as test * identifier (i.e. excludes "-test"). * * This class is only provided as a helper for converting existing TB2 tests * without renaming all screenshots. All new TB3+ tests should extend * {@link MultiBrowserTest} directly instead of this. * * @author Vaadin Ltd */ public abstract class SimpleMultiBrowserTest extends MultiBrowserTest { @Test public abstract void test() throws Exception; /* * (non-Javadoc) * * @see com.vaadin.tests.tb3.ScreenshotTB3Test#getScreenshotBaseName() */ @Override public String getScreenshotBaseName() { return super.getScreenshotBaseName().replaceFirst("-test$", ""); } }
Reduce contrast of sparse keys
package org.jusecase.properties.ui; import org.jusecase.properties.entities.Key; import org.jusecase.properties.entities.KeyPopulation; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map; public class KeyListCellRenderer extends DefaultListCellRenderer { Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>(); public KeyListCellRenderer() { backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(255, 250, 227)); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Key key = (Key) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (!isSelected) { Color color = backgroundColorForPopulation.get(key.getPopulation()); if (color != null) { label.setBackground(color); } } return label; } }
package org.jusecase.properties.ui; import org.jusecase.properties.entities.Key; import org.jusecase.properties.entities.KeyPopulation; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map; public class KeyListCellRenderer extends DefaultListCellRenderer { Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>(); public KeyListCellRenderer() { backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(231, 211, 186)); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Key key = (Key) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (!isSelected) { Color color = backgroundColorForPopulation.get(key.getPopulation()); if (color != null) { label.setBackground(color); } } return label; } }
Fix nombre de los campos
<?php include_once $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php'; Use \App\System\Helpers\UserHelper as UserHelper; if ( !isset($_POST['username']) && !isset($_POST['password']) ){ header('Location: /account/bad_login'); die(); } $user = array( 'username' => $_POST['username'], 'password' => $_POST['password'] ); if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){ $remember = true; }else{ $remember = false; } if (UserHelper::login($user, $remember) === true){ header('Location: /home'); die(); }else{ header('Location: /account/bad_login'); die(); } ?>
<?php include_once $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php'; Use \App\System\Helpers\UserHelper as UserHelper; if ( !isset($_POST['username-modal']) && !isset($_POST['password-modal']) ){ header('Location: /account/bad_login'); die(); } $user = array( 'username' => $_POST['username-modal'], 'password' => $_POST['password-modal'] ); if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){ $remember = true; }else{ $remember = false; } if (UserHelper::login($user, $remember) === true){ header('Location: /home'); die(); }else{ header('Location: /account/bad_login'); die(); } ?>
Switch to version 1 for the next release.
"""Fill missing values in a grid.""" # Copyright (c) 2012-2014 Andrew Dawson # # 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. from __future__ import absolute_import from .gridfill import fill, fill_cube # Define a version string. __version__ = '1.0.dev0' # Define the objects to be imported by imports of the form: # from gridfill import * __all__ = ['fill', 'fill_cube']
"""Fill missing values in a grid.""" # Copyright (c) 2012-2014 Andrew Dawson # # 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. from __future__ import absolute_import from .gridfill import fill, fill_cube # Define a version string. __version__ = '0.4.x' # Define the objects to be imported by imports of the form: # from gridfill import * __all__ = ['fill', 'fill_cube']
Fix integration tests due to Google Privacy Policy content changes. Signed-off-by: Danny Joyce <656eadb1608d5e3ea5db131e513d97abdf96b075@pivotal.io>
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("deploy a staticfile app", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) BeforeEach(func() { app = cutlass.New(filepath.Join(bpDir, "fixtures", "reverse_proxy")) PushAppAndConfirm(app) }) It("proxies", func() { Expect(app.GetBody("/intl/en/policies")).To(ContainSubstring("Google Privacy Policy")) By("hides the nginx.conf file", func() { Expect(app.GetBody("/nginx.conf")).To(ContainSubstring("<title>404 Not Found</title>")) }) }) })
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("deploy a staticfile app", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) BeforeEach(func() { app = cutlass.New(filepath.Join(bpDir, "fixtures", "reverse_proxy")) PushAppAndConfirm(app) }) It("proxies", func() { Expect(app.GetBody("/intl/en/policies")).To(ContainSubstring("Welcome to the Google Privacy Policy")) By("hides the nginx.conf file", func() { Expect(app.GetBody("/nginx.conf")).To(ContainSubstring("<title>404 Not Found</title>")) }) }) })
Fix a test case failing to build.
package net.floodlightcontroller.linkdiscovery.internal; import java.util.Set; import com.thinkaurelius.titan.core.TitanGraph; import com.tinkerpop.blueprints.TransactionalGraph.Conclusion; import com.tinkerpop.blueprints.Vertex; /** * Seam that allows me to set up a testable instance of LinkStorageImpl that * writes to a file database rather than a Cassandra cluster. * It seems the init() API on LinkStorageImpl might change so I won't rely * on it yet. * * @author jono * */ public class TestableLinkStorageImpl extends LinkStorageImpl { protected TitanGraph graph; public TestableLinkStorageImpl(TitanGraph graph){ this.graph = graph; } @Override public void init(String conf){ Set<String> s = graph.getIndexedKeys(Vertex.class); if (!s.contains("dpid")) { graph.createKeyIndex("dpid", Vertex.class); graph.stopTransaction(Conclusion.SUCCESS); } if (!s.contains("type")) { graph.createKeyIndex("type", Vertex.class); graph.stopTransaction(Conclusion.SUCCESS); } } }
package net.floodlightcontroller.linkdiscovery.internal; import java.util.Set; import com.thinkaurelius.titan.core.TitanGraph; import com.tinkerpop.blueprints.TransactionalGraph.Conclusion; import com.tinkerpop.blueprints.Vertex; /** * Seam that allows me to set up a testable instance of LinkStorageImpl that * writes to a file database rather than a Cassandra cluster. * It seems the init() API on LinkStorageImpl might change so I won't rely * on it yet. * * @author jono * */ public class TestableLinkStorageImpl extends LinkStorageImpl { public TestableLinkStorageImpl(TitanGraph graph){ this.graph = graph; } @Override public void init(String conf){ Set<String> s = graph.getIndexedKeys(Vertex.class); if (!s.contains("dpid")) { graph.createKeyIndex("dpid", Vertex.class); graph.stopTransaction(Conclusion.SUCCESS); } if (!s.contains("type")) { graph.createKeyIndex("type", Vertex.class); graph.stopTransaction(Conclusion.SUCCESS); } } }
Add message parameter to database when creating a post
//exports.list = function (req, res) { // res.send({ // "lat": 5.552, // "long": 2.342, // "message": "Bong!", // "tags": ["Lifestyle", "Restaurant", "YOLO"], // "relevance": 1337, // "user": 42 // }); //}; var db = require('../database.js'); var posts = db.get('posts'); exports.list = function (req, res) { var collection = db.get('posts'); collection.find({}, {}, function (e, docs) { res.send(docs); }); }; exports.create = function (req, res) { req.assert('lat', 'not a valid latitude value').isLat(); req.assert('long', 'not a valid longitude value').isLong(); req.assert('message', 'required').notEmpty(); req.sanitize('lat').toFloat(); req.sanitize('long').toFloat(); req.sanitize('message').toString(); var errors = req.validationErrors(); if (errors) { res.send({'error': errors}); return; } var post = { "lat": req.param('lat'), "long": req.param('long'), "message": req.param('message'), "tags": [], "relevance": 100, "user": 0 }; posts.insert(post); res.json(post); };
//exports.list = function (req, res) { // res.send({ // "lat": 5.552, // "long": 2.342, // "message": "Bong!", // "tags": ["Lifestyle", "Restaurant", "YOLO"], // "relevance": 1337, // "user": 42 // }); //}; var db = require('../database.js'); var posts = db.get('posts'); exports.list = function (req, res) { var collection = db.get('posts'); collection.find({}, {}, function (e, docs) { res.send(docs); }); }; exports.create = function (req, res) { req.assert('lat', 'not a valid latitude value').isLat(); req.assert('long', 'not a valid longitude value').isLong(); req.assert('message', 'required').notEmpty(); req.sanitize('lat').toFloat(); req.sanitize('long').toFloat(); req.sanitize('message').toString(); var errors = req.validationErrors(); if (errors) { res.send({'error': errors}); return; } var post = { "lat": req.param('lat'), "long": req.param('long'), "message": 'empty', "tags": [], "relevance": 100, "user": 0 }; posts.insert(post); res.json(post); };
Fix custom URLs masking admin URL
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
Use JS Objects for generating JSON Replace hand-coded JSON strings with JSON hashes (or Objects, I'm not sure what they are defined as at this point.)
var http = require('http') var moment = require('moment') var url = require('url') function stringifyTime(time) { return { hour: time.hour(), minute: time.minute(), second: time.second() } } function unixifyTime(time) { return { unixtime: time.valueOf() } } var server = http.createServer(function(req, resp) { if (req.method != 'GET') { resp.writeHead(405, {'Allow': 'GET'}) resp.end(JSON.stringify({message: 'bad method (method != GET)'})) } var parsed = url.parse(req.url, true) var result = null var date = moment(parsed.query.iso) switch(parsed.pathname) { case '/api/parsetime': result = stringifyTime(date) break; case '/api/unixtime': result = unixifyTime(date) break; } resp.writeHead(200, {'Content-Type': 'application/json'}) resp.end(JSON.stringify(result)) }) server.listen(8000)
var http = require('http') var moment = require('moment') var url = require('url') function stringifyTime(now) { var timeString = '{"hour":' + now.hour() + ',"minute":' + now.minute() + ',"second":' + now.second() + '}' return timeString; } function unixifyTime(now) { var timeString = '{"unixtime":' + now.valueOf() + '}'; return timeString; } var server = http.createServer(function(req, resp) { if (req.method != 'GET') { resp.writeHead(405, {'Allow': 'GET'}) resp.end('{"message": "bad method (method != GET)"}') } var hash = url.parse(req.url, true) var fcn = (function(now){ return null }); switch(hash.pathname) { case '/api/parsetime': fcn = stringifyTime; break; case '/api/unixtime': fcn = unixifyTime; break; } var dateString = hash.query.iso var dateObj = moment(dateString) resp.writeHead(200, {'Content-Type': 'application/json'}) resp.end(fcn(dateObj)) }) server.listen(8000)
Test JSON extension deoes not apply for 204 status responses.
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); it('should not apply when no content type at all (e.g. 204 response)', function() { expect(ext.applies({}, {}, 204)).to.be.false; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
Edit migration so it depends on 0008_auto_20160415_1854 Ensure the migrations will apply correctly without conflcit once merged Merging this branch is now blocked on PR #239
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pollingstations', '0008_auto_20160415_1854'), ] operations = [ migrations.CreateModel( name='CustomFinder', fields=[ ('area_code', models.CharField(serialize=False, max_length=9, primary_key=True)), ('base_url', models.CharField(max_length=255, blank=True)), ('can_pass_postcode', models.BooleanField(default=False)), ('message', models.TextField(blank=True)), ], ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pollingstations', '0006_residentialaddress_slug'), ] operations = [ migrations.CreateModel( name='CustomFinder', fields=[ ('area_code', models.CharField(serialize=False, max_length=9, primary_key=True)), ('base_url', models.CharField(max_length=255, blank=True)), ('can_pass_postcode', models.BooleanField(default=False)), ('message', models.TextField(blank=True)), ], ), ]
Add some more tests for AppView
/* global app, chai, describe, it, beforeEach, afterEach, sinon */ var expect = chai.expect; describe("AppView", function() { var sandbox; describe("#initialize", function() { beforeEach(function() { sandbox = sinon.sandbox.create(); sandbox.stub(app.views, "NotificationsView"); sandbox.stub(app.views, "LoginView"); sandbox.stub(app.views, "UsersView"); }); afterEach(function() { sandbox.restore(); }); it("should add initialize a notifications property", function() { var appView = new app.views.AppView(); expect(appView.notifications).to.be.an.instanceOf( app.views.NotificationsView); }); it("should add initialize a login property", function() { var appView = new app.views.AppView(); expect(appView.login).to.be.an.instanceOf( app.views.LoginView); }); it("should add initialize a users property", function() { var appView = new app.views.AppView(); expect(appView.users).to.be.an.instanceOf( app.views.UsersView); }); }); });
/* global app, chai, describe, it, beforeEach, afterEach, sinon */ var expect = chai.expect; describe("AppView", function() { var sandbox; describe("#initialize", function() { beforeEach(function() { sandbox = sinon.sandbox.create(); sandbox.stub(app.views, "NotificationsView"); sandbox.stub(app.views, "LoginView"); sandbox.stub(app.views, "UsersView"); }); afterEach(function() { sandbox.restore(); }); it("should add initialize a notifications property", function() { var appView = new app.views.AppView(); expect(appView.notifications).to.be.an.instanceOf( app.views.NotificationsView); }); }); });
Update google maps api key
<?php return function (CM_Config_Node $config) { $config->installationName = 'denkmal'; $config->CM_Site_Abstract->class = 'Denkmal_Site_Default'; $config->CM_Model_User->class = 'Denkmal_Model_User'; $config->CM_Params->class = 'Denkmal_Params'; $config->timeZone = 'Europe/Zurich'; $config->services['google-static-maps'] = [ 'class' => 'Denkmal_GoogleMaps_StaticMaps', 'arguments' => [ 'apiKey' => 'AIzaSyC5s-73wOdKqfCzNXV6YNJ-RNgJOl6HL80', ] ]; $config->Denkmal_Site_Default->name = 'Denkmal.org'; $config->Denkmal_Site_Default->emailAddress = 'kontakt@denkmal.org'; $config->Denkmal_Site_Default->webFontLoaderConfig = [ 'google' => ['families' => ['Open Sans']] ]; };
<?php return function (CM_Config_Node $config) { $config->installationName = 'denkmal'; $config->CM_Site_Abstract->class = 'Denkmal_Site_Default'; $config->CM_Model_User->class = 'Denkmal_Model_User'; $config->CM_Params->class = 'Denkmal_Params'; $config->timeZone = 'Europe/Zurich'; $config->services['google-static-maps'] = [ 'class' => 'Denkmal_GoogleMaps_StaticMaps', 'arguments' => [ 'apiKey' => 'AIzaSyB85laUBhcLyjf7vff7WE62__6jPxjK8qI', ] ]; $config->Denkmal_Site_Default->name = 'Denkmal.org'; $config->Denkmal_Site_Default->emailAddress = 'kontakt@denkmal.org'; $config->Denkmal_Site_Default->webFontLoaderConfig = [ 'google' => ['families' => ['Open Sans']] ]; };
Fix missing return statement in DJStripeSubscriptionPermission Fixes #1250
""" .. module:: dj-stripe.contrib.rest_framework.permissions. :synopsis: dj-stripe - Permissions to be used with the dj-stripe REST API. .. moduleauthor:: @kavdev, @pydanny """ from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscriptions. """ def has_permission(self, request, view) -> bool: """ Check if the subscriber has an active subscription. Returns false if: * a subscriber isn't passed through the request See ``utils.subscriber_has_active_subscription`` for more rules. """ try: return subscriber_has_active_subscription( subscriber_request_callback(request) ) except AttributeError: return False
""" .. module:: dj-stripe.contrib.rest_framework.permissions. :synopsis: dj-stripe - Permissions to be used with the dj-stripe REST API. .. moduleauthor:: @kavdev, @pydanny """ from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscriptions. """ def has_permission(self, request, view): """ Check if the subscriber has an active subscription. Returns false if: * a subscriber isn't passed through the request See ``utils.subscriber_has_active_subscription`` for more rules. """ try: subscriber_has_active_subscription(subscriber_request_callback(request)) except AttributeError: return False
Remove / from script path to make it search bin rather than /bin
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['bin/danboorsync'], name = 'danboorsync' )
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/bin/danboorsync'], name = 'danboorsync' )
Fix std::optional access in SplitPairedReader pythonization
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: yield record klass.__iter__ = __iter__ is_split, _ = is_template_inst(name, 'SplitPairedReader') if is_split: def __iter__(self): while not self.is_complete(): left, right = self.next() left, right = left.value() if left else None, right.value() if right else None if left is not None or right is not None: yield left, right klass.__iter__ = __iter__
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: yield record klass.__iter__ = __iter__ is_split, _ = is_template_inst(name, 'SplitPairedReader') if is_split: def __iter__(self): while not self.is_complete(): pair = self.next() left = pair.left if pair.has_left else None right = pair.right if pair.has_right else None if left is not None or right is not None: yield left, right klass.__iter__ = __iter__
Use longer TIMEOUT defined in sos_notebook.test_utils.
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') print(jupyter_client.kernelspec.find_kernel_specs()) # Test that sos kernel is functional import unittest from sos_notebook.test_utils import sos_kernel from ipykernel.tests.utils import execute, wait_for_idle, assemble_output class TestSoSKernel(unittest.TestCase): def testKernel(self): with sos_kernel() as kc: execute(kc=kc, code='a = 1\nprint(a)') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stderr, '') self.assertEqual(stdout.strip(), '1') if __name__ == '__main__': unittest.main()
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') print(jupyter_client.kernelspec.find_kernel_specs()) # Test that sos kernel is functional import unittest from ipykernel.tests.utils import execute, wait_for_idle, assemble_output from sos_notebook.test_utils import sos_kernel class TestSoSKernel(unittest.TestCase): def testKernel(self): with sos_kernel() as kc: execute(kc=kc, code='a = 1\nprint(a)') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stderr, '') self.assertEqual(stdout.strip(), '1') if __name__ == '__main__': unittest.main()
Use another compiler flag wich works for clang and gcc.
from setuptools import setup, find_packages from distutils.extension import Extension from Cython.Build import cythonize extension_defaults = { 'extra_compile_args': [ '-std=c++11', '-O3', '-Wall', '-Wextra', '-Wconversion', '-fno-strict-aliasing' ], 'language': 'c++', 'libraries': [ 'rocksdb', 'snappy', 'bz2', 'z' ] } mod1 = Extension( 'rocksdb._rocksdb', ['rocksdb/_rocksdb.pyx'], **extension_defaults ) setup( name="pyrocksdb", version='0.4', description="Python bindings for RocksDB", keywords='rocksdb', author='Stephan Hofmockel', author_email="Use the github issues", url="https://github.com/stephan-hof/pyrocksdb", license='BSD License', install_requires=[ 'setuptools', 'Cython>=0.20', ], package_dir={'rocksdb': 'rocksdb'}, packages=find_packages('.'), ext_modules=cythonize([mod1]), test_suite='rocksdb.tests', include_package_data=True )
from setuptools import setup, find_packages from distutils.extension import Extension from Cython.Build import cythonize extension_defaults = { 'extra_compile_args': [ '-std=gnu++11', '-O3', '-Wall', '-Wextra', '-Wconversion', '-fno-strict-aliasing' ], 'language': 'c++', 'libraries': [ 'rocksdb', 'snappy', 'bz2', 'z' ] } mod1 = Extension( 'rocksdb._rocksdb', ['rocksdb/_rocksdb.pyx'], **extension_defaults ) setup( name="pyrocksdb", version='0.4', description="Python bindings for RocksDB", keywords='rocksdb', author='Stephan Hofmockel', author_email="Use the github issues", url="https://github.com/stephan-hof/pyrocksdb", license='BSD License', install_requires=[ 'setuptools', 'Cython>=0.20', ], package_dir={'rocksdb': 'rocksdb'}, packages=find_packages('.'), ext_modules=cythonize([mod1]), test_suite='rocksdb.tests', include_package_data=True )
Remove no longer valid test
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
Use Nabu settings in token generation
from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': settings.NABU['jwt']['iss'], 'aud': settings.NABU['jwt']['aud'], 'exp': datetime.utcnow() + timedelta(**settings.NABU['jwt']['exp']), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': self.request.headers['Host'], 'aud': self.request.headers['Host'], 'exp': datetime.utcnow() + timedelta(seconds=30), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
Add a console_scripts entry point
#!/usr/bin/env python from __future__ import print_function from setuptools import setup setup(name="abzer", author="Wieland Hoffmann", author_email="themineo@gmail.com", packages=["abzer"], package_dir={"abzer": "abzer"}, download_url=["https://github.com/mineo/abzer/tarball/master"], url=["http://github.com/mineo/abzer"], license="MIT", classifiers=["Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5"], description="", long_description=open("README.rst").read(), setup_requires=["setuptools_scm"], use_scm_version={"write_to": "abzer/version.py"}, install_requires=["aiohttp"], extras_require={ 'docs': ['sphinx']}, entry_points={ 'console_scripts': ['abzer=abzer.__main__:main'] } )
#!/usr/bin/env python from __future__ import print_function from setuptools import setup setup(name="abzer", author="Wieland Hoffmann", author_email="themineo@gmail.com", packages=["abzer"], package_dir={"abzer": "abzer"}, download_url=["https://github.com/mineo/abzer/tarball/master"], url=["http://github.com/mineo/abzer"], license="MIT", classifiers=["Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5"], description="", long_description=open("README.rst").read(), setup_requires=["setuptools_scm"], use_scm_version={"write_to": "abzer/version.py"}, install_requires=["aiohttp"], extras_require={ 'docs': ['sphinx']} )
Fix a TypeError when load mergeTool setting cx-freeze isn't include pickle module on the Windows platform, it cause "TypeError: unable to convert a C++ 'QVariantList' instance to a Python object"
import sys from glob import glob from cx_Freeze import setup, Executable from version import VERSION # Dependencies are automatically detected, but it might need # fine tuning. excludes = ["Tkinter"] includes = ["logview", "colorwidget", "pickle"] includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"), ("data/licenses/Apache-2.0.html", "data/licenses/Apache-2.0.html"), ("LICENSE", "data/licenses/LICENSE")] for qm in glob("data/translations/*.qm"): includeFiles.append((qm, qm)) buildOptions = dict( packages=[], excludes=excludes, includes=includes, include_files=includeFiles, include_msvcr=True, silent=True) base = None icon = None if sys.platform == "win32": base = "Win32GUI" icon = "data/icons/gitc.ico" executables = [ Executable('gitc', base=base, icon=icon )] setup(name='gitc', version=VERSION, description='A file conflict viewer for git', options=dict(build_exe=buildOptions), executables=executables, )
import sys from glob import glob from cx_Freeze import setup, Executable from version import VERSION # Dependencies are automatically detected, but it might need # fine tuning. excludes = ["Tkinter"] includes = ["logview", "colorwidget"] includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"), ("data/licenses/Apache-2.0.html", "data/licenses/Apache-2.0.html"), ("LICENSE", "data/licenses/LICENSE")] for qm in glob("data/translations/*.qm"): includeFiles.append((qm, qm)) buildOptions = dict( packages=[], excludes=excludes, includes=includes, include_files=includeFiles, include_msvcr=True, silent=True) base = None icon = None if sys.platform == "win32": base = "Win32GUI" icon = "data/icons/gitc.ico" executables = [ Executable('gitc', base=base, icon=icon )] setup(name='gitc', version=VERSION, description='A file conflict viewer for git', options=dict(build_exe=buildOptions), executables=executables, )
Add another missing heroku config variable
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL', 'SQLALCHEMY_DATABASE_URI') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
Add an option to specify HTTP port.
/*_########################################################################## _## _## Copyright (C) 2012 Kaito Yamada _## _########################################################################## */ package com.github.kaitoy.sneo.giane.jetty; import java.net.URL; import java.security.ProtectionDomain; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; public class GianeStarter { public static void main(String[] args) throws Exception { int httpPort = 8080; for (int i = 0; i < args.length; i++) { String arg = args[i]; try { if ("--httpPort".equals(arg)) { httpPort = Integer.parseInt(args[++i]); } else { System.err.println("Invalid option: " + arg); System.exit(1); } } catch (Exception e) { System.err.println("An error occurred in processing an option: " + arg); System.exit(1); } } Server server = new Server(httpPort); WebAppContext context = new WebAppContext(); context.setServer(server); context.setContextPath("/giane"); ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); context.setWar(location.toExternalForm()); server.setHandler(context); server.start(); server.join(); } }
/*_########################################################################## _## _## Copyright (C) 2012 Kaito Yamada _## _########################################################################## */ package com.github.kaitoy.sneo.giane.jetty; import java.net.URL; import java.security.ProtectionDomain; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; public class GianeStarter { public static void main(String[] args) throws Exception { Server server = new Server(8080); WebAppContext context = new WebAppContext(); context.setServer(server); context.setContextPath("/giane"); //context.setWelcomeFiles(new String[] {"index.action"}); ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); context.setWar(location.toExternalForm()); server.setHandler(context); server.start(); server.join(); } }
Update user model with facebook_id
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'facebook_id', 'avatar']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['remember_token']; }
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
Fix problem with copying from text window. closes #9843
from PyQt5 import QtWidgets class TextSubWindow(QtWidgets.QTextEdit): """ TextEdit that saves it size when it closes and closes itself if the main widget disappears. """ def __init__(self): super(TextSubWindow, self).__init__() self._size = None def sizeHint(self, *args): """ Return the saved size. """ if self._size: return self._size else: return super(TextSubWindow, self).size() def closeEvent(self, *args): """ Store the size of the window. """ self._size = self.size() super(TextSubWindow, self).closeEvent(*args)
from PyQt5 import QtCore, QtWidgets class TextSubWindow(QtWidgets.QTextEdit): """ TextEdit that saves it size when it closes and closes itself if the main widget disappears. """ def __init__(self): super(TextSubWindow, self).__init__() self.setWindowFlags(QtCore.Qt.SubWindow) self._size = None def sizeHint(self, *args): """ Return the saved size. """ if self._size: return self._size else: return super(TextSubWindow, self).size() def closeEvent(self, *args): """ Store the size of the window. """ self._size = self.size() super(TextSubWindow, self).closeEvent(*args)
Add the CreateServiceCommand to the Menu
<?php /** * Copyright 2017 SURFnet B.V. * * 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. */ namespace Surfnet\ServiceProviderDashboard\Infrastructure\DashboardBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; class Builder implements ContainerAwareInterface { use ContainerAwareTrait; public function mainMenu(FactoryInterface $factory, array $options) { $menu = $factory->createItem('root'); $menu->addChild('Services', array('route' => 'entity_list')); $menu->addChild('Add new service', array( 'route' => 'service_add', )); $menu->addChild('Add new supplier', array( 'route' => 'supplier_add', )); $menu->addChild('Edit supplier', array( 'route' => 'supplier_edit', )); return $menu; } }
<?php /** * Copyright 2017 SURFnet B.V. * * 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. */ namespace Surfnet\ServiceProviderDashboard\Infrastructure\DashboardBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; class Builder implements ContainerAwareInterface { use ContainerAwareTrait; public function mainMenu(FactoryInterface $factory, array $options) { $menu = $factory->createItem('root'); $menu->addChild('Services', array('route' => 'entity_list')); $menu->addChild('Add new supplier', array( 'route' => 'supplier_add', )); $menu->addChild('Edit supplier', array( 'route' => 'supplier_edit', )); return $menu; } }
Fix for readonly hash args
import { helper } from '@ember/component/helper'; import config from '../config/environment'; import { shaRegExp, versionRegExp, versionExtendedRegExp } from 'ember-cli-app-version/utils/regexp'; const { APP: { version } } = config; export function makeHelper(version) { return function appVersion(_, hash = {}) { // e.g. 1.0.0-alpha.1+4jds75hf // Allow use of 'hideSha' and 'hideVersion' For backwards compatibility let versionOnly = hash.versionOnly || hash.hideSha; let shaOnly = hash.shaOnly || hash.hideVersion; let match = null; if (versionOnly) { if (hash.showExtended) { match = version.match(versionExtendedRegExp); // 1.0.0-alpha.1 } else { match = version.match(versionRegExp); // 1.0.0 } } if (shaOnly) { match = version.match(shaRegExp); // 4jds75hf } return match?match[0]:version; }; } export default helper(appVersion);
import { helper } from '@ember/component/helper'; import config from '../config/environment'; import { shaRegExp, versionRegExp, versionExtendedRegExp } from 'ember-cli-app-version/utils/regexp'; const { APP: { version } } = config; export function makeHelper(version) { return function appVersion(_, hash = {}) { // e.g. 1.0.0-alpha.1+4jds75hf // Allow use of 'hideSha' and 'hideVersion' For backwards compatibility hash.versionOnly = hash.versionOnly || hash.hideSha; hash.shaOnly = hash.shaOnly || hash.hideVersion; let match = null; if (hash.versionOnly) { if (hash.showExtended) { match = version.match(versionExtendedRegExp); // 1.0.0-alpha.1 } else { match = version.match(versionRegExp); // 1.0.0 } } if (hash.shaOnly) { match = version.match(shaRegExp); // 4jds75hf } return match?match[0]:version; }; } export default helper(appVersion);
Put seasons and subreddit into a response object for the api
from flask import Flask, jsonify, render_template import test, stats, os app = Flask(__name__) cache = {} @app.route('/') def hello_world(): return 'Hello World!' @app.route('/r/<string:subreddit>') def episodes(subreddit): seasonsAndEpisodes = _getEpisodes(subreddit) return render_template('index.html', result=seasonsAndEpisodes, subreddit=subreddit) @app.route('/api/r/<string:subreddit>', methods=['GET']) def get_episodes(subreddit): seasonsAndEpisodes = _getEpisodes(subreddit) seasons = [season.serialize() for season in seasonsAndEpisodes] result = {"seasons": seasons, "subreddit": subreddit} return jsonify(result) def _getEpisodes(subreddit): if subreddit in cache: return cache[subreddit] episodes = test.getData(subreddit) seasonsAndEpisodes = stats.extractSeasonsAndEpisodes(episodes) cache[subreddit] = seasonsAndEpisodes return seasonsAndEpisodes if __name__ == '__main__': port = int(os.environ.get('PORT', 33507)) app.run(debug=True, host='0.0.0.0', port=port)
from flask import Flask, jsonify, render_template import test, stats, os app = Flask(__name__) cache = {} @app.route('/') def hello_world(): return 'Hello World!' @app.route('/r/<string:subreddit>') def episodes(subreddit): seasonsAndEpisodes = _getEpisodes(subreddit) return render_template('index.html', result=seasonsAndEpisodes, subreddit=subreddit) @app.route('/api/r/<string:subreddit>', methods=['GET']) def get_episodes(subreddit): seasonsAndEpisodes = _getEpisodes(subreddit) return jsonify([season.serialize() for season in seasonsAndEpisodes]) def _getEpisodes(subreddit): if subreddit in cache: return cache[subreddit] episodes = test.getData(subreddit) seasonsAndEpisodes = stats.extractSeasonsAndEpisodes(episodes) cache[subreddit] = seasonsAndEpisodes return seasonsAndEpisodes if __name__ == '__main__': port = int(os.environ.get('PORT', 33507)) app.run(debug=True, host='0.0.0.0', port=port)
Return Integer instead of primitive int (why there is null in node id?!)
/** * */ package org.openforis.collect.model.proxy; import org.granite.messaging.amf.io.util.externalizer.annotation.ExternalizedProperty; import org.openforis.collect.Proxy; import org.openforis.idm.model.state.NodeState; /** * @author M. Togna * */ public class NodeStateProxy implements Proxy { private transient NodeState nodeState; public NodeStateProxy(NodeState nodeState) { this.nodeState = nodeState; } @ExternalizedProperty public Integer getNodeId() { return nodeState.getNode().getId(); } @ExternalizedProperty public boolean isRelevant() { return nodeState.isRelevant(); } @ExternalizedProperty public boolean isRequired() { return nodeState.isRequired(); } @ExternalizedProperty public ValidationResultsProxy getValidationResults() { return new ValidationResultsProxy(nodeState.getValidationResults()); } }
/** * */ package org.openforis.collect.model.proxy; import org.granite.messaging.amf.io.util.externalizer.annotation.ExternalizedProperty; import org.openforis.collect.Proxy; import org.openforis.idm.model.state.NodeState; /** * @author M. Togna * */ public class NodeStateProxy implements Proxy { private transient NodeState nodeState; public NodeStateProxy(NodeState nodeState) { this.nodeState = nodeState; } @ExternalizedProperty public int getNodeId() { return nodeState.getNode().getId(); } @ExternalizedProperty public boolean isRelevant() { return nodeState.isRelevant(); } @ExternalizedProperty public boolean isRequired() { return nodeState.isRequired(); } @ExternalizedProperty public ValidationResultsProxy getValidationResults() { return new ValidationResultsProxy(nodeState.getValidationResults()); } }
Change the text on the test
/* * Copyright 2015 Bridje Framework. * * 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.bridje.core.ioc.test; import org.bridje.core.ioc.ContextListener; import org.bridje.core.ioc.annotations.Component; @Component public class ContextListenerGeneric implements ContextListener<Object> { @Override public void preCreateComponent(Class<Object> clazz) { System.out.println("General method called for all the components preCreate: " + clazz.getName()); } @Override public void preInitComponent(Class<Object> clazz) { System.out.println("General method called for all the components preInit: " + clazz.getName()); } @Override public void postInitComponent(Class<Object> clazz) { System.out.println("General method called for all the components postInit: " + clazz.getName()); } }
/* * Copyright 2015 Bridje Framework. * * 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.bridje.core.ioc.test; import org.bridje.core.ioc.ContextListener; import org.bridje.core.ioc.annotations.Component; @Component public class ContextListenerGeneric implements ContextListener<Object> { @Override public void preCreateComponent(Class<Object> clazz) { System.out.println("preCreate: " + clazz.getName()); } @Override public void preInitComponent(Class<Object> clazz) { System.out.println("preInit: " + clazz.getName()); } @Override public void postInitComponent(Class<Object> clazz) { System.out.println("postInit: " + clazz.getName()); } }
Use null instead of empty object as {} != false but null == false
var needle = require('needle'); function Client(base_url, token) { this.base_url = base_url this.token = token || null } Client.prototype.get = function (path, body, callback) { this.__send('get', path, body, callback); } Client.prototype.post = function (path, body, callback) { this.__send('post', path, body, callback); } Client.prototype.put = function (path, body, callback) { this.__send('put', path, body, callback); } Client.prototype.delete = function (path, body, callback) { this.__send('delete', path, body, callback); } Client.prototype.__send = function (method, path, body, callback) { var headers = { 'X-Ticket-Sharing-Version': '1' } if (this.token) { headers['X-Ticket-Sharing-Token'] = this.token } var options = { 'headers': headers , 'json': true } needle.request(method, this.base_url + path, body, options, callback) } module.exports = Client
var needle = require('needle'); function Client(base_url, token) { this.base_url = base_url this.token = token || {} } Client.prototype.get = function (path, body, callback) { this.__send('get', path, body, callback); } Client.prototype.post = function (path, body, callback) { this.__send('post', path, body, callback); } Client.prototype.put = function (path, body, callback) { this.__send('put', path, body, callback); } Client.prototype.delete = function (path, body, callback) { this.__send('delete', path, body, callback); } Client.prototype.__send = function (method, path, body, callback) { var headers = { 'X-Ticket-Sharing-Version': '1' } if (this.token) { headers['X-Ticket-Sharing-Token'] = this.token } var options = { 'headers': headers , 'json': true } needle.request(method, this.base_url + path, body, options, callback) } module.exports = Client
Fix symfony 5 BC deprecation alert on TreeBuilder fix symfony v5.* breaking change on TreeBuilder::root()
<?php namespace Eschmar\CssInlinerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('eschmar_css_inliner'); // BC layer for symfony/config 4.1 and older if (! \method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->root('eschmar_css_inliner'); } else { $rootNode = $treeBuilder->getRootNode(); } return $treeBuilder; } }
<?php namespace Eschmar\CssInlinerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('eschmar_css_inliner'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
Create gcs group for test running
<?php declare(strict_types=1); namespace League\Flysystem\GoogleCloudStorage; use Google\Cloud\Storage\StorageClient; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\FilesystemAdapter; /** * @group gcs */ class GoogleCloudStorageAdapterTest extends FilesystemAdapterTestCase { /** * @var string */ private static $adapterPrefix = 'ci'; public static function setUpBeforeClass(): void { static::$adapterPrefix = 'ci/' . bin2hex(random_bytes(10)); } protected static function createFilesystemAdapter(): FilesystemAdapter { if ( ! file_exists(__DIR__ . '/../../google-cloud-service-account.json')) { self::markTestSkipped("No google service account found in project root."); } $clientOptions = [ 'projectId' => 'flysystem-testing', 'keyFilePath' => __DIR__ . '/../../google-cloud-service-account.json', ]; $storageClient = new StorageClient($clientOptions); $bucket = $storageClient->bucket('flysystem'); return new GoogleCloudStorageAdapter($bucket, static::$adapterPrefix); } }
<?php declare(strict_types=1); namespace League\Flysystem\GoogleCloudStorage; use Google\Cloud\Storage\StorageClient; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\FilesystemAdapter; class GoogleCloudStorageAdapterTest extends FilesystemAdapterTestCase { /** * @var string */ private static $adapterPrefix = 'ci'; public static function setUpBeforeClass(): void { static::$adapterPrefix = 'ci/' . bin2hex(random_bytes(10)); } protected static function createFilesystemAdapter(): FilesystemAdapter { if ( ! file_exists(__DIR__ . '/../../google-cloud-service-account.json')) { self::markTestSkipped("No google service account found in project root."); } $clientOptions = [ 'projectId' => 'flysystem-testing', 'keyFilePath' => __DIR__ . '/../../google-cloud-service-account.json', ]; $storageClient = new StorageClient($clientOptions); $bucket = $storageClient->bucket('flysystem'); return new GoogleCloudStorageAdapter($bucket, static::$adapterPrefix); } }
Make test work under Python 2.6.
from bpython import autocomplete import unittest try: from unittest import skip except ImportError: def skip(f): return lambda self: None #TODO: Parts of autocompletion to test: # Test that the right matches come back from find_matches (test that priority is correct) # Test the various complete methods (import, filename) to see if right matches # Test that MatchesIterator.substitute correctly subs given a match and a completer class TestSafeEval(unittest.TestCase): def test_catches_syntax_error(self): self.assertRaises(autocomplete.EvaluationError, autocomplete.safe_eval, '1re', {}) class TestFormatters(unittest.TestCase): def test_filename(self): last_part_of_filename = autocomplete.FilenameCompletion.format self.assertEqual(last_part_of_filename('abc'), 'abc') self.assertEqual(last_part_of_filename('abc/'), 'abc/') self.assertEqual(last_part_of_filename('abc/efg'), 'efg') self.assertEqual(last_part_of_filename('abc/efg/'), 'efg/') self.assertEqual(last_part_of_filename('/abc'), 'abc') self.assertEqual(last_part_of_filename('ab.c/e.f.g/'), 'e.f.g/') def test_attribute(self): self.assertEqual(autocomplete.after_last_dot('abc.edf'), 'edf')
from bpython import autocomplete import unittest try: from unittest import skip except ImportError: def skip(f): return lambda self: None #TODO: Parts of autocompletion to test: # Test that the right matches come back from find_matches (test that priority is correct) # Test the various complete methods (import, filename) to see if right matches # Test that MatchesIterator.substitute correctly subs given a match and a completer class TestSafeEval(unittest.TestCase): def test_catches_syntax_error(self): with self.assertRaises(autocomplete.EvaluationError): autocomplete.safe_eval('1re',{}) class TestFormatters(unittest.TestCase): def test_filename(self): last_part_of_filename = autocomplete.FilenameCompletion.format self.assertEqual(last_part_of_filename('abc'), 'abc') self.assertEqual(last_part_of_filename('abc/'), 'abc/') self.assertEqual(last_part_of_filename('abc/efg'), 'efg') self.assertEqual(last_part_of_filename('abc/efg/'), 'efg/') self.assertEqual(last_part_of_filename('/abc'), 'abc') self.assertEqual(last_part_of_filename('ab.c/e.f.g/'), 'e.f.g/') def test_attribute(self): self.assertEqual(autocomplete.after_last_dot('abc.edf'), 'edf')
Use single quotes around strings in example file
'use strict'; var gulp = require('gulp'), pkg = require('./package.json'), toolkit = require('gulp-wp-toolkit'); toolkit.extendConfig({ theme: { name: 'Craig Simpson Theme', homepage: pkg.homepage, description: pkg.description, author: pkg.author, version: pkg.version, licence: pkg.licence, textdomain: pkg.name }, js: { files: [ 'develop/vendor/vendor.js', 'develop/js/responsive-menu.js', 'develop/js/main.js' ] }, server: { url: 'craigsimpson.dev' } }); toolkit.extendTasks(gulp, { // Task Name. console: [ ['build'], function () { console.log('This is an extended task. It depends on `build`'); } ] });
'use strict'; var gulp = require('gulp'), pkg = require('./package.json'), toolkit = require('gulp-wp-toolkit'); toolkit.extendConfig({ theme: { name: "Craig Simpson Theme", homepage: pkg.homepage, description: pkg.description, author: pkg.author, version: pkg.version, licence: pkg.licence, textdomain: pkg.name }, js: { files: [ 'develop/vendor/vendor.js', 'develop/js/responsive-menu.js', 'develop/js/main.js' ] }, server: { url: 'craigsimpson.dev' } }); toolkit.extendTasks(gulp, { // Task Name. console: [ ['build'], function () { console.log("This is an extended task. It depends on `build`") } ] });
Allow passing in a custom directory.
var exec = require('child_process').exec function _command (cmd, dir, cb) { if (typeof dir === 'function') cb = dir, dir = __dirname exec(cmd, { cwd: dir }, function (err, stdout, stderr) { cb(stdout.split('\n').join('')) }) } module.exports = { short : function (cb) { _command('git rev-parse --short HEAD', cb) } , long : function (cb) { _command('git rev-parse HEAD', cb) } , branch : function (cb) { _command('git rev-parse --abbrev-ref HEAD', cb) } , tag : function (cb) { _command('git describe --always --tag --abbrev=0', cb) } , log : function (cb) { _command('git log --no-color --pretty=format:\'[ "%H", "%s", "%cr", "%an" ],\' --abbrev-commit', function (str) { str = str.substr(0, str.length-1) cb(JSON.parse('[' + str + ']')) }) } }
var exec = require('child_process').exec function _command (cmd, cb) { exec(cmd, { cwd: __dirname }, function (err, stdout, stderr) { cb(stdout.split('\n').join('')) }) } module.exports = { short : function (cb) { _command('git rev-parse --short HEAD', cb) } , long : function (cb) { _command('git rev-parse HEAD', cb) } , branch : function (cb) { _command('git rev-parse --abbrev-ref HEAD', cb) } , tag : function (cb) { _command('git describe --always --tag --abbrev=0', cb) } , log : function (cb) { _command('git log --no-color --pretty=format:\'[ "%H", "%s", "%cr", "%an" ],\' --abbrev-commit', function (str) { str = str.substr(0, str.length-1) cb(JSON.parse('[' + str + ']')) }) } }
Remove unused jQuery width size code Now, the textarea size is managed with CSS (no jQuery code anymore for that!)
<?php /** * Changes made by Pierre-Henry Soria. */ // JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl namespace PFBC\Element; class Textarea extends \PFBC\Element { /** @var array */ protected $attributes = array('class' => 'pfbc-textarea'); public function render() { $iLength = !empty($this->attributes['value']) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : 0; echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>'; if (!empty($this->attributes['value'])) { echo $this->filter($this->attributes['value']); } echo '</textarea><p><span id="', $this->attributes['id'], '_rem_len">' . $iLength . '</span> ', t('character(s).'), '</p>'; } }
<?php /** * Changes made by Pierre-Henry Soria. */ // JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl namespace PFBC\Element; class Textarea extends \PFBC\Element { /** @var array */ protected $attributes = array('class' => 'pfbc-textarea'); public function jQueryDocumentReady() { echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());'; } public function render() { $iLength = !empty($this->attributes['value']) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : 0; echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>'; if (!empty($this->attributes['value'])) { echo $this->filter($this->attributes['value']); } echo '</textarea><p><span id="', $this->attributes['id'], '_rem_len">' . $iLength . '</span> ', t('character(s).'), '</p>'; } }
Switch to new pliers plugin interface
var fs = require('fs') , request = require('request') module.exports = function (pliers) { return function (done) { fs.createReadStream('./npm-shrinkwrap.json').pipe( request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) { if (error) done(new Error('Problem contacting nodesecurity.io web service')) if (JSON.parse(res.body).length !== 0) { pliers.logger.error('NPM packages with security warnings found') JSON.parse(res.body).forEach(function (module) { pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version , 'https://nodesecurity.io/advisories/' + module.advisory.url) }) } })) } }
var fs = require('fs') , request = require('request') module.exports = function (pliers, name) { pliers(name || 'npmSecurityCheck', function (done) { fs.createReadStream('./npm-shrinkwrap.json').pipe( request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) { if (error) done(new Error('Problem contacting nodesecurity.io web service')) if (JSON.parse(res.body).length !== 0) { pliers.logger.error('NPM packages with security warnings found') JSON.parse(res.body).forEach(function (module) { pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version , 'https://nodesecurity.io/advisories/' + module.advisory.url) }) } })) }) }
Allow child classes to obtain db
package ru.ydn.wicket.wicketorientdb; import org.apache.wicket.Application; import org.apache.wicket.IApplicationListener; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; public abstract class AbstractDataInstallator implements IApplicationListener { @Override public void onAfterInitialized(Application application) { OrientDbWebApplication app = (OrientDbWebApplication)application; ODatabaseRecord db = getDatabase(app); db.begin(); try { installData(app, db); db.commit(); } catch(Exception ex) { db.rollback(); } finally { db.close(); } } protected ODatabaseRecord getDatabase(OrientDbWebApplication app) { IOrientDbSettings settings = app.getOrientDbSettings(); String username = settings.getDBInstallatorUserName(); String password = settings.getDBInstallatorUserPassword(); return DefaultODatabaseThreadLocalFactory.castToODatabaseRecord(settings.getDatabasePool().acquire(settings.getDBUrl(), username, password)); } protected abstract void installData(OrientDbWebApplication app, ODatabaseRecord db); @Override public void onBeforeDestroyed(Application application) { } }
package ru.ydn.wicket.wicketorientdb; import org.apache.wicket.Application; import org.apache.wicket.IApplicationListener; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; public abstract class AbstractDataInstallator implements IApplicationListener { @Override public void onAfterInitialized(Application application) { OrientDbWebApplication app = (OrientDbWebApplication)application; IOrientDbSettings settings = app.getOrientDbSettings(); String username = settings.getDBInstallatorUserName(); String password = settings.getDBInstallatorUserPassword(); ODatabaseRecord db = DefaultODatabaseThreadLocalFactory.castToODatabaseRecord(settings.getDatabasePool().acquire(settings.getDBUrl(), username, password)); db.begin(); try { installData(db); db.commit(); } catch(Exception ex) { db.rollback(); } finally { db.close(); } } protected abstract void installData(ODatabaseRecord db); @Override public void onBeforeDestroyed(Application application) { } }
Change check_db connection resize step to wait database start process
# -*- coding: utf-8 -*- import logging from ...util.base import BaseStep LOG = logging.getLogger(__name__) class CheckDatabaseStatus(BaseStep): def __unicode__(self): return "Checking database status..." def do(self, workflow_dict): try: if not 'database' in workflow_dict: return False if not 'databaseinfra' in workflow_dict: workflow_dict['databaseinfra'] = workflow_dict['database'].databaseinfra LOG.info("Getting driver class") driver = workflow_dict['databaseinfra'].get_driver() from time import sleep sleep(60) if driver.check_status(): LOG.info("Database is ok...") workflow_dict['database'].status=1 workflow_dict['database'].save() return True return False except Exception,e: LOG.info("Error: {}".format(e)) pass def undo(self, workflow_dict): LOG.info("Nothing to do here...") return True
# -*- coding: utf-8 -*- import logging from ...util.base import BaseStep LOG = logging.getLogger(__name__) class CheckDatabaseStatus(BaseStep): def __unicode__(self): return "Checking database status..." def do(self, workflow_dict): try: if not 'database' in workflow_dict: return False if not 'databaseinfra' in workflow_dict: workflow_dict['databaseinfra'] = workflow_dict['database'].databaseinfra LOG.info("Getting driver class") driver = workflow_dict['databaseinfra'].get_driver() if driver.check_status(): LOG.info("Database is ok...") workflow_dict['database'].status=1 workflow_dict['database'].save() return True return False except Exception,e: LOG.info("Error: {}".format(e)) pass def undo(self, workflow_dict): LOG.info("Nothing to do here...") return True
Fix read stencilset.json gibberish when in other languages
/* 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.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream, "utf-8"); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } }
/* 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.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } }
Change awkward Korean seconds, week text.
/* @flow */ import type {L10nsStrings} from '../formatters/buildFormatter' // Korean const strings: L10nsStrings = { prefixAgo: null, refixFromNow: null, suffixAgo: '์ „', suffixFromNow: 'ํ›„', seconds: '๋ฐฉ๊ธˆ', minute: '์•ฝ 1๋ถ„', minutes: '%d๋ถ„', hour: '์•ฝ 1์‹œ๊ฐ„', hours: '์•ฝ %d์‹œ๊ฐ„', day: 'ํ•˜๋ฃจ', days: '%d์ผ', week: '์•ฝ 1์ฃผ', weeks: '%d์ฃผ', month: '์•ฝ 1๊ฐœ์›”', months: '%d๊ฐœ์›”', year: '์•ฝ 1๋…„', years: '%d๋…„', wordSeparator: ' ', numbers: [] } export default strings
/* @flow */ import type {L10nsStrings} from '../formatters/buildFormatter' // Korean const strings: L10nsStrings = { prefixAgo: null, refixFromNow: null, suffixAgo: '์ „', suffixFromNow: 'ํ›„', seconds: '1๋ถ„', minute: '์•ฝ 1๋ถ„', minutes: '%d๋ถ„', hour: '์•ฝ 1์‹œ๊ฐ„', hours: '์•ฝ %d์‹œ๊ฐ„', day: 'ํ•˜๋ฃจ', days: '%d์ผ', week: '์ฃผ', weeks: '%d์ฃผ', month: '์•ฝ 1๊ฐœ์›”', months: '%d๊ฐœ์›”', year: '์•ฝ 1๋…„', years: '%d๋…„', wordSeparator: ' ', numbers: [] } export default strings
Fix update behavior removing shouldComponentUpdate The should component update was not such a good idea as the component did not update when props of other components changed
import React, { Component } from 'react'; import Polyglot from 'node-polyglot'; // Provider root component export default class I18n extends Component { constructor(props) { super(props); this._polyglot = new Polyglot({ locale: props.locale, phrases: props.messages, }); } getChildContext() { return { t: this._polyglot.t.bind(this._polyglot) }; } componentWillReceiveProps(newProps) { if (newProps.locale !== this.props.locale) { this._polyglot = new Polyglot({ locale: newProps.locale, phrases: newProps.messages }) } } render() { const children = this.props.children; return React.Children.only(children); } } I18n.propTypes = { locale: React.PropTypes.string.isRequired, messages: React.PropTypes.object.isRequired, children: React.PropTypes.element.isRequired, }; I18n.childContextTypes = { t: React.PropTypes.func.isRequired, };
import React, { Component } from 'react'; import Polyglot from 'node-polyglot'; // Provider root component export default class I18n extends Component { constructor(props) { super(props); this._polyglot = new Polyglot({ locale: props.locale, phrases: props.messages, }); } getChildContext() { return { t: this._polyglot.t.bind(this._polyglot) }; } componentWillReceiveProps(newProps) { if (newProps.locale !== this.props.locale) { this._polyglot = new Polyglot({ locale: newProps.locale, phrases: newProps.messages }) } } shouldComponentUpdate(nextProps) { return this.props.locale !== nextProps.locale } render() { const children = this.props.children; return React.Children.only(children); } } I18n.propTypes = { locale: React.PropTypes.string.isRequired, messages: React.PropTypes.object.isRequired, children: React.PropTypes.element.isRequired, }; I18n.childContextTypes = { t: React.PropTypes.func.isRequired, };
Modify to average the L2 norm loss of output vectors
from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) / (2.0 * N) loss = loss_sce + l2_reg * l2_loss return loss
from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) loss = loss_sce + l2_reg * l2_loss return loss
Adjust night rainbow theme colors
function NightRainbowTheme () { this.paletteBuilder = new SingleColorPaletteBuilder(new HSL(180, 60, 30)); } NightRainbowTheme.prototype.colors = [ new HSL(0, 100, 77), new HSL(25, 100, 64), new HSL(57, 100, 37), new HSL(150, 100, 43), new HSL(200, 100, 60), new HSL(252, 100, 80), new HSL(290, 100, 77) ]; NightRainbowTheme.prototype.numberColor = '#202030'; NightRainbowTheme.prototype.defaultBackgroundColor = '#202030'; NightRainbowTheme.prototype.textColor = '#000000'; NightRainbowTheme.prototype.textBackground = '#FFFFFF'; NightRainbowTheme.prototype.sliderColor = '#FFFFFF'; NightRainbowTheme.prototype.changesDocumentTextColor = true; NightRainbowTheme.prototype.getLevelPalette = function (level) { var numberColor = this.colors[(level - 1) % 7]; var boardColors = this.paletteBuilder.build(16); return new LevelPalette(numberColor, boardColors); };
function NightRainbowTheme () { this.paletteBuilder = new SingleColorPaletteBuilder(new HSL(180, 60, 29)); } NightRainbowTheme.prototype.colors = [ new HSL(0, 100, 84), new HSL(25, 100, 72), new HSL(55, 100, 43), new HSL(150, 100, 50), new HSL(200, 100, 70), new HSL(252, 100, 86), new HSL(290, 100, 82) ]; NightRainbowTheme.prototype.numberColor = '#202030'; NightRainbowTheme.prototype.defaultBackgroundColor = '#202030'; NightRainbowTheme.prototype.textColor = '#000000'; NightRainbowTheme.prototype.textBackground = '#FFFFFF'; NightRainbowTheme.prototype.sliderColor = '#FFFFFF'; NightRainbowTheme.prototype.changesDocumentTextColor = true; NightRainbowTheme.prototype.getLevelPalette = function (level) { var numberColor = this.colors[(level - 1) % 7]; var boardColors = this.paletteBuilder.build(16); return new LevelPalette(numberColor, boardColors); };
Add boardsMenu reducer to the store
import { reducer as formReducer } from 'redux-form'; import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import { organization, starredBoard, notification, modals, board, home } from '../app/routes/home/modules/index'; import { signUp } from '../app/routes/signUp/modules/index'; import { login } from '../app/routes/login/modules/index'; import { boardsMenu, popOver, app } from '../app/modules/index'; import { boardView, card } from '../app/routes/home/routes/boardView/modules/index'; const rootReducer = combineReducers({ organization, starredBoard, notification, modals, board, home, signUp, login, boardsMenu, popOver, app, boardView, card, form: formReducer, routing: routerReducer }) export default rootReducer;
import { reducer as formReducer } from 'redux-form'; import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import { organization, starredBoard, notification, modals, board, home } from '../app/routes/home/modules/index'; import { signUp } from '../app/routes/signUp/modules/index'; import { login } from '../app/routes/login/modules/index'; import { popOver, app } from '../app/modules/index'; import { boardView, card } from '../app/routes/home/routes/boardView/modules/index'; const rootReducer = combineReducers({ organization, starredBoard, notification, modals, board, home, signUp, login, popOver, app, boardView, card, form: formReducer, routing: routerReducer }) export default rootReducer;
Remove unnecessary client alias in AvailabilityZoneTestJson The class AvailabilityZoneTestJson is inherited from base.BaseVolumeTest, and the latter has already declared the availability_zone_client. This patch removes the unnecessary client alias for availability_zone_client. Change-Id: I287d742087a72928774325681bb70837ecad72f7
# Copyright 2014 NEC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.lib import decorators class AvailabilityZoneTestJSON(base.BaseVolumeTest): """Tests Availability Zone API List""" @decorators.idempotent_id('01f1ae88-eba9-4c6b-a011-6f7ace06b725') def test_get_availability_zone_list(self): # List of availability zone availability_zone = ( self.availability_zone_client.list_availability_zones() ['availabilityZoneInfo']) self.assertNotEmpty(availability_zone)
# Copyright 2014 NEC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.volume import base from tempest.lib import decorators class AvailabilityZoneTestJSON(base.BaseVolumeTest): """Tests Availability Zone API List""" @classmethod def setup_clients(cls): super(AvailabilityZoneTestJSON, cls).setup_clients() cls.client = cls.availability_zone_client @decorators.idempotent_id('01f1ae88-eba9-4c6b-a011-6f7ace06b725') def test_get_availability_zone_list(self): # List of availability zone availability_zone = (self.client.list_availability_zones() ['availabilityZoneInfo']) self.assertNotEmpty(availability_zone)
Add import statements breaking linter
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5