text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Optimize package for dev and prod
import webpack from 'webpack' import path from 'path' const production = process.env.NODE_ENV === 'production' module.exports = { devtool: 'cheap-module-source-map', watch: !production, module: { noParse: ['ws'], loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loaders: [ 'babel?presets[]=react,presets[]=es2015,presets[]=stage-0', ], // 'babel-loader' is also a legal name to reference }, { test: /\.json$/, exclude: /(node_modules|bower_components)/, loader: 'json', }, ], }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, entry: { bot: ['babel-polyfill', path.join(__dirname, 'src', 'botPage')], index: path.join(__dirname, 'src', 'indexPage'), }, externals: ['ws'], output: { filename: production ? '[name].min.js' : '[name].js', sourceMapFilename: production ? '[name].min.js.map' : '[name].js.map', }, plugins: production && [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.UglifyJsPlugin({ include: /\.js$/, minimize: true, sourceMap: true, compress: { warnings: false, }, }), ], }
import webpack from 'webpack'; import path from 'path'; const production = process.env.NODE_ENV === 'production'; module.exports = { devtool: 'source-map', watch: !production, module: { noParse: ['ws'], loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loaders: [ 'babel?presets[]=react,presets[]=es2015,presets[]=stage-0', ], // 'babel-loader' is also a legal name to reference }, { test: /\.json$/, exclude: /(node_modules|bower_components)/, loader: 'json', }, ], }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, entry: { bot: ['babel-polyfill', path.join(__dirname, 'src', 'botPage')], index: path.join(__dirname, 'src', 'indexPage'), }, externals: ['ws'], output: { filename: production ? '[name].min.js' : '[name].js', sourceMapFilename: production ? '[name].min.js.map' : '[name].js.map', }, plugins: production && [ new webpack.optimize.UglifyJsPlugin({ include: /\.js$/, minimize: true, sourceMap: true, compress: { warnings: false, }, }), ], };
Allow multiple SSH keys per file
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import sys from . import util class SSHKey(object): @staticmethod def rebuild_authorized_keys(): lines = [] ssh_dir = os.path.expanduser('~/.ssh') util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d')) for name in os.listdir(os.path.join(ssh_dir, 'authorized_keys.d')): keyfilename = os.path.join(ssh_dir, 'authorized_keys.d', name) with open(keyfilename) as keyfile: for key in keyfile: keyparts = key.split() assert keyparts[0].startswith('ssh-') key = ' '.join(keyparts[:2]) name = name.replace('.pub', '') lines.append( ('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' + 'no-agent-forwarding,no-user-rc,no-X11-forwarding,' + 'no-port-forwarding {key} {name}').format( pypaas_cmd=os.path.join( os.path.dirname(sys.executable), 'pypaas' ), key=key, name=name ) ) util.replace_file(os.path.join(ssh_dir, 'authorized_keys'), '\n'.join(lines)+'\n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import sys from . import util class SSHKey(object): @staticmethod def rebuild_authorized_keys(): lines = [] ssh_dir = os.path.expanduser('~/.ssh') util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d')) for name in os.listdir(os.path.join(ssh_dir, 'authorized_keys.d')): key = open(os.path.join(ssh_dir, 'authorized_keys.d', name)).read() keyparts = key.split() assert keyparts[0].startswith('ssh-') key = ' '.join(keyparts[:2]) name = name.replace('.pub', '') lines.append( ('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' + 'no-agent-forwarding,no-user-rc,no-X11-forwarding,' + 'no-port-forwarding {key} {name}').format( pypaas_cmd=os.path.join( os.path.dirname(sys.executable), 'pypaas' ), key=key, name=name ) ) util.replace_file(os.path.join(ssh_dir, 'authorized_keys'), '\n'.join(lines)+'\n')
Disable flake8 warning on `__version__` import
from trakt.core.errors import ERRORS from trakt.core.exceptions import RequestError, ClientError, ServerError from trakt.client import TraktClient from trakt.helpers import has_attribute from trakt.version import __version__ # NOQA from six import add_metaclass __all__ = [ 'Trakt', 'RequestError', 'ClientError', 'ServerError', 'ERRORS' ] class TraktMeta(type): def __getattr__(self, name): if has_attribute(self, name): return super(TraktMeta, self).__getattribute__(name) if self.client is None: self.construct() return getattr(self.client, name) def __setattr__(self, name, value): if has_attribute(self, name): return super(TraktMeta, self).__setattr__(name, value) if self.client is None: self.construct() setattr(self.client, name, value) def __getitem__(self, key): if self.client is None: self.construct() return self.client[key] @add_metaclass(TraktMeta) class Trakt(object): client = None @classmethod def construct(cls): cls.client = TraktClient() # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
from trakt.core.errors import ERRORS from trakt.core.exceptions import RequestError, ClientError, ServerError from trakt.client import TraktClient from trakt.helpers import has_attribute from trakt.version import __version__ from six import add_metaclass __all__ = [ 'Trakt', 'RequestError', 'ClientError', 'ServerError', 'ERRORS' ] class TraktMeta(type): def __getattr__(self, name): if has_attribute(self, name): return super(TraktMeta, self).__getattribute__(name) if self.client is None: self.construct() return getattr(self.client, name) def __setattr__(self, name, value): if has_attribute(self, name): return super(TraktMeta, self).__setattr__(name, value) if self.client is None: self.construct() setattr(self.client, name, value) def __getitem__(self, key): if self.client is None: self.construct() return self.client[key] @add_metaclass(TraktMeta) class Trakt(object): client = None @classmethod def construct(cls): cls.client = TraktClient() # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
Add @xstate/vue to publishable packages
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = [ 'xstate', '@xstate/fsm', '@xstate/test', '@xstate/vue' ]; (async () => { const currentBranchName = (await execWithOutput('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ])).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = (await execWithOutput('git', [ 'log', '-1', '--pretty=%B' ])).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = ['xstate', '@xstate/fsm', '@xstate/test']; (async () => { const currentBranchName = (await execWithOutput('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ])).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = (await execWithOutput('git', [ 'log', '-1', '--pretty=%B' ])).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
Disable union wrap for clickhouse
from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE, wrap_union_queries=False)
from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE)
Add missing file from merge
package com.moac.android.opensecretsanta.util; import com.moac.android.opensecretsanta.database.DatabaseManager; import com.moac.android.opensecretsanta.model.ContactMethod; import com.moac.android.opensecretsanta.model.Member; import java.util.List; public class NotifyUtils { public static boolean containsSendableEntry(List<Member> _members) { for(Member member : _members) { if(member.getContactMethod().isSendable()) { return true; } } return false; } public static boolean containsEmailSendableEntry(List<Member> _members) { for(Member member : _members) { if(member.getContactMethod() == ContactMethod.EMAIL) { return true; } } return false; } public static boolean containsEmailSendableEntry(DatabaseManager db, long[] _memberIds) { for(long id : _memberIds) { Member member = db.queryById(id, Member.class); if(member.getContactMethod() == ContactMethod.EMAIL) { return true; } } return false; } private boolean isSendable(Member member) { return (member != null && member.getContactMethod() != null) && member.getContactMethod().isSendable(); } public static int getShareableCount(List<Member> _members) { int count = 0; for(Member member : _members) { if(member.getContactMethod().isSendable()) { count++; } } return count; } }
package com.moac.android.opensecretsanta.util; import com.moac.android.opensecretsanta.database.DatabaseManager; import com.moac.android.opensecretsanta.model.ContactMode; import com.moac.android.opensecretsanta.model.Member; import java.util.List; public class NotifyUtils { public static boolean containsSendableEntry(List<Member> _members) { for(Member member : _members) { if(member.getContactMode().isSendable()) { return true; } } return false; } public static boolean containsEmailSendableEntry(List<Member> _members) { for(Member member : _members) { if(member.getContactMode() == ContactMode.EMAIL) { return true; } } return false; } public static boolean containsEmailSendableEntry(DatabaseManager db, long[] _memberIds) { for(long id : _memberIds) { Member member = db.queryById(id, Member.class); if(member.getContactMode() == ContactMode.EMAIL) { return true; } } return false; } private boolean isSendable(Member member) { return (member != null && member.getContactMode() != null) && member.getContactMode().isSendable(); } public static int getShareableCount(List<Member> _members) { int count = 0; for(Member member : _members) { if(member.getContactMode().isSendable()) { count++; } } return count; } }
Fix name of parameter `disabledCategories`
# -*- coding: utf-8 -*- import requests def get_languages(api_url): r = requests.get(api_url + "languages") return r.json() def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None, enabled_rules=None, disabled_rules=None, enabled_categories=None, disabled_categories=None, enabled_only=False, verbose=False, **kwargs): post_parameters = { "text": input_text, "language": lang, } if mother_tongue: post_parameters["motherTongue"] = mother_tongue if preferred_variants: post_parameters["preferredVariants"] = preferred_variants if enabled_rules: post_parameters["enabledRules"] = enabled_rules if disabled_rules: post_parameters["disabledRules"] = disabled_rules if enabled_categories: post_parameters["enabledCategories"] = enabled_categories if disabled_categories: post_parameters["disabledCategories"] = disabled_categories if enabled_only: post_parameters["enabledOnly"] = True r = requests.post(api_url + "check", data=post_parameters) if r.status_code != 200: raise ValueError(r.text) if verbose: print(post_parameters) print(r.json()) return r.json()
# -*- coding: utf-8 -*- import requests def get_languages(api_url): r = requests.get(api_url + "languages") return r.json() def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None, enabled_rules=None, disabled_rules=None, enabled_categories=None, disabled_categories=None, enabled_only=False, verbose=False, **kwargs): post_parameters = { "text": input_text, "language": lang, } if mother_tongue: post_parameters["motherTongue"] = mother_tongue if preferred_variants: post_parameters["preferredVariants"] = preferred_variants if enabled_rules: post_parameters["enabledRules"] = enabled_rules if disabled_rules: post_parameters["disabledRules"] = disabled_rules if enabled_categories: post_parameters["enabledCategories"] = enabled_categories if disabled_categories: post_parameters["enabledCategories"] = disabled_categories if enabled_only: post_parameters["enabledOnly"] = True r = requests.post(api_url + "check", data=post_parameters) if r.status_code != 200: raise ValueError(r.text) if verbose: print(post_parameters) print(r.json()) return r.json()
Fix C++ accelerator constructor invocation
import numpy as np import pandas as pd from typing import Tuple, List from queryexpander.semantic_similarity import CppSemanticSimilarity class QueryExpander: def __init__(self, vocabulary_path: str, vocabulary_length: int, sums_cache_file: str, centroids_file_path: str): self._words: List[str] = pd.read_csv( vocabulary_path, sep=' ', quoting=3, header=None, usecols=(0,), na_filter=False).values.squeeze().tolist() self._vectors: np.ndarray = pd.read_csv(vocabulary_path, sep=' ', quoting=3, header=None, usecols=range(1, vocabulary_length + 1), na_filter=False, dtype=np.float32).values self._similarity = CppSemanticSimilarity(self._words, self._vectors, sums_cache_file, centroids_file_path) def generate_sums_cache(self): self._similarity.generate_sums_cache() def generate_local_centroids(self, centroids_neighbourhood_size: int): self._similarity.generate_local_centroids(centroids_neighbourhood_size) def find_most_similar_words(self, query: List[str], number_of_results: int) -> List[Tuple[str, float]]: return self._similarity.find_most_similar_words(query, number_of_results)
import numpy as np import pandas as pd from typing import Tuple, List from queryexpander.semantic_similarity import CppSemanticSimilarity class QueryExpander: def __init__(self, vocabulary_path: str, vocabulary_length: int, sums_cache_file: str, centroids_file_path: str): self._words: List[str] = pd.read_csv( vocabulary_path, sep=' ', quoting=3, header=None, usecols=(0,), na_filter=False).values.squeeze().tolist() self._vectors: np.ndarray = pd.read_csv(vocabulary_path, sep=' ', quoting=3, header=None, usecols=range(1, vocabulary_length + 1), na_filter=False, dtype=np.float32).values self._similarity = CppSemanticSimilarity(self._words, self._vectors, sums_cache_file) def generate_sums_cache(self): self._similarity.generate_sums_cache() def generate_local_centroids(self, centroids_neighbourhood_size: int): self._similarity.generate_local_centroids(centroids_neighbourhood_size) def find_most_similar_words(self, query: List[str], number_of_results: int) -> List[Tuple[str, float]]: return self._similarity.find_most_similar_words(query, number_of_results)
Fix typo in log message
'use strict'; const winston = require('winston'); const Twitter = require('twitter'); const cache = require('./cache'); const parse = require('./parse'); const uniq = require('uniq'); const searchTerm = 't.d3fc.io'; const client = new Twitter({ consumer_key: process.env.consumer_key, consumer_secret: process.env.consumer_secret, access_token_key: process.env.access_token_key, access_token_secret: process.env.access_token_secret }); module.exports = () => { winston.info('Updating search results'); client.get( 'search/tweets', { q: searchTerm, count: 100 }, (error, tweets, response) => { if (error) { return winston.warn(error); } winston.info('Search completed', tweets.statuses.length); const statuses = tweets.statuses .filter((status) => !status.retweeted_status) .map(parse); const validStatuses = statuses.filter((status) => status.es5); winston.info('Valid statuses', validStatuses.length); const existingStatuses = cache.statuses(); winston.info('Existing statuses', existingStatuses.length); const mergedStatuses = uniq( existingStatuses ? validStatuses.concat(cache.statuses()) : validStatuses, (a, b) => b.id_str.localeCompare(a.id_str) ); cache.statuses(mergedStatuses); winston.info('Merged statuses', mergedStatuses.length); } ); };
'use strict'; const winston = require('winston'); const Twitter = require('twitter'); const cache = require('./cache'); const parse = require('./parse'); const uniq = require('uniq'); const searchTerm = 't.d3fc.io'; const client = new Twitter({ consumer_key: process.env.consumer_key, consumer_secret: process.env.consumer_secret, access_token_key: process.env.access_token_key, access_token_secret: process.env.access_token_secret }); module.exports = () => { winston.info('Updating search results'); client.get( 'search/tweets', { q: searchTerm, count: 100 }, (error, tweets, response) => { if (error) { return winston.warn(error); } winston.info('Search completed', tweets.statuses.length); const statuses = tweets.statuses .filter((status) => !status.retweeted_status) .map(parse); const validStatuses = statuses.filter((status) => status.es5); winston.info('Valid statuses', validStatuses.length); const existingStatuses = cache.statuses(); winston.info('Existing statuses', validStatuses.length); const mergedStatuses = uniq( existingStatuses ? validStatuses.concat(cache.statuses()) : validStatuses, (a, b) => b.id_str.localeCompare(a.id_str) ); cache.statuses(mergedStatuses); winston.info('Merged statuses', mergedStatuses.length); } ); };
Allow delete operation in NEW state - nc-1148
from __future__ import unicode_literals from rest_framework import mixins from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates from nodeconductor.core.exceptions import IncorrectStateException class ListModelMixin(mixins.ListModelMixin): def __init__(self, *args, **kwargs): import warnings warnings.warn( "nodeconductor.core.mixins.ListModelMixin is deprecated. " "Use stock rest_framework.mixins.ListModelMixin instead.", DeprecationWarning, ) super(ListModelMixin, self).__init__(*args, **kwargs) class UpdateOnlyStableMixin(object): """ Allow modification of entities in stable state only. """ def initial(self, request, *args, **kwargs): acceptable_states = { 'update': SynchronizationStates.STABLE_STATES, 'partial_update': SynchronizationStates.STABLE_STATES, 'destroy': SynchronizationStates.STABLE_STATES | {SynchronizationStates.NEW}, } if self.action in acceptable_states.keys(): obj = self.get_object() if obj and isinstance(obj, SynchronizableMixin): if obj.state not in acceptable_states[self.action]: raise IncorrectStateException( 'Modification allowed in stable states only.') return super(UpdateOnlyStableMixin, self).initial(request, *args, **kwargs) class UserContextMixin(object): """ Pass current user to serializer context """ def get_serializer_context(self): context = super(UserContextMixin, self).get_serializer_context() context['user'] = self.request.user return context
from __future__ import unicode_literals from rest_framework import mixins from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates from nodeconductor.core.exceptions import IncorrectStateException class ListModelMixin(mixins.ListModelMixin): def __init__(self, *args, **kwargs): import warnings warnings.warn( "nodeconductor.core.mixins.ListModelMixin is deprecated. " "Use stock rest_framework.mixins.ListModelMixin instead.", DeprecationWarning, ) super(ListModelMixin, self).__init__(*args, **kwargs) class UpdateOnlyStableMixin(object): """ Allow modification of entities in stable state only. """ def initial(self, request, *args, **kwargs): if self.action in ('update', 'partial_update', 'destroy'): obj = self.get_object() if obj and isinstance(obj, SynchronizableMixin): if obj.state not in SynchronizationStates.STABLE_STATES: raise IncorrectStateException( 'Modification allowed in stable states only.') return super(UpdateOnlyStableMixin, self).initial(request, *args, **kwargs) class UserContextMixin(object): """ Pass current user to serializer context """ def get_serializer_context(self): context = super(UserContextMixin, self).get_serializer_context() context['user'] = self.request.user return context
Add environment output on application boot.
(function () { 'use strict'; // Initialise RequireJS module loader require.config({ urlArgs: 'm=' + (new Date()).getTime(), baseUrl: '/app/', paths: { // RequireJS extensions text: '../lib/text/text', // Vendor libraries knockout: '../lib/knockout/dist/knockout.debug', lodash: '../lib/lodash/lodash', jquery: '../lib/jquery/dist/jquery', bootstrap: '../lib/bootstrap/dist/js/bootstrap', typeahead: '../lib/typeahead.js/dist/typeahead.jquery', bloodhound: '../lib/typeahead.js/dist/bloodhound', page: '../lib/page/page', // Application modules config: 'config/', models: 'models/', services: 'services/', ui: 'ui/', util: 'util/' }, shim: { bloodhound: { exports: 'Bloodhound' }, typeahead: { deps: [ 'jquery' ] } } }); // Boot the application require([ 'jquery' ], function () { require([ 'bootstrap' ], function () { require([ 'util/router' ], function (router) { var environment = 'development'; if (environment !== 'production') { console.log('Running in "' + environment + '" environment'); } router(); }); }); }); }());
(function () { 'use strict'; // Initialise RequireJS module loader require.config({ urlArgs: 'm=' + (new Date()).getTime(), baseUrl: '/app/', paths: { // RequireJS extensions text: '../lib/text/text', // Vendor libraries knockout: '../lib/knockout/dist/knockout.debug', lodash: '../lib/lodash/lodash', jquery: '../lib/jquery/dist/jquery', bootstrap: '../lib/bootstrap/dist/js/bootstrap', typeahead: '../lib/typeahead.js/dist/typeahead.jquery', bloodhound: '../lib/typeahead.js/dist/bloodhound', page: '../lib/page/page', // Application modules config: 'config/', models: 'models/', services: 'services/', ui: 'ui/', util: 'util/' }, shim: { bloodhound: { exports: 'Bloodhound' }, typeahead: { deps: [ 'jquery' ] } } }); // Boot the application require([ 'jquery' ], function () { require([ 'bootstrap' ], function () { require([ 'util/router' ], function (router) { router(); }); }); }); }());
Add some basic error handling
import { ReactiveVar } from 'meteor/reactive-var'; export class Result { constructor({ observer, defaultValue = {} } = {}) { this.observer = observer; this._isReady = new ReactiveVar(false); this._errors = new ReactiveVar(); this._var = new ReactiveVar(defaultValue); this.subscribe(); } isReady() { return this._isReady.get(); } get() { return this._var.get(); } getErrors() { return this._errors.get(); } unsubscribe() { return this._subscription && this._subscription.unsubscribe(); } subscribe() { if (this._subscription) { this.unsubscribe(); } this._subscription = this.observer.subscribe({ next: ({ errors, data }) => { if (errors) { this._errors.set(errors); } else { this._errors.set(null); this._var.set(data); } this._isReady.set(true); }, error: (error) => { this._errors.set([].concat(error)); this._isReady.set(true); } }); } }
import { ReactiveVar } from 'meteor/reactive-var'; export class Result { constructor({ observer, defaultValue = {} } = {}) { this.observer = observer; this._isReady = new ReactiveVar(false); this._errors = new ReactiveVar(); this._var = new ReactiveVar(defaultValue); this.subscribe(); } isReady() { return this._isReady.get(); } get() { return this._var.get(); } getErrors() { return this._errors.get(); } unsubscribe() { return this._subscription && this._subscription.unsubscribe(); } subscribe() { if (this._subscription) { this.unsubscribe(); } this._subscription = this.observer.subscribe({ next: ({ errors, data }) => { if (errors) { this._errors.set(errors); } else { this._errors.set(null); this._var.set(data); } this._isReady.set(true); } }); } }
Fix 'You must call one of in() or append() methods before iterating over a Finder.'
<?php namespace Tienvx\Bundle\MbtBundle; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Finder\Finder; use Symfony\Component\HttpKernel\Bundle\Bundle; use Tienvx\Bundle\MbtBundle\DependencyInjection\Compiler\AddGeneratorDirectoriesCompilerPass; class TienvxMbtBundle extends Bundle { public function build(ContainerBuilder $container) { $container->addCompilerPass(new AddGeneratorDirectoriesCompilerPass()); // Read models configurations. Add these code in a compiler pass is too late. $paths = []; foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) { $path = $bundle['path'] . '/Resources/config/models'; if (is_dir($path)) { $paths[] = $path; } } $path = $container->getParameter('kernel.root_dir') . '/config/models'; if (is_dir($path)) { $paths[] = $path; } if ($paths) { $loader = new YamlFileLoader($container, new FileLocator($paths)); foreach (Finder::create()->followLinks()->files()->in($paths)->name('/\.(ya?ml)$/') as $file) { $loader->load($file->getRelativePathname()); } } } }
<?php namespace Tienvx\Bundle\MbtBundle; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Finder\Finder; use Symfony\Component\HttpKernel\Bundle\Bundle; use Tienvx\Bundle\MbtBundle\DependencyInjection\Compiler\AddGeneratorDirectoriesCompilerPass; class TienvxMbtBundle extends Bundle { public function build(ContainerBuilder $container) { $container->addCompilerPass(new AddGeneratorDirectoriesCompilerPass()); // Read models configurations. Add these code in a compiler pass is too late. $paths = []; foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) { $path = $bundle['path'] . '/Resources/config/models'; if (is_dir($path)) { $paths[] = $path; } } $path = $container->getParameter('kernel.root_dir') . '/config/models'; if (is_dir($path)) { $paths[] = $path; } $loader = new YamlFileLoader($container, new FileLocator($paths)); foreach (Finder::create()->followLinks()->files()->in($paths)->name('/\.(ya?ml)$/') as $file) { $loader->load($file->getRelativePathname()); } } }
Update path and file references
<?php /** * @file * Contains \Drupal\AppConsole\Generator\PluginBlockGenerator. */ namespace Drupal\AppConsole\Generator; class PluginRulesActionGenerator extends Generator { /** * Generator Plugin RulesAction * @param $module * @param $class_name * @param $label * @param $plugin_id * @param $category * @param $context */ public function generate($module, $class_name, $label, $plugin_id, $category, $context, $type) { $parameters = [ 'module' => $module, 'class_name' => $class_name, 'label' => $label, 'plugin_id' => $plugin_id, 'category' => $category, 'context' => $context, 'type' => $type ]; $this->renderFile( 'module/src/Plugin/Action/rulesaction.php.twig', $this->getPluginPath($module, 'Action') . '/' . $class_name . '.php', $parameters ); $this->renderFile( 'module/system.action.action.yml.twig', $this->getModulePath($module) . '/config/install/system.action.' . $plugin_id .'.yml', $parameters ); } }
<?php /** * @file * Contains \Drupal\AppConsole\Generator\PluginBlockGenerator. */ namespace Drupal\AppConsole\Generator; class PluginRulesActionGenerator extends Generator { /** * Generator Plugin RulesAction * @param $module * @param $class_name * @param $label * @param $plugin_id * @param $category * @param $context */ public function generate($module, $class_name, $label, $plugin_id, $category, $context, $type) { $parameters = [ 'module' => $module, 'class_name' => $class_name, 'label' => $label, 'plugin_id' => $plugin_id, 'category' => $category, 'context' => $context, 'type' => $type ]; $this->renderFile( 'module/src/Plugin/RulesAction/rulesaction.php.twig', $this->getPluginPath($module, 'Action') . '/' . $class_name . '.php', $parameters ); $this->renderFile( 'module/system.action.action.yml', $this->getModulePath($module) . '/config/install/system.action.' . $plugin_id .'.yml', $parameters ); } }
Stop using ord with ints
""" Test mujoco viewer. """ import unittest from mujoco_py import mjviewer, mjcore class MjLibTest(unittest.TestCase): xml_path = 'tests/models/cartpole.xml' def setUp(self): self.width = 100 self.height = 100 self.viewer = mjviewer.MjViewer(visible=False, init_width=self.width, init_height=self.height) def tearDown(self): self.viewer.finish() self.viewer = None def test_start(self): self.viewer.start() self.assertTrue(self.viewer.running) def test_render(self): self.viewer.start() model = mjcore.MjModel(self.xml_path) self.viewer.set_model(model) (data, width, height) = self.viewer.get_image() # check image size is consistent # note that width and height may not equal self.width and self.height # e.g. on a computer with retina screen, # the width and height are scaled self.assertEqual(len(data), 3 * width * height) # make sure the image is not pitch black self.assertTrue(any(map(lambda x: x > 0, data)))
""" Test mujoco viewer. """ import unittest from mujoco_py import mjviewer, mjcore class MjLibTest(unittest.TestCase): xml_path = 'tests/models/cartpole.xml' def setUp(self): self.width = 100 self.height = 100 self.viewer = mjviewer.MjViewer(visible=False, init_width=self.width, init_height=self.height) def tearDown(self): self.viewer.finish() self.viewer = None def test_start(self): self.viewer.start() self.assertTrue(self.viewer.running) def test_render(self): self.viewer.start() model = mjcore.MjModel(self.xml_path) self.viewer.set_model(model) (data, width, height) = self.viewer.get_image() # check image size is consistent # note that width and height may not equal self.width and self.height # e.g. on a computer with retina screen, # the width and height are scaled self.assertEqual(len(data), 3 * width * height) # make sure the image is not pitch black self.assertTrue(any(map(ord, data)))
Use http scheme to reduce test times
# -*- coding: UTF-8 -*- from geopy.geocoders import Teleport from test.geocoders.util import GeocoderTestBase class TeleportTestCaseUnitTest(GeocoderTestBase): def test_user_agent_custom(self): geocoder = Teleport( user_agent='my_user_agent/1.0' ) self.assertEqual(geocoder.headers['User-Agent'], 'my_user_agent/1.0') class TeleportTestCase(GeocoderTestBase): @classmethod def setUpClass(cls): cls.delta = 0.04 def test_unicode_name(self): """ Teleport.geocode unicode """ # work around ConfigurationError raised in GeoNames init self.geocoder = Teleport(scheme='http') self.geocode_run( {"query": "New York, NY"}, {"latitude": 40.71427, "longitude": -74.00597}, ) def test_reverse(self): """ Teleport.reverse """ # work around ConfigurationError raised in GeoNames init self.geocoder = Teleport(scheme='http') self.reverse_run( {"query": "40.71427, -74.00597"}, {"latitude": 40.71427, "longitude": -74.00597, "address": "New York City, New York, United States"}, )
# -*- coding: UTF-8 -*- from geopy.geocoders import Teleport from test.geocoders.util import GeocoderTestBase class TeleportTestCaseUnitTest(GeocoderTestBase): def test_user_agent_custom(self): geocoder = Teleport( user_agent='my_user_agent/1.0' ) self.assertEqual(geocoder.headers['User-Agent'], 'my_user_agent/1.0') class TeleportTestCase(GeocoderTestBase): @classmethod def setUpClass(cls): cls.delta = 0.04 def test_unicode_name(self): """ Teleport.geocode unicode """ # work around ConfigurationError raised in GeoNames init self.geocoder = Teleport() self.geocode_run( {"query": "New York, NY"}, {"latitude": 40.71427, "longitude": -74.00597}, ) def test_reverse(self): """ Teleport.reverse """ # work around ConfigurationError raised in GeoNames init self.geocoder = Teleport() self.reverse_run( {"query": "40.71427, -74.00597"}, {"latitude": 40.71427, "longitude": -74.00597, "address": "New York City, New York, United States"}, )
Use PHP 8 throw expression
<?php declare(strict_types = 1); /** * /src/Form/DataTransformer/RoleTransformer.php * * @author TLe, Tarmo Leppänen <[email protected]> */ namespace App\Form\DataTransformer; use App\Entity\Role; use App\Resource\RoleResource; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; use Throwable; use function is_string; use function sprintf; /** * Class RoleTransformer * * @package App\Form\Console\DataTransformer * @author TLe, Tarmo Leppänen <[email protected]> */ class RoleTransformer implements DataTransformerInterface { public function __construct( private RoleResource $resource, ) { } /** * {@inheritDoc} * * Transforms an object (Role) to a string (Role id). */ public function transform($value): string { return $value instanceof Role ? $value->getId() : ''; } /** * {@inheritDoc} * * Transforms a string (Role id) to an object (Role). * * @throws Throwable */ public function reverseTransform($value): ?Role { $role = null; if (is_string($value)) { $role = $this->resource->findOne($value, false) ?? throw new TransformationFailedException( sprintf( 'Role with name "%s" does not exist!', $value ), ); } return $role; } }
<?php declare(strict_types = 1); /** * /src/Form/DataTransformer/RoleTransformer.php * * @author TLe, Tarmo Leppänen <[email protected]> */ namespace App\Form\DataTransformer; use App\Entity\Role; use App\Resource\RoleResource; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; use Throwable; use function sprintf; /** * Class RoleTransformer * * @package App\Form\Console\DataTransformer * @author TLe, Tarmo Leppänen <[email protected]> */ class RoleTransformer implements DataTransformerInterface { public function __construct( private RoleResource $resource, ) { } /** * {@inheritDoc} * * Transforms an object (Role) to a string (Role id). */ public function transform($value): string { return $value instanceof Role ? $value->getId() : ''; } /** * {@inheritDoc} * * Transforms a string (Role id) to an object (Role). * * @throws Throwable */ public function reverseTransform($value): ?Role { $role = null; if ($roleName !== null) { $role = $this->resource->findOne((string)$roleName, false); if ($role === null) { throw new TransformationFailedException(sprintf( 'Role with name "%s" does not exist!', (string)$roleName )); } } return $role; } }
Check for null values when setting primitives.
package com.datasift.client.pylon; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; public class PylonParametersData { @JsonProperty @JsonInclude(JsonInclude.Include.NON_EMPTY) protected String interval; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected float span; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected int threshold; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected String target; public PylonParametersData() { } public PylonParametersData(String interval, Float span, Integer threshold, String target) { this.interval = interval; this.target = target; if (span != null) this.span = span; if (threshold != null) this.threshold = threshold; } public Float getSpan() { return this.span; } public Integer getThreshold() { return this.threshold; } public String getTarget() { return this.target; } public void setInterval(String interval) { this.interval = interval; } public void setSpan(Float span) { this.span = span; } public void setThreshold(Integer threshold) { this.threshold = threshold; } public void setTarget(String target) { this.target = target; } }
package com.datasift.client.pylon; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; public class PylonParametersData { @JsonProperty @JsonInclude(JsonInclude.Include.NON_EMPTY) protected String interval; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected float span; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected int threshold; @JsonProperty @JsonInclude(JsonInclude.Include.NON_DEFAULT) protected String target; public PylonParametersData() { } public PylonParametersData(String interval, Float span, Integer threshold, String target) { this.interval = interval; this.span = span; this.threshold = threshold; this.target = target; } public Float getSpan() { return this.span; } public Integer getThreshold() { return this.threshold; } public String getTarget() { return this.target; } public void setInterval(String interval) { this.interval = interval; } public void setSpan(Float span) { this.span = span; } public void setThreshold(Integer threshold) { this.threshold = threshold; } public void setTarget(String target) { this.target = target; } }
Fix refs to body of sconsole
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.body_frame = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body_frame, header=self.header, footer=self.footer) def body(self): dump = urwid.Filler(urwid.Text('', align='left'), valign='top') return urwid.Frame(dump, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.run()
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.body = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body(), header=self.header, footer=self.footer) def body(self): dump = urwid.Filler(urwid.Text('', align='left'), valign='top') return urwid.Frame(dump, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.run()
Remove unnecessary dependency on ordereddict
from setuptools import setup, find_packages import os requires = [ 'Flask==0.9', 'elasticsearch', 'PyJWT==0.1.4', 'iso8601==0.1.4', ] def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name = 'annotator', version = '0.10.0', packages = find_packages(exclude=['test*']), install_requires = requires, extras_require = { 'docs': ['Sphinx'], 'testing': ['nose', 'coverage'], }, # metadata for upload to PyPI author = 'Rufus Pollock and Nick Stenning (Open Knowledge Foundation)', author_email = '[email protected]', description = 'Database backend for the Annotator (http://annotateit.org)', long_description = (read('README.rst') + '\n\n' + read('CHANGES.rst')), license = 'MIT', keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
from setuptools import setup, find_packages import sys import os requires = [ 'Flask==0.9', 'elasticsearch', 'PyJWT==0.1.4', 'iso8601==0.1.4', ] if sys.version_info < (2, 7): requires.append('ordereddict==1.1') def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name = 'annotator', version = '0.10.0', packages = find_packages(exclude=['test*']), install_requires = requires, extras_require = { 'docs': ['Sphinx'], 'testing': ['nose', 'coverage'], }, # metadata for upload to PyPI author = 'Rufus Pollock and Nick Stenning (Open Knowledge Foundation)', author_email = '[email protected]', description = 'Database backend for the Annotator (http://annotateit.org)', long_description = (read('README.rst') + '\n\n' + read('CHANGES.rst')), license = 'MIT', keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
issue-1809: Fix issue hiding zero-balance categories in move money menu
import { Feature } from 'toolkit/extension/features/feature'; import { isCurrentRouteBudgetPage } from 'toolkit/extension/utils/ynab'; export class RemoveZeroCategories extends Feature { shouldInvoke() { return isCurrentRouteBudgetPage(); } invoke() { let coverOverbudgetingCategories = $('.modal-budget-overspending .dropdown-list > li'); coverOverbudgetingCategories.each(function() { let t = $(this) .find('.category-available') .attr('title'); // Category balance text. if (t == null) { return; } let categoryBalance = parseInt(t.replace(/[^\d-]/g, '')); if (categoryBalance <= 0) { $(this).remove(); } }); coverOverbudgetingCategories = $('.modal-budget-overspending .dropdown-list > li'); // Remove empty sections. for (let i = 0; i < coverOverbudgetingCategories.length - 1; i++) { if ( $(coverOverbudgetingCategories[i]).hasClass('section-item') && $(coverOverbudgetingCategories[i + 1]).hasClass('section-item') ) { $(coverOverbudgetingCategories[i]).remove(); } } // Remove last section empty. if (coverOverbudgetingCategories.last().hasClass('section-item')) { coverOverbudgetingCategories.last().remove(); } } observe(changedNodes) { if (!this.shouldInvoke()) { return; } if (changedNodes.has('category-item-container')) { this.invoke(); } } }
import { Feature } from 'toolkit/extension/features/feature'; import { isCurrentRouteBudgetPage } from 'toolkit/extension/utils/ynab'; export class RemoveZeroCategories extends Feature { shouldInvoke() { return isCurrentRouteBudgetPage(); } invoke() { let coverOverbudgetingCategories = $('.modal-budget-overspending .dropdown-list > li'); coverOverbudgetingCategories.each(function() { let t = $(this) .find('.category-available') .attr('title'); // Category balance text. if (t == null) { return; } let categoryBalance = parseInt(t.replace(/[^\d-]/g, '')); if (categoryBalance <= 0) { $(this).remove(); } }); coverOverbudgetingCategories = $('.modal-budget-overspending .dropdown-list > li'); // Remove empty sections. for (let i = 0; i < coverOverbudgetingCategories.length - 1; i++) { if ( $(coverOverbudgetingCategories[i]).hasClass('section-item') && $(coverOverbudgetingCategories[i + 1]).hasClass('section-item') ) { $(coverOverbudgetingCategories[i]).remove(); } } // Remove last section empty. if (coverOverbudgetingCategories.last().hasClass('section-item')) { coverOverbudgetingCategories.last().remove(); } } observe(changedNodes) { if (!this.shouldInvoke()) { return; } if (changedNodes.has('dropdown-container categories-dropdown-container')) { this.invoke(); } } }
Fix trouble about the output filename
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
Move "Add message" button to top
import React, {Component} from 'react'; import io from 'socket.io-client'; import './App.css'; class App extends Component { state = {messages: []}; socket = io('http://localhost:8080'); componentDidMount() { this.socket .on('connect', () => { //console.log('CONNECT'); }) .on('messages', (messages) => { this.setState({messages: messages}); }) .on('message-added', (message) => { this.setState({messages: [...this.state.messages, message]}); }) .on('message-toggled', (message) => { const messages = [...this.state.messages]; messages[message.id] = message; this.setState({messages: messages}); }) .on('disconnect', () => { //console.log('DISCONNECT'); }); this.socket.emit('get-messages'); } renderMessages() { return this.state.messages.map(message => <li key={message.id}> {message.message}&nbsp; <button onClick={() => this.socket.emit('toggle-message', message.id)}>toggle</button> </li> ) } render() { return <div className={App}> <ul> <button onClick={() => this.socket.emit('add-message')}>Add message</button> {this.renderMessages()} </ul> </div>; } } export default App;
import React, {Component} from 'react'; import io from 'socket.io-client'; import './App.css'; class App extends Component { state = {messages: []}; socket = io('http://localhost:8080'); componentDidMount() { this.socket .on('connect', () => { //console.log('CONNECT'); }) .on('messages', (messages) => { this.setState({messages: messages}); }) .on('message-added', (message) => { this.setState({messages: [...this.state.messages, message]}); }) .on('message-toggled', (message) => { const messages = [...this.state.messages]; messages[message.id] = message; this.setState({messages: messages}); }) .on('disconnect', () => { //console.log('DISCONNECT'); }); this.socket.emit('get-messages'); } renderMessages() { return this.state.messages.map(message => <li key={message.id}> {message.message}&nbsp; <button onClick={() => this.socket.emit('toggle-message', message.id)}>toggle</button> </li> ) } render() { return <div className={App}> <ul> {this.renderMessages()} <button onClick={() => this.socket.emit('add-message')}>add message</button> </ul> </div>; } } export default App;
Fix access level for setLogTag
<?php /** * @license MIT * @copyright 2017 Tim Gunter */ namespace Kaecyra\AppCommon\Log\Tagged; /** * Tagged log trait * * @author Tim Gunter <[email protected]> * @package app-common */ trait TaggedLogTrait { /** * Log tag * @var string|Callable */ protected $logTag = null; /** * Log tagged message * * @param string $level * @param string $message * @param array $context */ public function tLog(string $level, string $message, array $context) { $logtag = $this->getLogTag(); if (is_array($message) || is_object($message)) { $message = print_r($message, true); } $this->log($level, "[{$logtag}] ".$message, $context); } /** * Get log tag * * @return string */ protected function getLogTag() { return is_callable($this->logTag) ? $this->logtag() : $this->logTag; } /** * Set log tag * * @param string|Callable $logTag */ public function setLogTag($logTag) { $this->logTag = $logTag; } /** * Set default logtag callback * * */ public function setDefaultLogCallback() { $this->setLogTag(function(){ return (new \ReflectionClass($this))->getShortName(); }); } }
<?php /** * @license MIT * @copyright 2017 Tim Gunter */ namespace Kaecyra\AppCommon\Log\Tagged; /** * Tagged log trait * * @author Tim Gunter <[email protected]> * @package app-common */ trait TaggedLogTrait { /** * Log tag * @var string|Callable */ protected $logTag = null; /** * Log tagged message * * @param string $level * @param string $message * @param array $context */ public function tLog(string $level, string $message, array $context) { $logtag = $this->getLogTag(); if (is_array($message) || is_object($message)) { $message = print_r($message, true); } $this->log($level, "[{$logtag}] ".$message, $context); } /** * Get log tag * * @return string */ protected function getLogTag() { return is_callable($this->logTag) ? $this->logtag() : $this->logTag; } /** * Set log tag * * @param string|Callable $logTag */ protected function setLogTag($logTag) { $this->logTag = $logTag; } /** * Set default logtag callback * * */ public function setDefaultLogCallback() { $this->setLogTag(function(){ return (new \ReflectionClass($this))->getShortName(); }); } }
Fix regression in D-01186, introduced by B-03523 The solution for B-03523 incorrectly tests when the status is set to "DOWN". It appears to be testings if the service is visible to the public OR if the status is "DOWN". This ends up exposing non-public services to anonymous, thereby re-introducing D-01186. Change the filterByStatus() condition parameter to an array so that multiple status can be checked via a single pass.
app.filter('dashboardServices', function () { var reduceArray = function (arr, condition1, condition2) { var resultingArr = []; if (condition1) { angular.forEach(arr, function (el) { if (el[condition2]) { resultingArr.push(el); } }); } else { resultingArr = arr; } return resultingArr; }; var filterByStatus = function (arr, filterStatus) { var filtered = []; var remaining = []; angular.forEach(arr, function (el) { if (filterStatus.indexOf(el.status) >= 0) { filtered.push(el); } else { remaining.push(el); } }); return { 'filtered': filtered, 'remaining': remaining }; }; return function (services, options) { var shownServices = reduceArray(services, options.showPublic(), "isPublic"); var byStatus = filterByStatus(shownServices, ["MAINTENANCE", "DOWN"]); var shortList = reduceArray(byStatus.remaining, options.showShortList, "onShortList"); return byStatus.filtered.concat(shortList); }; });
app.filter('dashboardServices', function () { var reduceArray = function (arr, condition1, condition2) { var resultingArr = []; if (condition1) { angular.forEach(arr, function (el) { if (el[condition2] || el.status === 'DOWN') { resultingArr.push(el); } }); } else { resultingArr = arr; } return resultingArr; }; var filterByStatus = function (arr, filterStatus) { var filtered = []; var remaining = []; angular.forEach(arr, function (el) { if (el.status === filterStatus) { filtered.push(el); } else { remaining.push(el); } }); return { 'filtered': filtered, 'remaining': remaining }; }; return function (services, options) { var shownServices = reduceArray(services, options.showPublic(), "isPublic"); var byStatus = filterByStatus(shownServices, "MAINTENANCE"); var shortList = reduceArray(byStatus.remaining, options.showShortList, "onShortList"); return byStatus.filtered.concat(shortList); }; });
Increase size of category field.
from django.db import models class Position(models.Model): job_id = models.CharField(max_length=25, unique=True) title = models.CharField(max_length=100) requisition_id = models.PositiveIntegerField() category = models.CharField(max_length=50) job_type = models.CharField(max_length=10) location = models.CharField(max_length=150) date = models.CharField(max_length=100) detail_url = models.URLField() apply_url = models.URLField() description = models.TextField() brief_description = models.TextField(null=True, blank=True) def __unicode__(self): return u"%s - %s" % (self.job_id, self.title) @models.permalink def get_absolute_url(self): return ('django_jobvite_position', (), { 'job_id': self.job_id, }) def to_dict(self): """Return the model as a dictionary keyed on ``job_id``.""" fields = self._meta.fields position_dict = {self.job_id: {}} for field in fields: if field.primary_key: continue if field.name == 'job_id': continue position_dict[self.job_id][field.name] = getattr(self, field.name) return position_dict
from django.db import models class Position(models.Model): job_id = models.CharField(max_length=25, unique=True) title = models.CharField(max_length=100) requisition_id = models.PositiveIntegerField() category = models.CharField(max_length=35) job_type = models.CharField(max_length=10) location = models.CharField(max_length=150) date = models.CharField(max_length=100) detail_url = models.URLField() apply_url = models.URLField() description = models.TextField() brief_description = models.TextField(null=True, blank=True) def __unicode__(self): return u"%s - %s" % (self.job_id, self.title) @models.permalink def get_absolute_url(self): return ('django_jobvite_position', (), { 'job_id': self.job_id, }) def to_dict(self): """Return the model as a dictionary keyed on ``job_id``.""" fields = self._meta.fields position_dict = {self.job_id: {}} for field in fields: if field.primary_key: continue if field.name == 'job_id': continue position_dict[self.job_id][field.name] = getattr(self, field.name) return position_dict
Add warning on niceb5y mirror
import React, { Component } from 'react' export default class extends Component { render() { return ( <div className="block pt-3 pb-5 text-center"> <div className="row"> <div className="col-12"> <h1> Ubuntu JE <a className="text-takasuki" href="http://bugbear5.tumblr.com/post/103450583331/je-14-04" target="_blank"> <small><span className="icon icon-popup" aria-hidden="true"></span></small> </a> / JE Classic <a className="text-takasuki" href="http://bugbear5.tumblr.com/post/108634866076/je-classic-14-04" target="_blank"> <small><span className="icon icon-popup" aria-hidden="true"></span></small> </a> &nbsp;mirror </h1> <p className="lead"> <a className="text-takasuki" href="https://twitter.com/bugbear5">떠돌이</a>님이 제작하신 Ubuntu JE의 비공식 미러입니다. </p> <div className="alert alert-warning" role="alert"> niceb5y mirror 서비스가 2018년 2월 1일에 종료됩니다. </div> </div> </div> </div> ) } }
import React, { Component } from 'react' export default class extends Component { render() { return ( <div className="block pt-3 pb-5 text-center"> <div className="row"> <div className="col-12"> <h1> Ubuntu JE <a className="text-takasuki" href="http://bugbear5.tumblr.com/post/103450583331/je-14-04" target="_blank"> <small><span className="icon icon-popup" aria-hidden="true"></span></small> </a> / JE Classic <a className="text-takasuki" href="http://bugbear5.tumblr.com/post/108634866076/je-classic-14-04" target="_blank"> <small><span className="icon icon-popup" aria-hidden="true"></span></small> </a> &nbsp;mirror </h1> <p className="lead"> <a className="text-takasuki" href="https://twitter.com/bugbear5">떠돌이</a>님이 제작하신 Ubuntu JE의 비공식 미러입니다. </p> </div> </div> </div> ) } }
Add client-side JS files to JSHint task
module.exports = function(grunt) { require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ jshint: { all: [ '*.js', 'lib/**/*.js', 'app/js/**/*.js' ], options: { } }, // ## // browserify: { dist: { src: 'lib/client/common.js', dest: 'dist/common.js' } }, // ## // watch: { jshint: { files: ['lib/**/*.js', 'public/js/**/*.js', '*.js'], tasks: ['jshint:all'] }, browserify: { files: ['lib/**/*.js', 'public/js/**/*.js', '*.js'], tasks: ['browserify:dist'] } }, // ## // bower: { install: { options: { copy: false } } } }); grunt.registerTask('default', [ 'jshint:all', 'browserify:dist' ]); grunt.registerTask('heroku:development', [ 'bower:install', 'jshint:all', 'browserify:dist' ]); };
module.exports = function(grunt) { require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ jshint: { all: [ '*.js', 'lib/**/*.js' ], options: { } }, // ## // browserify: { dist: { src: 'lib/client/common.js', dest: 'dist/common.js' } }, // ## // watch: { jshint: { files: ['lib/**/*.js', 'public/js/**/*.js', '*.js'], tasks: ['jshint:all'] }, browserify: { files: ['lib/**/*.js', 'public/js/**/*.js', '*.js'], tasks: ['browserify:dist'] } }, // ## // bower: { install: { options: { copy: false } } } }); grunt.registerTask('default', [ 'jshint:all', 'browserify:dist' ]); grunt.registerTask('heroku:development', [ 'bower:install', 'jshint:all', 'browserify:dist' ]); };
Change session cookie ttl to 1 month
<?php namespace BNETDocs\Libraries; use CarlBennett\MVC\Libraries\Router; use CarlBennett\MVC\Libraries\Session as BaseSession; class Session extends BaseSession { const COOKIE_NAME = 'uid'; const LOGIN_TTL = 2592000; // 1 month public static function checkLogin(Router &$router) { // Check if logged in by session but long-term cookie not set if (isset($_SESSION['user_id']) && !isset($_COOKIE[self::COOKIE_NAME])) { $router->setResponseCookie( self::COOKIE_NAME, // key $_SESSION['user_id'], // value self::LOGIN_TTL, // ttl true, // http only true, // secure getenv('HTTP_HOST'), // domain '/' // path ); } // Check for login manipulation if (isset($_SESSION['user_id']) && isset($_COOKIE[self::COOKIE_NAME]) && $_SESSION['user_id'] != $_COOKIE[self::COOKIE_NAME]) { unset($_SESSION['user_id']); $router->setResponseCookie( self::COOKIE_NAME, '', 0, true, true, // delete it getenv('HTTP_HOST'), '/' ); } } }
<?php namespace BNETDocs\Libraries; use CarlBennett\MVC\Libraries\Router; use CarlBennett\MVC\Libraries\Session as BaseSession; class Session extends BaseSession { const COOKIE_NAME = 'uid'; const LOGIN_TTL = 86400; // 1 day public static function checkLogin(Router &$router) { // Check if logged in by session but long-term cookie not set if (isset($_SESSION['user_id']) && !isset($_COOKIE[self::COOKIE_NAME])) { $router->setResponseCookie( self::COOKIE_NAME, // key $_SESSION['user_id'], // value self::LOGIN_TTL, // ttl true, // http only true, // secure getenv('HTTP_HOST'), // domain '/' // path ); } // Check for login manipulation if (isset($_SESSION['user_id']) && isset($_COOKIE[self::COOKIE_NAME]) && $_SESSION['user_id'] != $_COOKIE[self::COOKIE_NAME]) { unset($_SESSION['user_id']); $router->setResponseCookie( self::COOKIE_NAME, '', 0, true, true, // delete it getenv('HTTP_HOST'), '/' ); } } }
Use sure in project tools cases
import sure from mock import MagicMock from django.core.exceptions import PermissionDenied from django.test import TestCase from accounts.tests.factories import UserFactory from ..utils import ProjectAccessMixin from ..models import Project from . import factories class ProjectAccessMixinCase(TestCase): """Project access mixin case""" def setUp(self): self._orig_can_access = Project.can_access Project.can_access = MagicMock() self._orig_update = Project.objects.update_user_projects Project.objects.update_user_projects = MagicMock() self.mixin = ProjectAccessMixin() self.project = factories.ProjectFactory() self.mixin.get_project = MagicMock(return_value=self.project) self.user = UserFactory() def tearDown(self): Project.can_access = self._orig_can_access Project.objects.update_user_projects = self._orig_update def test_can_access(self): """Test can access""" Project.can_access.return_value = True self.mixin.check_can_access( MagicMock(user=self.user), ).should.be.none def test_call_update_if_organization(self): """Test call update if organization""" Project.can_access.return_value = False self.mixin.check_can_access.when\ .called_with(MagicMock(user=self.user))\ .should.throw(PermissionDenied) Project.objects.update_user_projects.asset_called_once_with( self.user, )
from mock import MagicMock from django.core.exceptions import PermissionDenied from django.test import TestCase from accounts.tests.factories import UserFactory from ..utils import ProjectAccessMixin from ..models import Project from . import factories class ProjectAccessMixinCase(TestCase): """Project access mixin case""" def setUp(self): self._orig_can_access = Project.can_access Project.can_access = MagicMock() self._orig_update = Project.objects.update_user_projects Project.objects.update_user_projects = MagicMock() self.mixin = ProjectAccessMixin() self.project = factories.ProjectFactory() self.mixin.get_project = MagicMock(return_value=self.project) self.user = UserFactory() def tearDown(self): Project.can_access = self._orig_can_access Project.objects.update_user_projects = self._orig_update def test_can_access(self): """Test can access""" Project.can_access.return_value = True self.assertIsNone(self.mixin.check_can_access( MagicMock(user=self.user), )) def test_call_update_if_organization(self): """Test call update if organization""" Project.can_access.return_value = False with self.assertRaises(PermissionDenied): self.mixin.check_can_access(MagicMock(user=self.user)) Project.objects.update_user_projects.asset_called_once_with( self.user, )
Fix metadata addition when the results are empty
<?php /* * This file is part of Packagist. * * (c) Jordi Boggiano <[email protected]> * Nils Adermann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Packagist\WebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController; /** * @author Jordi Boggiano <[email protected]> */ class Controller extends BaseController { protected function getPackagesMetadata($packages) { $metadata = null; try { $dlKeys = array(); foreach ($packages as $package) { $id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId(); $dlKeys[$id] = 'dl:'.$id; } if (!$dlKeys) { return $metadata; } $res = $this->get('snc_redis.default')->mget(array_values($dlKeys)); $metadata = array( 'downloads' => array_combine(array_keys($dlKeys), $res), 'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)), ); } catch (\Predis\Network\ConnectionException $e) {} return $metadata; } }
<?php /* * This file is part of Packagist. * * (c) Jordi Boggiano <[email protected]> * Nils Adermann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Packagist\WebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController; /** * @author Jordi Boggiano <[email protected]> */ class Controller extends BaseController { protected function getPackagesMetadata($packages) { $metadata = null; try { $dlKeys = array(); foreach ($packages as $package) { $id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId(); $dlKeys[$id] = 'dl:'.$id; } $res = $this->get('snc_redis.default')->mget(array_values($dlKeys)); $metadata = array( 'downloads' => array_combine(array_keys($dlKeys), $res), 'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)), ); } catch (\Predis\Network\ConnectionException $e) {} return $metadata; } }
Fix a target window of keyboard shortcuts for tab
chrome.commands.onCommand.addListener(function(command) { var callback; if ( command === "show-next-tab" ) { callback = function(tabs) { var tab = tabs[0]; chrome.tabs.query({ windowId: tab.windowId, index: tab.index + 1 }, function(tabs) { var tab = tabs[0]; chrome.tabs.update(tab.id, { active: true }); }); }; } else if ( command === "show-prev-tab" ) { callback = function(tabs) { var tab = tabs[0]; if ( tab.index > 0 ) { chrome.tabs.query({ windowId: tab.windowId, index: tab.index - 1 }, function(tabs) { var tab = tabs[0]; chrome.tabs.update(tab.id, { active: true }); }); } }; } else if ( command === "move-tab-next" ) { callback = function(tabs) { var tab = tabs[0]; chrome.tabs.move(tab.id, { index: tab.index + 1 }); }; } else if ( command === "move-tab-prev" ) { callback = function(tabs) { var tab = tabs[0]; if ( tab.index > 0 ) { chrome.tabs.move(tab.id, { index: tab.index - 1 }); } }; } if ( callback ) { chrome.tabs.query({ active: true, currentWindow: true }, callback); } });
chrome.commands.onCommand.addListener(function(command) { var callback; if ( command === "show-next-tab" ) { callback = function(tabs) { var tab = tabs[0]; chrome.tabs.query({ windowId: tab.windowId, index: tab.index + 1 }, function(tabs) { var tab = tabs[0]; chrome.tabs.update(tab.id, { active: true }); }); }; } else if ( command === "show-prev-tab" ) { callback = function(tabs) { var tab = tabs[0]; if ( tab.index > 0 ) { chrome.tabs.query({ windowId: tab.windowId, index: tab.index - 1 }, function(tabs) { var tab = tabs[0]; chrome.tabs.update(tab.id, { active: true }); }); } }; } else if ( command === "move-tab-next" ) { callback = function(tabs) { var tab = tabs[0]; chrome.tabs.move(tab.id, { index: tab.index + 1 }); }; } else if ( command === "move-tab-prev" ) { callback = function(tabs) { var tab = tabs[0]; if ( tab.index > 0 ) { chrome.tabs.move(tab.id, { index: tab.index - 1 }); } }; } if ( callback ) { chrome.tabs.query({ active: true }, callback); } });
Simplify the construction of change events and make them protected
package org.realityforge.replicant.client; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * An event indicating that an imitation has changed. */ public final class EntityChangeEvent { private final EntityChangeType _type; private final Object _object; private final String _name; private final Object _value; protected EntityChangeEvent( @Nonnull final EntityChangeType type, @Nonnull final Object object, @Nullable final String name, @Nullable final Object value ) { _type = type; _object = object; _name = name; _value = value; } @Nonnull public final EntityChangeType getType() { return _type; } @Nonnull public final Object getObject() { return _object; } @Nullable public final String getName() { return _name; } @Nullable public final Object getValue() { return _value; } /** * {@inheritDoc} */ public final String toString() { final StringBuilder sb = new StringBuilder(); sb.append( "EntityChange[type=" ); sb.append( getType().name() ); sb.append( ",name=" ); sb.append( getName() ); sb.append( ",value=" ); sb.append( getValue() ); sb.append( ",object=" ); sb.append( getObject() ); sb.append( "]" ); return sb.toString(); } }
package org.realityforge.replicant.client; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * An event indicating that an imitation has changed. */ public final class EntityChangeEvent { private final EntityChangeType _type; private final Object _object; private final String _name; private final Object _value; public EntityChangeEvent( @Nonnull final EntityChangeType type, @Nonnull final Object object ) { this( type, object, null, null ); } @SuppressWarnings( { "ConstantConditions" } ) public EntityChangeEvent( @Nonnull final EntityChangeType type, @Nonnull final Object object, @Nullable final String name, @Nullable final Object value ) { if ( null == type ) { throw new NullPointerException( "type" ); } if ( null == object ) { throw new NullPointerException( "object" ); } _type = type; _object = object; _name = name; _value = value; } @Nonnull public final EntityChangeType getType() { return _type; } @Nonnull public final Object getObject() { return _object; } @Nullable public final String getName() { return _name; } @Nullable public final Object getValue() { return _value; } public final String toString() { final StringBuilder sb = new StringBuilder(); sb.append( "EntityChange[type=" ); sb.append( getType().name() ); sb.append( ",name=" ); sb.append( getName() ); sb.append( ",value=" ); sb.append( getValue() ); sb.append( ",object=" ); sb.append( getObject() ); sb.append( "]" ); return sb.toString(); } }
Fix cdr timezone test issue
package org.asteriskjava.manager.event; import static org.junit.Assert.assertEquals; import java.util.TimeZone; import org.junit.Before; import org.junit.After; import org.junit.Test; public class CdrEventTest { CdrEvent cdrEvent; TimeZone defaultTimeZone; @Before public void setUp() { cdrEvent = new CdrEvent(this); cdrEvent.setStartTime("2006-05-19 11:54:48"); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } @After public void tearDown() { TimeZone.setDefault(defaultTimeZone); } @Test public void testGetStartTimeAsDate() { assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime()); } @Test public void testGetStartTimeAsDateWithTimeZone() { TimeZone tz = TimeZone.getTimeZone("GMT+2"); assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime()); } @Test public void testBug() { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco")); cdrEvent.setStartTime("2006-05-29 13:17:21"); assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString()); } }
package org.asteriskjava.manager.event; import static org.junit.Assert.assertEquals; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; public class CdrEventTest { CdrEvent cdrEvent; TimeZone defaultTimeZone; @Before public void setUp() { cdrEvent = new CdrEvent(this); cdrEvent.setStartTime("2006-05-19 11:54:48"); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } @Before public void tearDown() { TimeZone.setDefault(defaultTimeZone); } @Test public void testGetStartTimeAsDate() { assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime()); } @Test public void testGetStartTimeAsDateWithTimeZone() { TimeZone tz = TimeZone.getTimeZone("GMT+2"); assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime()); } @Test public void testBug() { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco")); cdrEvent.setStartTime("2006-05-29 13:17:21"); assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString()); } }
Add light service and unit tests
'use strict'; exports.seed = function (knex, Promise) { return Promise.join( // Deletes ALL existing entries knex('lights').del(), // Inserts seed entries knex('lights').insert({ id: 1, name: 'Lounge', enabled: 1, device: 1, instance: 0, controllerHost: 'localhost', controllerPort: 8080 }), knex('lights').insert({ id: 2, name: 'Front Flood Light', enabled: 1, device: 2, instance: 0, controllerHost: 'localhost', controllerPort: 8080 }), knex('lights').insert({ id: 3, name: 'Side Passage', enabled: 1, device: 3, instance: 0, controllerHost: 'otherhost', controllerPort: 9090 }), knex('lights').insert({ id: 4, name: 'Side Entrance', enabled: 1, device: 4, instance: 0, controllerHost: 'otherhost', controllerPort: 9090 }), knex('lights').insert({ id: 5, name: 'Broken Light', enabled: 0, device: 5, instance: 0, controllerHost: 'otherhost', controllerPort: 9090 }) ); };
'use strict'; exports.seed = function (knex, Promise) { return Promise.join( // Deletes ALL existing entries knex('lights').del(), // Inserts seed entries knex('lights').insert({ id: 1, name: 'Lounge', enabled: 1, device: 1, instance: 0, controllerHost: 'localhost', controllerPort: 8080 }), knex('lights').insert({ id: 2, name: 'Front Flood Light', enabled: 1, device: 2, instance: 0, controllerHost: 'localhost', controllerPort: 8080 }), knex('lights').insert({ id: 3, name: 'Side Passage', enabled: 1, device: 3, instance: 0, controllerHost: 'otherhost', controllerPort: 9090 }), knex('lights').insert({ id: 4, name: 'Side Entrance', enabled: 1, device: 4, instance: 0, controllerHost: 'otherhost', controllerPort: 9090 }) ); };
Fix linting paths to match previous refactor
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: 'Gruntfile.js', bin: [ 'cli.js', 'yoyo.js' ], test: { options: { globals: { describe: true, it: true, beforeEach: true, afterEach: true, before: true, after: true } }, src: 'test/**/*.js' } }, watch: { files: [ 'Gruntfile.js', '<%= jshint.test.src %>', '<%= jshint.bin.src %>' ], tasks: [ 'jshint', 'mochaTest' ] }, mochaTest: { test: { options: { slow: 1500, timeout: 50000, reporter: 'spec', globals: [ 'events', 'AssertionError', 'TAP_Global_Harness' ] }, src: ['test/**/*.js'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('default', ['jshint', 'mochaTest']); };
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: 'Gruntfile.js', bin: { src: [ 'bin/*.js', 'bin/yo' ] }, test: { options: { globals: { describe: true, it: true, beforeEach: true, afterEach: true, before: true, after: true } }, src: 'test/**/*.js' } }, watch: { files: [ 'Gruntfile.js', '<%= jshint.test.src %>', '<%= jshint.bin.src %>' ], tasks: [ 'jshint', 'mochaTest' ] }, mochaTest: { test: { options: { slow: 1500, timeout: 50000, reporter: 'spec', globals: [ 'events', 'AssertionError', 'TAP_Global_Harness' ] }, src: ['test/**/*.js'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('default', ['jshint', 'mochaTest']); };
Simplify code pertaining to running all testscases in controller
<?php class TestrunController extends ControllerBase { public $environment = 'test'; public function create( $name = '' ) { require_once 'models/test/base.php'; require_once 'models/test/functional.php'; require_once 'models/test/withfixtures.php'; if ( $name == '' ) { set_time_limit( 360 ); $tests = UnitTest::findAll(); } else { $tests = [ $name ]; } $unittests = []; $failed = false; foreach ( $tests as $test ) { $path = 'tests/' . $test . '.php'; if ( !file_exists( $path ) ) { throw new HTTPNotFoundException( 'No such test "' . $path . '"' ); } $unittest = require_once $path; $unittest->run(); foreach ( $unittest->tests as $test ) { if ( !$test->success ) { $failed = true; } } $unittests[] = $unittest; } require_once 'views/testrun/results.php'; if ( $failed ) { return 1; } return 0; } public function createView() { require_once 'models/test/base.php'; $tests = UnitTest::findAll(); require_once 'views/testrun/create.php'; } } ?>
<?php class TestrunController extends ControllerBase { public $environment = 'test'; public function create( $name = '' ) { $all = $name == ''; if ( $all ) { set_time_limit( 360 ); } require_once 'models/test/base.php'; require_once 'models/test/functional.php'; require_once 'models/test/withfixtures.php'; if ( $all ) { $tests = UnitTest::findAll(); } else { $tests = [ $name ]; } $unittests = []; $failed = false; foreach ( $tests as $test ) { $path = 'tests/' . $test . '.php'; if ( !file_exists( $path ) ) { throw new HTTPNotFoundException( 'No such test "' . $path . '"' ); } $unittest = require_once $path; $unittest->run(); foreach ( $unittest->tests as $test ) { if ( !$test->success ) { $failed = true; } } $unittests[] = $unittest; } require_once 'views/testrun/results.php'; if ( $failed ) { return 1; } return 0; } public function createView() { require_once 'models/test/base.php'; $tests = UnitTest::findAll(); require_once 'views/testrun/create.php'; } } ?>
Add tentative fix to isFinished using magnitudes rather than the pos/neg values
package edu.stuy.commands; import edu.stuy.Robot; import edu.wpi.first.wpilibj.command.Command; /** * Rotates the Robot without PID values */ public class DrivetrainRotateNoPIDCommand extends Command { private double degrees; private double startAngle; public DrivetrainRotateNoPIDCommand(double _degrees) { requires(Robot.drivetrain); degrees = _degrees; startAngle = Robot.drivetrain.getGyroAngle(); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { if (degrees < 0) { Robot.drivetrain.tankDrive(-0.5, 0.5); } else if (degrees > 0) { Robot.drivetrain.tankDrive(0.5, -0.5); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { if (degrees == 0) { return true; } else { return Math.abs(Robot.drivetrain.getGyroAngle() - startAngle) >= Math.abs(degrees); } } // Called once after isFinished returns true protected void end() { Robot.drivetrain.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package edu.stuy.commands; import edu.stuy.Robot; import edu.wpi.first.wpilibj.command.Command; /** * Rotates the Robot without PID values */ public class DrivetrainRotateNoPIDCommand extends Command { private double degrees; private double startAngle; public DrivetrainRotateNoPIDCommand(double _degrees) { requires(Robot.drivetrain); degrees = _degrees; startAngle = Robot.drivetrain.getGyroAngle(); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { if (degrees < 0) { Robot.drivetrain.tankDrive(-0.5, 0.5); } else if (degrees > 0) { Robot.drivetrain.tankDrive(0.5, -0.5); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { double soFar = Math.abs(startAngle - Robot.drivetrain.getGyroAngle()); if (degrees < 0) { return soFar <= degrees; } else if (degrees > 0) { return soFar >= degrees; } else { return true; } } // Called once after isFinished returns true protected void end() { Robot.drivetrain.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Add some print statements for debugging.
from __future__ import absolute_import from datetime import datetime from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 count = 0 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors print("deleting") doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects.filter(doc_id__in=doc_ids).delete() count += num_retrieved print(count) print(datetime.utcnow())
from __future__ import absolute_import from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects(doc_id__in=doc_ids).delete()
Hide link if no photo
import React from 'react'; import {NavigationLink} from 'navigation-react'; import Banner from './Banner'; import Tweets from './Tweets'; export default ({tweet: {account: {id: accountId, name, username, logo}, id, text, photo, time, retweets, likes, replies}}) => ( <div> <Banner title="Tweet" /> <div className="tweet"> <div className="heading"> <NavigationLink className="logo" stateKey="timeline" navigationData={{id: accountId}}> <img src={logo} alt={name}/> </NavigationLink> <div className="details"> <div className="name">{name}</div> <div className="username">{username}</div> </div> </div> <div className="text">{text}</div> {photo && <NavigationLink className="photo" stateKey="photo" navigationData={{id}}> <img src={photo}/> </NavigationLink>} <div className="time">{time}</div> <div className="interactions"> <div className="count">{retweets}</div> <div className="interaction">Retweets</div> <div className="count">{likes}</div> <div className="interaction">Likes</div> </div> </div> <Tweets tweets={replies} /> </div> );
import React from 'react'; import {NavigationLink} from 'navigation-react'; import Banner from './Banner'; import Tweets from './Tweets'; export default ({tweet: {account: {id: accountId, name, username, logo}, id, text, photo, time, retweets, likes, replies}}) => ( <div> <Banner title="Tweet" /> <div className="tweet"> <div className="heading"> <NavigationLink className="logo" stateKey="timeline" navigationData={{id: accountId}}> <img src={logo} alt={name}/> </NavigationLink> <div className="details"> <div className="name">{name}</div> <div className="username">{username}</div> </div> </div> <div className="text">{text}</div> <NavigationLink className="photo" stateKey="photo" navigationData={{id}}> <img src={photo}/> </NavigationLink> <div className="time">{time}</div> <div className="interactions"> <div className="count">{retweets}</div> <div className="interaction">Retweets</div> <div className="count">{likes}</div> <div className="interaction">Likes</div> </div> </div> <Tweets tweets={replies} /> </div> );
Add CSRF token to JS POST header
var csrftoken = $('input[name=csrf_token]').attr('value'); $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken) } } }); $(function () { $('#single').submit(function (event) { event.preventDefault(); $(':submit').button('loading') $.post('/thread', { submission: $('input[name="submission"]').val(), email: $('input[name="email"]').val() }) .done(function (data) { $(':submit').button('reset') $('form') .before( '<div class="alert alert-' + data.type + ' alert-dismissible fade in" role="alert">\ <button type="button" class="close" data-dismiss="alert">\ <span\ aria-hidden="true">&times;</span>\ <span class="sr-only">Close</span>\ </button>\ ' + data.text + '\ </div>' ) window.setTimeout(function () { $(".alert:first").alert('close'); }, 10000); }); }); });
$(function () { $('#single').submit(function (event) { event.preventDefault(); $(':submit').button('loading') $.post('/thread', { submission: $('input[name="submission"]').val(), email: $('input[name="email"]').val() }) .done(function (data) { $(':submit').button('reset') $('form') .before( '<div class="alert alert-' + data.type + ' alert-dismissible fade in" role="alert">\ <button type="button" class="close" data-dismiss="alert">\ <span\ aria-hidden="true">&times;</span>\ <span class="sr-only">Close</span>\ </button>\ ' + data.text + '\ </div>' ) window.setTimeout(function () { $(".alert:first").alert('close'); }, 10000); }); }); });
Update job when job detail clicked
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // update the job before displaying, as the job in the collection // could be stale and out of sync from the display in the job panel job.once('g:fetched', function () { this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this).fetch(); }, this); girder.events.on('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // TODO right way to update specific job? // otherwise can get a detail that is out of sync with actual job status // seems weird to update the entire collection from here // another option is to refresh the job specifically this.jobListWidget.collection.on('g:changed', function () { job = this.jobListWidget.collection.get(job.get('id')); this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this); this.jobListWidget.collection.fetch({}, true); }, this); girder.events.on('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
Add error function to remove duplicate code
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import argparse import getpass import sys import github3 def error(message): print(message) sys.exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument('--username') parser.add_argument('--password') parser.add_argument('organization') parser.add_argument('channel') args = parser.parse_args() if args.password is None: password = getpass.getpass( 'Password for github user "{}":'.format(args.username)) else: password = args.password github = github3.login(args.username, password=password) if github is None: error('Failed to sign into github') org = github.organization(args.organization) if org is None: error('Organization "{}" does not appear to exist'.format(args.org)) conf = {'nickserv_password': '', 'no_colors': '0', 'password': '', 'branch_regexes': '', 'room': args.channel, 'ssl': '0', 'port': '', 'branches': '', 'server': 'chat.freenode.net', 'long_url': '0', 'notice': '0', 'message_without_join': '1', 'nick': 'github' } events = [ 'push', 'delete', 'create', 'issues', 'pull_request' ] for r in org.iter_repos(): r.create_hook('irc', conf, events=events)
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import argparse import getpass import sys import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username') parser.add_argument('--password') parser.add_argument('organization') parser.add_argument('channel') args = parser.parse_args() if args.password is None: password = getpass.getpass( 'Password for github user "{}":'.format(args.username)) else: password = args.password github = github3.login(args.username, password=password) if github is None: print('Failed to sign into github') sys.exit(1) org = github.organization(args.organization) if org is None: print('Organization "{}" does not appear to exist'.format(args.org)) sys.exit(1) conf = {'nickserv_password': '', 'no_colors': '0', 'password': '', 'branch_regexes': '', 'room': args.channel, 'ssl': '0', 'port': '', 'branches': '', 'server': 'chat.freenode.net', 'long_url': '0', 'notice': '0', 'message_without_join': '1', 'nick': 'github' } events = [ 'push', 'delete', 'create', 'issues', 'pull_request' ] for r in org.iter_repos(): r.create_hook('irc', conf, events=events)
Remove superfluous string from format variable
'use strict'; var request = require('request'); var opts = parseOptions(process.argv[2]); request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s'; for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } }); /* * Verify param is present, and just return it. * TODO * Check for multiple params, and check validity * as well as presence. */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; } function parseOptions(opts) { // org or users, resource, query topic var who = '/users' , where = '/' + opts , what = '/events' var options = { uri: 'https://api.github.com' + who + where + what, json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } return options; }
'use strict'; var request = require('request'); var opts = parseOptions(process.argv[2]); request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } }); /* * Verify param is present, and just return it. * TODO * Check for multiple params, and check validity * as well as presence. */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; } function parseOptions(opts) { // org or users, resource, query topic var who = '/users' , where = '/' + opts , what = '/events' var options = { uri: 'https://api.github.com' + who + where + what, json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } return options; }
Add warning when server handler task queue is full
__all__ = [ 'SocketServer', ] import errno import logging from g1.asyncs.bases import servers from g1.asyncs.bases import tasks LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) class SocketServer: def __init__(self, socket, handler, max_connections=0): self._socket = socket self._handler = handler self._max_connections = max_connections async def serve(self): LOG.info('start server: %r', self._socket) with self._socket: if self._max_connections <= 0: capacity = self._max_connections else: # +1 for the `_accept` task. capacity = self._max_connections + 1 async with tasks.CompletionQueue(capacity) as queue: await servers.supervise_server( queue, (queue.spawn(self._accept(queue)), ), ) LOG.info('stop server: %r', self._socket) async def _accept(self, queue): while True: if queue.is_full(): LOG.warning( 'handler task queue is full; ' 'we cannot accept any new connections' ) await queue.puttable() try: sock, addr = await self._socket.accept() except OSError as exc: if exc.errno == errno.EBADF: LOG.info('server socket close: %r', self._socket) break raise LOG.debug('serve client: %r', addr) queue.spawn(self._handler(sock, addr)) def shutdown(self): self._socket.close()
__all__ = [ 'SocketServer', ] import errno import logging from g1.asyncs.bases import servers from g1.asyncs.bases import tasks LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) class SocketServer: def __init__(self, socket, handler, max_connections=0): self._socket = socket self._handler = handler self._max_connections = max_connections async def serve(self): LOG.info('start server: %r', self._socket) with self._socket: if self._max_connections <= 0: capacity = self._max_connections else: # +1 for the `_accept` task. capacity = self._max_connections + 1 async with tasks.CompletionQueue(capacity) as queue: await servers.supervise_server( queue, (queue.spawn(self._accept(queue)), ), ) LOG.info('stop server: %r', self._socket) async def _accept(self, queue): while True: await queue.puttable() try: sock, addr = await self._socket.accept() except OSError as exc: if exc.errno == errno.EBADF: LOG.info('server socket close: %r', self._socket) break raise LOG.debug('serve client: %r', addr) queue.spawn(self._handler(sock, addr)) def shutdown(self): self._socket.close()
Add reference to CollectionItems by singular collection name, if possible
<?php namespace TightenCo\Jigsaw; use Exception; use TightenCo\Jigsaw\IterableObject; class ViewData extends IterableObject { private $data; private $globals = ['extends', 'section', 'content', 'link']; public $item; public static function withCollectionItem($data, $collectionName, $itemName) { $viewData = new static($data); $viewData->setCollectionItem($collectionName, $itemName); return $viewData; } public function __call($method, $args) { return $this->getHelper($method)->__invoke($this, ...$args); } private function getHelper($name) { $helper = $this->has('helpers') ? $this->helpers->{$name} : null; return $helper ?: function() use ($name) { throw new Exception("No helper function named '$name' in 'config.php'."); }; } private function setCollectionItem($collection, $item) { if ($this->has($collection)) { $this->item = $this->get($collection)->get($item); $this->addSingularCollectionReference($collection); $this->setGloballyAvailableItemVariables(); } } private function addSingularCollectionReference($collection) { if (str_singular($collection) != $collection) { $this->{str_singular($collection)} = $this->item; }; } private function setGloballyAvailableItemVariables() { collect($this->globals)->each(function ($variable) { $this[$variable] = $this->item->{$variable}; }); } }
<?php namespace TightenCo\Jigsaw; use Exception; use TightenCo\Jigsaw\IterableObject; class ViewData extends IterableObject { private $data; private $globals = ['extends', 'section', 'content', 'link']; public $item; public static function withCollectionItem($data, $collectionName, $itemName) { $viewData = new static($data); $viewData->setCollectionItem($collectionName, $itemName); return $viewData; } public function __call($method, $args) { return $this->getHelper($method)->__invoke($this, ...$args); } private function getHelper($name) { $helper = $this->has('helpers') ? $this->helpers->{$name} : null; return $helper ?: function() use ($name) { throw new Exception("No helper function named '$name' in 'config.php'."); }; } private function setCollectionItem($collection, $item) { if ($this->has($collection)) { $this->item = $this->get($collection)->get($item); $this->setGloballyAvailableItemVariables(); } } private function setGloballyAvailableItemVariables() { collect($this->globals)->each(function ($variable) { $this[$variable] = $this->item->{$variable}; }); } }
Fix level 1 phpstan issues
<?php declare(strict_types=1); namespace League\Container\Inflector; use Generator; use League\Container\ContainerAwareTrait; class InflectorAggregate implements InflectorAggregateInterface { use ContainerAwareTrait; /** * @var \League\Container\Inflector\Inflector[] */ protected $inflectors = []; /** * {@inheritdoc} */ public function add(string $type, callable $callback = null) : Inflector { $inflector = new Inflector($type, $callback); $this->inflectors[] = $inflector; return $inflector; } /** * {@inheritdoc} */ public function getIterator() : Generator { $count = count($this->inflectors); for ($i = 0; $i < $count; $i++) { yield $this->inflectors[$i]; } } /** * {@inheritdoc} */ public function inflect($object) { foreach ($this->getIterator() as $inflector) { $type = $inflector->getType(); if (! $object instanceof $type) { continue; } $inflector->setContainer($this->getContainer()); $inflector->inflect($object); } return $object; } }
<?php declare(strict_types=1); namespace League\Container\Inflector; use Generator; use League\Container\ContainerAwareTrait; class InflectorAggregate implements InflectorAggregateInterface { use ContainerAwareTrait; /** * @var \League\Container\Inflector[] */ protected $inflectors = []; /** * {@inheritdoc} */ public function add(string $type, callable $callback = null) : Inflector { $inflector = new Inflector($type, $callback); $this->inflectors[] = $inflector; return $inflector; } /** * {@inheritdoc} */ public function getIterator() : Generator { $count = count($this->inflectors); for ($i = 0; $i < $count; $i++) { yield $this->inflectors[$i]; } } /** * {@inheritdoc} */ public function inflect($object) { foreach ($this->getIterator() as $inflector) { $type = $inflector->getType(); if (! $object instanceof $type) { continue; } $inflector->setContainer($this->getContainer()); $inflector->inflect($object); } return $object; } }
Fix syntax to work with php 5.3
<?php namespace Phive\Twig\Extensions\Deferred; class DeferredExtension extends \Twig_Extension { /** * @var \Twig_Environment */ protected $environment; /** * @var array */ private $blocks = array(); /** * {@inheritdoc} */ public function initRuntime(\Twig_Environment $environment) { $this->environment = $environment; } /** * {@inheritdoc} */ public function getTokenParsers() { return array(new DeferredTokenParser()); } /** * {@inheritdoc} */ public function getNodeVisitors() { return array(new DeferredNodeVisitor()); } /** * {@inheritdoc} */ public function getName() { return 'deferred'; } public function defer(\Twig_Template $template, $blockName, array $args) { $templateName = $template->getTemplateName(); if (!isset($this->blocks[$templateName])) { $this->blocks[$templateName] = array(); } $this->blocks[$templateName][] = array($blockName, $args); } public function resolve(\Twig_Template $template) { $templateName = $template->getTemplateName(); if (empty($this->blocks[$templateName])) { return; } while ($block = array_pop($this->blocks[$templateName])) { call_user_func_array(array($template, $block[0]), $block[1]); } } }
<?php namespace Phive\Twig\Extensions\Deferred; class DeferredExtension extends \Twig_Extension { /** * @var \Twig_Environment */ protected $environment; /** * @var array */ private $blocks = array(); /** * {@inheritdoc} */ public function initRuntime(\Twig_Environment $environment) { $this->environment = $environment; } /** * {@inheritdoc} */ public function getTokenParsers() { return array(new DeferredTokenParser()); } /** * {@inheritdoc} */ public function getNodeVisitors() { return array(new DeferredNodeVisitor()); } /** * {@inheritdoc} */ public function getName() { return 'deferred'; } public function defer(\Twig_Template $template, $blockName, array $args) { $templateName = $template->getTemplateName(); if (!isset($this->blocks[$templateName])) { $this->blocks[$templateName] = array(); } $this->blocks[$templateName][] = array($blockName, $args); } public function resolve(\Twig_Template $template) { $templateName = $template->getTemplateName(); if (empty($this->blocks[$templateName])) { return; } while ($block = array_pop($this->blocks[$templateName])) { call_user_func_array([$template, $block[0]], $block[1]); } } }
AP-6: Fix check for email and password.
<?php namespace Application\Module { class User extends \Application\Module { public function Index() { return $this->Login(); } public function Login() { $Request = $this->getRequest(); $User = $this->getModel("User"); if (isset($Request['Arguments']['Email']) && $Request['Arguments']['Email'] !== "") { $User->setEmail($Request['Arguments']['Email']); } if (isset($Request['Arguments']['Password']) && $Request['Arguments']['Password'] !== "") { $User->setPassword($Request['Arguments']['Password']); } $Error = null; $Email = $User->getEmail(); $Password = $User->getPassword(); if (isset($Email)) ; else { $Error = "No email given."; }; if (isset($Password)) ; else { $Error = "No password given."; } $User->Error = $Error; $View = $this->getView("Login.phtml", array("User" => $User)); return $View; } protected function Info() { $User = $this->getModel("User"); $View = $this->getView("User.phtml", array("User" => $User)); return $View; } } } ?>
<?php namespace Application\Module { class User extends \Application\Module { public function Index() { return $this->Login(); } public function Login() { $Request = $this->getRequest(); $User = $this->getModel("User"); if (isset($Request['Arguments']['Email'])) { $User->setEmail($Request['Arguments']['Email']); } if (isset($Request['Arguments']['Password'])) { $User->setPassword($Request['Arguments']['Password']); } $Error = null; $Email = $User->getEmail(); $Password = $User->getPassword(); if (isset($Email)) ; else { $Error = "No email given."; }; if (isset($Password)) ; else { $Error = "No password given."; } $User->Error = $Error; $View = $this->getView("Login.phtml", array("User" => $User)); return $View; } protected function Info() { $User = $this->getModel("User"); $View = $this->getView("User.phtml", array("User" => $User)); return $View; } } } ?>
Write new users to database.
(function () { 'use strict'; angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window', function ($scope, $firebase, $firebaseAuth, $window) { var ref = new Firebase("https://jpointme.firebaseio.com/"); var auth = $firebaseAuth(ref); var authData = auth.$getAuth(); if (authData) { $scope.username = authData.github.displayName; $scope.userId = authData.auth.provider + '/' + authData.auth.uid; } else { $scope.username = "anonymous"; $scope.userId = ""; } $scope.authenticate = function (provider) { var auth = $firebaseAuth(ref); auth.$authWithOAuthPopup("github").then(function (authData) { console.log("Logged in as:", authData); $scope.username = authData.github.displayName; }).catch(function (error) { console.error("Authentication failed: ", error); }); }; $scope.logout = function () { ref.unauth(); $window.location.reload(); }; var users = $firebase(ref.child("users")); var userExists = false; users.$asArray() .$loaded() .then(function(data) { angular.forEach(data,function(user,index){ if (user.oAuthId === $scope.userId) { userExists = true; } }) }).then(function(data) { if (!userExists) { users.$push({name: $scope.username, oAuthId: $scope.userId}).then(function(newChildRef) { console.log('user with userId ' + $scope.userId + ' does not exist; adding'); }); } else { console.log('user with userId ' + $scope.userId + ' already exists; not adding.'); } }); } ]); }());
(function () { 'use strict'; angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window', function ($scope, $firebase, $firebaseAuth, $window) { var ref = new Firebase("https://jpointme.firebaseio.com/"); var auth = $firebaseAuth(ref); if (auth.$getAuth()) { $scope.username = auth.$getAuth().github.displayName; } else { $scope.username = "anonymous"; } $scope.authenticate = function (provider) { var auth = $firebaseAuth(ref); auth.$authWithOAuthPopup("github").then(function (authData) { console.log("Logged in as:", authData); $scope.username = authData.github.displayName; }).catch(function (error) { console.error("Authentication failed: ", error); }); }; $scope.logout = function () { ref.unauth(); $window.location.reload(); }; } ]); }());
Update user creation method in register serializer.
from rest_framework import serializers from django.core import exceptions from django.contrib.auth import password_validation from user.models import User class CaptchaSerializer(serializers.Serializer): OPERATION_CHOICES = ( ('+', '+'), ('-', '-'), # ('/', '/'), # ('*', '*'), ) hash = serializers.CharField(max_length=100) base64image = serializers.CharField(max_length=100000) operation = serializers.ChoiceField(choices=OPERATION_CHOICES) number = serializers.IntegerField() class UserRegistrationSerializer(serializers.ModelSerializer): password_repeat = serializers.CharField(max_length=128, required=True, label='Repeat password') class Meta: model = User fields = ('id', 'username', 'email', 'password', 'password_repeat') def validate_password(self, password): password_validation.validate_password(password=password) return password def validate(self, attrs): try: # use django default validators password_validation.validate_password(password=attrs['password_repeat']) # compare passwords if attrs['password'] != attrs['password_repeat']: raise exceptions.ValidationError({'password_repeat': 'Does not equal password field.'}) except exceptions.ValidationError as e: raise serializers.ValidationError( {'password_repeat': e.messages[0]} ) return attrs def create(self, validated_data): del validated_data['password_repeat'] return User.objects.create_user(**validated_data)
from rest_framework import serializers from django.core import exceptions from django.contrib.auth import password_validation from user.models import User class CaptchaSerializer(serializers.Serializer): OPERATION_CHOICES = ( ('+', '+'), ('-', '-'), # ('/', '/'), # ('*', '*'), ) hash = serializers.CharField(max_length=100) base64image = serializers.CharField(max_length=100000) operation = serializers.ChoiceField(choices=OPERATION_CHOICES) number = serializers.IntegerField() class UserRegistrationSerializer(serializers.ModelSerializer): password_repeat = serializers.CharField(max_length=128, required=True, label='Repeat password') class Meta: model = User fields = ('id', 'username', 'email', 'password', 'password_repeat') def validate_password(self, password): password_validation.validate_password(password=password) return password def validate(self, attrs): try: # use django default validators password_validation.validate_password(password=attrs['password_repeat']) # compare passwords if attrs['password'] != attrs['password_repeat']: raise exceptions.ValidationError({'password_repeat': 'Does not equal password field.'}) except exceptions.ValidationError as e: raise serializers.ValidationError( {'password_repeat': e.messages[0]} ) return attrs def create(self, validated_data): del validated_data['password_repeat'] return User.objects.create(**validated_data)
Fix simpletag -> simple_tag Fix imports
from django import template from ..processors import find_processor, AssetRegistry register = template.Library() class AssetsNode(template.Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): context.render_context['AMN'] = AssetRegistry() content = self.nodelist.render(context) # Now output out tags extra_tags = '\n'.join(context.render_context['AMN'].items()) return mark_safe(extra_tags) + content @register.tag def assets(parser, token): nodelist = parser.parse() return AssetsNode(nodelist) @register.simple_tag(takes_context=True) def asset(context, name=None, alias=None, mode=None, *args): ''' {% asset alias mode=? ... %} {% asset file.js ... %} {% asset name depends depends... %} alias = short name for asset file = static relative filename mode = asset mode [inferred from filename extension] args == dependencies [aliases or files] ''' if alias is None and name is None: raise template.TemplateSyntaxError( 'asset tag requires at least one of name or alias' ) if name is None and mode is None: raise template.TemplateSyntaxError( 'asset tag reqires mode when using an alias' ) context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args) return ''
from django import template from damn.processors import find_processor from damn.utils import AssetRegistry, DepNode register = template.Library() class AssetsNode(template.Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): context.render_context['AMN'] = AssetRegistry() content = self.nodelist.render(context) # Now output out tags extra_tags = '\n'.join(context.render_context['AMN'].items()) return mark_safe(extra_tags) + content @register.tag def assets(parser, token): nodelist = parser.parse() return AssetsNode(nodelist) @register.simpletag(takes_context=True) def asset(context, name=None, alias=None, mode=None, *args): ''' {% asset alias mode=? ... %} {% asset file.js ... %} {% asset name depends depends... %} alias = short name for asset file = static relative filename mode = asset mode [inferred from filename extension] args == dependencies [aliases or files] ''' if alias is None and name is None: raise template.TemplateSyntaxError( 'asset tag requires at least one of name or alias' ) if name is None and mode is None: raise template.TemplateSyntaxError( 'asset tag reqires mode when using an alias' ) context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args) return ''
Add unsetProperty for property managers
<?php declare(strict_types=1); namespace LotGD\Core\Tools\Model; /** * Provides method and doctrine annotation for a property submodel */ trait PropertyManager { private $propertyStorage = null; public function loadProperties() { if ($this->propertyStorage !== null) { return; } foreach ($this->properties as $property) { $this->propertyStorage[$property->getName()] = $property; } } public function getProperty(string $name, $default = null) { $this->loadProperties(); if (isset($this->propertyStorage[$name])) { return $this->propertyStorage[$name]->getValue(); } else { return $default; } } public function unsetProperty(string $name) { $this->loadProperties(); if (isset($this->propertyStorage[$name])) { $property = $this->propertyStorage[$name]; $this->properties->removeElement($property); unset($this->propertyStorage[$name]); } } public function setProperty(string $name, $value) { $this->loadProperties(); if (isset($this->propertyStorage[$name])) { $this->propertyStorage[$name]->setValue($value); } else { $className = $this->properties->getTypeClass()->name; $property = new $className(); if (method_exists($property, "setOwner")) { $property->setOwner($this); } $property->setName($name); $property->setValue($value); $this->propertyStorage[$name] = $property; $this->properties->add($property); } } }
<?php declare(strict_types=1); namespace LotGD\Core\Tools\Model; /** * Provides method and doctrine annotation for a property submodel */ trait PropertyManager { private $propertyStorage = null; public function loadProperties() { if ($this->propertyStorage !== null) { return; } foreach ($this->properties as $property) { $this->propertyStorage[$property->getName()] = $property; } } public function getProperty(string $name, $default = null) { $this->loadProperties(); if (isset($this->propertyStorage[$name])) { return $this->propertyStorage[$name]->getValue(); } else { return $default; } } public function setProperty(string $name, $value) { $this->loadProperties(); if (isset($this->propertyStorage[$name])) { $this->propertyStorage[$name]->setValue($value); } else { $className = $this->properties->getTypeClass()->name; $property = new $className(); if (method_exists($property, "setOwner")) { $property->setOwner($this); } $property->setName($name); $property->setValue($value); $this->propertyStorage[$name] = $property; $this->properties->add($property); } } }
Fix opening files from GMail * MOPPAND-751 Signed-off-by: [email protected]
package ee.ria.DigiDoc.common; import java.io.File; import java.io.IOException; public class FileUtil { /** * Check if file path is in cache directory * * @param file File to check * @return Boolean indicating if file is in the cache directory. */ public static File getFileInDirectory(File file, File directory) throws IOException { if (file.getCanonicalPath().startsWith(directory.getCanonicalPath())) { return file; } throw new IOException("Invalid file path"); } /** * Replace invalid string characters * * @param input Input to replace invalid characters * @param replacement Replacement to replace invalid characters with * @return String with valid characters */ public static String sanitizeString(String input, char replacement) { String allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.:/%;+=@?&"; StringBuilder sb = new StringBuilder(input.length()); for (int offset = 0; offset < input.length(); offset++) { char c = input.charAt(offset); if (allowedCharacters.indexOf(c) == -1) { sb.append(replacement); } else { // Coverity does not want to see usages of the original string sb.append(allowedCharacters.charAt(allowedCharacters.indexOf(c))); } } return sb.toString(); } }
package ee.ria.DigiDoc.common; import java.io.File; import java.io.IOException; public class FileUtil { /** * Check if file path is in cache directory * * @param file File to check * @return Boolean indicating if file is in the cache directory. */ public static File getFileInDirectory(File file, File directory) throws IOException { if (file.getCanonicalPath().startsWith(directory.getCanonicalPath())) { return file; } throw new IOException("Invalid file path"); } /** * Replace invalid string characters * * @param input Input to replace invalid characters * @param replacement Replacement to replace invalid characters with * @return String with valid characters */ public static String sanitizeString(String input, char replacement) { String allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.:/%;+="; StringBuilder sb = new StringBuilder(input.length()); for (int offset = 0; offset < input.length(); offset++) { char c = input.charAt(offset); if (allowedCharacters.indexOf(c) == -1) { sb.append(replacement); } else { // Coverity does not want to see usages of the original string sb.append(allowedCharacters.charAt(allowedCharacters.indexOf(c))); } } return sb.toString(); } }
Change variable name & int comparison.
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
Fix serializer to keep 'false' values
import Ember from 'ember'; import DS from 'ember-data'; // Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html export default DS.RESTSerializer.extend({ serializeIntoHash: function(hash, type, record, options) { var serialized = this.serialize(record, options); //Remove id from the payload for new records //Jackson was complaining when it received a null or 'new' id ... if (record.get('id') == null || record.get('isNew')) { delete serialized.id; } //Remove null values Object.keys(serialized).forEach(function(k) { if (serialized[k] === null) { delete serialized[k]; } }); //Remove the root element Ember.merge(hash, serialized); }, extractMeta: function (store, type, payload) { // Read the meta information about objects that should be // reloaded - purge them from the store to force reload if (payload && payload.meta && payload.meta.purge) { payload.meta.purge.forEach(function (p) { var entity = store.getById(p.type, p.id); if (!Ember.isNone(entity)) { Ember.run.next(entity, "reload"); } }); } return this._super(store, type, payload); } });
import Ember from 'ember'; import DS from 'ember-data'; // Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html export default DS.RESTSerializer.extend({ serializeIntoHash: function(hash, type, record, options) { var serialized = this.serialize(record, options); //Remove id from the payload for new records //Jackson was complaining when it received a null or 'new' id ... if (record.get('id') == null || record.get('isNew')) { delete serialized.id; } //Remove null values Object.keys(serialized).forEach(function(k) { if (!serialized[k]) { delete serialized[k]; } }); //Remove the root element Ember.merge(hash, serialized); }, extractMeta: function (store, type, payload) { // Read the meta information about objects that should be // reloaded - purge them from the store to force reload if (payload && payload.meta && payload.meta.purge) { payload.meta.purge.forEach(function (p) { var entity = store.getById(p.type, p.id); if (!Ember.isNone(entity)) { Ember.run.next(entity, "reload"); } }); } return this._super(store, type, payload); } });
Return empty response when StopIteration is raised on exhausted iterator
from django.core.urlresolvers import reverse from avocado.events import usage from .base import FieldBase class FieldStats(FieldBase): "Field Stats Resource" def get(self, request, pk): uri = request.build_absolute_uri instance = request.instance if instance.simple_type == 'number': stats = instance.max().min().avg() elif (instance.simple_type == 'date' or instance.simple_type == 'time' or instance.simple_type == 'datetime'): stats = instance.max().min() else: stats = instance.count(distinct=True) if stats is None: resp = {} else: try: resp = next(iter(stats)) except StopIteration: resp = {} resp['_links'] = { 'self': { 'href': uri( reverse('serrano:field-stats', args=[instance.pk])), }, 'parent': { 'href': uri(reverse('serrano:field', args=[instance.pk])), }, } usage.log('stats', instance=instance, request=request) return resp
from django.core.urlresolvers import reverse from avocado.events import usage from .base import FieldBase class FieldStats(FieldBase): "Field Stats Resource" def get(self, request, pk): uri = request.build_absolute_uri instance = request.instance if instance.simple_type == 'number': stats = instance.max().min().avg() elif (instance.simple_type == 'date' or instance.simple_type == 'time' or instance.simple_type == 'datetime'): stats = instance.max().min() else: stats = instance.count(distinct=True) if stats is None: resp = {} else: resp = next(iter(stats)) resp['_links'] = { 'self': { 'href': uri( reverse('serrano:field-stats', args=[instance.pk])), }, 'parent': { 'href': uri(reverse('serrano:field', args=[instance.pk])), }, } usage.log('stats', instance=instance, request=request) return resp
Make Timeout inherit from BaseException for now.
"""Client exceptions.""" class OkException(BaseException): """Base exception for ok.py.""" pass # TODO(albert): extend from a base class designed for student bugs. class Timeout(BaseException): """Exception for timeouts.""" _message = 'Evaluation timed out!' def __init__(self, timeout): """Constructor. PARAMTERS: timeout -- int; number of seconds before timeout error occurred """ super().__init__(self) self.timeout = timeout class DeserializeError(OkException): """Exceptions related to deserialization.""" @classmethod def expect_dict(cls, json): return cls('Expected JSON dict, got {}'.format( type(json).__name__)) @classmethod def expect_list(cls, json): return cls('Expected JSON list, got {}'.format( type(json).__name__)) @classmethod def missing_fields(cls, fields): return cls('Missing fields: {}'.format( ', '.join(fields))) @classmethod def unexpected_field(cls, field): return cls('Unexpected field: {}'.format(field)) @classmethod def unexpected_value(cls, field, expect, actual): return cls( 'Field "{}" expected value {}, got {}'.format( field, expect, actual)) @classmethod def unexpected_type(cls, field, expect, actual): return cls( 'Field "{}" expected type {}, got {}'.format( field, expect, repr(actual))) @classmethod def unknown_type(cls, type_, case_map): return cls( 'TestCase type "{}" is unknown in case map {}'.format( type_, case_map))
"""Client exceptions.""" class OkException(BaseException): """Base exception for ok.py.""" pass class Timeout(OkException): """Exception for timeouts.""" _message = 'Evaluation timed out!' def __init__(self, timeout): """Constructor. PARAMTERS: timeout -- int; number of seconds before timeout error occurred """ super().__init__(self) self.timeout = timeout class DeserializeError(OkException): """Exceptions related to deserialization.""" @classmethod def expect_dict(cls, json): return cls('Expected JSON dict, got {}'.format( type(json).__name__)) @classmethod def expect_list(cls, json): return cls('Expected JSON list, got {}'.format( type(json).__name__)) @classmethod def missing_fields(cls, fields): return cls('Missing fields: {}'.format( ', '.join(fields))) @classmethod def unexpected_field(cls, field): return cls('Unexpected field: {}'.format(field)) @classmethod def unexpected_value(cls, field, expect, actual): return cls( 'Field "{}" expected value {}, got {}'.format( field, expect, actual)) @classmethod def unexpected_type(cls, field, expect, actual): return cls( 'Field "{}" expected type {}, got {}'.format( field, expect, repr(actual))) @classmethod def unknown_type(cls, type_, case_map): return cls( 'TestCase type "{}" is unknown in case map {}'.format( type_, case_map))
Fix reading in for layer_colors.
def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [ int(fields[i]) for i in range(6, len(fields), 4)] cores[core_id] = data return cores
def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [i for i in range(6, len(fields), 4)] cores[core_id] = data return cores
BB-4270: Call nonexistent method in layout expression - add exception to deteprovider decorator
<?php namespace Oro\Component\Layout; /** * The data provider decorator that allows calls methods with pre-defined prefix */ class DataProviderDecorator { /** * @var object */ protected $dataProvider; /** * @var string[] */ protected $methodPrefixes; /** * @param object $dataProvider * @param string[] $methodPrefixes */ public function __construct($dataProvider, $methodPrefixes) { if (!is_object($dataProvider)) { throw new \InvalidArgumentException( sprintf( 'Data provider must be "object" instance, "%s" given.', gettype($dataProvider) ) ); } $this->dataProvider = $dataProvider; $this->methodPrefixes = $methodPrefixes; } /** * @param string $name * @param array $arguments * @throws \BadMethodCallException */ public function __call($name, $arguments) { if (preg_match(sprintf('/^(%s)(.+)$/i', implode('|', $this->methodPrefixes)), $name, $matches)) { try { return call_user_func_array([$this->dataProvider, $name], $arguments); } catch (\BadMethodCallException $e) { throw sprintf('In the data provider does not exist method "%s".', $name); } } else { throw new \BadMethodCallException( sprintf( 'Method "%s" cannot be called. The called method in data provider should beginning with "%s".', $name, implode('", "', $this->methodPrefixes) ) ); } } }
<?php namespace Oro\Component\Layout; /** * The data provider decorator that allows calls methods with pre-defined prefix */ class DataProviderDecorator { /** * @var object */ protected $dataProvider; /** * @var string[] */ protected $methodPrefixes; /** * @param object $dataProvider * @param string[] $methodPrefixes */ public function __construct($dataProvider, $methodPrefixes) { if (!is_object($dataProvider)) { throw new \InvalidArgumentException( sprintf( 'Data provider must be "object" instance, "%s" given.', gettype($dataProvider) ) ); } $this->dataProvider = $dataProvider; $this->methodPrefixes = $methodPrefixes; } /** * @param string $name * @param array $arguments * @throws \BadMethodCallException */ public function __call($name, $arguments) { if (preg_match(sprintf('/^(%s)(.+)$/i', implode('|', $this->methodPrefixes)), $name, $matches)) { return call_user_func_array([$this->dataProvider, $name], $arguments); } else { throw new \BadMethodCallException( sprintf( 'Method "%s" cannot be called. The called method in data provider should beginning with "%s".', $name, implode('", "', $this->methodPrefixes) ) ); } } }
Move type_chack_prod module level variable and change its name to _type_check_prod
import numpy from chainer import function from chainer.utils import type_check _type_check_prod = type_check.Variable(numpy.prod, 'prod') class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_types): type_check.expect( in_types.size() == 1, _type_check_prod(in_types[0].shape) == _type_check_prod(self.shape) ) def check_type_backward(self, in_types, out_types): type_check.expect( out_types.size() == 1, _type_check_prod(in_types[0].shape) == _type_check_prod(out_types[0].shape) ) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): type_check_prod = type_check.Variable(numpy.prod, 'prod') """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_types): type_check.expect( in_types.size() == 1, self.type_check_prod(in_types[0].shape) == self.type_check_prod(self.shape) ) def check_type_backward(self, in_types, out_types): type_check.expect( out_types.size() == 1, self.type_check_prod(in_types[0].shape) == self.type_check_prod(out_types[0].shape) ) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
Introduce a more reliable id and channel for Notifications.
package com.novoda.downloadmanager; import android.app.Notification; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.v4.app.NotificationCompat; class DownloadBatchNotification implements NotificationCreator { private static final boolean NOT_INDETERMINATE = false; private static final String CHANNEL_ID = "download_manager"; private final Context context; private final int iconDrawable; DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) { this.context = context.getApplicationContext(); this.iconDrawable = iconDrawable; } @Override public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle, int percentageDownloaded, int bytesFileSize, int bytesDownloaded) { String title = downloadBatchTitle.asString(); String content = percentageDownloaded + "% downloaded"; Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID) .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE) .setSmallIcon(iconDrawable) .setContentTitle(title) .setContentText(content) .build(); return new DownloadBatchNotificationInformation(downloadBatchTitle.hashCode(), notification); } private static class DownloadBatchNotificationInformation implements NotificationInformation { private final int id; private final Notification notification; DownloadBatchNotificationInformation(int id, Notification notification) { this.id = id; this.notification = notification; } @Override public int getId() { return id; } @Override public Notification getNotification() { return notification; } } }
package com.novoda.downloadmanager; import android.app.Notification; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.v4.app.NotificationCompat; class DownloadBatchNotification implements NotificationCreator { private static final int ID = 1; private static final boolean NOT_INDETERMINATE = false; private final Context context; private final int iconDrawable; DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) { this.context = context.getApplicationContext(); this.iconDrawable = iconDrawable; } @Override public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle, int percentageDownloaded, int bytesFileSize, int bytesDownloaded) { String title = downloadBatchTitle.asString(); String content = percentageDownloaded + "% downloaded"; Notification notification = new NotificationCompat.Builder(context) .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE) .setSmallIcon(iconDrawable) .setContentTitle(title) .setContentText(content) .build(); return new DownloadBatchNotificationInformation(ID, notification); } private static class DownloadBatchNotificationInformation implements NotificationInformation { private final int id; private final Notification notification; DownloadBatchNotificationInformation(int id, Notification notification) { this.id = id; this.notification = notification; } @Override public int getId() { return id; } @Override public Notification getNotification() { return notification; } } }
Fix PHPUnit cleanup listener on suite name change
<?php declare(strict_types=1); namespace Symplify\Tests\PHPUnit\Listener; use Nette\Utils\FileSystem; use Nette\Utils\Finder; use Nette\Utils\Strings; use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use SplFileInfo; final class ClearLogAndCacheTestListener implements TestListener { use TestListenerDefaultImplementation; public function endTestSuite(TestSuite $testSuite): void { if ($testSuite->getName() !== 'all') { // skip for tests, run only for whole Test Suite return; } foreach ($this->getTempDirectories() as $path => $info) { FileSystem::delete($path); } } /** * @return string[] */ private function getTempDirectories(): array { $finder = Finder::findDirectories('cache', 'logs') ->from([ __DIR__ . '/../../../packages', sys_get_temp_dir() . '/_statie_kernel', sys_get_temp_dir() . '/_easy_coding_standard' ]); $directories = iterator_to_array($finder->getIterator()); $tempDirectories = array_filter($directories, function (SplFileInfo $file): bool { return ! Strings::contains($file->getPathname(), 'Cache'); }); return $tempDirectories; } }
<?php declare(strict_types=1); namespace Symplify\Tests\PHPUnit\Listener; use Nette\Utils\FileSystem; use Nette\Utils\Finder; use Nette\Utils\Strings; use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use SplFileInfo; final class ClearLogAndCacheTestListener implements TestListener { use TestListenerDefaultImplementation; public function endTestSuite(TestSuite $testSuite): void { if ($testSuite->getName()) { // skip for tests, run only for whole Test Suite return; } foreach ($this->getTempDirectories() as $path => $info) { FileSystem::delete($path); } } /** * @return string[] */ private function getTempDirectories(): array { $finder = Finder::findDirectories('cache', 'logs') ->from([ __DIR__ . '/../../../packages', sys_get_temp_dir() . '/_statie_kernel', sys_get_temp_dir() . '/_easy_coding_standard' ]); $directories = iterator_to_array($finder->getIterator()); $tempDirectories = array_filter($directories, function (SplFileInfo $file): bool { return ! Strings::contains($file->getPathname(), 'Cache'); }); return $tempDirectories; } }
Make the query of dataset name more reliable on different kind datasets Some datasets are created at runtime, so it could be missing fields Also prepare for dataset rename feature
import View from '../view'; import template from '../../templates/widgets/datasetInfoWidget.pug'; import '../../stylesheets/widgets/datasetInfoWidget.styl'; /** * This widget is used to diplay minerva metadata for a dataset. */ const DatasetInfoWidget = View.extend({ initialize: function (settings) { this.dataset = settings.dataset; this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this); }, render: function () { var modal = this.$el.html(template(this)) .girderModal(this); modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal })); return this; }, normalizeMetaInfo() { var meta = this.dataset.get('meta').minerva; var output = { Name: this.dataset.get('name'), Source: 'file' }; if (meta.original_files && meta.original_files[0] && meta.original_files[0].name) { output['Original name'] = meta.original_files[0].name; } else if (meta.geojson_file && meta.geojson_file.name) { output['Original name'] = meta.geojson_file.name; } switch (meta.dataset_type) { case 'geojson': output.Type = 'GeoJSON'; if (meta.postgresGeojson) { output.Source = 'PostgreSQL'; } break; case 'geotiff': output.Type = 'GeoTiff'; break; } return output; } }); export default DatasetInfoWidget;
import View from '../view'; import template from '../../templates/widgets/datasetInfoWidget.pug'; import '../../stylesheets/widgets/datasetInfoWidget.styl'; /** * This widget is used to diplay minerva metadata for a dataset. */ const DatasetInfoWidget = View.extend({ initialize: function (settings) { this.dataset = settings.dataset; this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this); }, render: function () { var modal = this.$el.html(template(this)) .girderModal(this); modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal })); return this; }, normalizeMetaInfo() { var meta = this.dataset.get('meta').minerva; var name = meta.original_files ? meta.original_files[0].name : meta.geojson_file.name; var output = { Name: name, Source: 'file' }; switch (meta.dataset_type) { case 'geojson': output.Type = 'GeoJSON'; if (meta.postgresGeojson) { output.Source = 'PostgreSQL'; } break; case 'geotiff': output.Type = 'GeoTiff'; break; } return output; } }); export default DatasetInfoWidget;
Change self.accounts to self.info for getting the cached password hash
from module.plugins.Account import Account from module.common.json_layer import json_loads class ReloadCc(Account): __name__ = "ReloadCc" __version__ = "0.1" __type__ = "account" __description__ = """Reload.Cc account plugin""" __author_name__ = ("Reload Team") __author_mail__ = ("[email protected]") def loadAccountInfo(self, user, req): # Get user data from reload.cc status = self.getAccountStatus(user, req) # Parse account info account_info = {"validuntil": float(status['msg']['expires']), "pwdhash": status['msg']['hash'], "trafficleft": -1} return account_info def login(self, user, data, req): # Get user data from reload.cc status = self.getAccountStatus(user, req) # Check if user and password are valid if status['status'] != "ok": self.wrongPassword() def getAccountStatus(self, user, req): pwd = "pwd=%s" % self.accounts[user]['password'] try: pwd = "hash=%s" % self.infos[user]['pwdhash'] except Exception: pass # Use reload.cc API v1 to retrieve account info and return the parsed json answer answer = req.load("https://api.reload.cc/login?via=pyload&v=1&get_traffic=true&user=%s&%s" % (user, pwd)) return json_loads(answer)
from module.plugins.Account import Account from module.common.json_layer import json_loads class ReloadCc(Account): __name__ = "ReloadCc" __version__ = "0.1" __type__ = "account" __description__ = """Reload.Cc account plugin""" __author_name__ = ("Reload Team") __author_mail__ = ("[email protected]") def loadAccountInfo(self, user, req): # Get user data from reload.cc status = self.getAccountStatus(user, req) # Parse account info account_info = {"validuntil": float(status['msg']['expires']), "pwdhash": status['msg']['hash'], "trafficleft": -1} return account_info def login(self, user, data, req): # Get user data from reload.cc status = self.getAccountStatus(user, req) # Check if user and password are valid if status['status'] != "ok": self.wrongPassword() def getAccountStatus(self, user, req): pwd = "pwd=%s" % self.accounts[user]['password'] try: pwd = "hash=%s" % self.accounts[user]['pwdhash'] except Exception: pass # Use reload.cc API v1 to retrieve account info and return the parsed json answer answer = req.load("https://api.reload.cc/login?via=pyload&v=1&get_traffic=true&user=%s&%s" % (user, pwd)) return json_loads(answer)
Change gender to represent boolean female
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnimalTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('animal', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string("name", 255); $table->integer("dob")->nullable(); $table->boolean("female")->default(true); $table->integer("father")->unsigned()->nullable(); $table->integer("mother")->unsigned()->nullable(); $table->boolean("active")->default(false); $table->boolean("own")->default(false); $table->dateTime('created_at'); $table->dateTime('updated_at'); }); Schema::table('animal', function (Blueprint $table) { $table->foreign("father")->references("id")->on("animal"); $table->foreign("mother")->references("id")->on("animal"); $table->unique(["name", "dob"]); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('animal'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnimalTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('animal', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string("name", 255); $table->integer("dob")->nullable(); $table->enum("gender", ["male", "female"]); $table->integer("father")->unsigned()->nullable(); $table->integer("mother")->unsigned()->nullable(); $table->boolean("active")->default(false); $table->boolean("own")->default(false); $table->dateTime('created_at'); $table->dateTime('updated_at'); }); Schema::table('animal', function (Blueprint $table) { $table->foreign("father")->references("id")->on("animal"); $table->foreign("mother")->references("id")->on("animal"); $table->unique(["name", "dob"]); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('animal'); } }
[Test] Change testTypeInvalid: string to integer
<?php include 'plan.php'; class PlanTest extends \PHPUnit_Framework_TestCase { /** * @covers ScalarValidator::__invoke */ public function testScalar() { $validator = plan('hello'); $result = $validator('hello'); $this->assertEquals('hello', $result); } /** * @expectedException InvalidException * @expectedExceptionMessage 'world' is not 'hello' */ public function testScalarInvalid() { $validator = plan('hello'); $validator('world'); } /** * @covers Type::__invoke */ public function testType() { $validator = plan(new StringType()); $this->assertEquals('hello', $validator('hello')); $this->assertEquals('world', $validator('world')); } /** * @expectedException SchemaException * @expectedExceptionMessage Unknown type ravioli */ public function testTypeUnknown() { plan(new Type('ravioli')); } /** * @expectedException InvalidException * @expectedExceptionMessage '123' is not of type integer */ public function testTypeInvalid() { $validator = plan(new IntegerType()); $validator('123'); } }
<?php include 'plan.php'; class PlanTest extends \PHPUnit_Framework_TestCase { /** * @covers ScalarValidator::__invoke */ public function testScalar() { $validator = plan('hello'); $result = $validator('hello'); $this->assertEquals('hello', $result); } /** * @expectedException InvalidException * @expectedExceptionMessage 'world' is not 'hello' */ public function testScalarInvalid() { $validator = plan('hello'); $validator('world'); } /** * @covers Type::__invoke */ public function testType() { $validator = plan(new StringType()); $this->assertEquals('hello', $validator('hello')); $this->assertEquals('world', $validator('world')); } /** * @expectedException SchemaException * @expectedExceptionMessage Unknown type ravioli */ public function testTypeUnknown() { plan(new Type('ravioli')); } /** * @expectedException InvalidException * @expectedExceptionMessage 123 is not of type string */ public function testTypeInvalid() { $validator = plan(new StringType()); $validator(123); } }
Revert setting methods as protected
<?php namespace Tait\ModelLogging; use Tait\ModelLogging\ModelLog; use Auth; trait LoggableTrait { /** * Get all logs for this object * * @return collection */ public function getAllLogs() { return ModelLog:: with('user') ->where('content_id', '=', $this->id) ->where('content_type', '=', class_basename($this)) ->get(); } /** * Get paginated logs for this object * * @return collection */ public function getPaginatedLogs($per_page = 10) { return ModelLog:: with('user') ->where('content_id', '=', $this->id) ->where('content_type', '=', class_basename($this)) ->paginate($per_page); } /** * Save a new log * * @param array $settings An array of settings to override the defaults * * @return void */ public function saveLog(array $settings) { $log = new ModelLog; $log->fill(array_merge($this->getDefaults(), $settings)); $log->save(); } /** * Get some sensible defaults for this class * * @return array */ protected function getDefaults() { return [ 'user_id' => Auth::id(), 'content_id' => $this->id, 'content_type' => class_basename($this), 'action' => '', 'description' => null, ]; } }
<?php namespace Tait\ModelLogging; use Tait\ModelLogging\ModelLog; use Auth; trait LoggableTrait { /** * Get all logs for this object * * @return collection */ protected function getAllLogs() { return ModelLog:: with('user') ->where('content_id', '=', $this->id) ->where('content_type', '=', class_basename($this)) ->get(); } /** * Get paginated logs for this object * * @return collection */ protected function getPaginatedLogs($per_page = 10) { return ModelLog:: with('user') ->where('content_id', '=', $this->id) ->where('content_type', '=', class_basename($this)) ->paginate($per_page); } /** * Save a new log * * @param array $settings An array of settings to override the defaults * * @return void */ public function saveLog(array $settings) { $log = new ModelLog; $log->fill(array_merge($this->getDefaults(), $settings)); $log->save(); } /** * Get some sensible defaults for this class * * @return array */ protected function getDefaults() { return [ 'user_id' => Auth::id(), 'content_id' => $this->id, 'content_type' => class_basename($this), 'action' => '', 'description' => null, ]; } }
Return DNS data in the correct format
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
Rename var to more meaningful name
package com.fourlastor.dante.html; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ImageSpan; import com.fourlastor.dante.parser.Block; import com.fourlastor.dante.parser.BlockListener; class ImgListener implements BlockListener { private static final String UNICODE_REPLACE = "\uFFFC"; private static final String IMG = "img"; private final ImgLoader imgLoader; ImgListener(ImgLoader imgLoader) { this.imgLoader = imgLoader; } @Override public void start(Block block, SpannableStringBuilder text) { String src = ((HtmlBlock) block).getAttributes().get("src"); if (src == null) { return; } int originalLength = text.length(); text.append(UNICODE_REPLACE); Drawable image = imgLoader.loadImage(src); text.setSpan( new ImageSpan(image, src), originalLength, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } @Override public void end(Block block, SpannableStringBuilder text) { // nothing to do here } @Override public boolean match(Block block) { return block instanceof HtmlBlock && IMG.equalsIgnoreCase(((HtmlBlock) block).getName()); } }
package com.fourlastor.dante.html; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ImageSpan; import com.fourlastor.dante.parser.Block; import com.fourlastor.dante.parser.BlockListener; class ImgListener implements BlockListener { private static final String UNICODE_REPLACE = "\uFFFC"; private static final String IMG = "img"; private final ImgLoader imgLoader; ImgListener(ImgLoader imgLoader) { this.imgLoader = imgLoader; } @Override public void start(Block block, SpannableStringBuilder text) { String src = ((HtmlBlock) block).getAttributes().get("src"); if (src == null) { return; } int len = text.length(); text.append(UNICODE_REPLACE); Drawable image = imgLoader.loadImage(src); text.setSpan( new ImageSpan(image, src), len, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } @Override public void end(Block block, SpannableStringBuilder text) { // nothing to do here } @Override public boolean match(Block block) { return block instanceof HtmlBlock && IMG.equalsIgnoreCase(((HtmlBlock) block).getName()); } }
Change names for CNR,SNR fields
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMamsurveydataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mamsurveydata', function (Blueprint $table) { $table->increments('id'); $table->integer('survey_id')->unsigned(); $table->integer('machine_id')->unsigned(); $table->integer('tube_id')->unsigned()->nullable(); $table->string('target_filter',6); $table->float('avg_illumination')->nullable(); $table->float('mgd_2d', 4, 2)->nullable(); $table->float('mgd_3d', 4, 2)->nullable(); $table->float('mgd_combo', 4, 2)->nullable(); $table->float('cnr', 5, 2)->nullable(); $table->float('snr', 5, 2)->nullable(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mamsurveydata'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMamsurveydataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mamsurveydata', function (Blueprint $table) { $table->increments('id'); $table->integer('survey_id')->unsigned(); $table->integer('machine_id')->unsigned(); $table->integer('tube_id')->unsigned()->nullable(); $table->string('target_filter',6); $table->float('avg_illumination')->nullable(); $table->float('mgd_2d', 4, 2)->nullable(); $table->float('mgd_3d', 4, 2)->nullable(); $table->float('mgd_combo', 4, 2)->nullable(); $table->float('CNR', 5, 2)->nullable(); $table->float('SNR', 5, 2)->nullable(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mamsurveydata'); } }
Add cancel button to note
<div class='note-form-wrapper'> <textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea> <button class="submit btn btn-green">Submit</button> <button class="cancel btn btn-gray">Cancel</button> </div> <script type='text/javascript'> jQuery('.submit').bind('click', submitNote); jQuery('.cancel').bind('click', cancelNote); function submitNote(event){ event.preventDefault(); var btn = jQuery(this); var note = jQuery('.flight-note').val(); var root_li = btn.closest('li'); var form = jQuery('.note-form', root_li); var open_link = jQuery('.flight-note-link', root_li); jQuery.ajax({ url: '<?php echo url_for("@flight_note_process?id={$flight->getId()}") ?>', dataType: 'json', data: {note: note}, type: 'post', success: function(data) { if(data.result == 'OK'){ if(note){ open_link.text('Update Note'); } else { open_link.text('Add Note'); } form.removeClass('open').hide(500); jQuery('.note-form-wrapper', form).remove(); } } }); } function cancelNote(event){ event.preventDefault(); var btn = jQuery(this); var root_li = btn.closest('li'); var form = jQuery('.note-form', root_li); form.removeClass('open').hide(500); jQuery('.note-form-wrapper', form).remove(); } </script>
<div class='note-form-wrapper'> <textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea> <button type="submit" class="submit btn btn-green"><?php echo $flight->getFlightNote() ? 'Update Note' : 'Add Note' ?></button> </div> <script type='text/javascript'> jQuery('.submit').bind('click', function(event){ event.preventDefault(); var btn = jQuery(this); var note = jQuery('.flight-note').val(); jQuery.ajax({ url: '<?php echo url_for("@flight_note_process?id={$flight->getId()}") ?>', dataType: 'json', data: {note: note}, type: 'post', success: function(data) { if(data.result == 'OK'){ var root_li = btn.closest('li'); var form = jQuery('.note-form', root_li); var open_link = jQuery('.flight-note-link', root_li); if(note){ open_link.text('Update Note'); } else { open_link.text('Add Note'); } form.removeClass('open').hide(500); jQuery('.note-form-wrapper', form).remove(); } } }); }); </script>
tests: Remove reference to deleted file
var path = require('path'); var chai = require('chai'); chai.use(require('chai-fs')); chai.should(); const ROOT_DIR = path.join(process.cwd(), '..'); describe('As a dev', function() { describe('when testing cartridge file structure', function() { it('then _config files should exist', function() { var pathToTest = path.join(ROOT_DIR, '_config/'); var filePathToTest; var files = [ 'project.json' ]; files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required base files should exist', function() { var filePathToTest; var files = [ 'gulpfile.js', 'package.json', 'readme.md', ]; files.forEach(function(fileName) { filePathToTest = path.join(ROOT_DIR, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required handlebars view files should exist', function() { var pathToTest = path.join(ROOT_DIR, 'views/'); var files = [ 'index.hbs', 'styleguide.hbs', ] files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) }); });
var path = require('path'); var chai = require('chai'); chai.use(require('chai-fs')); chai.should(); const ROOT_DIR = path.join(process.cwd(), '..'); describe('As a dev', function() { describe('when testing cartridge file structure', function() { it('then _config files should exist', function() { var pathToTest = path.join(ROOT_DIR, '_config/'); var filePathToTest; var files = [ 'project.json', 'paths.js' ]; files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required base files should exist', function() { var filePathToTest; var files = [ 'gulpfile.js', 'package.json', 'readme.md', ]; files.forEach(function(fileName) { filePathToTest = path.join(ROOT_DIR, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required handlebars view files should exist', function() { var pathToTest = path.join(ROOT_DIR, 'views/'); var files = [ 'index.hbs', 'styleguide.hbs', ] files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) }); });
Increase coverage to match update
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 100, statements: 100 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 98, statements: 98 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
Delete non-digit characters in ISBN in server side
from decimal import Decimal import re from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from books.models import BookType, Book from common.bookchooserwizard import BookChooserWizard class SellWizard(BookChooserWizard): @property def page_title(self): return _("Sell books") @property def url_namespace(self): return "sell" @property def session_var_name(self): return "sell_chosen_books" @property def feature_add_new(self): return True def process_books_summary(self, session, user, book_list): for book in book_list: amount = book['amount'] del book['amount'] user.save() dbbook = Book(owner=user, accepted=False, sold=False) if 'pk' in book: dbbook.book_type_id = book['pk'] else: book['isbn'] = re.sub(r'[^\d.]+', '', book['isbn']) book['price'] = Decimal(book['price']) if book['publication_year'] == "": book['publication_year'] = 1970 book_type = BookType(**book) book_type.save() dbbook.book_type = book_type for i in range(0, amount): dbbook.pk = None dbbook.save() return True, None def success(self, request): return render(request, 'sell/success.html')
from decimal import Decimal from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from books.models import BookType, Book from common.bookchooserwizard import BookChooserWizard class SellWizard(BookChooserWizard): @property def page_title(self): return _("Sell books") @property def url_namespace(self): return "sell" @property def session_var_name(self): return "sell_chosen_books" @property def feature_add_new(self): return True def process_books_summary(self, session, user, book_list): for book in book_list: amount = book['amount'] del book['amount'] user.save() dbbook = Book(owner=user, accepted=False, sold=False) if 'pk' in book: dbbook.book_type_id = book['pk'] else: book['price'] = Decimal(book['price']) if book['publication_year'] == "": book['publication_year'] = 1970 book_type = BookType(**book) book_type.save() dbbook.book_type = book_type for i in range(0, amount): dbbook.pk = None dbbook.save() return True, None def success(self, request): return render(request, 'sell/success.html')
Exclude 1.11's "unbreakable" common tag
package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** Exclusions class for blacklisting objects and fields in Gson */ public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); return // Ignore dynamic CraftBukkit handle field name.equalsIgnoreCase("handle") // Ignore book page contents || name.equalsIgnoreCase("pages") // Ignore unsupported tags || name.equalsIgnoreCase("unhandledTags") // Ignore redundant data object || name.equalsIgnoreCase("data") // Ignore hide flags || name.equalsIgnoreCase("hideFlag") // Ignore repair costs || name.equalsIgnoreCase("repairCost") // Ignore skull profiles || name.equalsIgnoreCase("profile") // Ignore shield patterns || name.equalsIgnoreCase("blockEntityTag") // Ignore 1.11 unbreakable tag || name.equalsIgnoreCase("unbreakable"); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); if ( name.equalsIgnoreCase("ItemStack") ) if ( clazz.getTypeName().startsWith("net.minecraft.server") ) return true; return name.equalsIgnoreCase("ChatComponentText"); } }
package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** Exclusions class for blacklisting objects and fields in Gson */ public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); return // Ignore dynamic CraftBukkit handle field name.equalsIgnoreCase("handle") // Ignore book page contents || name.equalsIgnoreCase("pages") // Ignore unsupported tags || name.equalsIgnoreCase("unhandledTags") // Ignore redundant data object || name.equalsIgnoreCase("data") // Ignore hide flags || name.equalsIgnoreCase("hideFlag") // Ignore repair costs || name.equalsIgnoreCase("repairCost") // Ignore skull profiles || name.equalsIgnoreCase("profile") // Ignore shield patterns || name.equalsIgnoreCase("blockEntityTag"); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); if ( name.equalsIgnoreCase("ItemStack") ) if ( clazz.getTypeName().startsWith("net.minecraft.server") ) return true; return name.equalsIgnoreCase("ChatComponentText"); } }
Edit gruntfile: create task less2css
module.exports = function(grunt) { // config grunt.initConfig({ less: { build: { expand: true, cwd: 'src/less/', src: ['**/*.less'], dest: 'build/css/', ext: '.css' } }, csslint: { check: { src: '<%= less.build.dest %>**/*.css' } }, watch: { less: { files: 'src/less/**/*.less', tasks: ['less', 'csslint'] } }, typescript: { build: { expand: true, cwd: 'src/ts/', src: ['**/*.ts', '!node_modules/**/*.ts'], dest: 'build/js/', ext: '.js', options: { noImplicitAny: true } } } }); // plugin grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-csslint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-typescript'); // tasks grunt.registerTask('less2css', ['less', 'csslint']); grunt.registerTask('default', ['less2css', 'typescript']); };
module.exports = function(grunt) { // config grunt.initConfig({ less: { build: { expand: true, cwd: 'src/less/', src: ['**/*.less'], dest: 'build/css/', ext: '.css' } }, csslint: { check: { src: '<%= less.build.dest %>**/*.css' } }, watch: { less2css: { files: 'src/css/*.less', tasks: ['less', 'csslint'] } }, typescript: { build: { expand: true, cwd: 'src/ts/', src: ['**/*.ts', '!node_modules/**/*.ts'], dest: 'build/js/', ext: '.js', options: { noImplicitAny: true } } } }); // plugin grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-csslint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-typescript'); // tasks grunt.registerTask('default', ['less', 'csslint', 'typescript']); };
Remove useless logic to show page action when activate tab.
( function () { var isDebugging = false; var re = /saas.hp(.*).com\/agm/; function isAgmSite(url){ return re.test(url); } function onCopyClicked(tab) { var re = /saas.hp(.*).com\//; if (!isAgmSite(tab.url)) { console.log("Nothing to copy, since the URL does not look like AGM site, URL: " + tab.url); if (!isDebugging){ return; } } chrome.tabs.sendMessage(tab.id, { action: "copy" }, function (response) { if (response && response.data) { copyText(response.data); } }); } // show page action for tabs that matches the condition. chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) { if (!isAgmSite(tab.url)) { chrome.pageAction.hide(tabid); if (!isDebugging) { return; } } chrome.pageAction.show(tabid); chrome.pageAction.onClicked.removeListener(onCopyClicked); chrome.pageAction.onClicked.addListener(onCopyClicked); }); function copyText(text) { var input = document.createElement('textarea'); document.body.appendChild(input); input.value = text; input.focus(); input.select(); document.execCommand('Copy'); input.remove(); }; })();
( function () { var isDebugging = false; var re = /saas.hp(.*).com\/agm/; function isAgmSite(url){ return re.test(url); } function onCopyClicked(tab) { var re = /saas.hp(.*).com\//; if (!isAgmSite(tab.url)) { console.log("Nothing to copy, since the URL does not look like AGM site, URL: " + tab.url); if (!isDebugging){ return; } } chrome.tabs.sendMessage(tab.id, { action: "copy" }, function (response) { if (response && response.data) { copyText(response.data); } }); } // show page action for tabs that matches the condition. chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) { if (!isAgmSite(tab.url)) { chrome.pageAction.hide(tabid); if (!isDebugging) { return; } } chrome.pageAction.show(tabid); chrome.pageAction.onClicked.removeListener(onCopyClicked); chrome.pageAction.onClicked.addListener(onCopyClicked); }); chrome.tabs.onActivated.addListener(function(activeInfo){ chrome.pageAction.show(activeInfo.tabId); chrome.pageAction.onClicked.removeListener(onCopyClicked); chrome.pageAction.onClicked.addListener(onCopyClicked); }) function copyText(text) { var input = document.createElement('textarea'); document.body.appendChild(input); input.value = text; input.focus(); input.select(); document.execCommand('Copy'); input.remove(); }; })();
Fix bug in no sha use case
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
Add a sortyBy comparator to spine collection
"use strict"; /** * Collection of spines. **/ define([ "underscore", "backbone" ], function(_, Backbone) { var SpineCollection = Backbone.Collection.extend({ filterKey: null, /** * sortBy comparator: return the title, by which BB will sort the collection. **/ comparator: function(spine) { return spine.get("title"); }, url: function() { var url = "_view/spines"; if (!_.isNull(this.filterKey)) { // Get a subset of the spines, by the given key. url = url + '?key="' + this.filterKey + '"'; } return url; }, /** * Parse the returned JSON. **/ parse: function(response, options){ var parsed = []; if (_.has(response, "rows") && _.isArray(response.rows)) { _.each(response.rows, function(row) { parsed.push({ id: row.id, firstLetter: row.value.firstLetter, title: row.value.title }); }); } return parsed; } }); return SpineCollection; });
"use strict"; /** * Collection of spines. **/ define([ "underscore", "backbone" ], function(_, Backbone) { var SpineCollection = Backbone.Collection.extend({ filterKey: null, url: function() { var url = "_view/spines"; if (!_.isNull(this.filterKey)) { // Get a subset of the spines, by the given key. url = url + '?key="' + this.filterKey + '"'; } return url; }, /** * Parse the returned JSON. **/ parse: function(response, options){ var parsed = []; if (_.has(response, "rows") && _.isArray(response.rows)) { _.each(response.rows, function(row) { parsed.push({ id: row.id, firstLetter: row.value.firstLetter, title: row.value.title }); }); } return parsed; } }); return SpineCollection; });
Set utf-8 as default encoding.
# -*- coding: utf-8 -*- import scrapy import scrapy.selector from brasileirao.items import BrasileiraoItem import hashlib class ResultsSpider(scrapy.Spider): name = "results" start_urls = [ 'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/', ] def parse(self, response): actual_round = 0 for rodada in response.css('.rodadas .confrontos li'): actual_round += 1 for game in rodada.css(".confronto"): home_team = game.css(".partida .time1") away_team = game.css(".partida .time2") item = BrasileiraoItem() item['rodada'] = actual_round item['home_team'] = home_team.css("abbr::attr(title)").extract_first() item['away_team'] = away_team.css("abbr::attr(title)").extract_first() item['home_score'] = home_team.css(".gols::text").extract_first() item['away_score'] = away_team.css(".gols::text").extract_first() item['date'] = game.css(".info-partida time::attr(datetime)").extract_first() id = item['home_team'] + item['away_team'] item['id'] = hashlib.md5(id).hexdigest() yield item
import scrapy import scrapy.selector from brasileirao.items import BrasileiraoItem import hashlib class ResultsSpider(scrapy.Spider): name = "results" start_urls = [ 'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/', ] def parse(self, response): actual_round = 0 for rodada in response.css('.rodadas .confrontos li'): actual_round += 1 for game in rodada.css(".confronto"): home_team = game.css(".partida .time1") away_team = game.css(".partida .time2") item = BrasileiraoItem() item['rodada'] = actual_round item['home_team'] = home_team.css("abbr::attr(title)").extract_first().encode('utf8') item['away_team'] = away_team.css("abbr::attr(title)").extract_first().encode('utf8') item['home_score'] = home_team.css(".gols::text").extract_first() item['away_score'] = away_team.css(".gols::text").extract_first() item['date'] = game.css(".info-partida time::attr(datetime)").extract_first() id = item['home_team'] + item['away_team'] item['id'] = hashlib.md5(id).hexdigest() yield item
Add KDE show & hide logging
# -*- coding: utf-8 -*- # Copyright 2013 Jacek Mitręga # 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 __future__ import unicode_literals import envoy import logging logger = logging.getLogger(__name__) class KdeWindowManager(object): def __init__(self, workspace=6): self.prev_workspace = 1 self.workspace = 6 def show(self): logger.info('kde show') envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6', timeout=2) # envoy.run('killall firefox', timeout=2) # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12') def hide(self): logger.info('kde hide') envoy.run(('qdbus org.kde.kwin /KWin ' 'org.kde.KWin.setCurrentDesktop {}') .format(self.prev_workspace), timeout=2) # envoy.run('killall firefox', timeout=2)
# -*- coding: utf-8 -*- # Copyright 2013 Jacek Mitręga # 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 __future__ import unicode_literals import envoy import logging logger = logging.getLogger(__name__) class KdeWindowManager(object): def __init__(self, workspace=6): self.prev_workspace = 1 self.workspace = 6 def show(self): envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6', timeout=2) # envoy.run('killall firefox', timeout=2) # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12') def hide(self): envoy.run(('qdbus org.kde.kwin /KWin ' 'org.kde.KWin.setCurrentDesktop {}') .format(self.prev_workspace), timeout=2) # envoy.run('killall firefox', timeout=2)
STASHDEV-6530: Update front-end code to stop using APIs removed in Stash 3.0
define('plugin/download-archive', [ 'jquery', 'aui', 'model/page-state', 'util/navbuilder', 'exports' ], function( $, AJS, pageState, navBuilder, exports ) { exports.onReady = function (buttonSelector) { var $button = $(buttonSelector); /** * Update the "download archive" button's URL to target the specified ref. * * @param revisionRef the ref that the archive button should target. Falsey means no ref to be set, which will * cause the server to default to HEAD of the default branch. */ var updateDownloadRef = function(revisionRef) { $button.attr("href", AJS.contextPath() + "/plugins/servlet/archive/projects/" + encodeURIComponent(pageState.getProject().getKey()) + "/repos/" + encodeURIComponent(pageState.getRepository().getSlug()) + (revisionRef ? "?at=" + encodeURIComponent(revisionRef) : "")); }; // On page load, grab the current ref out of page-state var currentRef = pageState.getRevisionRef() ? pageState.getRevisionRef().id : null; updateDownloadRef(currentRef); // Also, bind to the branch selector's change event to grab the newly selected ref eve.on('stash.feature.repository.revisionReferenceSelector.revisionRefChanged', function(revisionRef, context) { updateDownloadRef(revisionRef.id); }); } }); AJS.$(function() { require('plugin/download-archive').onReady('#download-archive-button'); });
define('plugin/download-archive', ['jquery', 'aui', 'model/page-state', 'util/navbuilder', 'exports'], function ($, AJS, pageState, navBuilder, exports) { exports.onReady = function (buttonSelector) { var $button = $(buttonSelector); /** * Update the "download archive" button's URL to target the specified ref. * * @param revisionRef the ref that the archive button should target. Falsey means no ref to be set, which will * cause the server to default to HEAD of the default branch. */ var updateDownloadRef = function(revisionRef) { $button.attr("href", AJS.contextPath() + "/plugins/servlet/archive/projects/" + encodeURIComponent(pageState.getProject().key) + "/repos/" + encodeURIComponent(pageState.getRepository().slug) + (revisionRef ? "?at=" + encodeURIComponent(revisionRef) : "")); }; // On page load, grab the current ref out of page-state var currentRef = pageState.getRevisionRef() ? pageState.getRevisionRef().id : null; updateDownloadRef(currentRef); // Also, bind to the branch selector's change event to grab the newly selected ref eve.on('stash.feature.repository.revisionReferenceSelector.revisionRefChanged', function(revisionRef, context) { updateDownloadRef(revisionRef.id); }); } }); AJS.$(function() { require('plugin/download-archive').onReady('#download-archive-button'); });
Remove _getView() usages from renderAdapter
<?php class CM_RenderAdapter_FormField extends CM_RenderAdapter_Abstract { public function fetch(array $params, CM_FormField_Abstract $field, CM_Form_Abstract $form, $fieldName) { $fieldName = (string) $fieldName; /** @var CM_FormField_Abstract $field */ $field->prepare($params); $field->setTplParam('field', $field); $field->setTplParam('id', $form->getTagAutoId($fieldName . '-input')); $field->setTplParam('name', $fieldName); $field->setTplParam('value', $field->getValue()); $field->setTplParam('options', $field->getOptions()); $html = '<div class="' . implode(' ', $field->getClassHierarchy()) . '" id="' . $form->getAutoId() . '-' . $fieldName . '">'; $viewResponse = new CM_ViewResponse($field); $viewResponse->setTemplateName('default'); $viewResponse->setData($field->getTplParams()); $html .= trim($this->getRender()->renderViewResponse($viewResponse)); if (!$field instanceof CM_FormField_Hidden) { $html .= '<span class="messages"></span>'; } $html .= '</div>'; return $html; } /** * @param string $tplName * @param array $params * @return string */ public function fetchTemplate($tplName, array $params) { return $this->_renderTemplate($tplName, $params, true); } }
<?php class CM_RenderAdapter_FormField extends CM_RenderAdapter_Abstract { public function fetch(array $params, CM_FormField_Abstract $field, CM_Form_Abstract $form, $fieldName) { $fieldName = (string) $fieldName; /** @var CM_FormField_Abstract $field */ $field->prepare($params); $field->setTplParam('field', $field); $field->setTplParam('id', $form->getTagAutoId($fieldName . '-input')); $field->setTplParam('name', $fieldName); $field->setTplParam('value', $field->getValue()); $field->setTplParam('options', $field->getOptions()); $html = '<div class="' . implode(' ', $field->getClassHierarchy()) . '" id="' . $form->getAutoId() . '-' . $fieldName . '">'; $viewResponse = new CM_ViewResponse($this->_getView()); $viewResponse->setTemplateName('default'); $viewResponse->setData($field->getTplParams()); $html .= trim($this->getRender()->renderViewResponse($viewResponse)); if (!$field instanceof CM_FormField_Hidden) { $html .= '<span class="messages"></span>'; } $html .= '</div>'; return $html; } /** * @param string $tplName * @param array $params * @return string */ public function fetchTemplate($tplName, array $params) { return $this->_renderTemplate($tplName, $params, true); } }
Add very basic date filtering
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var start = new Date(1971, 0, 1); if (req.query.start) { start = new Date(req.query.start); } var o = { map: function () { if (this.parents.length === 1 && this.date >= start) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; }, out: { replace: 'PersonReduce' }, scope: { start: start } }; db.Commit.mapReduce(o, function (err, model) { if (err) { res.send(err); } else { model.find().populate({ path: "_id", model: "Person" }).exec(function (err, results) { if (err) { res.send(err); } else { var data = results.map(function (result) { return { author: result._id.name, additions: result.value.additions, deletions: result.value.deletions }; }); res.send(data); } }); } }); }); module.exports = router;
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var o = { map: function () { if (this.parents.length === 1) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; }, out: { replace: 'PersonReduce' } }; db.Commit.mapReduce(o, function (err, model) { if (err) { res.send(err); } else { model.find().populate({ path: "_id", model: "Person" }).exec(function (err, results) { if (err) { res.send(err); } else { var data = results.map(function (result) { return { author: result._id.name, additions: result.value.additions, deletions: result.value.deletions }; }); res.send(data); } }); } }); }); module.exports = router;
Add SearchButton component to Header component
import React from 'react'; import styled from 'styled-components'; import theme from 'theme'; import Hamburger, { Bar } from 'components/Hamburger'; import SearchButton from 'components/SearchButton'; const Logo = styled.h1` font-family: Poppins, sans-serif; letter-spacing: 1px; font-size: 30px; margin: 0; display: inline; flex: 0 0 calc(100% - 130px); text-align: center; `; const MenuButton = styled.div` display: inline-flex; cursor: pointer; justify-content: center; align-items: center; height: 100%; width: 65px; border-right: 1px solid ${theme.lightGray}; flex: 0 0 65px; &:hover { ${Bar} { &::after { left: 0; } } } `; const StyledHeader = styled.header` border-bottom: 1px solid ${theme.lightGray}; height: 70px; display: flex; align-items: center; `; class Header extends React.PureComponent { render() { return ( <StyledHeader role="banner"> <MenuButton> <Hamburger /> </MenuButton> <Logo>MMDb</Logo> <MenuButton> <SearchButton /> </MenuButton> </StyledHeader> ); } } Header.propTypes = { }; export default Header;
import React from 'react'; import styled from 'styled-components'; import theme from 'theme'; import Hamburger, { Bar } from 'components/Hamburger'; const Logo = styled.h1` font-family: Poppins, sans-serif; letter-spacing: 1px; font-size: 30px; margin: 0; display: inline; flex: 0 0 calc(100% - 130px); text-align: center; `; const MenuButton = styled.div` display: inline-flex; cursor: pointer; justify-content: center; align-items: center; height: 100%; width: 65px; border-right: 1px solid ${theme.lightGray}; flex: 0 0 65px; &:hover { ${Bar} { &::after { left: 0; } } } `; const StyledHeader = styled.header` border-bottom: 1px solid ${theme.lightGray}; height: 70px; display: flex; align-items: center; `; class Header extends React.PureComponent { render() { return ( <StyledHeader role="banner"> <MenuButton> <Hamburger /> </MenuButton> <Logo>MMDb</Logo> </StyledHeader> ); } } Header.propTypes = { }; export default Header;
Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it.
package net.minecraftforge.common; import java.util.UUID; import net.minecraft.src.*; import net.minecraftforge.event.*; import net.minecraftforge.event.entity.*; import net.minecraftforge.event.world.WorldEvent; public class ForgeInternalHandler { @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onEntityJoinWorld(EntityJoinWorldEvent event) { if (!event.world.isRemote) { if (event.entity.getPersistentID() == null) { event.entity.generatePersistentID(); } else { ForgeChunkManager.loadEntity(event.entity); } } Entity entity = event.entity; if (entity.getClass().equals(EntityItem.class)) { ItemStack item = ((EntityItem)entity).item; if (item != null && item.getItem().hasCustomEntity(item)) { Entity newEntity = item.getItem().createEntity(event.world, entity, item); if (newEntity != null) { entity.setDead(); event.setCanceled(true); event.world.spawnEntityInWorld(newEntity); } } } } @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onDimensionLoad(WorldEvent.Load event) { ForgeChunkManager.loadWorld(event.world); } @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onDimensionSave(WorldEvent.Save event) { ForgeChunkManager.saveWorld(event.world); } }
package net.minecraftforge.common; import java.util.UUID; import net.minecraft.src.*; import net.minecraftforge.event.*; import net.minecraftforge.event.entity.*; import net.minecraftforge.event.world.WorldEvent; public class ForgeInternalHandler { @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onEntityJoinWorld(EntityJoinWorldEvent event) { if (!event.world.isRemote) { if (event.entity.getPersistentID() == null) { event.entity.generatePersistentID(); } else { ForgeChunkManager.loadEntity(event.entity); } } Entity entity = event.entity; if (entity instanceof EntityItem) { ItemStack item = ((EntityItem)entity).item; if (item != null && item.getItem().hasCustomEntity(item)) { Entity newEntity = item.getItem().createEntity(event.world, entity, item); if (newEntity != null) { entity.setDead(); event.setCanceled(true); event.world.spawnEntityInWorld(newEntity); } } } } @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onDimensionLoad(WorldEvent.Load event) { ForgeChunkManager.loadWorld(event.world); } @ForgeSubscribe(priority = EventPriority.HIGHEST) public void onDimensionSave(WorldEvent.Save event) { ForgeChunkManager.saveWorld(event.world); } }
Allow RedirectMixin to work within flask-admin
# -*- coding: utf-8 -*- """ Module provides mixins for issuing HTTP Status codes using the Flask ``View``. """ from flask import url_for from flask.views import View from werkzeug.utils import redirect class RedirectMixin(View): """ Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used however this can be overridden using the ``code`` attribute. Example ------- .. code-block:: python :linenos: from flask.ext.velox.mixins.http import RedirectMixin class MyView(RedirectMixin): rule = 'some.url.rule' code = 301 Attributes ---------- rule : str Flask URL Rule passed into ``url_for`` code : int, optional Status code to raise, defaults to ``302`` """ code = 302 def pre_dispatch(self, *args, **kwargs): """ If you wish to run an arbitrary piece of code before the redirect is dispatched you can override this method which is called before dispatch. """ pass def get_url(self): """ Return a generated url from ``rule`` attribute. Returns ------- str Generated url """ try: rule = self.rule except AttributeError: raise NotImplementedError('``rule`` attr must be defined.') return url_for(rule) def dispatch_request(self, *args, **kwargs): """ Dispatch the request, returning the redirect.func_closure Returns ------- werkzeug.wrappers.Response Redirect response """ self.pre_dispatch() return redirect(self.get_url(), code=getattr(self, 'code', 302))
# -*- coding: utf-8 -*- """ Module provides mixins for issuing HTTP Status codes using the Flask ``View``. """ from flask import url_for from flask.views import View from werkzeug.utils import redirect class RedirectMixin(View): """ Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used however this can be overridden using the ``code`` attribute. Example ------- .. code-block:: python :linenos: from flask.ext.velox.mixins.http import RedirectMixin class MyView(RedirectMixin): rule = 'some.url.rule' code = 301 Attributes ---------- rule : str Flask URL Rule passed into ``url_for`` code : int, optional Status code to raise, defaults to ``302`` """ code = 302 def pre_dispatch(self, *args, **kwargs): """ If you wish to run an arbitrary piece of code before the redirect is dispatched you can override this method which is called before dispatch. """ pass def get_url(self): """ Return a generated url from ``rule`` attribute. Returns ------- str Generated url """ try: rule = self.rule except AttributeError: raise NotImplementedError('``rule`` attr must be defined.') return url_for(rule) def dispatch_request(self): """ Dispatch the request, returning the redirect.func_closure Returns ------- werkzeug.wrappers.Response Redirect response """ self.pre_dispatch() return redirect(self.get_url(), code=getattr(self, 'code', 302))
Enable proper websocket support in webpack proxy
const merge = require('webpack-merge'); const config = require('./webpack.config'); const host = process.env.SDF_HOST || 'localhost'; const port = process.env.SDF_PORT || '8080'; const backendHost = process.env.SDF_BACKEND_HOST || 'backend'; const backendPort = process.env.SDF_BACKEND_PORT || '3000'; module.exports = merge.smart(config, { devtool: 'eval-source-map', module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[name]__[local]___[hash:base64:5]', }, }, { loader: 'postcss-loader', }, ], }, ], }, devServer: { host, port, proxy: [ { context: ['/login', '/auth', '/logout', '/openid-login', '/openid-auth'], target: `http://${backendHost}:${backendPort}`, }, { context: ['/socket.io/'], target: `http://${backendHost}:${backendPort}`, ws: true, }, ], historyApiFallback: { index: '/', }, }, });
const merge = require('webpack-merge'); const config = require('./webpack.config'); const host = process.env.SDF_HOST || 'localhost'; const port = process.env.SDF_PORT || '8080'; const backendHost = process.env.SDF_BACKEND_HOST || 'backend'; const backendPort = process.env.SDF_BACKEND_PORT || '3000'; module.exports = merge.smart(config, { devtool: 'eval-source-map', module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[name]__[local]___[hash:base64:5]', }, }, { loader: 'postcss-loader', }, ], }, ], }, devServer: { host, port, proxy: [ { context: ['/socket.io/', '/login', '/auth', '/logout', '/openid-login', '/openid-auth'], target: `http://${backendHost}:${backendPort}`, }, ], historyApiFallback: { index: '/', }, }, });
Add method to check is content is in another collection Former-commit-id: b5590a20f5a01e0fbe3aa4a856e6450a12d5cf8f Former-commit-id: 7c42e5bbf445bfffb43de66ed823417c51d6e4df Former-commit-id: 2675c6ef54e4d1ad9118400029a8ead243f426e9
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } }
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } }
[FIX] Add Item doesn`t appears instantly
import { EventEmitter } from "events"; import dispatcher from "../dispatcher"; class BlogStore extends EventEmitter { constructor() { super(); //this is a kind of initial load message. // it will be overwrite till the first GET :P this.blogs = [ { "id": 38, "title": "Loading..", "content": "" } ]; } createBlog(data) { const id = Date.now(), title = data.data.title, content = data.data.content; this.blogs.unshift({ id, title,//thanks es6 for all the magic xD content }); this.emit("change"); } getAll() { return this.blogs; } handleActions(action) { switch(action.type) { case "CREATE_BLOG": { this.createBlog(action.data); break; } case "RECEIVE_BLOGS": { this.blogs = action.blog; this.emit("change"); break; } } } } const blogStore = new BlogStore; dispatcher.register(blogStore.handleActions.bind(blogStore)); export default blogStore;
import { EventEmitter } from "events"; import dispatcher from "../dispatcher"; class BlogStore extends EventEmitter { constructor() { super(); //this is a kind of initial load message. // it will be overwrite till the first GET :P this.blogs = [ { "id": 38, "title": "Loading..", "content": "" } ]; } createTodo(title, content) { const id = Date.now(); this.todos.push({//thanks es6 xD id, title, content }); this.emit("change"); } getAll() { return this.blogs; } handleActions(action) { switch(action.type) { case "CREATE_BLOG": { this.createBlog(action.title, action.content); break; } case "RECEIVE_BLOGS": { this.blogs = action.blog; this.emit("change"); break; } } } } const blogStore = new BlogStore; dispatcher.register(blogStore.handleActions.bind(blogStore)); export default blogStore;
Switch to stacked area graph
import _ from 'lodash'; import Highcharts from 'highcharts'; function patientsByGroupDateGraph(adapter) { return { scope: { groupType: '@', type: '@' }, template: '<div loading="loading" class="graph"></div>', link: function(scope, element) { var params = { groupType: scope.groupType, type: scope.type }; var title = scope.type === 'new' ? 'New Patients' : 'Total Patients'; adapter.get('/stats/patients-by-group-date', params).then(function(response) { var options = { chart: { renderTo: element.get(0), type: 'area' }, title: { text: title }, xAxis: { type: 'datetime' }, yAxis: { title: { text: 'Patients' }, min: 0 }, series: [], plotOptions: { area: { stacking: 'normal', marker: { enabled: false } } } }; var data= _.sortBy(response.data, 'group.name'); _.forEach(data, function(group) { var series = { name: group.group.name, data: [] }; options.series.push(series); _.forEach(group.counts, function(count) { series.data.push([Date.parse(count.date), count.count]); }); }); new Highcharts.Chart(options); }); } }; } patientsByGroupDateGraph.$inject = ['adapter']; export default patientsByGroupDateGraph;
import _ from 'lodash'; import Highcharts from 'highcharts'; function patientsByGroupDateGraph(adapter) { return { scope: { groupType: '@', type: '@' }, template: '<div loading="loading" class="graph"></div>', link: function(scope, element) { var params = { groupType: scope.groupType, type: scope.type }; var title = scope.type === 'new' ? 'New Patients' : 'Total Patients'; adapter.get('/stats/patients-by-group-date', params).then(function(response) { var options = { chart: { renderTo: element.get(0) }, title: { text: title }, xAxis: { type: 'datetime' }, yAxis: { title: { text: 'Patients' }, min: 0 }, series: [] }; var data= _.sortBy(response.data, 'group.name'); _.forEach(data, function(group) { var series = { name: group.group.name, data: [] }; options.series.push(series); _.forEach(group.counts, function(count) { series.data.push([Date.parse(count.date), count.count]); }); }); new Highcharts.Chart(options); }); } }; } patientsByGroupDateGraph.$inject = ['adapter']; export default patientsByGroupDateGraph;
Add NamedModulesPlugin to webpack config
const webpack = require('webpack') const path = require('path') const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', output: { path: path.resolve(__dirname, './dist'), }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { importLoaders: 1 } }, { loader: 'postcss-loader', options: { plugins: [ require('postcss-nested'), require('postcss-triangle') ] } } ] }) } ] }, plugins: [ new ExtractTextPlugin('styles.css'), new webpack.optimize.CommonsChunkPlugin({ name: 'lib', minChunks: function minChunks (module) { return module.context && module.context.indexOf('node_modules') !== -1; } }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index-template.html' }), new webpack.NamedModulesPlugin() ] }
const webpack = require('webpack') const path = require('path') const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', output: { path: path.resolve(__dirname, './dist'), }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { importLoaders: 1 } }, { loader: 'postcss-loader', options: { plugins: [ require('postcss-nested'), require('postcss-triangle') ] } } ] }) } ] }, plugins: [ new ExtractTextPlugin('styles.css'), new webpack.optimize.CommonsChunkPlugin({ name: 'lib', minChunks: function minChunks (module) { return module.context && module.context.indexOf('node_modules') !== -1; } }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index-template.html' }) ] }
Change names of timing pvs
import sirius def get_record_names(family_name = None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be segmented, in which case the value is a python list of lists.""" if family_name == None: families = ['ti'] record_names_dict = {} for i in range(len(families)): record_names_dict.update(get_record_names(families[i])) return record_names_dict if family_name.lower() == 'ti': _dict = { 'TI-CYCLE':{}, # when set starts entire injection cycle 'TI-BO-KICKIN-ENABLED':{}, # whether to pulse BO injection kicker 'TI-BO-KICKIN-DELAY':{}, # when to pulse BO injection kickes 'TI-BO-KICKEX-ENABLED':{}, # whether to pulse BO extraction kicker 'TI-BO-KICKEX-DELAY':{}, # when to pulse BO extraction kicker 'TI-SI-KICKIN-ENABLED':{} , # whether to pulse SI injection kicker 'TI-SI-KICKIN-DELAY':{}, # when to pulse SI injection kicker 'TI-DELAY':{}, 'TI-DELAY-INC':{}, } return _dict else: raise Exception('Family name %s not found'%family_name) -
import sirius def get_record_names(family_name = None): """Return a dictionary of record names for given subsystem each entry is another dictionary of model families whose values are the indices in the pyaccel model of the magnets that belong to the family. The magnet models ca be segmented, in which case the value is a python list of lists.""" if family_name == None: families = ['ti'] record_names_dict = {} for i in range(len(families)): record_names_dict.update(get_record_names(families[i])) return record_names_dict if family_name.lower() == 'ti': _dict = { 'TI-CYCLE':{}, # when set starts entire injection cycle 'TI-BO-KICKIN-ON':{}, # whether to pulse BO injection kicker 'TI-BO-KICKIN-DELAY':{}, # when to pulse BO injection kickes 'TI-BO-KICKEX-ON':{}, # whether to pulse BO extraction kicker 'TI-BO-KICKEX-DELAY':{}, # when to pulse BO extraction kicker 'TI-BO-KICKEX-INC':{}, # increment to SI injection kicker delay 'TI-SI-KICKIN-ON':{} , # whether to pulse SI injection kicker 'TI-SI-KICKIN-DELAY':{}, # when to pulse SI injection kicker #'TI-SI-KICKIN-INC':{}, # increment to SI injection kicker delay } return _dict else: raise Exception('Family name %s not found'%family_name)
Correct unit test assertion for XHR object
/*! Copyright 2013 Rustici Software 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. */ var TinCanTest, TinCanTestCfg = { recordStores: {} }, log ; log = function () {}; if (typeof console !== "undefined" && console.log) { log = function (msg) { console.log("Test: " + msg); } } (function () { TinCanTest = {}; TinCanTest.assertHttpRequestType = function (xhr, name) { var desc = "assertHttpRequestType: " + name; if (TinCan.environment().useXDR) { ok(xhr instanceof XDomainRequest, desc); } else { // // in IE7 at least XMLHttpRequest is an 'object' but it fails // the instanceof check because it apparently isn't considered // a constructor function // if (typeof XMLHttpRequest === "function") { ok(xhr instanceof XMLHttpRequest, desc); } else if (typeof XMLHttpRequest === "object") { ok(true, desc + " (XMLHttpRequest found but not constructor)"); } else { ok(true, desc + " (unplanned for xhr)"); } } }; }());
/*! Copyright 2013 Rustici Software 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. */ var TinCanTest, TinCanTestCfg = { recordStores: {} }, log ; log = function () {}; if (typeof console !== "undefined" && console.log) { log = function (msg) { console.log("Test: " + msg); } } (function () { TinCanTest = {}; TinCanTest.assertHttpRequestType = function (xhr, name) { var desc = "assertHttpRequestType: " + name; if (TinCan.environment().useXDR) { ok(xhr instanceof XDomainRequest, desc); } else { if (typeof XMLHttpRequest !== "undefined") { ok(xhr instanceof XMLHttpRequest, desc); } else { ok(true, "unplanned for xhr: " + desc); } } }; }());
Return array consistently from query method
<?php namespace Rogue\Services; use Illuminate\Support\Facades\Log; use Softonic\GraphQL\ClientBuilder; class GraphQL { /** * Build a new GraphQL client. */ public function __construct() { $this->client = ClientBuilder::build(config('services.graphql.url')); } /** * Run a GraphQL query using the client and return the data result. * * @param $query String * @param $variables Array * @return array */ public function query($query, $variables) { // Use try/catch to avoid any GraphQL related errors breaking the application. try { $response = $this->client->query($query, $variables); } catch (\Exception $exception) { Log::error('GraphQL request failed.', [ 'query' => $query, 'variables' => $variables, 'exception' => $exception->getMessage(), ]); return []; } return $response ? $response->getData() : []; } /** * Query for a CampaignWebsite by campaignId field. * * @param $campaignId String * @return array */ public function getCampaignWebsiteByCampaignId($campaignId) { $query = ' query GetCampaignWebsiteByCampaignId($campaignId: String!) { campaignWebsiteByCampaignId(campaignId: $campaignId) { title slug } }'; $variables = [ 'campaignId' => $campaignId, ]; return $this->query($query, $variables); } }
<?php namespace Rogue\Services; use Illuminate\Support\Facades\Log; use Softonic\GraphQL\ClientBuilder; class GraphQL { /** * Build a new GraphQL client. */ public function __construct() { $this->client = ClientBuilder::build(config('services.graphql.url')); } /** * Run a GraphQL query using the client and return the data result. * * @param $query String * @param $variables Array * @return array|null */ public function query($query, $variables) { // Use try/catch to avoid any GraphQL related errors breaking the application. try { $response = $this->client->query($query, $variables); } catch (\Exception $exception) { Log::error('GraphQL request failed.', [ 'query' => $query, 'variables' => $variables, 'exception' => $exception->getMessage(), ]); return null; } return $response ? $response->getData() : null; } /** * Query for a CampaignWebsite by campaignId field. * * @param $campaignId String * @return array|null */ public function getCampaignWebsiteByCampaignId($campaignId) { $query = ' query GetCampaignWebsiteByCampaignId($campaignId: String!) { campaignWebsiteByCampaignId(campaignId: $campaignId) { title slug } }'; $variables = [ 'campaignId' => $campaignId, ]; return $this->query($query, $variables); } }
Use Django's module loading rather than __import__ __import__ doesn't deal well with dotted paths, in my instance my root url conf is in a few levels "appname.config.urls". unfortunately, for __import__ this means that just `appname` is imported, but `config.urls` is loaded and no other modules in between are usable. Switching to Django's `import_string` method allows importing the final module in the path string, in my case the equivalent would be `from appname.config import urls`.
from django.conf import settings from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from django.utils.module_loading import import_string from rest_framework.views import APIView from rest_framework_docs.api_endpoint import ApiEndpoint class ApiDocumentation(object): def __init__(self): self.endpoints = [] root_urlconf = import_string(settings.ROOT_URLCONF) if hasattr(root_urlconf, 'urls'): self.get_all_view_names(root_urlconf.urls.urlpatterns) else: self.get_all_view_names(root_urlconf.urlpatterns) def get_all_view_names(self, urlpatterns, parent_pattern=None): for pattern in urlpatterns: if isinstance(pattern, RegexURLResolver): parent_pattern = None if pattern._regex == "^" else pattern self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern) elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern): api_endpoint = ApiEndpoint(pattern, parent_pattern) self.endpoints.append(api_endpoint) def _is_drf_view(self, pattern): # Should check whether a pattern inherits from DRF's APIView return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView) def get_endpoints(self): return self.endpoints
from django.conf import settings from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from rest_framework.views import APIView from rest_framework_docs.api_endpoint import ApiEndpoint class ApiDocumentation(object): def __init__(self): self.endpoints = [] root_urlconf = __import__(settings.ROOT_URLCONF) if hasattr(root_urlconf, 'urls'): self.get_all_view_names(root_urlconf.urls.urlpatterns) else: self.get_all_view_names(root_urlconf.urlpatterns) def get_all_view_names(self, urlpatterns, parent_pattern=None): for pattern in urlpatterns: if isinstance(pattern, RegexURLResolver): parent_pattern = None if pattern._regex == "^" else pattern self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern) elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern): api_endpoint = ApiEndpoint(pattern, parent_pattern) self.endpoints.append(api_endpoint) def _is_drf_view(self, pattern): # Should check whether a pattern inherits from DRF's APIView return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView) def get_endpoints(self): return self.endpoints
Use sys in error cases.
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
Fix race condition in purge test.
require('./harness').run(); var recvCount = 0; var body = "hello world"; connection.addListener('ready', function () { puts("connected to " + connection.serverProperties.product); var e = connection.exchange('node-purge-fanout', {type: 'fanout', confirm: true}); var q = connection.queue('node-purge-queue', function() { q.bind(e, "*"); q.on('queueBindOk', function() { puts("publishing 1 json message"); e.publish('ackmessage.json1', { name: 'A' }, {}, function() { puts('Purge queue'); q.purge().addCallback(function(ok){ puts('Deleted '+ok.messageCount+' message'); assert.equal(1,ok.messageCount); puts("publishing another json message"); e.publish('ackmessage.json2', { name: 'B' }); }); q.on('basicConsumeOk', function () { setTimeout(function () { // wait one second to receive the message, then quit connection.end(); }, 1000); }); q.subscribe({ ack: true }, function (json) { recvCount++; puts('Got message ' + JSON.stringify(json)); if (recvCount == 1) { assert.equal('B', json.name); q.shift(); } else { throw new Error('Too many message!'); } }); }); }); }); }); process.addListener('exit', function () { assert.equal(1, recvCount); });
require('./harness').run(); var recvCount = 0; var body = "hello world"; connection.addListener('ready', function () { puts("connected to " + connection.serverProperties.product); var e = connection.exchange('node-purge-fanout', {type: 'fanout'}); var q = connection.queue('node-purge-queue', function() { q.bind(e, "*") q.on('queueBindOk', function() { puts("publishing 1 json messages"); e.publish('ackmessage.json1', { name: 'A' }); puts('Purge queue') q.purge().addCallback(function(ok){ puts('Deleted '+ok.messageCount+' messages') assert.equal(1,ok.messageCount) puts("publishing another json messages"); e.publish('ackmessage.json2', { name: 'B' }); }) q.on('basicConsumeOk', function () { setTimeout(function () { // wait one second to receive the message, then quit connection.end(); }, 1000); }); q.subscribe({ ack: true }, function (json) { recvCount++; puts('Got message ' + JSON.stringify(json)); if (recvCount == 1) { assert.equal('B', json.name); q.shift(); } else { throw new Error('Too many message!'); } }) }) }); }); process.addListener('exit', function () { assert.equal(1, recvCount); });
Make into a real object instead of lots of static methods.
package net.happygiraffe.jslint; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * A command line interface to {@link JSLint}. * * @author dom * @version $Id$ */ public class Main { /** * The main entry point. Try passing in "--help" for more details. * * @param args * One or more JavaScript files. * @throws IOException */ public static void main(String[] args) throws IOException { Main main = new Main(); for (String file : args) { main.lintFile(file); } } private JSLint lint; private Main() throws IOException { lint = new JSLint(); lint.addOption(Option.EQEQEQ); lint.addOption(Option.UNDEF); lint.addOption(Option.WHITE); } private void lintFile(String file) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(file))); List<Issue> issues = lint.lint(file, reader); for (Issue issue : issues) { System.err.println(issue); } } catch (FileNotFoundException e) { System.err.println(file + ":no such file"); } } }
package net.happygiraffe.jslint; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * A command line interface to {@link JSLint}. * * @author dom * @version $Id$ */ public class Main { /** * The main entry point. Try passing in "--help" for more details. * * @param args * One or more JavaScript files. * @throws IOException */ public static void main(String[] args) throws IOException { JSLint lint = new JSLint(); lint.addOption(Option.EQEQEQ); lint.addOption(Option.UNDEF); lint.addOption(Option.WHITE); for (String file : args) { lintFile(lint, file); } } private static void lintFile(JSLint lint, String file) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(file))); List<Issue> issues = lint.lint(file, reader); for (Issue issue : issues) { System.err.println(issue); } } catch (FileNotFoundException e) { System.err.println(file + ":no such file"); } } }