hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
9c0d8eaa01ce412f68165b03f4dbdf709f173322
diff --git a/stmt/stmts/insert.go b/stmt/stmts/insert.go index <HASH>..<HASH> 100644 --- a/stmt/stmts/insert.go +++ b/stmt/stmts/insert.go @@ -254,6 +254,7 @@ func (s *InsertIntoStmt) Exec(ctx context.Context) (_ rset.Recordset, err error) } rows := make([][]interface{}, len(s.Lists)) + lastInsertIds := make([]uint64, len(s.Lists)) for i, list := range s.Lists { if err = s.checkValueCount(insertValueCount, len(list), i, cols); err != nil { return nil, errors.Trace(err) @@ -263,6 +264,8 @@ func (s *InsertIntoStmt) Exec(ctx context.Context) (_ rset.Recordset, err error) if err != nil { return nil, errors.Trace(err) } + + lastInsertIds[i] = variable.GetSessionVars(ctx).LastInsertID } err = s.prefetchIndices(ctx, t, rows) @@ -270,12 +273,13 @@ func (s *InsertIntoStmt) Exec(ctx context.Context) (_ rset.Recordset, err error) return nil, errors.Trace(err) } - for _, row := range rows { + for i, row := range rows { // Notes: incompatible with mysql // MySQL will set last insert id to the first row, as follows: // `t(id int AUTO_INCREMENT, c1 int, PRIMARY KEY (id))` // `insert t (c1) values(1),(2),(3);` // Last insert id will be 1, not 3. + variable.GetSessionVars(ctx).SetLastInsertID(lastInsertIds[i]) h, err := t.AddRecord(ctx, row) if err == nil { continue diff --git a/stmt/stmts/insert_test.go b/stmt/stmts/insert_test.go index <HASH>..<HASH> 100644 --- a/stmt/stmts/insert_test.go +++ b/stmt/stmts/insert_test.go @@ -96,3 +96,30 @@ func (s *testStmtSuite) TestInsert(c *C) { _, err = s.testDB.Exec(`insert into insert_test (id, c2) values(1, 1) on duplicate key update t.c2 = 10`) c.Assert(err, NotNil) } + +func (s *testStmtSuite) TestInsertAutoInc(c *C) { + createSQL := `drop table if exists insert_autoinc_test; create table insert_autoinc_test (id int auto_increment, c1 int);` + mustExec(c, s.testDB, createSQL) + + insertSQL := `insert into insert_autoinc_test(c1) values (1), (2)` + mustExec(c, s.testDB, insertSQL) + + tx := mustBegin(c, s.testDB) + rows, err := tx.Query("select * from insert_autoinc_test;") + c.Assert(err, IsNil) + + c.Assert(rows.Next(), IsTrue) + var id, c1 int + rows.Scan(&id, &c1) + c.Assert(id, Equals, 1) + c.Assert(c1, Equals, 1) + + c.Assert(rows.Next(), IsTrue) + rows.Scan(&id, &c1) + c.Assert(id, Equals, 2) + c.Assert(c1, Equals, 2) + + c.Assert(rows.Next(), IsFalse) + rows.Close() + mustCommit(c, tx) +}
stmt: fix insert list issue
pingcap_tidb
train
595176c0531350dc7ca49ac283e6213b6dd50c28
diff --git a/lib/sql_tree/node/select_query.rb b/lib/sql_tree/node/select_query.rb index <HASH>..<HASH> 100644 --- a/lib/sql_tree/node/select_query.rb +++ b/lib/sql_tree/node/select_query.rb @@ -13,7 +13,7 @@ module SQLTree::Node raise "At least one SELECT expression is required" if self.select.empty? sql = (self.distinct) ? "SELECT DISTINCT " : "SELECT " sql << select.map { |s| s.to_sql }.join(', ') - sql << " FROM " << from.map { |f| f.to_sql }.join(', ') + sql << " FROM " << from.map { |f| f.to_sql }.join(', ') if from sql << " WHERE " << where.to_sql if where sql << " GROUP BY " << group_by.map { |g| g.to_sql }.join(', ') if group_by sql << " ORDER BY " << order_by.map { |o| o.to_sql }.join(', ') if order_by diff --git a/spec/integration/parse_and_generate_spec.rb b/spec/integration/parse_and_generate_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/parse_and_generate_spec.rb +++ b/spec/integration/parse_and_generate_spec.rb @@ -2,6 +2,10 @@ require "#{File.dirname(__FILE__)}/../spec_helper" describe SQLTree, 'parsing and generating SQL' do + it "should parse an generate q query without FROM" do + SQLTree['SELECT 1'].to_sql.should == 'SELECT 1' + end + it "should parse and generate SQL fo a simple list query" do SQLTree["SELECT * FROM table"].to_sql.should == 'SELECT * FROM "table"' end diff --git a/spec/unit/select_query_spec.rb b/spec/unit/select_query_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/select_query_spec.rb +++ b/spec/unit/select_query_spec.rb @@ -1,5 +1,29 @@ require "#{File.dirname(__FILE__)}/../spec_helper" +describe SQLTree::Node::SelectQuery do + + it "should parse a query without FROM, WHERE, ORDER, GROUP or HAVING clause" do + tree = SQLTree::Node::SelectQuery['SELECT 1'] + tree.select.first.expression.value.should == 1 + tree.from.should be_nil + tree.where.should be_nil + tree.group_by.should be_nil + tree.having.should be_nil + tree.order_by.should be_nil + end + + it "should parse a query with all clauses" do + tree = SQLTree::Node::SelectQuery['SELECT 1 AS static, field FROM table1 AS t1, table2 LEFT JOIN table3 t3 ON (t1.id = t2.id) + WHERE t1.field = 1234 GROUP BY t2.group_field HAVING SUM(t2.group_field) > 100 ORDER BY t.timestamp DESC'] + + tree.select.length.should == 2 + tree.from.length.should == 2 + tree.where.should be_kind_of(SQLTree::Node::ComparisonExpression) + tree.group_by.first.should be_kind_of(SQLTree::Node::Field) + tree.having.should be_kind_of(SQLTree::Node::ComparisonExpression) + end +end + describe SQLTree::Node::Source do it "should parse the table name correctly" do
Added some SELECT query specs.
wvanbergen_sql_tree
train
a71c776fb3cad823a32cbf5766b3ef78928cbea2
diff --git a/demo/index.rst b/demo/index.rst index <HASH>..<HASH> 100644 --- a/demo/index.rst +++ b/demo/index.rst @@ -271,6 +271,20 @@ If you make docs as Reveal.js presentation, you call ``make revealjs`` This presentation is made from ``https://github.com/attakei/sphinx-revealjs/blob/demo/docs/index.rst`` +SUpport features +================ + +Fragments +--------- + +This is support fragment with groups. + +.. revealjs_fragments:: + + * First + * Second + * Third + Enjoy writing reST as presentation ================================== diff --git a/sphinx_revealjs/__init__.py b/sphinx_revealjs/__init__.py index <HASH>..<HASH> 100644 --- a/sphinx_revealjs/__init__.py +++ b/sphinx_revealjs/__init__.py @@ -7,14 +7,15 @@ from sphinx.application import Sphinx from sphinx_revealjs.builders import RevealjsHTMLBuilder from sphinx_revealjs.directives import ( - RevealjsBreak, RevealjsSection, RevealjsSlide + RevealjsBreak, RevealjsFragments, RevealjsSection, RevealjsSlide, ) from sphinx_revealjs.nodes import ( - revealjs_break, revealjs_section, revealjs_slide + revealjs_break, revealjs_fragments, revealjs_section, revealjs_slide, ) from sphinx_revealjs.themes import get_theme_path from sphinx_revealjs.writers import ( - depart_revealjs_break, not_write, visit_revealjs_break + depart_revealjs_break, + not_write, visit_revealjs_break ) @@ -33,9 +34,14 @@ def setup(app: Sphinx): revealjs_slide, html=(not_write, not_write), revealjs=(not_write, not_write)) + app.add_node( + revealjs_fragments, + html=(not_write, not_write), + revealjs=(not_write, not_write)) app.add_directive('revealjs_break', RevealjsBreak) app.add_directive('revealjs_section', RevealjsSection) app.add_directive('revealjs_slide', RevealjsSlide) + app.add_directive('revealjs_fragments', RevealjsFragments) app.add_config_value('revealjs_theme', 'sphinx_revealjs', True) app.add_config_value('revealjs_theme_options', {}, True) app.add_html_theme( diff --git a/sphinx_revealjs/directives.py b/sphinx_revealjs/directives.py index <HASH>..<HASH> 100644 --- a/sphinx_revealjs/directives.py +++ b/sphinx_revealjs/directives.py @@ -4,7 +4,8 @@ import json from docutils.parsers.rst import Directive, directives from sphinx_revealjs.nodes import ( - FlagAttribute, revealjs_break, revealjs_section, revealjs_slide + FlagAttribute, revealjs_break, revealjs_fragments, + revealjs_section, revealjs_slide ) @@ -74,3 +75,16 @@ class RevealjsSlide(Directive): # noqa: D101 node = revealjs_slide() node.attributes = self.options return [node, ] + + +class RevealjsFragments(Directive): # noqa: D101 + has_content = True + + def run(self): + node = revealjs_fragments() + if self.content: + self.state.nested_parse(self.content, self.content_offset, node) + # TODO: Parameter ? + for child in node.children[0].children: + child['classes'].append('fragment') + return [node, ] diff --git a/sphinx_revealjs/nodes.py b/sphinx_revealjs/nodes.py index <HASH>..<HASH> 100644 --- a/sphinx_revealjs/nodes.py +++ b/sphinx_revealjs/nodes.py @@ -38,3 +38,7 @@ class revealjs_break(SectionTagRenderer, nodes.Structural, nodes.Element): # no class revealjs_slide(nodes.Structural, nodes.Element): # noqa: D101 pass + + +class revealjs_fragments(nodes.Structural, nodes.Element): # noqa: D101 + pass
Add 'revealjs_fragments' directive. * This add 'fragment' class into children of nested contents.
attakei_sphinx-revealjs
train
3b99b05c16db4e84b80eb16dc19a5638c4aee067
diff --git a/spyder/plugins/editor/widgets/codeeditor.py b/spyder/plugins/editor/widgets/codeeditor.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/editor/widgets/codeeditor.py +++ b/spyder/plugins/editor/widgets/codeeditor.py @@ -4316,6 +4316,7 @@ class CodeEditor(TextEditBaseWidget): key = event.key() text = to_text_string(event.text()) has_selection = self.has_selected_text() + alt = event.modifiers() & Qt.AltModifier ctrl = event.modifiers() & Qt.ControlModifier shift = event.modifiers() & Qt.ShiftModifier @@ -4404,7 +4405,7 @@ class CodeEditor(TextEditBaseWidget): self.textCursor().endEditBlock() elif key == Qt.Key_Insert and not shift and not ctrl: self.setOverwriteMode(not self.overwriteMode()) - elif key == Qt.Key_Backspace and not shift and not ctrl: + elif key == Qt.Key_Backspace and not shift and not ctrl and not alt: if has_selection or not self.intelligent_backspace: # See spyder-ide/spyder#12663 for why redefining this # action is necessary. Also see
Allow Alt+Backspace to be handled by default handler This commit causes Backspaces key presses with the Alt-modifier to be handled by Qt's default event handler. Previously only the Ctrl- and Shift-modifiers were considered. Needed to pass test_builtin_undo_redo in spyder/plugins/editor/widgets/tests/test_shortcuts.py
spyder-ide_spyder
train
df552d496c72e8527a92ebb48267ded86123c380
diff --git a/lib/components/services/audit/generate-trigger-statement.js b/lib/components/services/audit/generate-trigger-statement.js index <HASH>..<HASH> 100644 --- a/lib/components/services/audit/generate-trigger-statement.js +++ b/lib/components/services/audit/generate-trigger-statement.js @@ -16,5 +16,7 @@ module.exports = function generateTriggerStatement (options) { case 'REMOVE': return `DROP TRIGGER IF EXISTS ${namespace}_${name}_auditor ON ${namespace}.${name};` + default: + return `` } } diff --git a/lib/components/services/audit/index.js b/lib/components/services/audit/index.js index <HASH>..<HASH> 100644 --- a/lib/components/services/audit/index.js +++ b/lib/components/services/audit/index.js @@ -1,5 +1,6 @@ 'use strict' +const _ = require('lodash') const path = require('path') const schema = require('./schema.json') const HlPgClient = require('hl-pg-client') @@ -39,11 +40,19 @@ class AuditService { this.auditFunctions.map(func => { Object.keys(this.models).map(async model => { const audit = this.models[model].audit !== false + + // Check if trigger already exists - if so then don't query + // TODO: Ideally this should be read from pg-info rather than hardcoded but this does the job for now + const namespace = _.snakeCase(this.models[model].namespace) + const name = _.snakeCase(this.models[model].name) + const res = await this.client.query(`SELECT * FROM information_schema.triggers WHERE trigger_name = '${namespace}_${name}_auditor';`) + const action = (res.rowCount === 0 && audit) ? 'ADD' : ((res.rowCount === 1 && !audit) ? 'REMOVE' : '') const triggerSQL = generateTriggerStatement({ model: this.models[model], function: func, - action: audit ? 'ADD' : 'REMOVE' + action: action }) + await this.client.query(triggerSQL) }) })
a kind of fix for stopping trying to create a trigger that already exists ideally it should come through the model via pg-model or pg-info or something rather than hardcoded query
wmfs_tymly-pg-plugin
train
9f1d5b8c7c06c195daeee1dcd2b9f2ab0921a115
diff --git a/src/com/opencms/file/CmsResourceTypePage.java b/src/com/opencms/file/CmsResourceTypePage.java index <HASH>..<HASH> 100644 --- a/src/com/opencms/file/CmsResourceTypePage.java +++ b/src/com/opencms/file/CmsResourceTypePage.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/Attic/CmsResourceTypePage.java,v $ -* Date : $Date: 2001/08/03 11:24:53 $ -* Version: $Revision: 1.12 $ +* Date : $Date: 2001/08/03 12:26:57 $ +* Version: $Revision: 1.13 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -45,7 +45,7 @@ import com.opencms.file.genericSql.*; * Access class for resources of the type "Page". * * @author Alexander Lucas - * @version $Revision: 1.12 $ $Date: 2001/08/03 11:24:53 $ + * @version $Revision: 1.13 $ $Date: 2001/08/03 12:26:57 $ */ public class CmsResourceTypePage implements I_CmsResourceType, Serializable, I_CmsConstants, com.opencms.workplace.I_CmsWpConstants { @@ -842,7 +842,11 @@ public class CmsResourceTypePage implements I_CmsResourceType, Serializable, I_C cms.doChgrp(newfolder.getAbsolutePath(),cms.readGroup(folder).getName()); cms.doChmod(newfolder.getAbsolutePath(),folder.getAccessFlags()); cms.doChown(newfolder.getAbsolutePath(),cms.readOwner(folder).getName()); - cms.doUnlockResource(newfolder.getAbsolutePath()); + try{ + cms.doUnlockResource(newfolder.getAbsolutePath()); + } catch (CmsException ex){ + // unable to unlock folder if parent folder is locked + } } completePath+=foldername+"/"; }
method checkFolders: do not throw exception when unlocking new folder fails
alkacon_opencms-core
train
ab69759b8e59bec9afd831d36e8e6f435d65a1ce
diff --git a/plaso/formatters/windows.py b/plaso/formatters/windows.py index <HASH>..<HASH> 100644 --- a/plaso/formatters/windows.py +++ b/plaso/formatters/windows.py @@ -65,7 +65,7 @@ class WindowsRegistryListEventFormatter(interface.ConditionalEventFormatter): class WindowsRegistryNetworkEventFormatter(interface.ConditionalEventFormatter): - """Formatter for a Windows network event.""" + """Formatter for a Windows NetworkList event formatter.""" DATA_TYPE = 'windows:registry:network' diff --git a/plaso/parsers/winreg_plugins/networks.py b/plaso/parsers/winreg_plugins/networks.py index <HASH>..<HASH> 100644 --- a/plaso/parsers/winreg_plugins/networks.py +++ b/plaso/parsers/winreg_plugins/networks.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""This file contains the NetworkList registry plugin.""" +"""This file contains the NetworkList Registry plugin.""" from __future__ import unicode_literals @@ -14,8 +14,8 @@ from plaso.parsers.winreg_plugins import dtfabric_plugin from plaso.parsers.winreg_plugins import interface -class WindowsRegistryNetworkEventData(events.EventData): - """Windows network event data. +class WindowsRegistryNetworkListEventData(events.EventData): + """Windows NetworkList event data. Attributes: connection_type (str): type of connection. @@ -29,7 +29,7 @@ class WindowsRegistryNetworkEventData(events.EventData): def __init__(self): """Initializes event data.""" - super(WindowsRegistryNetworkEventData, self).__init__( + super(WindowsRegistryNetworkListEventData, self).__init__( data_type=self.DATA_TYPE) self.connection_type = None self.default_gateway_mac = None @@ -156,7 +156,7 @@ class NetworksWindowsRegistryPlugin( default_gateway_mac, dns_suffix = network_info.get( subkey.name, (None, None)) - event_data = WindowsRegistryNetworkEventData() + event_data = WindowsRegistryNetworkListEventData() event_data.default_gateway_mac = default_gateway_mac event_data.dns_suffix = dns_suffix diff --git a/tests/parsers/winreg_plugins/networks.py b/tests/parsers/winreg_plugins/networks.py index <HASH>..<HASH> 100644 --- a/tests/parsers/winreg_plugins/networks.py +++ b/tests/parsers/winreg_plugins/networks.py @@ -217,6 +217,7 @@ class NetworksWindowsRegistryPluginTest(test_lib.RegistryPluginTestCase): event = events[0] + self.assertEqual(event.data_type, 'windows:registry:network') self.CheckTimestamp(event.timestamp, '2014-05-06 17:02:19.795000') self.assertEqual( event.timestamp_desc, definitions.TIME_DESCRIPTION_CREATION) @@ -233,6 +234,7 @@ class NetworksWindowsRegistryPluginTest(test_lib.RegistryPluginTestCase): event = events[3] + self.assertEqual(event.data_type, 'windows:registry:network') self.CheckTimestamp(event.timestamp, '2015-01-27 15:15:27.965000') self.assertEqual( event.timestamp_desc, definitions.TIME_DESCRIPTION_LAST_CONNECTED)
Clean up of NetworkList Windows Registry plugin #<I> (#<I>)
log2timeline_plaso
train
87dc8cee8f0fb463c256775d58ae5ad627fe7410
diff --git a/lib/spring/test/watcher_test.rb b/lib/spring/test/watcher_test.rb index <HASH>..<HASH> 100644 --- a/lib/spring/test/watcher_test.rb +++ b/lib/spring/test/watcher_test.rb @@ -162,6 +162,33 @@ module Spring watcher.add './foobar' assert watcher.files.empty? end + + test "add symlink" do + File.write("#{dir}/bar", "bar") + File.symlink("#{dir}/bar", "#{dir}/foo") + watcher.add './foo' + assert_equal ["#{dir}/bar"], watcher.files.to_a + end + + test "add dangling symlink" do + File.symlink("#{dir}/bar", "#{dir}/foo") + watcher.add './foo' + assert watcher.files.empty? + end + + test "add directory with dangling symlink" do + subdir = "#{@dir}/subdir" + FileUtils.mkdir(subdir) + File.symlink("dangling", "#{subdir}/foo") + + watcher.add subdir + assert_not_stale + + # Adding a new file should mark as stale despite the dangling symlink. + File.write("#{subdir}/new-file", "new") + watcher.check_stale + assert_stale + end end end end diff --git a/lib/spring/watcher/abstract.rb b/lib/spring/watcher/abstract.rb index <HASH>..<HASH> 100644 --- a/lib/spring/watcher/abstract.rb +++ b/lib/spring/watcher/abstract.rb @@ -48,14 +48,30 @@ module Spring end end - items = items.select(&:exist?) + items = items.select do |item| + if item.symlink? + item.readlink.exist?.tap do |exists| + if !exists + debug { "add: ignoring dangling symlink: #{item.inspect} -> #{item.readlink.inspect}" } + end + end + else + item.exist? + end + end synchronize { items.each do |item| if item.directory? directories << item.realpath.to_s else - files << item.realpath.to_s + begin + files << item.realpath.to_s + rescue Errno::ENOENT + # Race condition. Ignore symlinks whose target was removed + # since the check above, or are deeply chained. + debug { "add: ignoring now-dangling symlink: #{item.inspect} -> #{item.readlink.inspect}" } + end end end diff --git a/lib/spring/watcher/polling.rb b/lib/spring/watcher/polling.rb index <HASH>..<HASH> 100644 --- a/lib/spring/watcher/polling.rb +++ b/lib/spring/watcher/polling.rb @@ -64,10 +64,24 @@ module Spring private def compute_mtime - expanded_files.map { |f| File.mtime(f).to_f }.max || 0 - rescue Errno::ENOENT - # if a file does no longer exist, the watcher is always stale. - Float::MAX + expanded_files.map do |f| + # Get the mtime of symlink targets. Ignore dangling symlinks. + if File.symlink?(f) + begin + File.mtime(f) + rescue Errno::ENOENT + 0 + end + # If a file no longer exists, treat it as changed. + else + begin + File.mtime(f) + rescue Errno::ENOENT + debug { "compute_mtime: no longer exists: #{f}" } + Float::MAX + end + end.to_f + end.max || 0 end def expanded_files
Gracefully deal with dangling symlinks * Don't add files that are dangling symlinks * When watching a directory, ignore dangling symlinks rather than treating them as forever-stale
rails_spring
train
4fb856af3bfa58b7ce305e2f8d2cc35736e7c374
diff --git a/src/ol/reproj.js b/src/ol/reproj.js index <HASH>..<HASH> 100644 --- a/src/ol/reproj.js +++ b/src/ol/reproj.js @@ -198,7 +198,7 @@ export function calculateSourceExtentResolution( * @param {Array<ImageExtent>} sources Array of sources. * @param {number} gutter Gutter of the sources. * @param {boolean} [opt_renderEdges] Render reprojection edges. - * @param {Object} [opt_interpolate] Use linear interpolation when resampling. + * @param {boolean} [opt_interpolate] Use linear interpolation when resampling. * @return {HTMLCanvasElement} Canvas with reprojected data. */ export function render(
change typedef to boolean
openlayers_openlayers
train
982d721659c7e97efce3f6a0b1fcc4e2b63b2609
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -2,13 +2,18 @@ var Resource = require('./lib/resource.js') -var Marvel, merge +var Marvel, merge, hasProp + +hasProp = function(o, p) { + return Object.prototype.hasOwnProperty.call(o, p) +} // merge merge = function(a, b) { var k + for (k in a) { - if (a.hasOwnProperty(k) && b.hasOwnProperty(k) === false) { + if (hasProp(a, k) && hasProp(b, k) === false) { b[k] = a[k] } } @@ -17,9 +22,10 @@ merge = function(a, b) { Marvel = function(opts) { var defaults = { - apiDomain: 'https://gateway.marvel.com' - , gzip: true - }, resOpt + apiDomain: 'https://gateway.marvel.com', + gzip: true + } + var resOpt opts = merge(defaults, opts || {}) diff --git a/lib/resource.js b/lib/resource.js index <HASH>..<HASH> 100644 --- a/lib/resource.js +++ b/lib/resource.js @@ -5,7 +5,7 @@ var crypto = require('crypto') var plural = require('plural').addRule(/series/i, function(w) { return w }) var fields = require('./resource_fields') -var Resource, responseFn, resources, res, fn, lower, merge +var Resource, responseFn, resources, res, fn, lower, merge, hasProp // lowercase helper lower = function(s) { @@ -21,7 +21,7 @@ merge = function(a, b) { var k for (k in a) { - if (a.hasOwnProperty(k) && b.hasOwnProperty(k) === false) { + if (hasProp(a, k) && hasProp(b, k) === false) { b[k] = a[k] } }
added hasProp function to deal with node.js changes seems like somewhere we're creating a non-Object map, which should not have functions from the Object prototype.
swang_marvel
train
ddee70e6661b1a4982c1abfe20243802cd252ac9
diff --git a/src/main/java/org/craftercms/engine/util/spring/cors/SiteAwareCorsConfigurationSource.java b/src/main/java/org/craftercms/engine/util/spring/cors/SiteAwareCorsConfigurationSource.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/craftercms/engine/util/spring/cors/SiteAwareCorsConfigurationSource.java +++ b/src/main/java/org/craftercms/engine/util/spring/cors/SiteAwareCorsConfigurationSource.java @@ -80,7 +80,7 @@ public class SiteAwareCorsConfigurationSource implements CorsConfigurationSource protected CorsConfiguration getConfiguration(HierarchicalConfiguration<?> corsConfig) { if (corsConfig.getBoolean(ENABLE_KEY, false)) { CorsConfiguration config = new CorsConfiguration(); - config.setAllowedOriginPatterns(getValues(corsConfig, ALLOW_ORIGIN_KEY, ALLOW_ORIGIN_DEFAULT)); + config.setAllowedOriginPatterns(getOrigins(corsConfig)); config.setAllowedMethods(getValues(corsConfig, ALLOW_METHODS_KEY, ALLOW_METHODS_DEFAULT)); config.setAllowedHeaders(getValues(corsConfig, ALLOW_HEADERS_KEY, ALLOW_HEADERS_DEFAULT)); config.setMaxAge(corsConfig.getLong(MAX_AGE_KEY, MAX_AGE_DEFAULT)); @@ -92,7 +92,18 @@ public class SiteAwareCorsConfigurationSource implements CorsConfigurationSource } protected List<String> getValues(HierarchicalConfiguration<?> config, String key, String defaultValue) { - return Arrays.stream(config.getString(key, defaultValue).split(",")).map(String::trim).collect(toList()); + return Arrays.stream(config.getString(key, defaultValue).split(",")) + .map(String::trim) + .collect(toList()); + } + + //This is a special case because each pattern can contain additional commas, so we can't split on all of them + //The value should look like this "http://localhost:[8000\,3000], http://domain.com" + protected List<String> getOrigins(HierarchicalConfiguration<?> config) { + // Apache Commons Config will automatically split only the commas that are not escaped + return config.getList(String.class, ALLOW_ORIGIN_KEY, List.of(ALLOW_ORIGIN_DEFAULT)).stream() + .map(String::trim) + .collect(toList()); } }
Fix for patterns in CORS config (#<I>)
craftercms_engine
train
bb4774440266e560f4e0e762c4a88a18ed1523db
diff --git a/aiotg/chat.py b/aiotg/chat.py index <HASH>..<HASH> 100644 --- a/aiotg/chat.py +++ b/aiotg/chat.py @@ -209,6 +209,23 @@ class Chat: **options ) + def send_contact(self, phone_number, first_name, **options): + """ + Send phone contacts. + + :param str phone_number: Contact's phone number + :param str first_name: Contact's first name + :param options: Additional sendContact options (see + https://core.telegram.org/bots/api#sendcontact) + """ + return self.bot.api_call( + "sendContact", + chat_id=self.id, + phone_number=phone_number, + first_name=first_name, + **options + ) + def send_chat_action(self, action): """ Send a chat action, to tell the user that something is happening on the diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py index <HASH>..<HASH> 100644 --- a/tests/test_callbacks.py +++ b/tests/test_callbacks.py @@ -213,6 +213,9 @@ def test_send_methods(): chat.send_venue(13.0, 37.0, b"foo", b"foo") assert "sendVenue" in bot.calls + chat.send_contact("+79260000000", b"foo") + assert "sendContact" in bot.calls + chat.send_chat_action("typing") assert "sendChatAction" in bot.calls
Document send_contact (#<I>)
szastupov_aiotg
train
da236238303d0a3fd0cc6d889cad1afb58058040
diff --git a/lib/Api/Leads.php b/lib/Api/Leads.php index <HASH>..<HASH> 100644 --- a/lib/Api/Leads.php +++ b/lib/Api/Leads.php @@ -73,4 +73,15 @@ class Leads extends Contacts { return $this->makeRequest('contacts/'.$id.'/campaigns'); } + + /** + * Change the number of points a lead + * + * @param int $leadId + * @param int $points + * @return mixed + */ + public function setPointsToLead($leadId, $points) { + return $this->makeRequest('leads/'.$leadId.'/setpoints/'.$points); + } }
API - added function setPointsToLead
mautic_api-library
train
f8f6cd976af3b81d9b06f7b1ec87f31aa0f70427
diff --git a/packages/ra-core/src/actions/undoActions.js b/packages/ra-core/src/actions/undoActions.js index <HASH>..<HASH> 100644 --- a/packages/ra-core/src/actions/undoActions.js +++ b/packages/ra-core/src/actions/undoActions.js @@ -3,7 +3,7 @@ export const UNDO = 'RA/UNDO'; export const START_OPTIMISTIC_MODE = 'RA/START_OPTIMISTIC_MODE'; export const STOP_OPTIMISTIC_MODE = 'RA/STOP_OPTIMISTIC_MODE'; -export const startUndoable = (action, delay = 3000) => ({ +export const startUndoable = (action, delay = 4000) => ({ type: UNDOABLE, payload: { action, delay }, });
Synchronize undoable with default snackbar delay
marmelab_react-admin
train
ad18d9bb5f7a6ed3e703c1c944e97d5866b24cb4
diff --git a/src/Stream.php b/src/Stream.php index <HASH>..<HASH> 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -76,7 +76,7 @@ final class Stream implements StreamInterface $new = new self(); $new->stream = $body; $meta = \stream_get_meta_data($new->stream); - $new->seekable = $meta['seekable']; + $new->seekable = $meta['seekable'] && 0 === \fseek($new->stream, 0, \SEEK_CUR); $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]); $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]); $new->uri = $new->getMetadata('uri'); diff --git a/tests/StreamTest.php b/tests/StreamTest.php index <HASH>..<HASH> 100644 --- a/tests/StreamTest.php +++ b/tests/StreamTest.php @@ -160,4 +160,34 @@ class StreamTest extends TestCase $this->assertNull($stream->getSize()); $this->assertEmpty($stream->getMetadata()); } + + public function testUnseekableStreamWrapper() + { + stream_wrapper_register('nyholm-psr7-test', TestStreamWrapper::class); + $handle = fopen('nyholm-psr7-test://', 'r'); + stream_wrapper_unregister('nyholm-psr7-test'); + + $stream = Stream::create($handle); + $this->assertFalse($stream->isSeekable()); + } +} + +class TestStreamWrapper +{ + public $context; + + public function stream_open() + { + return true; + } + + public function stream_seek(int $offset, int $whence = SEEK_SET) + { + return false; + } + + public function stream_eof() + { + return true; + } }
Fix checking for seekable stream resources (#<I>) Userland stream wrappers always return true for the "seekable" metadata, yet this can be wrong. Here is a more accurate check.
Nyholm_psr7
train
f5a9c38a36cfebccaa4bd92021b02d0ed9d05113
diff --git a/spec/overcommit/utils_spec.rb b/spec/overcommit/utils_spec.rb index <HASH>..<HASH> 100644 --- a/spec/overcommit/utils_spec.rb +++ b/spec/overcommit/utils_spec.rb @@ -207,7 +207,7 @@ describe Overcommit::Utils do end describe '.execute_in_background' do - let(:arguments) { %w[touch some-file] } + let(:arguments) { %w[(echo Hello World) > some-file] } subject { described_class.execute_in_background(arguments) } around do |example| @@ -218,7 +218,7 @@ describe Overcommit::Utils do it 'executes the command' do wait_until { subject.exited? } # Make sure process terminated before checking - File.exist?('some-file').should == true + File.read('some-file').should == "Hello World\n" end end
Use echo rather than touch for Windows compatibility
sds_overcommit
train
d416b90424063f1596f09843aee9bd10729c4740
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,3 +1,8 @@ +'use-strict'; + +////////////////////////////// +// Requires +////////////////////////////// var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync').create(); var exec = require('child_process').exec; @@ -10,6 +15,11 @@ var sass = require('gulp-sass'); // var scsslint = require('gulp-scss-lint'); var stylish = require('jshint-stylish'); +////////////////////////////// +// Variables +////////////////////////////// + +// Autoprefixer: // Target these browsers for adding vendor prefixes to CSS var BROWSERS = [ "> 5%", @@ -25,6 +35,24 @@ var BROWSERS = [ "Android > 0" ]; +var dirs = { + 'sass': 'dev/patterns/**/*.scss', + 'js': { + 'lint': [ + 'Gulpfile.js', + '*.json', + 'dev/dev.js', + 'dev/patterns/**/package.json' + ] + }, + 'html': { + 'reload': [ + 'dev/index.html', + 'dev/patterns/**/html/*.html' + ] + } +}; + // Initialize browser-sync and proxy web server gulp.task('browser-sync', function() { browserSync.init({
Create dirs object, 'use strict' and comments
carbon-design-system_carbon-components
train
6128625435d413b3f73ac9b60e6500b84b8261e3
diff --git a/lib/process-adapter.js b/lib/process-adapter.js index <HASH>..<HASH> 100644 --- a/lib/process-adapter.js +++ b/lib/process-adapter.js @@ -24,7 +24,17 @@ exports.send = (name, data) => { // `process.channel` was added in Node.js 7.1.0, but the channel was available // through an undocumented API as `process._channel`. -exports.ipcChannel = process.channel || process._channel; +const ipcChannel = process.channel || process._channel; +let allowUnref = true; +exports.unrefChannel = () => { + if (allowUnref) { + ipcChannel.unref(); + } +}; +exports.forceRefChannel = () => { + allowUnref = false; + ipcChannel.ref(); +}; const opts = JSON.parse(process.argv[2]); require('./worker-options').set(opts); diff --git a/lib/test-worker.js b/lib/test-worker.js index <HASH>..<HASH> 100644 --- a/lib/test-worker.js +++ b/lib/test-worker.js @@ -41,7 +41,7 @@ function exit() { exiting = true; // Reference the IPC channel so the exit sequence can be completed. - adapter.ipcChannel.ref(); + adapter.forceRefChannel(); const stats = runner.buildStats(); adapter.send('results', {stats}); @@ -116,7 +116,7 @@ function handleUncaughtException(exception) { // Ensure the IPC channel is referenced. The uncaught exception will kick off // the teardown sequence, for which the messages must be received. - adapter.ipcChannel.ref(); + adapter.forceRefChannel(); adapter.send('uncaughtException', {exception: serialized}); } @@ -139,7 +139,7 @@ process.on('ava-teardown', () => { tearingDown = true; // Reference the IPC channel so the teardown sequence can be completed. - adapter.ipcChannel.ref(); + adapter.forceRefChannel(); let rejections = currentlyUnhandled() .filter(rejection => !attributedRejections.has(rejection.promise)); @@ -206,6 +206,6 @@ try { // used to detect when tests stall. // If AVA was not required then the parent process will initiated a teardown // sequence, for which this process ought to stay active. - adapter.ipcChannel.unref(); + adapter.unrefChannel(); } }
Keep IPC channel referenced once it's needed again Ensure the IPC channel stays referenced. This is a safe-guard: it's easy to end up in a situation where the channel needs to be referenced but it's unreferenced because other code wasn't aware.
avajs_ava
train
048427f0e35d235b5a913f9b130048cfe75fbf55
diff --git a/index.js b/index.js index <HASH>..<HASH> 100755 --- a/index.js +++ b/index.js @@ -13,7 +13,7 @@ const app = express(); const allowedMethods = ['GET', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE']; const DEFAULT_PORT = 8081; -const DEFAULT_PATH = path.join(__dirname, 'data'); +const DEFAULT_PATH = path.join(process.cwd(), 'data'); const DEFAULT_LOG_PATH = path.join(__dirname, 'saray.log'); const DEFAULT_ROOT_PATH = ''; @@ -169,7 +169,7 @@ app.use(function(req, res, next) { const port = program.port; module.exports.port = port; -const apiDataPath = program.path; +const apiDataPath = path.resolve(program.path); module.exports.apiDataPath = apiDataPath; sarayRouter.all('/*', function(req, res) {
Refs #<I> - Now all paths to stubbed data are converted to absolute paths
contactlab_saray
train
8bdf80375dd9012f14cf6ec977252fa0bfd10ab4
diff --git a/Kwf/Component/Cache/Redis.php b/Kwf/Component/Cache/Redis.php index <HASH>..<HASH> 100644 --- a/Kwf/Component/Cache/Redis.php +++ b/Kwf/Component/Cache/Redis.php @@ -123,8 +123,13 @@ class Kwf_Component_Cache_Redis extends Kwf_Component_Cache } if ($update === array()) { - //using keys command here is ok as that happens only when executing "clear-view-cache --all" on cli - $keysToDelete = $this->_redis->keys('viewcache:*'); + //only when executing "clear-view-cache --all" on cli + $it = null; + while ($keys = $this->_redis->scan($it, 'viewcache:*')) { + $keysToDelete = array_merge($keys); + } + $keysToDelete = array_unique($keysToDelete); + } else { $keysToDelete = $this->_redis->sInter($keys); }
Redis: Don't use keys, port to scan for better performance
koala-framework_koala-framework
train
e01aab02591f2127fabe0c5c1c8a7b754bfb474e
diff --git a/lib/services/base.rb b/lib/services/base.rb index <HASH>..<HASH> 100644 --- a/lib/services/base.rb +++ b/lib/services/base.rb @@ -25,15 +25,11 @@ module Services private - def find_objects(ids_or_objects, klass = nil) - if klass.nil? - klass = self.class.to_s[/Services::([^:]+)/, 1].singularize.constantize rescue nil - raise "Could not determine class from #{self.class}" if klass.nil? - end - ids_or_objects_array = Array(ids_or_objects) - ids, objects = ids_or_objects_array.grep(Fixnum), ids_or_objects_array.grep(klass) - if ids.size + objects.size < ids_or_objects_array.size - raise "All params must be either #{klass.to_s.pluralize} or Fixnums: #{ids_or_objects_array.map(&:class)}" + def find_objects(ids_or_objects, klass = determine_service_class) + ids_or_objects = Array(ids_or_objects) + ids, objects = ids_or_objects.grep(Fixnum), ids_or_objects.grep(klass) + if ids.size + objects.size < ids_or_objects.size + raise "All params must be either #{klass.to_s.pluralize} or Fixnums: #{ids_or_objects.map(&:class)}" end if ids.any? find_service = "Services::#{klass.to_s.pluralize}::Find" @@ -47,9 +43,20 @@ module Services raise self.class::Error, "#{klass.to_s.pluralize(missing_ids)} #{missing_ids.join(', ')} not found." if missing_ids.size > 0 objects.concat objects_from_ids end - ids_or_objects.is_a?(Array) ? objects : objects.first + objects + end + + def find_object(*args) + find_objects(*args).tap do |objects| + raise "Expected only one object but found #{objects.size}" unless objects.size == 1 + end.first + end + + def determine_service_class + self.class.to_s[/Services::([^:]+)/, 1].singularize.constantize + rescue + raise "Could not determine service class from #{self.class}" end - alias_method :find_object, :find_objects def controller @controller ||= begin diff --git a/spec/services/base_spec.rb b/spec/services/base_spec.rb index <HASH>..<HASH> 100644 --- a/spec/services/base_spec.rb +++ b/spec/services/base_spec.rb @@ -1,24 +1,24 @@ require 'spec_helper' describe Services::Base do - describe '#find_objects' do - let(:objects) { (1..5).to_a.shuffle.map { |id| Model.new(id) } } + let(:model_objects) { (1..5).to_a.shuffle.map { |id| Model.new(id) } } + describe '#find_objects' do context 'when passing in objects' do it 'returns the same objects' do - expect(Services::Models::FindObjectsTest.call(objects)).to eq(objects) + expect(Services::Models::FindObjectsTest.call(model_objects)).to eq(model_objects) end end context 'when passing in IDs' do it 'returns the objects for the IDs' do - expect(Services::Models::FindObjectsTest.call(objects.map(&:id))).to eq(objects) + expect(Services::Models::FindObjectsTest.call(model_objects.map(&:id))).to eq(model_objects) end end context 'when passing in objects and IDs' do it 'returns the objects plus the objects for the IDs' do - objects_as_objects, objects_as_ids = objects.partition do |object| + objects_as_objects, objects_as_ids = model_objects.partition do |object| rand(2) == 1 end @@ -30,10 +30,29 @@ describe Services::Base do end context 'when passing in a single object or ID' do - it 'returns a single object' do - object = objects.sample + it 'returns an array containing the object' do + object = model_objects.sample [object.id, object].each do |id_or_object| - expect(Services::Models::FindObjectsTest.call(id_or_object)).to eq(object) + expect(Services::Models::FindObjectsTest.call(id_or_object)).to eq([object]) + end + end + end + end + + describe '#find_object' do + context 'when passing in a single object or ID' do + it 'returns the object' do + object = model_objects.sample + [object.id, object].each do |id_or_object| + expect(Services::Models::FindObjectTest.call(id_or_object)).to eq(object) + end + end + end + + context 'when passing in something else than a single object or ID' do + it 'raises an error' do + [%w(foo bar), nil, Object.new].each do |object| + expect { Services::Models::FindObjectTest.call(object) }.to raise_error end end end diff --git a/spec/support/test_services.rb b/spec/support/test_services.rb index <HASH>..<HASH> 100644 --- a/spec/support/test_services.rb +++ b/spec/support/test_services.rb @@ -38,6 +38,12 @@ module Services find_objects ids_or_objects end end + + class FindObjectTest < Services::Base + def call(id_or_object) + find_object id_or_object + end + end end end
Always return an array from Services::Base#find_objects and a single object from Services::Base#find_object
krautcomputing_services
train
2d2d374881d293266f6c7c575c9ba388e688a028
diff --git a/python_utils/__about__.py b/python_utils/__about__.py index <HASH>..<HASH> 100644 --- a/python_utils/__about__.py +++ b/python_utils/__about__.py @@ -6,4 +6,4 @@ __description__: str = ( 'with the standard Python install') __url__: str = 'https://github.com/WoLpH/python-utils' # Omit type info due to automatic versioning script -__version__ = '2.7.1' +__version__ = '3.0.0'
Incrementing version to <I>
WoLpH_python-utils
train
5dd7b6fbf9b110cab0f86bc002d08bf3748a718c
diff --git a/lib/geometry/point_zero.rb b/lib/geometry/point_zero.rb index <HASH>..<HASH> 100644 --- a/lib/geometry/point_zero.rb +++ b/lib/geometry/point_zero.rb @@ -30,6 +30,11 @@ everything else, regardless of size. You can think of it as an application of th end end + def is_a?(klass) + (klass == Point) || super + end + alias :kind_of? :is_a? + # This is a hack to get Array#== to work properly. It works on ruby 2.0 and 1.9.3. def to_ary [] diff --git a/test/geometry/point_zero.rb b/test/geometry/point_zero.rb index <HASH>..<HASH> 100644 --- a/test/geometry/point_zero.rb +++ b/test/geometry/point_zero.rb @@ -2,12 +2,24 @@ require 'minitest/autorun' require 'geometry/point_zero' describe Geometry::PointZero do + subject { Geometry::PointZero.new } let(:zero) { Geometry::PointZero.new } describe "arithmetic" do let(:left) { Point[1,2] } let(:right) { Point[3,4] } - + + it 'must pretend to be a Point' do + subject.is_a?(Point).must_equal true + subject.kind_of?(Point).must_equal true + + subject.is_a?(PointZero).must_equal true + subject.kind_of?(PointZero).must_equal true + + subject.instance_of?(Point).must_equal false + subject.instance_of?(PointZero).must_equal true + end + it "must have +@" do (+zero).must_be :eql?, 0 (+zero).must_be_instance_of(Geometry::PointZero)
PointZero should pretend to be a Point
bfoz_geometry
train
d20757b6598dacc555d47c4bf9a6695ba8e9e05d
diff --git a/test/cli.test.js b/test/cli.test.js index <HASH>..<HASH> 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -45,5 +45,5 @@ describe('CLI', () => { proc.on('exit', () => { done(); }); - }).timeout(6000); + }).timeout(18000); });
Upgrade another timeout for slow CI
webpack_webpack-dev-server
train
edbe5f043094f73de437bdd95c8e4ed9224865c8
diff --git a/decidim-core/lib/decidim/core/engine.rb b/decidim-core/lib/decidim/core/engine.rb index <HASH>..<HASH> 100644 --- a/decidim-core/lib/decidim/core/engine.rb +++ b/decidim-core/lib/decidim/core/engine.rb @@ -22,6 +22,7 @@ require "omniauth" require "omniauth-facebook" require "omniauth-twitter" require "omniauth-google-oauth2" +require "omniauth/rails_csrf_protection" require "invisible_captcha" require "premailer/rails" require "premailer/adapter/decidim"
Require omniauth/rails_csrf_protection explicitly (#<I>)
decidim_decidim
train
5da1f8822420a48ef15dd6da6a0f06f14b6858c7
diff --git a/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/search/IdolDocumentService.java b/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/search/IdolDocumentService.java index <HASH>..<HASH> 100644 --- a/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/search/IdolDocumentService.java +++ b/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/search/IdolDocumentService.java @@ -30,6 +30,9 @@ import java.util.List; @SuppressWarnings("WeakerAccess") public class IdolDocumentService implements DocumentsService<String, IdolSearchResult, AciErrorException> { + // fake token in a format that IDOL is happy with + private static final String EMPTY_RESULT_SET_TOKEN = "NULL-0"; + protected final ConfigService<? extends IdolSearchCapable> configService; protected final HavenSearchAciParameterHandler parameterHandler; protected final QueryResponseParser queryResponseParser; @@ -125,7 +128,8 @@ public class IdolDocumentService implements DocumentsService<String, IdolSearchR aciParameters.remove(QueryParams.Combine.name()); final QueryResponseData responseData = contentAciService.executeAction(aciParameters, queryResponseProcessor); - final TypedStateToken tokenData = new TypedStateToken(responseData.getState(), promotions ? TypedStateToken.StateTokenType.PROMOTIONS : TypedStateToken.StateTokenType.QUERY); + final String token = responseData.getState() != null ? responseData.getState() : EMPTY_RESULT_SET_TOKEN; + final TypedStateToken tokenData = new TypedStateToken(token, promotions ? TypedStateToken.StateTokenType.PROMOTIONS : TypedStateToken.StateTokenType.QUERY); // Now fetch result count with combine=simple final AciParameters resultCountAciParameters = new AciParameters(QueryActions.Query.name());
FIND-<I> Comparison fails when one search has 0 results :: use fake token when there are no results and IDOL doesn't generate a state token [rev. matthew.gordon]
microfocus-idol_haven-search-components
train
45fa772fe79d77e10839e3cbb42a695a868600e8
diff --git a/src/Jobs/Form/ListFilter.php b/src/Jobs/Form/ListFilter.php index <HASH>..<HASH> 100644 --- a/src/Jobs/Form/ListFilter.php +++ b/src/Jobs/Form/ListFilter.php @@ -21,6 +21,16 @@ use Core\Form\ViewPartialProviderInterface; class ListFilter extends Form implements ViewPartialProviderInterface { /** + * adds filter fields like my jobs or all jobs of my companies + */ + const MODE_ACL = 1; + + /** + * Adds the regional fields "location" and "distance" to the search form. + */ + const MODE_REGIONAL = 2; + + /** * @var string $viewPartial view script for the search formular */ protected $viewPartial = 'jobs/form/list-filter'; diff --git a/src/Jobs/Form/ListFilterFieldset.php b/src/Jobs/Form/ListFilterFieldset.php index <HASH>..<HASH> 100644 --- a/src/Jobs/Form/ListFilterFieldset.php +++ b/src/Jobs/Form/ListFilterFieldset.php @@ -83,6 +83,29 @@ class ListFilterFieldset extends Fieldset 'label' => /*@translate*/ 'Job title', ), )); + + $this->add(array( + 'name' => 'l', + 'type' => 'Location', + 'options' => array( + 'label' => /*@translate*/ 'Location', + ), + )); + + $this->add(array( + 'name' => 'd', + 'type' => 'Zend\Form\Element\Select', + 'options' => array( + 'label' => /*@translate*/ 'Distance', + 'value_options' => array( + '5' => '5 km', + '10' => '10 km', + '20' => '20 km', + '50' => '50 km', + '100' => '100 km' + ), + ), + )); } /** diff --git a/view/form/list-filter.phtml b/view/form/list-filter.phtml index <HASH>..<HASH> 100644 --- a/view/form/list-filter.phtml +++ b/view/form/list-filter.phtml @@ -41,6 +41,7 @@ if (empty($action)) { $form->setAttributes(array( 'action' => $action, 'method' => 'GET', + 'class' => 'form-inline' )); echo $this->form()->openTag($form); @@ -49,12 +50,31 @@ echo $this->formHidden($params->get('page')); $byElement = $params->get('by'); $statusElement = $params->get('status'); ?> -<div id="params-search-wrapper" class="input-group"> - <span class="input-group-addon">?</span> - <?php echo $this->formText($params->get('search')->setAttributes(array('class' => 'form-control ','placeholder' => /* @translate */ 'search for jobs' ))) ?> - <span class="input-group-btn"> - <button class="btn btn-primary" type="submit"><?php echo $this->translate('Search') ?></button> - </span> + +<?php #echo $this->form($form, Core\Form\View\Helper\Form::LAYOUT_INLINE);?> + +<div id="params-search-wrapper" class="xinput-group"> + <?php echo $this->formText($params->get('search')->setAttributes(array('class' => 'form-control ','placeholder' => /* @translate */ 'search for position or company' ))) ?> + + <?php #echo $this->formElement($params->get('l')->setAttributes(array('class' => 'form-control ','placeholder' => /* @translate */ ))) ?> + + + + + X <input type="text" value="<?php echo $params->get("l")->getValue(); ?>" + class=" form-control geolocation" + style="vertical-align: middle" + id="job-location" + name="<?php echo $params->get("l")->getName(); ?>" + data-provide="typeahead" + placeholder="<?php echo $this->translate('search for a location');?>">Y + <span id="<?php echo preg_replace('/\W/','-',$params->get("l")->getName()); ?>errors"> + </span> + + <?php echo $this->formSelect($params->get('d')->setAttributes(array('class' => 'form-control ','placeholder' => /* @translate */ 'search for a location' ))) ?> + + + <button class="btn btn-primary" type="submit"><?php echo $this->translate('Search') ?></button> </div> <?php $showButtons = $params->has('by') && $this->acl()->isRole( Auth\Entity\User::ROLE_RECRUITER );
adds location "l" and distance "d" to search job search formular
yawik_jobs
train
890e02964f4dcd3687ac9def985aede01ef889f4
diff --git a/examples/tp/hello_tp.py b/examples/tp/hello_tp.py index <HASH>..<HASH> 100644 --- a/examples/tp/hello_tp.py +++ b/examples/tp/hello_tp.py @@ -39,9 +39,11 @@ PLEASE READ THROUGH THE CODE COMMENTS - THEY EXPLAIN THE OUTPUT IN DETAIL # Can't live without numpy import numpy -# This is the class correspondingn to the C++ optimized Temporal Pooler -from nupic.research.TP10X2 import TP10X2 - +# here we choose TP implementation: (uncomment one only) +# This is the class correspondingn to the C++ optimized Temporal Pooler (default) +from nupic.research.TP10X2 import TP10X2 as TP +# This is simple implementation in Python +#from nupic.research.TP import TP as TP # Utility routine for printing the input vector def formatRow(x): @@ -58,7 +60,7 @@ def formatRow(x): ####################################################################### # # Step 1: create Temporal Pooler instance with appropriate parameters -tp = TP10X2(numberOfCols=50, cellsPerColumn=1, +tp = TP(numberOfCols=50, cellsPerColumn=1, initialPerm=0.5, connectedPerm=0.5, minThreshold=10, newSynapseCount=10, permanenceInc=0.1, permanenceDec=0.0,
document choice of TP implementation TP<I>X2 is fast,optimized implementation using C++ code TP is python, simple, slow Conflicts: examples/tp/hello_tp.py
numenta_nupic
train
7458d7d753b9cac430808ea6473818d10033474a
diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index <HASH>..<HASH> 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -186,13 +186,12 @@ class ThreadPool: def _clear_dead_threads(self): # Remove any dead threads from our list - for t in self._threads: - if not t.isAlive(): - self._threads.remove(t) - try: - self._pending_shutdowns.popleft() - except IndexError: - pass + for t in [t for t in self._threads if not t.isAlive()]: + self._threads.remove(t) + try: + self._pending_shutdowns.popleft() + except IndexError: + pass def grow(self, amount): """Spawn new worker threads (not above self.max)."""
More compact code in "clear dead threads" method.
cherrypy_cheroot
train
bd45ce8a95ad9d1ef97372d752b61d1dde4a8db0
diff --git a/src/Common/Misc/AnnotationBuilder/index.js b/src/Common/Misc/AnnotationBuilder/index.js index <HASH>..<HASH> 100644 --- a/src/Common/Misc/AnnotationBuilder/index.js +++ b/src/Common/Misc/AnnotationBuilder/index.js @@ -67,6 +67,28 @@ function fork(annotationObj) { return Object.assign({}, annotationObj, { generation, id }); } +function setDefaultName(annotationObject) { + if (annotationObject.selection.type === 'range') { + const rangeNames = Object.keys(annotationObject.selection.range.variables); + if (rangeNames.length > 0) { + annotationObject.name = rangeNames[0]; + if (rangeNames.length > 1) { + annotationObject.name += ` & ${rangeNames[1]}`; + } + if (rangeNames.length > 2) { + annotationObject.name += ' &...'; + } + } else { + annotationObject.name = 'empty'; + } + annotationObject.name += ' (range)'; + } else if (annotationObject.selection.type === 'partition') { + annotationObject.name = `${annotationObject.selection.partition.variable} (partition)`; + } else { + annotationObject.name = 'unknown'; + } +} + // ---------------------------------------------------------------------------- function markModified(annotationObject) { @@ -86,6 +108,7 @@ export default { EMPTY_ANNOTATION, fork, markModified, + setDefaultName, setInitialGenerationNumber, update, updateReadOnlyFlag, diff --git a/src/InfoViz/Native/HistogramSelector/score.js b/src/InfoViz/Native/HistogramSelector/score.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/HistogramSelector/score.js +++ b/src/InfoViz/Native/HistogramSelector/score.js @@ -124,7 +124,7 @@ export default function init(inPublicAPI, inModel) { } if (model.provider.isA('SelectionProvider')) { if (!scoreData.name) { - scoreData.name = `${scoreData.selection.partition.variable} (partition)`; + AnnotationBuilder.setDefaultName(scoreData); if (model.provider.isA('AnnotationStoreProvider')) { scoreData.name = model.provider.getNextStoredAnnotationName(scoreData.name); } diff --git a/src/InfoViz/Native/MutualInformationDiagram/index.js b/src/InfoViz/Native/MutualInformationDiagram/index.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/MutualInformationDiagram/index.js +++ b/src/InfoViz/Native/MutualInformationDiagram/index.js @@ -329,6 +329,13 @@ function informationDiagram(publicAPI, model) { lastAnnotationPushed = model.provider.getAnnotation(); if (!lastAnnotationPushed || model.provider.shouldCreateNewAnnotation() || lastAnnotationPushed.selection.type !== 'range') { lastAnnotationPushed = AnnotationBuilder.annotation(selection, [model.defaultScore], model.defaultWeight); + if (lastAnnotationPushed.name === '') { + // set default range annotation name + AnnotationBuilder.setDefaultName(lastAnnotationPushed); + if (model.provider.isA('AnnotationStoreProvider')) { + lastAnnotationPushed.name = model.provider.getNextStoredAnnotationName(lastAnnotationPushed.name); + } + } } else { lastAnnotationPushed = AnnotationBuilder.update(lastAnnotationPushed, { selection, diff --git a/src/InfoViz/Native/ParallelCoordinates/index.js b/src/InfoViz/Native/ParallelCoordinates/index.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/ParallelCoordinates/index.js +++ b/src/InfoViz/Native/ParallelCoordinates/index.js @@ -981,6 +981,13 @@ function parallelCoordinate(publicAPI, model) { lastAnnotationPushed = AnnotationBuilder.EMPTY_ANNOTATION; } else if (!lastAnnotationPushed || model.provider.shouldCreateNewAnnotation() || lastAnnotationPushed.selection.type !== 'range') { lastAnnotationPushed = AnnotationBuilder.annotation(selection, [model.defaultScore], model.defaultWeight); + if (lastAnnotationPushed.name === '') { + // set default range annotation name + AnnotationBuilder.setDefaultName(lastAnnotationPushed); + if (model.provider.isA('AnnotationStoreProvider')) { + lastAnnotationPushed.name = model.provider.getNextStoredAnnotationName(lastAnnotationPushed.name); + } + } } else { lastAnnotationPushed = AnnotationBuilder.update(lastAnnotationPushed, { selection,
Fix(AnnotationBuilder): Supply a default name for range annotations Derive from the fields that are in the range annotation when it is created - it doesn't update as fields are added/removed from the range annotation. Update might be desirable in the future.
Kitware_paraviewweb
train
d785d88141986acd05eaaa8456ddb6e44f8738ab
diff --git a/jmock2/test/org/jmock/test/unit/lib/JavaReflectionImposteriserTests.java b/jmock2/test/org/jmock/test/unit/lib/JavaReflectionImposteriserTests.java index <HASH>..<HASH> 100644 --- a/jmock2/test/org/jmock/test/unit/lib/JavaReflectionImposteriserTests.java +++ b/jmock2/test/org/jmock/test/unit/lib/JavaReflectionImposteriserTests.java @@ -57,7 +57,7 @@ public class JavaReflectionImposteriserTests extends TestCase { assertTrue("Signed JAR file does not exist (use Ant to build it)", jarFile.exists()); - URL jarURL = jarFile.toURL(); + URL jarURL = jarFile.toURI().toURL(); ClassLoader loader = new URLClassLoader(new URL[]{jarURL}); Class<?> typeInSignedJar = loader.loadClass("TypeInSignedJar"); diff --git a/jmock2/test/org/jmock/test/unit/lib/legacy/ClassImposteriserTests.java b/jmock2/test/org/jmock/test/unit/lib/legacy/ClassImposteriserTests.java index <HASH>..<HASH> 100644 --- a/jmock2/test/org/jmock/test/unit/lib/legacy/ClassImposteriserTests.java +++ b/jmock2/test/org/jmock/test/unit/lib/legacy/ClassImposteriserTests.java @@ -105,7 +105,7 @@ public class ClassImposteriserTests extends TestCase { assertTrue("Signed JAR file does not exist (use Ant to build it", jarFile.exists()); - URL jarURL = jarFile.toURL(); + URL jarURL = jarFile.toURI().toURL(); ClassLoader loader = new URLClassLoader(new URL[]{jarURL}); Class<?> typeInSignedJar = loader.loadClass("TypeInSignedJar");
Removing deprecation warnings in JDK 6
jmock-developers_jmock-library
train
d80d6df8c83b7dcb54eb5ca8951cf092657c7bf5
diff --git a/core/src/main/java/org/primefaces/extensions/component/scaffolding/ScaffoldingRenderer.java b/core/src/main/java/org/primefaces/extensions/component/scaffolding/ScaffoldingRenderer.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/primefaces/extensions/component/scaffolding/ScaffoldingRenderer.java +++ b/core/src/main/java/org/primefaces/extensions/component/scaffolding/ScaffoldingRenderer.java @@ -58,9 +58,7 @@ public class ScaffoldingRenderer extends CoreRenderer { public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { final Scaffolding scaffolding = (Scaffolding) component; encodeMarkup(context, scaffolding); - if (scaffolding.getValueExpression("loader") != null - && !scaffolding.isReady() - && !context.getPartialViewContext().isAjaxRequest()) { + if (scaffolding.getValueExpression("loader") != null && !scaffolding.isReady()) { encodeScript(context, scaffolding); } }
No need to check for Ajax (#<I>)
primefaces-extensions_core
train
46590799ad2fd143aba29e2947fc741088f08a0e
diff --git a/test-projects/01-basic-app/config/targets.js b/test-projects/01-basic-app/config/targets.js index <HASH>..<HASH> 100644 --- a/test-projects/01-basic-app/config/targets.js +++ b/test-projects/01-basic-app/config/targets.js @@ -14,5 +14,6 @@ if (isCI || isProduction) { } module.exports = { - browsers + browsers, + node: 'current' }; diff --git a/test-projects/02-app-that-excludes-mirage/config/targets.js b/test-projects/02-app-that-excludes-mirage/config/targets.js index <HASH>..<HASH> 100644 --- a/test-projects/02-app-that-excludes-mirage/config/targets.js +++ b/test-projects/02-app-that-excludes-mirage/config/targets.js @@ -14,5 +14,6 @@ if (isCI || isProduction) { } module.exports = { - browsers + browsers, + node: 'current' }; diff --git a/tests/dummy/config/targets.js b/tests/dummy/config/targets.js index <HASH>..<HASH> 100644 --- a/tests/dummy/config/targets.js +++ b/tests/dummy/config/targets.js @@ -14,5 +14,6 @@ if (isCI || isProduction) { } module.exports = { - browsers + browsers, + node: 'current' };
Add `node: 'current'` to targets.js for make FastBoot tests pass
samselikoff_ember-cli-mirage
train
ca47b3f78d75ba08ed6c169a3cd523364b897631
diff --git a/src/Util.php b/src/Util.php index <HASH>..<HASH> 100644 --- a/src/Util.php +++ b/src/Util.php @@ -126,7 +126,22 @@ class Util implements TaggingUtility 'š' => 's', 'ū' => 'u', 'ž' => 'z', //Romanian - 'Ă' => 'A', 'ă' => 'a', 'Ș' => 'S', 'ș' => 's', 'Ț' => 'T', 'ț' => 't' + 'Ă' => 'A', 'ă' => 'a', 'Ș' => 'S', 'ș' => 's', 'Ț' => 'T', 'ț' => 't', + + //Vietnamese + 'ả' => 'a', 'Ả' => 'A','ạ' => 'a', 'Ạ' => 'A', 'ắ' => 'a', 'Ắ' => 'A', 'ằ' => 'a', 'Ằ' => 'A', + 'ẳ' => 'a', 'Ẳ' => 'A', 'ẵ' => 'a', 'Ẵ' => 'A', 'ặ' => 'a', 'Ặ' => 'A', 'ẩ' => 'a', 'Ẩ' => 'A', + 'Ấ' => 'A', 'ấ' => 'a', 'Ầ' => 'A', 'ầ' => 'a', 'Ơ' => 'O', 'ơ' => 'o', 'Đ' => 'D', 'đ' => 'd', + 'ẫ' => 'a', 'Ẫ' => 'A', 'ậ' => 'a', 'Ậ' => 'A', 'ẻ' => 'e', 'Ẻ' => 'E', 'ẽ' => 'e', 'Ẽ' => 'E', + 'ẹ' => 'e', 'Ẹ' => 'E', 'ế' => 'e', 'Ế' => 'E', 'ề' => 'e', 'Ề' => 'E', 'ể' => 'e', 'Ể' => 'E', + 'ễ' => 'e', 'Ễ' => 'E', 'ệ' => 'e', 'Ệ' => 'E', 'ỉ' => 'i', 'Ỉ' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', + 'ị' => 'i', 'Ị' => 'I', 'ỏ' => 'o', 'Ỏ' => 'O', 'ọ' => 'o', 'Ọ' => 'O', 'ố' => 'o', 'Ố' => 'O', + 'ồ' => 'o', 'Ồ' => 'O', 'ổ' => 'o', 'Ổ' => 'O', 'ỗ' => 'o', 'Ỗ' => 'O', 'ộ' => 'o', 'Ộ' => 'O', + 'ớ' => 'o', 'Ớ' => 'O', 'ờ' => 'o', 'Ờ' => 'O', 'ở' => 'o', 'Ở' => 'O', 'ỡ' => 'o', 'Ỡ' => 'O', + 'ợ' => 'o', 'Ợ' => 'O', 'ủ' => 'u', 'Ủ' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'ụ' => 'u', 'Ụ' => 'U', + 'ư' => 'u', 'Ư' => 'U', 'ứ' => 'u', 'Ứ' => 'U', 'ừ' => 'u', 'Ừ' => 'U', 'ử' => 'u', 'Ử' => 'U', + 'ữ' => 'u', 'Ữ' => 'U', 'ự' => 'u', 'Ự' => 'U', 'ỳ' => 'y', 'Ỳ' => 'Y', 'ỷ' => 'y', 'Ỷ' => 'Y', + 'ỹ' => 'y', 'Ỹ' => 'Y', 'ỵ' => 'y', 'Ỵ' => 'Y' ); // Make custom replacements
Adding Vietnamese charmap for making slug
rtconner_laravel-tagging
train
6aa03819f6a78eae10dd72f83d3c9a19567c36d1
diff --git a/bigfloat_cython/bigfloat/__init__.py b/bigfloat_cython/bigfloat/__init__.py index <HASH>..<HASH> 100644 --- a/bigfloat_cython/bigfloat/__init__.py +++ b/bigfloat_cython/bigfloat/__init__.py @@ -61,6 +61,9 @@ __all__ = [ # numeric functions 'next_up', 'next_down', + # 5.2 Assignment Functions + 'pos', + # 5.5 Basic arithmetic functions 'add', 'sub', 'mul', 'sqr', 'div', 'sqrt', 'rec_sqrt', 'cbrt', 'root', 'pow', 'neg', 'abs', 'dim', @@ -111,9 +114,6 @@ from bigfloat.core import ( is_negative, is_integer, - # Standard functions: 1-ary - pos, - # Standard functions: 2-ary mod, @@ -121,6 +121,9 @@ from bigfloat.core import ( next_down, next_up, + # 5.2 Assignment Functions + pos, + # 5.5 Basic Arithmetic Functions add, sub, mul, sqr, div, sqrt, rec_sqrt, cbrt, root, pow, neg, abs, dim, diff --git a/bigfloat_cython/bigfloat/core.py b/bigfloat_cython/bigfloat/core.py index <HASH>..<HASH> 100644 --- a/bigfloat_cython/bigfloat/core.py +++ b/bigfloat_cython/bigfloat/core.py @@ -827,72 +827,9 @@ def set_str2(s, base, context=None): # Constants. -def const_log2(context=None): - """ - Return log(2), rounded according to the current context. - - Returns the natural logarithm of 2 = 0.693..., with precision and rounding - mode taken from the current context. - - """ - return _apply_function_in_current_context( - BigFloat, - mpfr.mpfr_const_log2, - (), - context, - ) - - -def const_pi(context=None): - """ - Return Pi, rounded according to the current context. - - Returns Pi = 3.141..., with precision and rounding mode taken from the - current context. - - """ - return _apply_function_in_current_context( - BigFloat, - mpfr.mpfr_const_pi, - (), - context, - ) - - -def const_euler(context=None): - """ - Return Euler's constant, rounded according to the current context. - - Returns the value of Euler's constant 0.577..., (also called the - Euler-Mascheroni constant) with precision and rounding mode taken from the - current context. - - """ - return _apply_function_in_current_context( - BigFloat, - mpfr.mpfr_const_euler, - (), - context, - ) - - -def const_catalan(context=None): - """ - Return Catalan's constant, rounded according to the current context. - - Returns the value of Catalan's constant 0.915..., with precision and - rounding mode taken from the current context. - - """ - return _apply_function_in_current_context( - BigFloat, - mpfr.mpfr_const_catalan, - (), - context, - ) - - -# Unary functions. +############################################################################### +# 5.2 Assignment Functions +############################################################################### def pos(x, context=None): """ @@ -1948,6 +1885,71 @@ def ai(x, context=None): ) +def const_log2(context=None): + """ + Return log(2), rounded according to the current context. + + Returns the natural logarithm of 2 = 0.693..., with precision and rounding + mode taken from the current context. + + """ + return _apply_function_in_current_context( + BigFloat, + mpfr.mpfr_const_log2, + (), + context, + ) + + +def const_pi(context=None): + """ + Return Pi, rounded according to the current context. + + Returns Pi = 3.141..., with precision and rounding mode taken from the + current context. + + """ + return _apply_function_in_current_context( + BigFloat, + mpfr.mpfr_const_pi, + (), + context, + ) + + +def const_euler(context=None): + """ + Return Euler's constant, rounded according to the current context. + + Returns the value of Euler's constant 0.577..., (also called the + Euler-Mascheroni constant) with precision and rounding mode taken from the + current context. + + """ + return _apply_function_in_current_context( + BigFloat, + mpfr.mpfr_const_euler, + (), + context, + ) + + +def const_catalan(context=None): + """ + Return Catalan's constant, rounded according to the current context. + + Returns the value of Catalan's constant 0.915..., with precision and + rounding mode taken from the current context. + + """ + return _apply_function_in_current_context( + BigFloat, + mpfr.mpfr_const_catalan, + (), + context, + ) + + def mod(x, y, context=None): """ Return x reduced modulo y, rounded according to the current context.
Reorganization: move const_??? functions to correct place in core.py; move pos import to correct place in __init__.py
mdickinson_bigfloat
train
ddd22be4e57a2ab6898c9d980b4c4e09e3b80a30
diff --git a/raven/transport/registry.py b/raven/transport/registry.py index <HASH>..<HASH> 100644 --- a/raven/transport/registry.py +++ b/raven/transport/registry.py @@ -51,15 +51,9 @@ class TransportRegistry(object): def supported_scheme(self, scheme): return scheme in self._schemes - def get_transport(self, parsed_url): + def get_transport(self, parsed_url, **options): full_url = parsed_url.geturl() if full_url not in self._transports: - # Grab options from the querystring to pass to the transport - # e.g. ?timeout=30 - if parsed_url.query: - options = dict(q.split('=', 1) for q in parsed_url.query.split('&')) - else: - options = dict() # Remove the options from the parsed_url parsed_url = urlparse.urlparse(full_url.split('?')[0]) self._transports[full_url] = self._schemes[parsed_url.scheme](parsed_url, **options)
fixed a transport init args.
getsentry_raven-python
train
fa5a5d899d26919410f51ecd3d3c9dce8ecd4f7f
diff --git a/src/components/BodyAttributes.js b/src/components/BodyAttributes.js index <HASH>..<HASH> 100644 --- a/src/components/BodyAttributes.js +++ b/src/components/BodyAttributes.js @@ -1,6 +1,11 @@ import { Component, Children, PropTypes } from "react"; import withSideEffect from "react-side-effect"; + +const supportedHTML4Attributes = { + "bgColor": "bgcolor" +}; + class BodyAttributes extends Component { render() { return Children.only(this.props.children); @@ -13,11 +18,8 @@ BodyAttributes.propTypes = { function reducePropsToState(propsList) { const attrs = {}; - const transformedAttrs = {}; propsList.forEach(function (props) { - if (props.hasOwnProperty("bgColor")) { - Object.assign(transformedAttrs, {"data-oy-bgcolor": props["bgColor"]}); - } + const transformedAttrs = transformHTML4Props(props); Object.assign(attrs, props, transformedAttrs); }); return attrs; @@ -29,6 +31,23 @@ function handleStateChangeOnClient(attrs) { } } +function transformHTML4Props(props) { + const transformedProps = {}; + + // Provide support for HTML4 attributes on the body tag for + // e-mail purposes. Convert tags to ones oy-vey can translate + // during the render. + Object.keys(supportedHTML4Attributes).forEach(propName => { + if (props.hasOwnProperty(propName)) { + const name = supportedHTML4Attributes[propName]; + const value = props[propName]; + const transformedProp = { [`data-oy-${name}`]: value }; + Object.assign(transformedProps, transformedProp); + } + }); + return transformedProps; +} + export default withSideEffect( reducePropsToState, handleStateChangeOnClient
Cleanup transform of HTML4 attributes Allows more flexible setting of the transformable attributes
TrueCar_gluestick-shared
train
e68ef3f67442701d663d96888c1341f59b9f77b9
diff --git a/src/jasmine.nunit_reporter.js b/src/jasmine.nunit_reporter.js index <HASH>..<HASH> 100644 --- a/src/jasmine.nunit_reporter.js +++ b/src/jasmine.nunit_reporter.js @@ -55,6 +55,10 @@ } }, + reportSpecStarting: function(spec) { + spec.startTime = new Date(); + }, + reportRunnerResults: function(runner) { var output = printTestResults(runner, this); this.writeFile(output); @@ -70,37 +74,25 @@ testSuite.success = results.passed(); }, - reportSpecStarting: function(spec) { + reportSpecResults: function(spec) { + var elapsed = spec.startTime ? (new Date() - spec.startTime) / 1000 : 0; + var results = spec.results(); + var skipped = !!results.skipped; + var id = spec.id; var suite = spec.suite; - var testSuite = this.testSuites[suite.id]; var testSpec = { - elapsed: null, - executed: false, + elapsed: elapsed, + executed: !skipped, failures: [], id: spec.id, name: spec.description, - success: false, - startTime: new Date() + success: results.passed() }; - this.testSpecs[spec.id] = testSpec; - testSuite.specs.push(testSpec); - }, - - reportSpecResults: function(spec) { - var endTime = new Date(); - var id = spec.id; - var results = spec.results(); - - var testSpec = this.testSpecs[id]; - testSpec.executed = true; - - var success = results.passed(); - testSpec.success = success; - if (!success) { + if (!testSpec.success) { var items = results.getItems(); for (var i = 0; i < items.length; i++) { @@ -110,18 +102,15 @@ message: result.toString(), stack: result.trace.stack ? result.trace.stack : "" }; - testSpec.failures.push(failure); } } } - var elapsed = (endTime - testSpec.startTime) / 1000; - testSpec.elapsed = elapsed; - - for (var suite = spec.suite; suite; suite = suite.parentSuite) { - var testSuite = this.testSuites[suite.id]; + while (suite) { + testSuite = this.testSuites[suite.id]; testSuite.elapsed = testSuite.elapsed ? (testSuite.elapsed + elapsed) : elapsed; + suite = suite.parentSuite; } }, @@ -198,19 +187,30 @@ .replace(/\&/g, "&amp;"); } + function getSkippedCount(specs) { + if (!specs.length) { return 0; } + for (var i = 0, count = 0; i < specs.length; i++) { + if (specs[i].results().skipped) { + count++; + } + } + return count; + } + function printTestResults(runner, reporter) { var testRun = reporter.testRun; var output = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; - var specCount = runner.specs().length; - var results = runner.results(); - var date = new Date(); + var results = runner.results(); + var specs = runner.specs(); + var specCount = specs.length; + var skippedCount = getSkippedCount(specs); output += "<test-results name=\"" + escapeInvalidXmlChars(reporter.reportName) + "\" "; output += "total=\"" + specCount + "\" "; output += "failures=\"" + results.failedCount + "\" "; - output += "not-run=\"0\" "; + output += "not-run=\"" + skippedCount + "\" "; output += "date=\"" + dateString(date) + "\" "; output += "time=\"" + timeString(date) + "\">";
Add skipped spec support to NUnitXmlReporter (fixes #<I>)
larrymyers_jasmine-reporters
train
86f101f02cad4b7cb6dd3681cc2c7bfa44946f44
diff --git a/src/openseadragon.js b/src/openseadragon.js index <HASH>..<HASH> 100644 --- a/src/openseadragon.js +++ b/src/openseadragon.js @@ -1385,17 +1385,16 @@ window.OpenSeadragon = window.OpenSeadragon || function( options ){ /** - * Loads a Deep Zoom Image description from a url, XML string or JSON string - * and provides a callback hook for the resulting Document + * Fully deprecated. Will throw an error. * @function * @name OpenSeadragon.createFromDZI * @param {String} xmlUrl * @param {String} xmlString * @param {Function} callback - * @deprecated - use Viewer.openTileSource + * @deprecated - use OpenSeadragon.Viewer.prototype.open */ createFromDZI: function( dzi, callback, tileHost ) { - throw "OpenSeadragon.createFromDZI is deprecated, use Viewer.openTileSource."; + throw "OpenSeadragon.createFromDZI is deprecated, use Viewer.open."; }, /**
refs #<I> - pointing deprecated method at correct current method.
openseadragon_openseadragon
train
d21cd9111f78bed5995672471bc5f42d4de389f3
diff --git a/lib/danger/request_sources/github.rb b/lib/danger/request_sources/github.rb index <HASH>..<HASH> 100644 --- a/lib/danger/request_sources/github.rb +++ b/lib/danger/request_sources/github.rb @@ -50,9 +50,16 @@ module Danger # Just remove the comment, if there's nothing to say. delete_old_comments! else + issues = client.issue_comments(ci_source.repo_slug, ci_source.pull_request_id) + editable_issues = issues.reject { |issue| issue[:body].include?("generated_by_danger") == false } body = generate_comment(warnings: warnings, errors: errors, messages: messages) - comment_result = client.add_comment(ci_source.repo_slug, ci_source.pull_request_id, body) - delete_old_comments!(except: comment_result[:id]) + + if editable_issues.empty? + comment_result = client.add_comment(ci_source.repo_slug, ci_source.pull_request_id, body) + else + original_id = editable_issues.first[:id] + comment_result = client.update_comment(ci_source.repo_slug, original_id ,body) + end end # Now, set the pull request status. @@ -105,7 +112,7 @@ module Danger end end - def generate_comment(warnings: nil, errors: nil, messages: nil) + def generate_comment(warnings: [], errors: [], messages: []) require 'erb' md_template = File.join(Danger.gem_path, "lib/danger/comment_generators/github.md.erb") diff --git a/spec/sources/github_spec.rb b/spec/sources/github_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sources/github_spec.rb +++ b/spec/sources/github_spec.rb @@ -66,7 +66,6 @@ describe Danger::GitHub do result = @g.generate_comment(warnings: ["my warning"], errors: ["some error"], messages: []) expect(result.gsub(/\s+/, "")).to include("generated_by_danger") end - end describe "status message" do @@ -74,18 +73,51 @@ describe Danger::GitHub do message = @g.generate_github_description(warnings: [], errors:[]) expect(message).to start_with("All green.") end + it "Shows an error messages when there are errors" do message = @g.generate_github_description(warnings: [1,2,3], errors:[]) expect(message).to eq("⚠ 3 Warnings. Don't worry, everything is fixable.") end + it "Shows an error message when errors and warnings" do message = @g.generate_github_description(warnings: [1,2], errors:[1,2,3]) expect(message).to eq("⚠ 3 Errors. 2 Warnings. Don't worry, everything is fixable.") end + it "Deals with singualars in messages when errors and warnings" do message = @g.generate_github_description(warnings: [1], errors:[1]) expect(message).to eq("⚠ 1 Error. 1 Warning. Don't worry, everything is fixable.") end + end + + describe "issue creation" do + it "creates an issue if no danger comments exist" do + issues = [] + allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(issues) + + body = @g.generate_comment(warnings: ["hi"], errors: [], messages: []) + expect(@g.client).to receive(:add_comment).with("artsy/eigen", "800", body).and_return({}) + + @g.update_pull_request!(warnings: ["hi"], errors: [], messages: []) + end + + it "updates the issue if no danger comments exist" do + issues = [{:body => "generated_by_danger", :id => "12"}] + allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(issues) + + body = @g.generate_comment(warnings: ["hi"], errors: [], messages: []) + expect(@g.client).to receive(:update_comment).with("artsy/eigen", "12", body).and_return({}) + + @g.update_pull_request!(warnings: ["hi"], errors: [], messages: []) + end + + it "deletes existing issues danger doesnt need to say anything" do + issues = [{:body => "generated_by_danger", :id => "12"}] + allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(issues) + + expect(@g.client).to receive(:delete_comment).with("artsy/eigen", "12").and_return({}) + @g.update_pull_request!(warnings: [], errors: [], messages: []) + end end end
Support issue editing instead of new issue creation
danger_danger
train
8a50f773089b7e5c55a179443cc07aef8315c9ec
diff --git a/monty/tempfile.py b/monty/tempfile.py index <HASH>..<HASH> 100644 --- a/monty/tempfile.py +++ b/monty/tempfile.py @@ -42,6 +42,7 @@ class ScratchDir: copy_from_current_on_enter=False, copy_to_current_on_exit=False, gzip_on_exit=False, + remove_symlink_on_exit=False, delete_removed_files=True, ): """ @@ -74,6 +75,8 @@ class ScratchDir: gzip_on_exit (bool): Whether to gzip the files generated in the ScratchDir before copying them back. Defaults to False. + remove_symlink_on_exit (bool): Whether to remove the symbolic link + created in the current working directory at the end. delete_removed_files (bool): Whether to delete files in the cwd that are removed from the tmp dir. Defaults to True @@ -122,3 +125,5 @@ class ScratchDir: os.chdir(self.cwd) remove(self.tempdir) + if self.remove_symlink_on_exit: + os.remove(ScratchDir.SCR_LINK) diff --git a/tests/test_tempfile.py b/tests/test_tempfile.py index <HASH>..<HASH> 100644 --- a/tests/test_tempfile.py +++ b/tests/test_tempfile.py @@ -44,6 +44,36 @@ class ScratchDirTest(unittest.TestCase): self.assertNotIn("pre_scratch_text", files) os.remove("scratch_text") + def test_with_copy_nodelete(self): + # We write a pre-scratch file. + with open("pre_scratch_text", "w") as f: + f.write("write") + + with ScratchDir( + self.scratch_root, + copy_from_current_on_enter=True, + copy_to_current_on_exit=True, + ) as d: + with open("scratch_text", "w") as f: + f.write("write") + files = os.listdir(d) + self.assertIn("scratch_text", files) + self.assertIn("empty_file.txt", files) + self.assertIn("pre_scratch_text", files) + + # We remove the pre-scratch file. + os.remove("pre_scratch_text") + + # Make sure the tempdir is deleted. + self.assertFalse(os.path.exists(d)) + files = os.listdir(".") + self.assertIn("scratch_text", files) + + # We check that the pre-scratch file no longer exists (because it is + # deleted in the scratch) + self.assertNotIn("pre_scratch_text", files) + os.remove("scratch_text") + def test_no_copy(self): with ScratchDir(
Ad another kwarg to tempfile
materialsvirtuallab_monty
train
abd4ce23ad27c96e473053bd0535b87a641ded14
diff --git a/library/tests/java/net/danlew/android/joda/test/TestDateTimeZone.java b/library/tests/java/net/danlew/android/joda/test/TestDateTimeZone.java index <HASH>..<HASH> 100644 --- a/library/tests/java/net/danlew/android/joda/test/TestDateTimeZone.java +++ b/library/tests/java/net/danlew/android/joda/test/TestDateTimeZone.java @@ -17,7 +17,6 @@ package net.danlew.android.joda.test; import android.content.Context; import android.test.InstrumentationTestCase; -import net.danlew.android.joda.JodaTimeAndroid; import net.danlew.android.joda.ResourceZoneInfoProvider; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; @@ -29,7 +28,6 @@ import org.joda.time.LocalDateTime; import org.joda.time.tz.DefaultNameProvider; import org.joda.time.tz.NameProvider; import org.joda.time.tz.Provider; -import org.joda.time.tz.UTCProvider; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -150,7 +148,7 @@ public class TestDateTimeZone extends InstrumentationTestCase { protected void setUp() throws Exception { Context context = getInstrumentation().getContext(); - JodaTimeAndroid.init(context); + DateTimeZone.setProvider(new ResourceZoneInfoProvider(context)); // Need to initialize these after ResourceZoneInfoProvider.init() PARIS = DateTimeZone.forID("Europe/Paris"); @@ -465,58 +463,12 @@ public class TestDateTimeZone extends InstrumentationTestCase { } //----------------------------------------------------------------------- - public void testProvider() { - try { - assertNotNull(DateTimeZone.getProvider()); - - Provider provider = DateTimeZone.getProvider(); - DateTimeZone.setProvider(null); - assertEquals(provider.getClass(), DateTimeZone.getProvider().getClass()); - - try { - DateTimeZone.setProvider(new MockNullIDSProvider()); - fail(); - } catch (IllegalArgumentException ex) {} - try { - DateTimeZone.setProvider(new MockEmptyIDSProvider()); - fail(); - } catch (IllegalArgumentException ex) {} - try { - DateTimeZone.setProvider(new MockNoUTCProvider()); - fail(); - } catch (IllegalArgumentException ex) {} - try { - DateTimeZone.setProvider(new MockBadUTCProvider()); - fail(); - } catch (IllegalArgumentException ex) {} - - Provider prov = new MockOKProvider(); - DateTimeZone.setProvider(prov); - assertSame(prov, DateTimeZone.getProvider()); - assertEquals(2, DateTimeZone.getAvailableIDs().size()); - assertTrue(DateTimeZone.getAvailableIDs().contains("UTC")); - assertTrue(DateTimeZone.getAvailableIDs().contains("Europe/London")); - } finally { - DateTimeZone.setProvider(null); - assertEquals(ResourceZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); - } - - try { - System.setProperty("org.joda.time.DateTimeZone.Provider", "org.joda.time.tz.UTCProvider"); - DateTimeZone.setProvider(null); - assertEquals(UTCProvider.class, DateTimeZone.getProvider().getClass()); - } finally { - System.getProperties().remove("org.joda.time.DateTimeZone.Provider"); - DateTimeZone.setProvider(null); - assertEquals(ResourceZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); - } - } public void testProvider_badClassName() { try { System.setProperty("org.joda.time.DateTimeZone.Provider", "xxx"); DateTimeZone.setProvider(null); - + } catch (RuntimeException ex) { // expected assertEquals(ResourceZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); @@ -525,7 +477,7 @@ public class TestDateTimeZone extends InstrumentationTestCase { DateTimeZone.setProvider(null); } } - + public void testProviderSecurity() { if (OLD_JDK) { return; @@ -626,7 +578,7 @@ public class TestDateTimeZone extends InstrumentationTestCase { try { System.setProperty("org.joda.time.DateTimeZone.NameProvider", "xxx"); DateTimeZone.setProvider(null); - + } catch (RuntimeException ex) { // expected assertEquals(DefaultNameProvider.class, DateTimeZone.getNameProvider().getClass());
Fixed tests for new provider setup It does't really matter if the provider settings work, we only care if we can set ResourceZoneInfoProvider ourselves.
dlew_joda-time-android
train
fe9ff6ddb7984189a83ee950e01dac04392bf8cd
diff --git a/Generator/Base.php b/Generator/Base.php index <HASH>..<HASH> 100644 --- a/Generator/Base.php +++ b/Generator/Base.php @@ -94,6 +94,8 @@ abstract class Base { /** * Reference to the base component of this component. + * + * This should be used to access the component data. */ public $base_component; @@ -106,6 +108,15 @@ abstract class Base { public $components = array(); /** + * The data for the component. + * + * This is only present on the base component (e.g., 'Module'), so that the + * data initially given by the user may be globally modified or added to by + * components. + */ + public $component_data = array(); + + /** * Constructor method; sets the component data. * * @param $component_name
Added declaration of $component_data variable to generator Base.
drupal-code-builder_drupal-code-builder
train
2df853b018db42023cb500b50746e9b33ec953be
diff --git a/jquery.geocomplete.js b/jquery.geocomplete.js index <HASH>..<HASH> 100644 --- a/jquery.geocomplete.js +++ b/jquery.geocomplete.js @@ -1,5 +1,5 @@ /** - * jQuery Geocoding and Places Autocomplete Plugin - V 1.4 + * jQuery Geocoding and Places Autocomplete Plugin - V 1.4.1 * * @author Martin Kleppe <kleppe@ubilabs.net>, 2012 * @author Ubilabs http://ubilabs.net, 2012 @@ -7,7 +7,7 @@ */ // # $.geocomplete() -// ## jQuery Geocoding and Places Autocomplete Plugin - V 1.4 +// ## jQuery Geocoding and Places Autocomplete Plugin - V 1.4.1 // // * https://github.com/ubilabs/geocomplete/ // * by Martin Kleppe <kleppe@ubilabs.net> @@ -222,6 +222,7 @@ if (latLng){ if (this.map){ this.map.setCenter(latLng); } + if (this.marker){ this.marker.setPosition(latLng); } } },
Add marker to map on initialize. Fixes #<I>
ubilabs_geocomplete
train
342385fa50f60302a3492f949b23ddc437b2f487
diff --git a/buildapi_client/buildapi_client.py b/buildapi_client/buildapi_client.py index <HASH>..<HASH> 100644 --- a/buildapi_client/buildapi_client.py +++ b/buildapi_client/buildapi_client.py @@ -26,11 +26,7 @@ class BuildapiAuthError(Exception): pass -class BuildapiError(Exception): - pass - - -def trigger_arbitrary_job(repo_name, builder, revision, auth, files=[], dry_run=False, +def trigger_arbitrary_job(repo_name, builder, revision, auth, files=None, dry_run=False, extra_properties=None): """ Request buildapi to trigger a job for us. @@ -58,10 +54,6 @@ def trigger_arbitrary_job(repo_name, builder, revision, auth, files=[], dry_run= if req.status_code == 401: raise BuildapiAuthError("Your credentials were invalid. Please try again.") - # We accept not setting files for build jobs, however, we don't accept lists of None - if files != [] and not any(files): - raise BuildapiError("The variable files was empty, please try again.") - try: req.json() return req diff --git a/test/test_buildapi_client.py b/test/test_buildapi_client.py index <HASH>..<HASH> 100644 --- a/test/test_buildapi_client.py +++ b/test/test_buildapi_client.py @@ -67,38 +67,6 @@ class TestTriggerJob(unittest.TestCase): buildapi_client.trigger_arbitrary_job( "repo", "builder", "123456123456", auth=None, dry_run=False) - @patch('requests.post', return_value=mock_response(POST_RESPONSE, 200)) - def test_with_empty_file1(self, post): - """trigger_arbitrary_job should raise an BuildapiError - if it receives files set to [None, None].""" - with self.assertRaises(buildapi_client.buildapi_client.BuildapiError): - buildapi_client.trigger_arbitrary_job( - repo_name="repo", builder="builder", revision="123456123456", auth=None, - files=[None, None], dry_run=False, extra_properties=None) - - @patch('requests.post', return_value=mock_response(POST_RESPONSE, 200)) - def test_with_empty_file2(self, post): - """trigger_arbitrary_job should raise an BuildapiError - if it receives files set to [None].""" - with self.assertRaises(buildapi_client.buildapi_client.BuildapiError): - buildapi_client.trigger_arbitrary_job( - repo_name="repo", builder="builder", revision="123456123456", auth=None, - files=[None], dry_run=False, extra_properties=None) - - @patch('requests.post', return_value=mock_response(POST_RESPONSE, 200)) - def test_call_with_empty_file3(self, post): - """trigger_arbitrary_job should call requests.post with files=[].""" - buildapi_client.trigger_arbitrary_job( - "repo", "builder", "123456123456", auth=None, files=[], dry_run=False) - # We expect that trigger_arbitrary_job will call requests.post - # once with the following arguments - post.assert_called_once_with( - '%s/%s/builders/%s/%s' % (SELF_SERVE, "repo", "builder", "123456123456"), - headers={'Accept': 'application/json'}, - data={'properties': - '{"branch": "repo", "revision": "123456123456"}'}, - auth=None) - class TestMakeRetriggerRequest(unittest.TestCase):
Do not raise BuildapiError if files are not set properly First of all, the implicit meanings of files was rather confusing. Second of all, mozci is the only module that actually knows if files should be set or not. We can decide there.
armenzg_buildapi_client
train
f387b7bf04fc69ccc0f95d5670c19000a6006e21
diff --git a/wakatime/logger.py b/wakatime/logger.py index <HASH>..<HASH> 100644 --- a/wakatime/logger.py +++ b/wakatime/logger.py @@ -9,6 +9,7 @@ :license: BSD, see LICENSE for more details. """ +import inspect import logging import os import sys @@ -47,14 +48,19 @@ class JsonFormatter(logging.Formatter): def format(self, record): data = OrderedDict([ ('now', self.formatTime(record, self.datefmt)), - ('version', self.version), - ('plugin', self.plugin), - ('time', self.timestamp), - ('isWrite', self.isWrite), - ('file', self.targetFile), - ('level', record.levelname), - ('message', record.msg), ]) + try: + data['package'] = inspect.stack()[9][0].f_globals.get('__package__') + data['lineno'] = inspect.stack()[9][2] + except: + pass + data['version'] = self.version + data['plugin'] = self.plugin + data['time'] = self.timestamp + data['isWrite'] = self.isWrite + data['file'] = self.targetFile + data['level'] = record.levelname + data['message'] = record.msg if not self.plugin: del data['plugin'] if not self.isWrite:
include package namespace and line number in logger output
wakatime_wakatime
train
62cdb7fc5080aa0fa836e9d972ca36c657a7f10d
diff --git a/src/net/sf/mpxj/mpx/TimeUnitUtility.java b/src/net/sf/mpxj/mpx/TimeUnitUtility.java index <HASH>..<HASH> 100644 --- a/src/net/sf/mpxj/mpx/TimeUnitUtility.java +++ b/src/net/sf/mpxj/mpx/TimeUnitUtility.java @@ -55,7 +55,7 @@ final class TimeUnitUtility @SuppressWarnings("unchecked") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException { Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP); - Integer result = map.get(units); + Integer result = map.get(units.toLowerCase()); if (result == null) { throw new MPXJException(MPXJException.INVALID_TIME_UNIT + " " + units);
Updated to make MPX duration parsing more lenient (Contributed by Jari Niskala).
joniles_mpxj
train
783eb84d04bba7617e353ddc4453678dbbbd2a9f
diff --git a/lib/bionode-ncbi.js b/lib/bionode-ncbi.js index <HASH>..<HASH> 100644 --- a/lib/bionode-ncbi.js +++ b/lib/bionode-ncbi.js @@ -142,7 +142,7 @@ function createAPISearchUrl(db, term) { APIROOT + 'esearch.fcgi?', DEFAULTS, 'db=' + db, - 'term=' + encodeURI(obj.replace(/['"]+/g, '')), + 'term=' + encodeURI(obj.toString().replace(/['"]+/g, '')), 'usehistory=y' ].join('&') debug('esearch request', query)
Make sure term is string before trying replace
bionode_bionode-ncbi
train
25bfb4aaece09fda0ede9386743babe0fdfee02d
diff --git a/gpapi/googleplay.py b/gpapi/googleplay.py index <HASH>..<HASH> 100644 --- a/gpapi/googleplay.py +++ b/gpapi/googleplay.py @@ -204,6 +204,11 @@ class GooglePlayAPI(object): raise LoginError("Auth token not found.") def _check_response_integrity(self, apps): + """Like described in issue #18, after some time it seems + that google invalidates the token. And the strange thing is that when + sending requests with an invalid token, it won't throw an error but + it returns empty responses. This is a function used to check if the + content returned is valid (usually a docId field is always present)""" if any([a['docId'] == '' for a in apps]): raise LoginError('Unexpected behaviour, probably expired ' 'token') @@ -295,9 +300,15 @@ class GooglePlayAPI(object): """Get several apps details from a list of package names. This is much more efficient than calling N times details() since it - requires only one request. + requires only one request. If an item is not found it returns an empty object + instead of throwing a RequestError('Item not found') like the details() function - packageNames is a list of app ID (usually starting with 'com.').""" + Args: + packageNames (list): a list of app IDs (usually starting with 'com.'). + + Returns: + a list of dictionaries containing docv1 data, or None + if the app doesn't exist""" path = "bulkDetails" req = googleplay_pb2.BulkDetailsRequest() @@ -307,9 +318,14 @@ class GooglePlayAPI(object): data.decode("utf-8"), "application/x-protobuf") response = message.payload.bulkDetailsResponse - detailsList = [entry.doc for entry in response.entry] - result = list(map(utils.fromDocToDictionary, detailsList)) - self._check_response_integrity(result) + result = [] + for entry in response.entry: + if not entry.HasField('doc'): + result.append(None) + else: + appDetails = utils.fromDocToDictionary(entry.doc) + self._check_response_integrity([appDetails]) + result.append(appDetails) return result def browse(self, cat=None, subCat=None): diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -9,7 +9,6 @@ ap.add_argument('-p', '--password', dest='password', help='google password') args = ap.parse_args() -testApps = ['org.mozilla.firefox'] server = GooglePlayAPI(debug=True) # LOGIN @@ -69,9 +68,16 @@ if not errorThrown: # BULK DETAILS -print('\nGetting bulkDetails for %s\n' % testApps[0]) +testApps = ['org.mozilla.firefox', 'com.non.existing.app'] bulk = server.bulkDetails(testApps) -print(bulk) + +print('\nTesting behaviour for non-existing apps\n') +if bulk[1] is not None: + print('bulkDetails should return None for non-existing apps') + sys.exit(1) + +print('\nResult from bulkDetails for %s\n' % testApps[0]) +print(bulk[0]) # DETAILS print('\nGetting details for %s\n' % testApps[0])
bulkDetails: handle case when app doesn't exist Now the function returns None if an app doesnt't exists. This does not apply for details() function, which instead return a RequestError if the app doesn't exist.
NoMore201_googleplay-api
train
2bf6435881a133c630fd50d610c6ef2e606fb1e1
diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/Bind.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/Bind.java index <HASH>..<HASH> 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/packet/Bind.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/Bind.java @@ -1,6 +1,6 @@ /** * - * Copyright 2003-2007 Jive Software. + * Copyright 2003-2007 Jive Software, 2015-2016 Florian Schmaus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.jxmpp.jid.parts.Resourcepart; * * @author Gaston Dombiak */ -public class Bind extends IQ { +public final class Bind extends IQ { public static final String ELEMENT = "bind"; public static final String NAMESPACE = "urn:ietf:params:xml:ns:xmpp-bind"; @@ -39,7 +39,7 @@ public class Bind extends IQ { private final Resourcepart resource; private final EntityFullJid jid; - public Bind(Resourcepart resource, EntityFullJid jid) { + private Bind(Resourcepart resource, EntityFullJid jid) { super(ELEMENT, NAMESPACE); this.resource = resource; this.jid = jid;
Make Bind IQ constructor private
igniterealtime_Smack
train
b35d4afe52781c39926b6a26455e1fc68f8bb01e
diff --git a/spyderlib/__init__.py b/spyderlib/__init__.py index <HASH>..<HASH> 100644 --- a/spyderlib/__init__.py +++ b/spyderlib/__init__.py @@ -80,7 +80,7 @@ def get_versions(reporev=True): 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': spyderlib.qt.QtCore.__version__, - 'qt_api': spyderlib.qt.API_NAME, # PySide or PyQt4 + 'qt_api': spyderlib.qt.API_NAME, # PyQt5 or PyQt4 'qt_api_ver': spyderlib.qt.__version__, 'system': system, # Linux, Windows, ... 'revision': revision, # '9fdf926eccce' diff --git a/spyderlib/requirements.py b/spyderlib/requirements.py index <HASH>..<HASH> 100644 --- a/spyderlib/requirements.py +++ b/spyderlib/requirements.py @@ -35,8 +35,7 @@ def check_path(): def check_qt(): """Check Qt binding requirements""" - qt_infos = dict(pyqt5=("PyQt5", "5.2"), pyqt=("PyQt4", "4.6"), - pyside=("PySide", "1.2.0")) + qt_infos = dict(pyqt5=("PyQt5", "5.2"), pyqt=("PyQt4", "4.6")) try: from spyderlib import qt package_name, required_ver = qt_infos[qt.API] @@ -51,5 +50,4 @@ def check_qt(): "%s %s+ or\n" "%s %s+\n\n" "is required to run Spyder" - % (qt_infos['pyqt'] + qt_infos['pyside'] + \ - qt_infos['pyqt5'])) + % (qt_infos['pyqt5'] + qt_infos['pyqt']))
Remove reference to PySide in requirements
spyder-ide_spyder
train
29040b7734c6b7fdbe6b24ecf36a042d67397f02
diff --git a/sheet.go b/sheet.go index <HASH>..<HASH> 100644 --- a/sheet.go +++ b/sheet.go @@ -56,6 +56,25 @@ func (s *Sheet) AddRow() *Row { return row } +// Make sure we always have as many Rows as we do cells. +func (s *Sheet) maybeAddRow(rowCount int) { + if rowCount > s.MaxRow { + loopCnt := rowCount - s.MaxRow + for i := 0; i < loopCnt; i++ { + + row := &Row{Sheet: s} + s.Rows = append(s.Rows, row) + } + s.MaxRow = rowCount + } +} + +// Make sure we always have as many Rows as we do cells. +func (s *Sheet) Row(idx int) *Row { + s.maybeAddRow(idx + 1) + return s.Rows[idx] +} + // Make sure we always have as many Cols as we do cells. func (s *Sheet) maybeAddCol(cellCount int) { if cellCount > s.MaxCol { diff --git a/sheet_test.go b/sheet_test.go index <HASH>..<HASH> 100644 --- a/sheet_test.go +++ b/sheet_test.go @@ -21,6 +21,19 @@ func (s *SheetSuite) TestAddRow(c *C) { c.Assert(len(sheet.Rows), Equals, 1) } +// Test we can get row by index from Sheet +func (s *SheetSuite) TestGetRowByIndex(c *C) { + var f *File + f = NewFile() + sheet, _ := f.AddSheet("MySheet") + row := sheet.Row(10) + c.Assert(row, NotNil) + c.Assert(len(sheet.Rows), Equals, 10) + row = sheet.Row(2) + c.Assert(row, NotNil) + c.Assert(len(sheet.Rows), Equals, 10) +} + func (s *SheetSuite) TestMakeXLSXSheetFromRows(c *C) { file := NewFile() sheet, _ := file.AddSheet("Sheet1")
sheet.row get row by index from sheet issue #<I>
tealeg_xlsx
train
1497e4dfeb61dd65b1b012f3e93433880e281e9d
diff --git a/gremlinpy/gremlin.py b/gremlinpy/gremlin.py index <HASH>..<HASH> 100644 --- a/gremlinpy/gremlin.py +++ b/gremlinpy/gremlin.py @@ -219,7 +219,7 @@ class Gremlin(LinkList): if value in self.stack_bound_params.values(): for n, v in self.bound_params.items(): - if v == value: + if v == value and not name: name = n break elif value in self.stack_bound_params.keys(): diff --git a/gremlinpy/tests/gremlin.py b/gremlinpy/tests/gremlin.py index <HASH>..<HASH> 100644 --- a/gremlinpy/tests/gremlin.py +++ b/gremlinpy/tests/gremlin.py @@ -487,6 +487,48 @@ class GremlinInjectionTests(unittest.TestCase): self.assertEqual(expected, string) self.assertEqual(len(params), 2) + def test_can_nest_with_unbound_params_of_same_value(self): + g = Gremlin() + n = Gremlin() + d = {'name': str(random()), 'age': str(random())} + + n.set_graph_variable('__').has("'name'", d['name']) + n.func('age', d['age']) + g.function('name', d['name']).nest(n) + + string = str(g) + params = g.bound_params + name = get_dict_key(params, d['name']) + age = get_dict_key(params, d['age']) + expected = ("g.function(name, {})" + ".nest(__.has('name', {}).age({}))").format(name, + name, age) + + self.assertEqual(2, len(params)) + self.assertEqual(expected, string) + + def test_can_double_nest_with_unbound_params_of_same_value(self): + g = Gremlin() + n = Gremlin() + nn = Gremlin() + d = {'name': str(random()), 'age': str(random())} + + nn.set_graph_variable('_').func('name', d['name']) + n.set_graph_variable('__').has("'name'", d['name']) + n.func('age', d['age']).nest(nn) + g.function('name', d['name']).nest(n) + + string = str(g) + params = g.bound_params + name = get_dict_key(params, d['name']) + age = get_dict_key(params, d['age']) + expected = ("g.function(name, {})" + ".nest(__.has('name', {}).age({})" + ".nest(_.name({})))").format(name,name, age, name) + + self.assertEqual(2, len(params)) + self.assertEqual(expected, string) + class PredicateTests(unittest.TestCase):
fixed issue reported by Rob McDaniel where nested Gremlin instances were not inheriting parent bound params correctly. tests added too
emehrkay_gremlinpy
train
de0b3a0e8d02b483787f51e312a56fda35546c77
diff --git a/foyer/forcefield.py b/foyer/forcefield.py index <HASH>..<HASH> 100755 --- a/foyer/forcefield.py +++ b/foyer/forcefield.py @@ -228,7 +228,9 @@ def _separate_urey_bradleys(system, topology): if isinstance(force, mm.HarmonicBondForce): for bond_idx in range(force.getNumBonds()): if (atoms[force.getBondParameters(bond_idx)[0]], - atoms[force.getBondParameters(bond_idx)[1]]) not in bonds: + atoms[force.getBondParameters(bond_idx)[1]]) not in bonds and + (atoms[force.getBondParameters(bond_idx)[1]], + atoms[force.getBondParameters(bond_idx)[0]]) not in bonds: ub_force.addBond(*force.getBondParameters(bond_idx)) else: harmonic_bond_force.addBond(*force.getBondParameters(bond_idx))
Update logic to handle different ordering of atom indices in bonds
mosdef-hub_foyer
train
e9dceb36e99a633f8b393589b7984e731f7b0d5d
diff --git a/pkg/kubelet/kubelet.go b/pkg/kubelet/kubelet.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/kubelet.go +++ b/pkg/kubelet/kubelet.go @@ -441,6 +441,7 @@ func NewMainKubelet( return nil, err } klet.runtimeCache = runtimeCache + klet.reasonCache = NewReasonCache() klet.workQueue = queue.NewBasicWorkQueue() klet.podWorkers = newPodWorkers(runtimeCache, klet.syncPod, recorder, klet.workQueue, klet.resyncInterval, backOffPeriod, klet.podCache) @@ -563,6 +564,10 @@ type Kubelet struct { // Container runtime. containerRuntime kubecontainer.Runtime + // reasonCache caches the failure reason of the last creation of all containers, which is + // used for generating ContainerStatus. + reasonCache *ReasonCache + // nodeStatusUpdateFrequency specifies how often kubelet posts node status to master. // Note: be cautious when changing the constant, it must work with nodeMonitorGracePeriod // in nodecontroller. There are several constraints: @@ -1676,8 +1681,8 @@ func (kl *Kubelet) syncPod(pod *api.Pod, mirrorPod *api.Pod, runningPod kubecont } result := kl.containerRuntime.SyncPod(pod, apiPodStatus, podStatus, pullSecrets, kl.backOff) - err = result.Error() - if err != nil { + kl.reasonCache.Update(pod.UID, result) + if err = result.Error(); err != nil { return err } diff --git a/pkg/kubelet/kubelet_test.go b/pkg/kubelet/kubelet_test.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/kubelet_test.go +++ b/pkg/kubelet/kubelet_test.go @@ -148,6 +148,7 @@ func newTestKubelet(t *testing.T) *TestKubelet { kubelet.containerRuntime = fakeRuntime kubelet.runtimeCache = kubecontainer.NewFakeRuntimeCache(kubelet.containerRuntime) + kubelet.reasonCache = NewReasonCache() kubelet.podWorkers = &fakePodWorkers{ syncPodFn: kubelet.syncPod, runtimeCache: kubelet.runtimeCache,
Start using reason cache in kubelet
kubernetes_kubernetes
train
e1c4f1e3da16c099e290ac6930f22d560355ee12
diff --git a/vsphere/datadog_checks/vsphere/config.py b/vsphere/datadog_checks/vsphere/config.py index <HASH>..<HASH> 100644 --- a/vsphere/datadog_checks/vsphere/config.py +++ b/vsphere/datadog_checks/vsphere/config.py @@ -124,6 +124,12 @@ class VSphereConfig(object): if 'property' not in resource_filter: resource_filter['property'] = 'name' + if resource_filter['property'] == 'tag' and not self.should_collect_tags: + raise ConfigurationError( + 'Your configuration is incorrectly attempting to filter resources ' + 'by the `tag` property but `collect_tags` is disabled.' + ) + # Check required fields and their types for (field, field_type) in iteritems( {'resource': string_types, 'property': string_types, 'type': string_types, 'patterns': list} diff --git a/vsphere/tests/test_filters.py b/vsphere/tests/test_filters.py index <HASH>..<HASH> 100644 --- a/vsphere/tests/test_filters.py +++ b/vsphere/tests/test_filters.py @@ -68,6 +68,7 @@ def test_is_realtime_resource_collected_by_filters(realtime_instance): {'resource': 'vm', 'property': 'tag', 'patterns': [r'env:production']}, {'resource': 'host', 'property': 'name', 'patterns': [r'10\.0\.0\.103'], 'type': 'blacklist'}, ] + realtime_instance['collect_tags'] = True collected_resources = [ 'VM2-1',
Properly error when filtering resources by the `tag` property but `collect_tags` is disabled (#<I>) * Properly error when filtering resources by the `tag` property but `collect_tags` is disabled * address
DataDog_integrations-core
train
18e78c1b8e1ad375cd8ef1d16b81ecbc7a61f545
diff --git a/class.krumo.php b/class.krumo.php index <HASH>..<HASH> 100644 --- a/class.krumo.php +++ b/class.krumo.php @@ -577,6 +577,8 @@ This is a list of all the values from the <code><b><?php echo realpath($ini_file print "</ul></div>\n"; + print "<!-- Krumo - HTML -->\n\n"; + // flee the hive $_recursion_marker = krumo::_marker(); if ($hive =& krumo::_hive($dummy)) { @@ -769,7 +771,7 @@ This is a list of all the values from the <code><b><?php echo realpath($ini_file <style type="text/css"> <?php echo $css?> </style> -<!-- CSS --> +<!-- Krumo - CSS --> <?php // the JS // @@ -777,8 +779,7 @@ This is a list of all the values from the <code><b><?php echo realpath($ini_file <script type="text/javascript"> <?php echo join(file(KRUMO_DIR . "krumo.min.js"));?> </script> -<!-- JavaScript --> - +<!-- Krumo - JavaScript --> <?php }
Show the CSS/JavaScript/HTML sections with appropriate tags This makes reading the HTML source a lot easier
mmucklo_krumo
train
2cb566f2cac846779a80a6d4dc4f6b9c4eaaa35d
diff --git a/build-lib/polyfills.js b/build-lib/polyfills.js index <HASH>..<HASH> 100644 --- a/build-lib/polyfills.js +++ b/build-lib/polyfills.js @@ -13,13 +13,15 @@ module.exports = function (/* env */) { header: ';(function (self) {', inputFiles: ['rsvp.js'], footer: `if (self.Promise === undefined) { - self.Promise = RSVP.Promise; - }}(window));`, - outputFile: 'promise.js' + self.Promise = RSVP.Promise; +}}(window));`, + outputFile: 'promise.js', + sourceMapConfig: { enabled: false } }); return concat(mergeTrees([fetchPolyfill, rsvpPolyfill]), { inputFiles: ['fetch.js', 'promise.js'], - outputFile: 'polyfills.js' + outputFile: 'polyfills.js', + sourceMapConfig: { enabled: false } }); };
Permamnently disable source mapping for polyfills and external files
Shopify_js-buy-sdk
train
95137c24c062c258a6c208b1599044ec93f23e07
diff --git a/src/DataTables/AbstractDataTable.php b/src/DataTables/AbstractDataTable.php index <HASH>..<HASH> 100644 --- a/src/DataTables/AbstractDataTable.php +++ b/src/DataTables/AbstractDataTable.php @@ -246,7 +246,7 @@ CDATA; 'print' => ['extend' => 'print', 'text' => '<i class="fa fa-print"></i> '.trans('cortex/foundation::common.print')], 'export' => ['extend' => 'export', 'text' => '<i class="fa fa-download"></i> '.trans('cortex/foundation::common.export').'&nbsp;<span class="caret"/>'], - 'bulk' => ['extend' => 'bulk', 'text' => '<i class="fa fa-list"></i> '.trans('cortex/foundation::common.bulk').'&nbsp;<span class="caret"/>', 'buttons' => $bulkButtons->keys()], + 'bulk' => ['extend' => 'bulk', 'text' => '<i class="fa fa-list"></i> '.trans('cortex/foundation::common.bulk').'&nbsp;<span class="caret"/>', 'buttons' => $bulkButtons->keys(), 'autoClose' => true], 'colvis' => ['extend' => 'colvis', 'text' => '<i class="fa fa-columns"></i> '.trans('cortex/foundation::common.colvis').'&nbsp;<span class="caret"/>'], 'pageLength' => ['extend' => 'pageLength', 'text' => '<i class="fa fa-list-ol"></i> '.trans('cortex/foundation::common.pageLength').'&nbsp;<span class="caret"/>'], ])->only($buttons->keys())->values()->toArray();
Auto close bulk menu after child actions are clicked
rinvex_cortex-foundation
train
44c12af62d28dadc4081cd904675becfcb4aabfa
diff --git a/spec/koala/api_base_tests.rb b/spec/koala/api_base_tests.rb index <HASH>..<HASH> 100644 --- a/spec/koala/api_base_tests.rb +++ b/spec/koala/api_base_tests.rb @@ -29,6 +29,10 @@ class ApiBaseTests < Test::Unit::TestCase service.api('anything') end + it "should properly handle the http_component parameter" + + it "should execute a block to test for errors if passed one" + it "should handle rogue true/false as responses" do Koala.should_receive(:make_request).and_return(Koala::Response.new(200, 'true', {})) @service.api('anything').should be_true
Added pending tests for api and http_service based on recent changes.
arsduo_koala
train
151d124c444962e6e34ad177b46bd6c0a1c01a7b
diff --git a/mcquery.js b/mcquery.js index <HASH>..<HASH> 100644 --- a/mcquery.js +++ b/mcquery.js @@ -46,10 +46,10 @@ var Query = module.exports = function Query(){ function doHandshake(){ var token = generateToken(); - session.idToken=token; + session.sessionToken=token; m.send(session, CHALLENGE_TYPE, function(err, res){ if(err){callback(err); return;} - session.sessionToken = res.sessionToken; + session.challengeToken = res.challengeToken; callback(null, session); }); } @@ -82,7 +82,7 @@ var Query = module.exports = function Query(){ if(err)callback(err); else{ delete res.type; - delete res.idToken; + delete res.sessionToken; delete res.rinfo; callback(null, res); } @@ -107,17 +107,17 @@ var Query = module.exports = function Query(){ */ function addQueue(session, type, callback){ var q; - if(typeof(m.requestQueue[session.idToken])==='undefined'){ + if(typeof(m.requestQueue[session.sessionToken])==='undefined'){ q = {}; - m.requestQueue[session.idToken]=q; + m.requestQueue[session.sessionToken]=q; } else{ - q = m.requestQueue[session.idToken]; + q = m.requestQueue[session.sessionToken]; } var t = setTimeout(function(){ delete q[type]; if(q.length===0){ - delete m.requestQueue[session.idToken]; + delete m.requestQueue[session.sessionToken]; } callback({error:'timeout'}); }, 1000); @@ -130,7 +130,7 @@ var Query = module.exports = function Query(){ * Check for requests matching the response given */ function deQueue(res){ - var key = res.idToken; + var key = res.sessionToken; if(typeof(m.requestQueue[key])==='undefined'){ //no such session running... just ignore return; @@ -169,7 +169,7 @@ var Query = module.exports = function Query(){ };// end Query /* -* Generate a idToken +* Generate a sessionToken */ function generateToken(){ counter +=1; @@ -185,14 +185,14 @@ function generateToken(){ */ function makePacket(type,session, payloadBuffer){ var pLength = typeof(payloadBuffer)==='undefined'? 0 : payloadBuffer.length; - var sLength = typeof(session.sessionToken)==='undefined'? 0: 4; + var sLength = typeof(session.challengeToken)==='undefined'? 0: 4; var b = new Buffer(7 + sLength+pLength); b.writeUInt8(0xFE, 0); b.writeUInt8(0xFD, 1); b.writeUInt8(type, 2); - b.writeUInt32BE(session.idToken, 3); + b.writeUInt32BE(session.sessionToken, 3); if(sLength>0){ - b.writeUInt32BE(session.sessionToken, 7); + b.writeUInt32BE(session.challengeToken, 7); } if(pLength>0){ payloadBuffer.copy(b, 7+sLength +1); @@ -207,11 +207,11 @@ function makePacket(type,session, payloadBuffer){ function readPacket(data){ var res = { type:data.readUInt8(0), - idToken:data.readUInt32BE(1), + sessionToken:data.readUInt32BE(1), }; data = data.slice(5); if(res.type===CHALLENGE_TYPE){ - res.sessionToken=parseInt(data.toString()); + res.challengeToken=parseInt(data.toString()); } else if(res.type===STAT_TYPE){ var r = readString(data); @@ -272,4 +272,4 @@ function readString(data, offset){ o+=1; } return {text:data.toString('utf-8', start, o), offset:o+1}; -} \ No newline at end of file +}
renamed tokens to better fit the protocol definition
kmpm_node-mcquery
train
c740da15d113c0b8f757fa2c914aeb3c6edf00c6
diff --git a/lib/config/configuration.go b/lib/config/configuration.go index <HASH>..<HASH> 100644 --- a/lib/config/configuration.go +++ b/lib/config/configuration.go @@ -34,9 +34,10 @@ import ( "github.com/gravitational/teleport/lib/service" "github.com/gravitational/teleport/lib/services" "github.com/gravitational/teleport/lib/utils" + "github.com/gravitational/trace" log "github.com/Sirupsen/logrus" - "github.com/gravitational/trace" + "github.com/kardianos/osext" ) // CommandLineFlags stores command line flag values, it's a much simplified subset @@ -542,6 +543,7 @@ func locateWebAssets() (string, error) { } // checker function to determine if dirPath contains the web assets locateAssets := func(dirPath string) bool { + fmt.Println("checking ", dirPath) for _, af := range assetsToCheck { if !fileExists(filepath.Join(dirPath, af)) { return false @@ -550,7 +552,7 @@ func locateWebAssets() (string, error) { return true } // check the directory where teleport binary is located first: - exeDir, err := filepath.Abs(filepath.Dir(os.Args[0])) + exeDir, err := osext.ExecutableFolder() if err != nil { return "", trace.Wrap(err) }
Started using "osext" library to determine the path to the executable
gravitational_teleport
train
77fc7a4d9f83fb9a26c817055be07798d53ed37f
diff --git a/concrete/single_pages/dashboard/system/update/update/local_available_update.php b/concrete/single_pages/dashboard/system/update/update/local_available_update.php index <HASH>..<HASH> 100644 --- a/concrete/single_pages/dashboard/system/update/update/local_available_update.php +++ b/concrete/single_pages/dashboard/system/update/update/local_available_update.php @@ -41,7 +41,7 @@ defined('C5_EXECUTE') or die('Access Denied.'); </ul> </div> <div class="col ccm-dashboard-update-detail-main"> - <a v-if="details.releaseNotesUrl" v-bind:href="details.releaseNotesUrl" target="_blank" class="btn btn-secondary btn-sm float-right"><?= t('View Full Release Notes') ?></a> + <a v-if="details &amp;&amp; details.releaseNotesUrl" v-bind:href="details.releaseNotesUrl" target="_blank" class="btn btn-secondary btn-sm float-right"><?= t('View Full Release Notes') ?></a> <h3 id="notes"><?= t('Release Notes') ?></h3> <div class="ccm-dashboard-update-detail-release-notes" v-html="releaseNotes"></div>
Avoid accessing property of null object
concrete5_concrete5
train
e0009065064a09d97346e19f5e14fa72efa54830
diff --git a/bosh-director/lib/bosh/director/api/task_helper.rb b/bosh-director/lib/bosh/director/api/task_helper.rb index <HASH>..<HASH> 100644 --- a/bosh-director/lib/bosh/director/api/task_helper.rb +++ b/bosh-director/lib/bosh/director/api/task_helper.rb @@ -11,18 +11,17 @@ module Bosh::Director :state => :queued, :timestamp => Time.now, :checkpoint_time => Time.now) - log_dir = File.join(Config.base_dir, "tasks", task.id.to_s) - task_status_file = File.join(log_dir, "debug") + log_dir = File.join(Config.base_dir, 'tasks', task.id.to_s) + task_status_file = File.join(log_dir, 'debug') FileUtils.mkdir_p(log_dir) - logger = Logging::Logger.new('DirectorTask') - logger.add_appenders(Logging.appenders.file('DirectorTaskFile', filename: task_status_file)) - logger.level = Config.logger.level - logger.info("Director Version : #{Bosh::Director::VERSION}") - logger.info("Enqueuing task: #{task.id}") + File.open(task_status_file, 'a') do |f| + f << "Director Version: #{Bosh::Director::VERSION}" + f << "Enqueuing task: #{task.id}" + end # remove old tasks - TaskRemover.new(Config.max_tasks, logger).remove + TaskRemover.new(Config.max_tasks).remove task.output = log_dir task.save diff --git a/bosh-director/lib/bosh/director/api/task_remover.rb b/bosh-director/lib/bosh/director/api/task_remover.rb index <HASH>..<HASH> 100644 --- a/bosh-director/lib/bosh/director/api/task_remover.rb +++ b/bosh-director/lib/bosh/director/api/task_remover.rb @@ -1,8 +1,7 @@ module Bosh::Director::Api class TaskRemover - def initialize(max_tasks, logger) + def initialize(max_tasks) @max_tasks = max_tasks - #@logger = logger end def remove diff --git a/bosh-director/spec/unit/api/task_helper_spec.rb b/bosh-director/spec/unit/api/task_helper_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-director/spec/unit/api/task_helper_spec.rb +++ b/bosh-director/spec/unit/api/task_helper_spec.rb @@ -16,8 +16,8 @@ module Bosh::Director Config.configure(config) Config.base_dir = tmpdir Config.max_tasks = 2 - Api::TaskRemover.stub(:new).and_return(task_remover) - task_remover.stub(:remove) + allow(Api::TaskRemover).to receive(:new).and_return(task_remover) + allow(task_remover).to receive(:remove) end it 'should create the task debug output file' do @@ -34,8 +34,8 @@ module Bosh::Director end it 'should clean up old tasks' do - Api::TaskRemover.should_receive(:new).with(Config.max_tasks, a_kind_of(Logging::Logger)).and_return(task_remover) - task_remover.should_receive(:remove) + expect(Api::TaskRemover).to receive(:new).with(Config.max_tasks).and_return(task_remover) + expect(task_remover).to receive(:remove) described_class.new.create_task(user.username, type, description) end diff --git a/bosh-director/spec/unit/api/task_remover_spec.rb b/bosh-director/spec/unit/api/task_remover_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-director/spec/unit/api/task_remover_spec.rb +++ b/bosh-director/spec/unit/api/task_remover_spec.rb @@ -14,7 +14,7 @@ module Bosh::Director::Api end end - subject(:remover) { described_class.new(3, double('logger')) } + subject(:remover) { described_class.new(3) } context 'when there are fewer than max_tasks in the database' do before { make_n_tasks(2) }
Fix leaking fds in task helper
cloudfoundry_bosh
train
fb5cff602229782c3b8ad835dd3e72340de26c32
diff --git a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/commands/CompositeCommand.java b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/commands/CompositeCommand.java index <HASH>..<HASH> 100644 --- a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/commands/CompositeCommand.java +++ b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/commands/CompositeCommand.java @@ -117,7 +117,8 @@ public class CompositeCommand<T> extends TaskCommand<T> { @XmlElement(name="suspend-task", type=SuspendTaskCommand.class), @XmlElement(name="undeploy-task-def", type=UndeployTaskDefCommand.class), @XmlElement(name="task-query", type=TaskQueryDataCommand.class), - @XmlElement(name="execute-reminder-command", type=ExecuteReminderCommand.class) + @XmlElement(name="execute-reminder-command", type=ExecuteReminderCommand.class), + @XmlElement(name="get-comment-by-id-command", type=GetCommentByIdCommand.class) } ) private TaskCommand<T> mainCommand;
BPMSPL-<I>: adding new command comments by id - fixed CompositeCommand to include newly added commands
kiegroup_jbpm
train
f72bb8e66634f87a1d73cc161ff7bfebfcb8518b
diff --git a/config/scout.php b/config/scout.php index <HASH>..<HASH> 100644 --- a/config/scout.php +++ b/config/scout.php @@ -45,6 +45,28 @@ return [ /* |-------------------------------------------------------------------------- + | Queue Connection + |-------------------------------------------------------------------------- + | + | This option allows you to control the queue connection that should be used when syncing. + | + */ + + 'connection' => '', + + /* + |-------------------------------------------------------------------------- + | Queue Name + |-------------------------------------------------------------------------- + | + | This option allows you to control the queue that should be used with syncing. + | + */ + + 'queue_name' => '', + + /* + |-------------------------------------------------------------------------- | Algolia Configuration |-------------------------------------------------------------------------- | diff --git a/src/Searchable.php b/src/Searchable.php index <HASH>..<HASH> 100644 --- a/src/Searchable.php +++ b/src/Searchable.php @@ -210,16 +210,16 @@ trait Searchable */ public function syncWithSearchUsing() { - return config('queue.default'); + return config('scout.connection') ?: config('queue.default'); } /** * Get the queue that should be used with syncing * - * @return string|null + * @return string */ public function syncWithSearchUsingQueue() { - return null; + return config('scout.queue_name'); } }
add config options to scout.php to allow specifying connection and queue
laravel_scout
train
24ee0031b2b738066e60be14122c84234a9e93ae
diff --git a/tinytag/tinytag.py b/tinytag/tinytag.py index <HASH>..<HASH> 100644 --- a/tinytag/tinytag.py +++ b/tinytag/tinytag.py @@ -562,7 +562,7 @@ class Wave(TinyTag): raise TinyTagException('not a wave file!') channels, bitdepth = 2, 16 # assume CD quality chunk_header = fh.read(8) - while len(chunk_header) > 0: + while len(chunk_header) == 8: subchunkid, subchunksize = struct.unpack('4sI', chunk_header) if subchunkid == b'fmt ': _, channels, self.samplerate = struct.unpack('HHI', fh.read(8))
Fixed reading of truncated wav files, closes #<I>
devsnd_tinytag
train
65801a9d5e74b19dda81ea981b4a4c91a1665c3c
diff --git a/src/Maker/MakeEntity.php b/src/Maker/MakeEntity.php index <HASH>..<HASH> 100644 --- a/src/Maker/MakeEntity.php +++ b/src/Maker/MakeEntity.php @@ -114,32 +114,32 @@ final class MakeEntity extends AbstractMaker implements InputAwareMakerInterface $argument = $command->getDefinition()->getArgument('name'); $question = $this->createEntityClassQuestion($argument->getDescription()); - $value = $io->askQuestion($question); + $entityClassName = $io->askQuestion($question); - $input->setArgument('name', $value); + $input->setArgument('name', $entityClassName); if ( !$input->getOption('api-resource') && class_exists(ApiResource::class) && - !class_exists($this->generator->createClassNameDetails($value, 'Entity\\')->getFullName()) + !class_exists($this->generator->createClassNameDetails($entityClassName, 'Entity\\')->getFullName()) ) { $description = $command->getDefinition()->getOption('api-resource')->getDescription(); $question = new ConfirmationQuestion($description, false); - $value = $io->askQuestion($question); + $isApiResource = $io->askQuestion($question); - $input->setOption('api-resource', $value); + $input->setOption('api-resource', $isApiResource); } if ( !$input->getOption('broadcast') && class_exists(Broadcast::class) && - !class_exists($this->generator->createClassNameDetails($value, 'Entity\\')->getFullName()) + !class_exists($this->generator->createClassNameDetails($entityClassName, 'Entity\\')->getFullName()) ) { $description = $command->getDefinition()->getOption('broadcast')->getDescription(); $question = new ConfirmationQuestion($description, false); - $value = $io->askQuestion($question); + $isBroadcast = $io->askQuestion($question); - $input->setOption('broadcast', $value); + $input->setOption('broadcast', $isBroadcast); } } diff --git a/tests/Maker/MakeEntityTest.php b/tests/Maker/MakeEntityTest.php index <HASH>..<HASH> 100644 --- a/tests/Maker/MakeEntityTest.php +++ b/tests/Maker/MakeEntityTest.php @@ -593,5 +593,28 @@ class MakeEntityTest extends MakerTestCase $this->assertStringContainsString(\PHP_VERSION_ID >= 80000 ? '#[Broadcast]' : '@Broadcast', $content); }), ]; + + yield 'entity_new_with_api_and_broadcast_dependencies' => [MakerTestDetails::createTest( + $this->getMakerInstance(MakeEntity::class), + [ + // entity class name + 'User', + // Mark the entity as not an API Platform resource + 'n', + // Mark the entity as not broadcasted + 'n', + // add not additional fields + '', + ]) + ->setRequiredPhpVersion(70200) + ->addExtraDependencies('api') + ->addExtraDependencies('ux-turbo-mercure') + ->setFixtureFilesPath(__DIR__.'/../fixtures/MakeEntity') + ->configureDatabase() + ->updateSchemaAfterCommand() + ->assert(function (string $output, string $directory) { + $this->assertFileExists($directory.'/src/Entity/User.php'); + }), + ]; } }
[make:entity] Fix error when API-Platform is installed.
symfony_maker-bundle
train
8b994ae931a1f2040c75b9618285fe29ec420d2b
diff --git a/core/raftlease/fsm.go b/core/raftlease/fsm.go index <HASH>..<HASH> 100644 --- a/core/raftlease/fsm.go +++ b/core/raftlease/fsm.go @@ -161,39 +161,53 @@ func (f *FSM) GlobalTime() time.Time { // Leases gets information about all of the leases in the system, // optionally filtered by the input lease keys. func (f *FSM) Leases(localTime time.Time, keys ...lease.Key) map[lease.Key]lease.Info { - filter := make(map[lease.Key]bool) - filtering := len(keys) > 0 - if filtering { - for _, key := range keys { - filter[key] = true + if len(keys) > 0 { + return f.filteredLeases(localTime, keys) + } + return f.allLeases(localTime) +} + +// filteredLeases is an optimisation for anticipated usage. +// There will usually be a single key for filtering, so iterating over the +// filter list and retrieving from entries will be fastest by far. +func (f *FSM) filteredLeases(localTime time.Time, keys []lease.Key) map[lease.Key]lease.Info { + results := make(map[lease.Key]lease.Info) + f.mu.Lock() + for _, key := range keys { + if entry, ok := f.entries[key]; ok { + results[key] = f.infoFromEntry(localTime, key, entry) } } + f.mu.Unlock() + return results +} +func (f *FSM) allLeases(localTime time.Time) map[lease.Key]lease.Info { results := make(map[lease.Key]lease.Info) f.mu.Lock() for key, entry := range f.entries { - if filtering && !filter[key] { - continue - } + results[key] = f.infoFromEntry(localTime, key, entry) + } + f.mu.Unlock() + return results +} - globalExpiry := entry.start.Add(entry.duration) +func (f *FSM) infoFromEntry(localTime time.Time, key lease.Key, entry *entry) lease.Info { + globalExpiry := entry.start.Add(entry.duration) - // If there is a pinned lease, always represent it as having an expiry - // in the future. This prevents the lease manager from waking up - // thinking it has some expiry events to handle. - remaining := globalExpiry.Sub(f.globalTime) - if f.isPinned(key) { - remaining = 30 * time.Second - } - localExpiry := localTime.Add(remaining) + // Pinned leases are always represented as having an expiry in the future. + // This prevents the lease manager from waking up thinking it has some + // expiry events to handle. + remaining := globalExpiry.Sub(f.globalTime) + if f.isPinned(key) { + remaining = 30 * time.Second + } + localExpiry := localTime.Add(remaining) - results[key] = lease.Info{ - Holder: entry.holder, - Expiry: localExpiry, - } + return lease.Info{ + Holder: entry.holder, + Expiry: localExpiry, } - f.mu.Unlock() - return results } // Pinned returns all of the currently known lease pins and applications
Raft FSM lease filtering iterates over the filter to select entries, rather than over the entries while checking the filter. This should be a good deal faster.
juju_juju
train
4dd1c561affb5408ed8dc12a79caf1d391005630
diff --git a/pyvex/block.py b/pyvex/block.py index <HASH>..<HASH> 100644 --- a/pyvex/block.py +++ b/pyvex/block.py @@ -112,8 +112,7 @@ class IRSB(VEXObject): @property def expressions(self): """ - All expressions contained in the IRSB. - :rtype: list of :class:`IRExpr` + A list of all expressions contained in the IRSB. """ expressions = [] for s in self.statements: @@ -125,7 +124,6 @@ class IRSB(VEXObject): def instructions(self): """ The number of instructions in this block - :rtype: int """ return len([s.addr for s in self.statements if isinstance(s, stmt.IMark)]) @@ -133,15 +131,13 @@ class IRSB(VEXObject): def size(self): """ The size of this block, in bytes - :rtype: int """ return sum([s.len for s in self.statements if isinstance(s, stmt.IMark)]) @property def operations(self): """ - All operations done by the IRSB, as libVEX enum names - :rtype: list of str + A list of all operations done by the IRSB, as libVEX enum names """ ops = [] for e in self.expressions: @@ -152,16 +148,14 @@ class IRSB(VEXObject): @property def all_constants(self): """ - Returns all constants (including incrementing of the program counter). - :rtype: list of :class:`IRConst` + Returns all constants in the block (including incrementing of the program counter) as :class:`pyvex.const.IRConst`. """ return sum((e.constants for e in self.expressions), []) @property def constants(self): """ - The constants (excluding updates of the program counter) in the IRSB. - :rtype: list of :class:`IRConst` + The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`. """ return sum( (s.constants for s in self.statements if not (isinstance(s, stmt.Put) and s.offset == self.offsIP)), []) @@ -169,8 +163,7 @@ class IRSB(VEXObject): @property def constant_jump_targets(self): """ - The static jump targets of the basic block. - :rtype: set of int + A set of the static jump targets of the basic block. """ exits = set() for s in self.statements: @@ -185,8 +178,7 @@ class IRSB(VEXObject): def _get_defaultexit_target(self): """ - Retrieves the default exit target, if it is constant. - :rtype: int or None + The default exit target, if it is constant, or None. """ if isinstance(self.next, expr.Const): return self.next.con.value @@ -214,7 +206,6 @@ class IRSB(VEXObject): def _is_defaultexit_direct_jump(self): """ Checks if the default of this IRSB a direct jump or not. - :rtype: bool """ if not (self.jumpkind == 'Ijk_Boring' or self.jumpkind == 'Ijk_Call'): return False
Apparently sphinx doesn't support :rtype: for parameters....
angr_pyvex
train
836774fcc004598310d8eef81ae2db15731e31cc
diff --git a/README.rst b/README.rst index <HASH>..<HASH> 100644 --- a/README.rst +++ b/README.rst @@ -306,6 +306,7 @@ EMC Contributors - Jay Xu <jay.xu@emc.com> - Ray Chen <ray.chen@emc.com> - Tina Tang <tina.tang@emc.com> +- Ryan Liang <ryan.liang@emc.com> Community Contributors `````````````````````` diff --git a/storops/vnx/enums.py b/storops/vnx/enums.py index <HASH>..<HASH> 100644 --- a/storops/vnx/enums.py +++ b/storops/vnx/enums.py @@ -83,6 +83,10 @@ class VNXSPEnum(VNXEnum): def index(self): return self.value.lower()[-1] + @property + def display_name(self): + return self.index.upper() + class VNXProvisionEnum(VNXEnum): # value of spec "provisioning:type" diff --git a/storops/vnx/resource/port.py b/storops/vnx/resource/port.py index <HASH>..<HASH> 100644 --- a/storops/vnx/resource/port.py +++ b/storops/vnx/resource/port.py @@ -46,6 +46,13 @@ class VNXPort(VNXCliResource): def wwn(self): return self._get_property('_wwn') + @property + def display_name(self): + items = [self.sp.display_name, str(self.port_id)] + if self.vport_id is not None: + items.append(str(self.vport_id)) + return '-'.join(items) + def config_ip(self, ip, mask, gateway, vport_id=None, vlan_id=None): if self.type != VNXPortType.ISCSI: raise TypeError('configure IP only works for iSCSI ports.') diff --git a/test/vnx/resource/test_port.py b/test/vnx/resource/test_port.py index <HASH>..<HASH> 100644 --- a/test/vnx/resource/test_port.py +++ b/test/vnx/resource/test_port.py @@ -73,6 +73,7 @@ class VNXSPPortTest(TestCase): assert_that(port.logged_in_initiators, equal_to(1)) assert_that(port.not_logged_in_initiators, equal_to(2)) assert_that(port.type, equal_to(VNXPortType.FC)) + assert_that(port.display_name, equal_to('A-0')) @patch_cli() def test_get_port_by_type(self): @@ -173,6 +174,7 @@ class VNXConnectionPortTest(TestCase): assert_that(port.gateway_address, equal_to('0.0.0.0')) assert_that(port.type, equal_to(VNXPortType.ISCSI)) assert_that(port.existed, equal_to(True)) + assert_that(port.display_name, equal_to('A-4-0')) @patch_cli() def test_get_all(self):
[GH-<I>] Add display_name to VNXPort (#<I>) Add property `display_name` to VNXPort and VNXSPEnum. If you have an `VNXPort` instance, let's say `port`. Then `port.display_name` will return a string like 'A-0-0' for iSCSI and 'A-1' for FC.
emc-openstack_storops
train
3b9f886e262c343430dd868046943be5112227e8
diff --git a/babel-watch.js b/babel-watch.js index <HASH>..<HASH> 100755 --- a/babel-watch.js +++ b/babel-watch.js @@ -274,13 +274,20 @@ function restartApp() { const sourceBuf = new Buffer(source || 0); const mapBuf = new Buffer(sourceMap ? JSON.stringify(sourceMap) : 0); const lenBuf = new Buffer(4); - lenBuf.writeUInt32BE(sourceBuf.length, 0); - fs.writeSync(pipeFd, lenBuf, 0, 4); - sourceBuf.length && fs.writeSync(pipeFd, sourceBuf, 0, sourceBuf.length); - - lenBuf.writeUInt32BE(mapBuf.length, 0); - fs.writeSync(pipeFd, lenBuf, 0, 4); - mapBuf.length && fs.writeSync(pipeFd, mapBuf, 0, mapBuf.length); + try { + lenBuf.writeUInt32BE(sourceBuf.length, 0); + fs.writeSync(pipeFd, lenBuf, 0, 4); + sourceBuf.length && fs.writeSync(pipeFd, sourceBuf, 0, sourceBuf.length); + + lenBuf.writeUInt32BE(mapBuf.length, 0); + fs.writeSync(pipeFd, lenBuf, 0, 4); + mapBuf.length && fs.writeSync(pipeFd, mapBuf, 0, mapBuf.length); + } catch (error) { + // EPIPE means `pipeFd` has been closed. We can ignore this + if (error.code !== 'EPIPE') { + throw error; + } + } }); });
Ignore EPIPE on writeSync (#<I>)
kmagiera_babel-watch
train
a5ad14f48fca97b3b0a800f14d0c963799be6dd5
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,14 @@ Changelog --------- +0.16.2 (unreleased) ++++++++++++++++++++ + +Bug fixes: + +* Prevent ValueError when using the ``exclude`` class Meta option with + ``TableSchema``. + 0.16.1 (2019-03-11) +++++++++++++++++++ diff --git a/src/marshmallow_sqlalchemy/convert.py b/src/marshmallow_sqlalchemy/convert.py index <HASH>..<HASH> 100644 --- a/src/marshmallow_sqlalchemy/convert.py +++ b/src/marshmallow_sqlalchemy/convert.py @@ -113,6 +113,8 @@ class ModelConverter(object): base_fields = base_fields or {} for column in table.columns: if self._should_exclude_field(column, fields=fields, exclude=exclude): + # Allow marshmallow to validate and exclude the field key. + result[column.key] = None continue if not include_fk and column.foreign_keys: continue diff --git a/tests/test_marshmallow_sqlalchemy.py b/tests/test_marshmallow_sqlalchemy.py index <HASH>..<HASH> 100644 --- a/tests/test_marshmallow_sqlalchemy.py +++ b/tests/test_marshmallow_sqlalchemy.py @@ -619,6 +619,16 @@ class TestTableSchema: data = unpack(schema.dump(school)) assert data == {"name": "Univ. of Whales", "school_id": 1} + def test_exclude(self, models, school): + class SchoolSchema(TableSchema): + class Meta: + table = models.School.__table__ + exclude = ("name",) + + schema = SchoolSchema() + data = unpack(schema.dump(school)) + assert "name" not in data + class TestModelSchema: @pytest.fixture() @@ -1193,6 +1203,16 @@ class TestModelSchema: keywords = {kw.keyword for kw in kw_objects} assert keywords == set(load_data.keywords) + def test_exclude(self, models, school): + class SchoolSchema(ModelSchema): + class Meta: + model = models.School + exclude = ("name",) + + schema = SchoolSchema() + data = unpack(schema.dump(school)) + assert "name" not in data + class TestNullForeignKey: @pytest.fixture()
Fix `exclude` with TableSchema
marshmallow-code_marshmallow-sqlalchemy
train
9a451fbcd16755fd75dd8e65c4e487771d43e306
diff --git a/src/main/java/com/basho/riak/client/query/indexes/BucketIndex.java b/src/main/java/com/basho/riak/client/query/indexes/BucketIndex.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/basho/riak/client/query/indexes/BucketIndex.java +++ b/src/main/java/com/basho/riak/client/query/indexes/BucketIndex.java @@ -24,7 +24,7 @@ public class BucketIndex extends BinIndex { private static final String BUCKETS_INDEX = "$bucket"; private static final String EMPTY = ""; - public static final Index index = new BucketIndex(); + public static final BucketIndex index = new BucketIndex(); private BucketIndex() { super(BUCKETS_INDEX);
Derp, fixed a compile issue.
basho_riak-java-client
train
f8e0c19633819b54cb8d81d11d589d90bfcacb66
diff --git a/visidata/clipboard.py b/visidata/clipboard.py index <HASH>..<HASH> 100644 --- a/visidata/clipboard.py +++ b/visidata/clipboard.py @@ -46,6 +46,7 @@ class _Clipboard: path = shutil.which(command) if path: return [path] + options + error('no available clipboard copy command') def copy(self, value): 'Copy a cell to the system clipboard.' @@ -83,6 +84,7 @@ clipboard = None def copyToClipboard(value): + 'copy single value to system clipboard' global clipboard clipboard = clipboard or _Clipboard() clipboard.copy(value) @@ -91,6 +93,7 @@ def copyToClipboard(value): @async def saveToClipboard(sheet, rows, filetype=None): + 'copy rows from sheet to system clipboard' global clipboard clipboard = clipboard or _Clipboard() filetype = filetype or options.filetype @@ -98,4 +101,3 @@ def saveToClipboard(sheet, rows, filetype=None): vs.rows = rows status('copying rows to clipboard') clipboard.save(vs, filetype) - status('done') diff --git a/visidata/data.py b/visidata/data.py index <HASH>..<HASH> 100644 --- a/visidata/data.py +++ b/visidata/data.py @@ -504,8 +504,6 @@ def reload_tsv_sync(vs, **kwargs): vs.addRow(L.split(delim)) prog.addProgress(len(L)) - status('loaded %s' % vs.name) - def tsv_trdict(delim=None): 'returns string.translate dictionary for replacing tabs and newlines'
[clipboard] cleanup docstrings and status msgs
saulpw_visidata
train
5f8bf28abd045cb12cbb7add1beb6593132513f7
diff --git a/lib/fitgem/activities.rb b/lib/fitgem/activities.rb index <HASH>..<HASH> 100644 --- a/lib/fitgem/activities.rb +++ b/lib/fitgem/activities.rb @@ -169,6 +169,28 @@ module Fitgem post("/user/#{@user_id}/activities/goals/daily.json", opts) end + # Create or update a user's weekly goal + # + # @param [Hash] :opts + # + # @option opts [Symbol] :type The type of goal to create or update; must be one of + # :steps, :distance, or :floors. REQUIRED + # @option opts [Decimal, Integer, String] :value The goal value; in the format 'X.XX' + # if a string. REQUIRED + # + # @since v0.9.0 + def create_or_update_weekly_goal(opts) + unless opts[:type] && [:steps, :distance, :floors].include?(opts[:type]) + raise InvalidArgumentError, 'Must specify type in order to create or update a weekly goal. One of (:steps, :distance, or :floors) is required.' + end + + unless opts[:value] + raise InvalidArgumentError, 'Must specify value of the weekly goal to be created or updated.' + end + + post("/user/#{@user_id}/activities/goals/weekly.json", opts) + end + # ========================================== # Activity Removal Methods # ========================================== diff --git a/spec/fitgem_activities_spec.rb b/spec/fitgem_activities_spec.rb index <HASH>..<HASH> 100644 --- a/spec/fitgem_activities_spec.rb +++ b/spec/fitgem_activities_spec.rb @@ -40,6 +40,38 @@ describe Fitgem::Client do end end + describe '#create_or_update_weekly_goal' do + before(:each) do + @opts = { type: :steps, value: '10000' } + end + + it 'raises an exception if the :type value is missing' do + @opts.delete :type + expect { + @client.create_or_update_weekly_goal @opts + }.to raise_error(Fitgem::InvalidArgumentError) + end + + it 'raises an exception if the :type value is not valid' do + @opts[:type] = :milesWalked + expect { + @client.create_or_update_weekly_goal @opts + }.to raise_error(Fitgem::InvalidArgumentError) + end + + it 'raises an exception if the :value value is missing' do + @opts.delete :value + expect { + @client.create_or_update_weekly_goal @opts + }.to raise_error(Fitgem::InvalidArgumentError) + end + + it 'posts to the correct URI if the :type and :value are valid' do + @client.should_receive(:post).with('/user/-/activities/goals/weekly.json', @opts) + @client.create_or_update_weekly_goal @opts + end + end + describe '#intraday_time_series' do before(:each) do @date_opts = {
Add the create_or_update_weekly_goal method and specs
whazzmaster_fitgem
train
067b349fb1b3e309676c7c4ebb2cf2c74a347102
diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java @@ -24,7 +24,6 @@ import org.springframework.boot.autoconfigure.domain.EntityScanner; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.data.annotation.Persistent; import org.springframework.data.couchbase.config.BeanNames; import org.springframework.data.couchbase.core.convert.CouchbaseCustomConversions; import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; @@ -65,7 +64,7 @@ class CouchbaseDataConfiguration { throws Exception { CouchbaseMappingContext mappingContext = new CouchbaseMappingContext(); mappingContext - .setInitialEntitySet(new EntityScanner(applicationContext).scan(Document.class, Persistent.class)); + .setInitialEntitySet(new EntityScanner(applicationContext).scan(Document.class)); mappingContext.setSimpleTypeHolder(couchbaseCustomConversions.getSimpleTypeHolder()); Class<?> fieldNamingStrategy = properties.getFieldNamingStrategy(); if (fieldNamingStrategy != null) {
Stop considering persistent when scanning for Couchbase entities See gh-<I>
spring-projects_spring-boot
train
e828eb16e43b31750b57e009ce8f14bba8de22b7
diff --git a/src/View/View.php b/src/View/View.php index <HASH>..<HASH> 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -1305,7 +1305,6 @@ class View implements EventDispatcherInterface 'response' => 'setResponse', 'subDir' => 'setSubDir', 'plugin' => 'setPlugin', - 'name' => 'setName', 'elementCache' => 'setElementCache', ]; if (isset($protected[$name])) { @@ -1330,6 +1329,13 @@ class View implements EventDispatcherInterface return $this->helpers = $value; } + if ($name === 'name') { + deprecationWarning( + 'View::$name is protected now. ' . + 'You can use viewBuilder()->setName() to change the name a view uses before building it.' + ); + } + $this->{$name} = $value; } @@ -1473,6 +1479,17 @@ class View implements EventDispatcherInterface } /** + * Returns the View's controller name. + * + * @return string|null + * @since 3.7.7 + */ + public function getName() + { + return $this->name; + } + + /** * Returns the plugin name. * * @return string|null diff --git a/tests/TestCase/View/ViewTest.php b/tests/TestCase/View/ViewTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/View/ViewTest.php +++ b/tests/TestCase/View/ViewTest.php @@ -2152,6 +2152,20 @@ TEXT; } /** + * Test getName() and getPlugin(). + * + * @return void + */ + public function testGetNamePlugin() + { + $this->assertSame('Posts', $this->View->getName()); + $this->assertNull($this->View->getPlugin()); + + $this->assertSame($this->View, $this->View->setPlugin('TestPlugin')); + $this->assertSame('TestPlugin', $this->View->getPlugin()); + } + + /** * Test testHasRendered property * * @return void
Add getName() to View We were emitting deprecation warnings telling folks to use methods that didn't exist. Make the required methods exist, and emit a better deprecation warning when trying to mutate View::$name. Fixes #<I>
cakephp_cakephp
train
54565bbd8908e21127a3c2f245d18b42895034d9
diff --git a/mapping/tests/test_mappings.py b/mapping/tests/test_mappings.py index <HASH>..<HASH> 100644 --- a/mapping/tests/test_mappings.py +++ b/mapping/tests/test_mappings.py @@ -229,23 +229,32 @@ class TestMappings(unittest.TestCase): index=idx, columns=cols) non_unique_index = pd.Series([pd.Timestamp('2016-10-20'), - pd.Timestamp('2016-11-21'), - pd.Timestamp('2016-12-20')], - index=['instr1', 'instr1', 'instr3']) + pd.Timestamp('2016-11-21')], + index=['instr1', 'instr1']) self.assertRaises(ValueError, mappings.roller, ts, non_unique_index, mappings.static_transition, transition=trans) - ts = [pd.Timestamp("2016-10-19"), pd.Timestamp("2016-10-20")] - non_monotonic_vals = pd.Series([pd.Timestamp('2016-10-20'), - pd.Timestamp('2016-10-20'), - pd.Timestamp('2016-12-20')], - index=['instr1', 'instr2', 'instr3']) + non_unique_vals = pd.Series([pd.Timestamp('2016-10-20'), + pd.Timestamp('2016-10-20')], + index=['instr1', 'instr2']) self.assertRaises(ValueError, mappings.roller, - ts, non_monotonic_vals, mappings.static_transition, + ts, non_unique_vals, mappings.static_transition, transition=trans) + non_monotonic_vals = pd.Series([pd.Timestamp('2016-10-20'), + pd.Timestamp('2016-10-19')], + index=['instr1', 'instr2']) + + self.assertRaises(ValueError, mappings.static_transition, + ts[0], non_monotonic_vals, transition=trans) + + not_enough_vals = pd.Series([pd.Timestamp('2016-10-19')], + index=['instr1']) + self.assertRaises(IndexError, mappings.static_transition, + ts[0], not_enough_vals, transition=trans) + def test_during_roll_two_generics_one_day_static_roller(self): dt = self.dates.iloc[0] contract_dates = self.dates
Add tests for contract_dates problem inputs Cover cases where contract_dates has insufficient dates and where it is non monotonic.
matthewgilbert_mapping
train
3248886466de0993f3e9c95ec1472b96a45528e4
diff --git a/napalm_base/clitools/cl_napalm_test.py b/napalm_base/clitools/cl_napalm_test.py index <HASH>..<HASH> 100644 --- a/napalm_base/clitools/cl_napalm_test.py +++ b/napalm_base/clitools/cl_napalm_test.py @@ -6,8 +6,6 @@ NAPALM CLI Tools: test connectivity Module to test connectivity with the network device through NAPALM. ''' from __future__ import absolute_import -from __future__ import print_function -from __future__ import unicode_literals # import helpers from napalm_base import get_network_driver @@ -18,7 +16,7 @@ from napalm_base.clitools.helpers import parse_optional_args # stdlib import sys import logging -logger = logging.getLogger(__file__) +logger = logging.getLogger('cl_napalm_test.py') def main(): @@ -30,7 +28,7 @@ def main(): optional_args = parse_optional_args(args.optional_args) logger.debug('Connecting to device "{}" with user "{}" and optional_args={}'.format( - device=args.hostname, user=args.user, optional_args=optional_args)) + args.hostname, args.user, optional_args)) with driver(args.hostname, args.user,
Fixing cli tool for testing connection
napalm-automation_napalm-base
train
ce08bf5f66d9d4cbef1db677fa4ff6bf7c8ce2c3
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -9,9 +9,6 @@ var async = require('async'); function _streamFtpGet(ftpConnectOptions, files, deferredStream) { var c = new FtpClient(); c.on('error', function(e) { - if(e.code === 530) { - e = new Error('Credentials are not correct'); - } deferredStream.emit('error', e); }); diff --git a/test/check-failures.test.js b/test/check-failures.test.js index <HASH>..<HASH> 100644 --- a/test/check-failures.test.js +++ b/test/check-failures.test.js @@ -40,7 +40,7 @@ test('stream emit error when incorrect credentials', function (t) { if(!error) { t.fail('error should have happend') } - t.equal(error.message, "Credentials are not correct"); + t.equal(error.message, "Not logged in."); server.completelyShutdown(); t.end(); }
removing special handling of error just to change the message
phillipgreenii_node-ftp-stream
train
0dfc54c9c5600647baa5ec362f571a5d0ba0e52f
diff --git a/src/Engine/Elasticsearch/ElasticsearchAdapter.php b/src/Engine/Elasticsearch/ElasticsearchAdapter.php index <HASH>..<HASH> 100644 --- a/src/Engine/Elasticsearch/ElasticsearchAdapter.php +++ b/src/Engine/Elasticsearch/ElasticsearchAdapter.php @@ -11,8 +11,9 @@ use G4\DataMapper\Exception\EmptyDataException; class ElasticsearchAdapter implements AdapterInterface { - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_DELETE = 'DELETE'; private $client; @@ -27,6 +28,7 @@ class ElasticsearchAdapter implements AdapterInterface */ public function delete(CollectionNameInterface $collectionName, SelectionFactoryInterface $selectionFactory) { + $this->client->setIndex($collectionName)->setMethod(self::METHOD_DELETE)->setId($selectionFactory->where())->execute(); } /**
<I> - Added logic for delete method.
g4code_data-mapper
train
2c1604b90109d0b22313d937c434f57563d47a5b
diff --git a/lib/mixlib/cli.rb b/lib/mixlib/cli.rb index <HASH>..<HASH> 100644 --- a/lib/mixlib/cli.rb +++ b/lib/mixlib/cli.rb @@ -38,31 +38,45 @@ module Mixlib # #parse_options. After calling this method, the attribute #config will # contain a hash of `:option_name => value` pairs. module CLI - + module InheritMethods def inherited(receiver) receiver.options = deep_dup(self.options) receiver.extend(Mixlib::CLI::InheritMethods) end - def deep_dup(thing) - new_thing = thing.respond_to?(:dup) ? thing.dup : thing - if(new_thing.kind_of?(Enumerable)) - if(new_thing.kind_of?(Hash)) - duped = new_thing.map do |key, value| - [deep_dup(key), deep_dup(value)] + # object:: Instance to clone + # This method will return a "deep clone" of the provided + # `object`. If the provided `object` is an enumerable type the + # contents will be iterated and cloned as well. + def deep_dup(object) + cloned_object = object.respond_to?(:dup) ? object.dup : object + if(cloned_object.kind_of?(Enumerable)) + if(cloned_object.kind_of?(Hash)) + new_hash = cloned_object.class.new + cloned_object.each do |key, value| + cloned_key = deep_dup(key) + cloned_value = deep_dup(value) + new_hash[cloned_key] = cloned_value end - new_thing = new_thing.class[*duped.flatten] + cloned_object.replace(new_hash) else - new_thing.map!{|value| deep_dup(value)} + cloned_object.map! do |shallow_instance| + deep_dup(shallow_instance) + end end end - new_thing + cloned_object rescue TypeError - thing + # Symbol will happily provide a `#dup` method even though + # attempts to clone it will result in an exception (atoms!). + # So if we run into an issue of TypeErrors, just return the + # original object as we gave our "best effort" + object end + end - + module ClassMethods # When this setting is set to +true+, default values supplied to the # mixlib-cli DSL will be stored in a separate Hash
Re-implement `#deep_dup` with better names and some comments
chef_mixlib-cli
train
b89dcb6a7cd3b85d1ea9f8cc2388e69f2e48201e
diff --git a/example/use-cases.rb b/example/use-cases.rb index <HASH>..<HASH> 100644 --- a/example/use-cases.rb +++ b/example/use-cases.rb @@ -1,4 +1,6 @@ +require 'fiber' +require 'em-http-request' require 'rest-core' RC.eagerload diff --git a/lib/rest-core/test.rb b/lib/rest-core/test.rb index <HASH>..<HASH> 100644 --- a/lib/rest-core/test.rb +++ b/lib/rest-core/test.rb @@ -1,4 +1,6 @@ +require 'fiber' +require 'em-http-request' require 'rest-core' require 'rr'
require fiber and em-http-request first to make sure we pick them
godfat_rest-core
train
24f810f440a886982da3db523d31990f1b5ae59f
diff --git a/src/main/java/com/tikinou/schedulesdirect/core/domain/Headend.java b/src/main/java/com/tikinou/schedulesdirect/core/domain/Headend.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/tikinou/schedulesdirect/core/domain/Headend.java +++ b/src/main/java/com/tikinou/schedulesdirect/core/domain/Headend.java @@ -16,9 +16,14 @@ package com.tikinou.schedulesdirect.core.domain; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + /** * @author Sebastien Astie */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_EMPTY) public class Headend { private String name; private String location;
Added toString override
Tikinou_schedules-direct-core-api
train
a6498c7538cbf2344c7124f1f611765c0fb17521
diff --git a/test/helper.rb b/test/helper.rb index <HASH>..<HASH> 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -8,7 +8,8 @@ rescue Bundler::BundlerError => e exit e.status_code end require 'test/unit' -require 'shoulda' +require 'turn' +require 'shoulda-context' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__))
[ADD] Few requirements for testing helper
ondrejbartas_redis-model-extension
train
479f3d7c111a33aae62bb8f1b3f602f96b75a858
diff --git a/test/support/helper.js b/test/support/helper.js index <HASH>..<HASH> 100644 --- a/test/support/helper.js +++ b/test/support/helper.js @@ -1,4 +1,6 @@ var _ = require('lodash') +var assert = require('assert') + var loggerFactory = require('./logger-factory') var teenytest = require('../../index') @@ -14,5 +16,17 @@ module.exports = { cb(er, result, logger) }) }) + }, + deepEqual: function (actual, expected, msg) { + try { + assert.deepEqual(actual, expected, msg) + } catch(e) { + console.log('Failed comparing actual:') + console.log(actual) + console.log('with expected:') + console.log(expected) + console.log('---') + throw e + } } }
(internal) provide a deepEqual that prints well
testdouble_teenytest
train
8cc2a6655ec48f9bbc0cf086f2a7415b2e14ba37
diff --git a/src/Http/Controllers/Adminarea/UsersController.php b/src/Http/Controllers/Adminarea/UsersController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/Adminarea/UsersController.php +++ b/src/Http/Controllers/Adminarea/UsersController.php @@ -124,7 +124,7 @@ class UsersController extends AuthorizedController })->values(); $authUser = $request->user($this->getGuard()); $languages = collect(languages())->pluck('name', 'iso_639_1'); - $genders = ['m' => trans('cortex/fort::common.male'), 'f' => trans('cortex/fort::common.female')]; + $genders = ['male' => trans('cortex/fort::common.male'), 'female' => trans('cortex/fort::common.female')]; $roles = $authUser->isSuperadmin() ? app('rinvex.fort.role')->all()->pluck('name', 'id')->toArray() diff --git a/src/Http/Controllers/Frontarea/AccountSettingsController.php b/src/Http/Controllers/Frontarea/AccountSettingsController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/Frontarea/AccountSettingsController.php +++ b/src/Http/Controllers/Frontarea/AccountSettingsController.php @@ -39,7 +39,7 @@ class AccountSettingsController extends AuthenticatedController ]; })->values(); $languages = collect(languages())->pluck('name', 'iso_639_1'); - $genders = ['m' => trans('cortex/fort::common.male'), 'f' => trans('cortex/fort::common.female')]; + $genders = ['male' => trans('cortex/fort::common.male'), 'female' => trans('cortex/fort::common.female')]; return view('cortex/fort::frontarea.pages.account-settings', compact('countries', 'languages', 'genders')); } diff --git a/src/Http/Controllers/Managerarea/UsersController.php b/src/Http/Controllers/Managerarea/UsersController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/Managerarea/UsersController.php +++ b/src/Http/Controllers/Managerarea/UsersController.php @@ -124,7 +124,7 @@ class UsersController extends AuthorizedController })->values(); $authUser = $request->user($this->getGuard()); $languages = collect(languages())->pluck('name', 'iso_639_1'); - $genders = ['m' => trans('cortex/fort::common.male'), 'f' => trans('cortex/fort::common.female')]; + $genders = ['male' => trans('cortex/fort::common.male'), 'female' => trans('cortex/fort::common.female')]; $owner = optional(optional(config('rinvex.tenants.active'))->owner)->getKey(); $roles = $authUser->isSuperadmin() || $authUser->getKey() === $owner diff --git a/src/Http/Controllers/Tenantarea/AccountSettingsController.php b/src/Http/Controllers/Tenantarea/AccountSettingsController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/Tenantarea/AccountSettingsController.php +++ b/src/Http/Controllers/Tenantarea/AccountSettingsController.php @@ -39,7 +39,7 @@ class AccountSettingsController extends AuthenticatedController ]; })->values(); $languages = collect(languages())->pluck('name', 'iso_639_1'); - $genders = ['m' => trans('cortex/fort::common.male'), 'f' => trans('cortex/fort::common.female')]; + $genders = ['male' => trans('cortex/fort::common.male'), 'female' => trans('cortex/fort::common.female')]; return view('cortex/fort::tenantarea.pages.account-settings', compact('countries', 'languages', 'genders')); }
Convert genders database storage to explicit male/female instead of m/f
rinvex_cortex-auth
train
8b0dda68896760c3f45bdfe881b2a6fcd36ff703
diff --git a/lib/CORL/node/aws.rb b/lib/CORL/node/aws.rb index <HASH>..<HASH> 100644 --- a/lib/CORL/node/aws.rb +++ b/lib/CORL/node/aws.rb @@ -24,13 +24,13 @@ class Aws < Node::Fog def regions [ - 'ap-northeast-1', - 'ap-southeast-1', - 'ap-southeast-2', - 'eu-west-1', 'us-east-1', 'us-west-1', - 'us-west-2', + 'us-west-2', + 'eu-west-1', + 'ap-northeast-1', + 'ap-southeast-1', + 'ap-southeast-2', 'sa-east-1' ] end @@ -41,7 +41,8 @@ class Aws < Node::Fog def machine_config super do |config| config.import({ - :provider => 'AWS' + :provider => 'AWS', + :region => region }) config[:aws_access_key_id] = api_user if api_user @@ -55,9 +56,6 @@ class Aws < Node::Fog def create(options = {}) super do |op, config| if op == :config - config[:private_key] = private_key if private_key - config[:public_key] = public_key if public_key - config.defaults({ :name => hostname, :flavor_id => machine_type,
Fixing issues and reordering regions in the aws node provider.
coralnexus_corl
train
0befd22626150b66b23ba71d7cedd1cbcefd360c
diff --git a/spock/task.py b/spock/task.py index <HASH>..<HASH> 100644 --- a/spock/task.py +++ b/spock/task.py @@ -44,34 +44,38 @@ class RunTask(object): return True # remove this handler def register(self, response): - self.expected.clear() self.parse_response(response) for event, check in self.expected.items(): self.reg_event_handler(event, self.handler) def parse_response(self, response): + # TODO what format do we want to use? also documentation # recursive check what the response is # generator: subtask # str: evt name - # iterable: check 1st elm - # - str: evt name + test func - # - other: recursive register + # iterable: check 2. element + # - str/generator: list of events, register recursively + # - other (func): evt name + test func + self.expected.clear() if isinstance(response, types.GeneratorType): # subtask RunTask(response, self.reg_event_handler, parent=self) elif isinstance(response, str): # event name self.expected[response] = accept elif hasattr(response, '__getitem__'): - if isinstance(response[0], str): # event name + check function + if isinstance(response[1], (str, types.GeneratorType)) \ + or hasattr(response[1], '__getitem__'): + # recursive check + for sub_response in response: + self.parse_response(sub_response) + else: # event name + check function # we should not split these tuples recursively, so catch them event, check = response self.expected[event] = check - else: # recursive check - for sub_response in response: - self.parse_response(sub_response) else: # unexpected - raise ValueError( - 'Illegal yield argument of type %s' % type(response)) + self.expected.clear() + raise ValueError('Illegal task yield argument of type %s: %s' + % type(response), response) class TaskCallback(object):
Improve parsing of event definitions in async tasks
SpockBotMC_SpockBot
train
c9fcad75b789de28715edb360503620b4f9b78ae
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -156,7 +156,6 @@ module.exports = function(grunt) { 'sdk/src/third-party/jquery.js', 'sdk/src/third-party/jquery.noconflict.js', 'sdk/src/third-party/eventemitter2.js', - 'sdk/src/third-party/easyXDM/easyXDM.js', '<%= jshint.files %>', 'sdk/src/template/footer.js.tmpl' ], @@ -236,14 +235,6 @@ module.exports = function(grunt) { 'package-no-bootstrap': { files: { 'sdk/packages/f2.no-bootstrap.min.js' : ['sdk/packages/f2.no-bootstrap.js'] }, options: { report: 'min' } - }, - 'package-no-easyXDM': { - files: { 'sdk/packages/f2.no-easyXDM.min.js' : ['sdk/packages/f2.no-easyXDM.js'] }, - options: { report: 'min' } - }, - 'package-basic': { - files: { 'sdk/packages/f2.basic.min.js' : ['sdk/packages/f2.basic.js'] }, - options: { report: 'min' } } }, sourcemap: { @@ -441,12 +432,8 @@ module.exports = function(grunt) { grunt.registerTask('packages', [ 'concat:no-jquery-or-bootstrap', 'concat:no-bootstrap', - 'concat:no-easyXDM', - 'concat:basic', 'uglify:package-no-jquery-or-bootstrap', - 'uglify:package-no-bootstrap', - 'uglify:package-no-easyXDM', - 'uglify:package-basic' + 'uglify:package-no-bootstrap' ]); grunt.registerTask('test', ['jshint', 'express', 'jasmine']); grunt.registerTask('test-live', ['jshint', 'express', 'express-keepalive']);
Clean up Gruntfile to remove basic, easyxdm packages
OpenF2_F2
train
32da8c9781f55a5e7672a188b9b496aad263d282
diff --git a/psiturk/models.py b/psiturk/models.py index <HASH>..<HASH> 100644 --- a/psiturk/models.py +++ b/psiturk/models.py @@ -34,7 +34,7 @@ class Participant(Base): endhit = Column(DateTime) bonus = Column(Float, default = 0) status = Column(Integer, default = 1) - datastring = Column(UnicodeText) + datastring = Column(UnicodeText(convert_unicode=False)) def __init__(self, **kwargs): self.uniqueid = "{workerid}:{assignmentid}".format(**kwargs)
Fix bug encoding non-unicode strings This lets it just save the ascii strings, which seems to work.
NYUCCL_psiTurk
train
e1662759edd6b900d3792a3a466a5d27586f86a7
diff --git a/packages/babel-helper-transform-fixture-test-runner/src/index.js b/packages/babel-helper-transform-fixture-test-runner/src/index.js index <HASH>..<HASH> 100644 --- a/packages/babel-helper-transform-fixture-test-runner/src/index.js +++ b/packages/babel-helper-transform-fixture-test-runner/src/index.js @@ -126,9 +126,6 @@ function wrapPackagesArray(type, names, optionsDir) { } function checkDuplicatedNodes(ast) { - // TODO Remove all these function when regenerator doesn't - // insert duplicated nodes - const nodes = new WeakSet(); const parents = new WeakMap(); @@ -152,156 +149,15 @@ function checkDuplicatedNodes(ast) { } }; - const parentIs = (node, test) => { - return (parents.get(node) || []).some(parent => test(parent)); - }; - const isByRegenerator = node => { - if (!node) { - return false; - } else if (node.type === "Identifier") { - if (/^_(?:context|value|callee|marked)\d*$/.test(node.name)) { - return true; - } else if ( - /^t\d+$/.test(node.name) && - parentIs( - node, - parent => - parent.type === "MemberExpression" && - isByRegenerator(parent.object), - ) - ) { - // _context.t* // <-- t* - return true; - } else if ( - parentIs( - node, - parent => - parent.type === "VariableDeclarator" && - parentIs( - parent, - parent => - parent.type === "VariableDeclaration" && - parentIs( - parent, - parent => - parent.type === "BlockStatement" && - parentIs( - parent, - parent => - parent.type === "FunctionExpression" && - isByRegenerator(parent.id), - ), - ), - ), - ) - ) { - // regeneratorRuntime.mark(function _callee3() { - // var bar, _bar2; // <-- Those identifiers - return true; - } else if ( - parentIs( - node, - parent => - parent.type === "VariableDeclarator" && - parentIs( - parent, - parent => - parent.type === "VariableDeclaration" && - parentIs( - parent, - parent => - parent.type === "BlockStatement" && - parent.body.length === 2 && - parent.body[1].type === "ReturnStatement" && - parent.body[1].argument.type === "CallExpression" && - parent.body[1].argument.callee.type === - "MemberExpression" && - parent.body[1].argument.callee.property.type === - "Identifier" && - parent.body[1].argument.callee.property.name === "wrap", - ), - ), - ) - ) { - // function foo() { - // var _len, // <-- Those identifiers - // items, - // _key, - // _args = arguments; - // return regeneratorRuntime.wrap(function foo$(_context) { - return true; - } else if ( - parentIs( - node, - parent => - parent.type === "CallExpression" && - parent.arguments.length === 3 && - parent.arguments[1] === node && - parent.callee.type === "MemberExpression" && - parent.callee.property.type === "Identifier" && - parent.callee.property.name === "wrap", - ) - ) { - // regeneratorRuntime.wrap(function foo$(_context) { - // ... - // }, foo, this); // <- foo - return true; - } else if ( - parentIs( - node, - parent => - parent.type === "CallExpression" && - parent.callee.type === "MemberExpression" && - parent.callee.property.type === "Identifier" && - parent.callee.property.name === "mark", - ) - ) { - // regeneratorRuntime.mark(foo); // foo - return true; - } - } else if (node.type === "MemberExpression") { - // _context.next - return isByRegenerator(node.object); - } else if (node.type === "CallExpression") { - return isByRegenerator(node.callee); - } else if (node.type === "AssignmentExpression") { - // _context.next = 4; - return isByRegenerator(node.left); - } else if (node.type === "NumericLiteral") { - if ( - parentIs( - node, - parent => - parent.type === "AssignmentExpression" && - isByRegenerator(parent.left), - ) - ) { - // _context.next = 4; // <-- The 4 - return true; - } else if ( - parentIs( - node, - parent => - parent.type === "CallExpression" && - parent.callee.type === "MemberExpression" && - isByRegenerator(parent.callee.object), - ) - ) { - // return _context.abrupt("break", 11); // <-- The 11 - return true; - } - } - return false; - }; const hidePrivateProperties = (key, val) => { // Hides properties like _shadowedFunctionLiteral, // which makes the AST circular if (key[0] === "_") return "[Private]"; return val; }; + babel.types.traverseFast(ast, node => { registerChildren(node); - if (isByRegenerator(node)) return; if (nodes.has(node)) { throw new Error( "Do not reuse nodes. Use `t.cloneNode` to copy them.\n" +
Remove regenerator hacks in checkDuplicatedNodes (#<I>)
babel_babel
train
fd6ed32c6ace85e27368674be84f5dfd19f7d872
diff --git a/wpull/version.py b/wpull/version.py index <HASH>..<HASH> 100644 --- a/wpull/version.py +++ b/wpull/version.py @@ -6,4 +6,4 @@ A string conforming to `Semantic Versioning Guidelines <http://semver.org/>`_ ''' -__version__ = '0.17.3' +__version__ = '0.18'
Bumps version to <I>.
ArchiveTeam_wpull
train
22e56382784af82960d9feca42fc67be29aba16c
diff --git a/rrrspec-client/spec/spec_helper.rb b/rrrspec-client/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/rrrspec-client/spec/spec_helper.rb +++ b/rrrspec-client/spec/spec_helper.rb @@ -27,7 +27,7 @@ RSpec.configure do |config| retry_count = 1 loop do begin - redis.client.connect + redis.ping break rescue Redis::CannotConnectError if retry_count < 10 diff --git a/rrrspec-server/spec/spec_helper.rb b/rrrspec-server/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/rrrspec-server/spec/spec_helper.rb +++ b/rrrspec-server/spec/spec_helper.rb @@ -30,7 +30,7 @@ RSpec.configure do |config| retry_count = 1 loop do begin - redis.client.connect + redis.ping break rescue Redis::CannotConnectError if retry_count < 10 diff --git a/rrrspec-web/spec/spec_helper.rb b/rrrspec-web/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/rrrspec-web/spec/spec_helper.rb +++ b/rrrspec-web/spec/spec_helper.rb @@ -28,7 +28,7 @@ RSpec.configure do |config| retry_count = 1 loop do begin - redis.client.connect + redis.ping break rescue Redis::CannotConnectError if retry_count < 10
use Redis#ping to detect if redis-server is up because Redis::Client#connect has an issue that described in <URL>
cookpad_rrrspec
train
ffc1cb4cfc8317bcf57664d0becace016b4fc4b3
diff --git a/law/parser.py b/law/parser.py index <HASH>..<HASH> 100644 --- a/law/parser.py +++ b/law/parser.py @@ -98,11 +98,12 @@ def root_task_parser(): def global_cmdline_args(exclude=None): """ - Returns the list of command line arguments that do not belong to the root task. The returned - list is cached. *exclude* can be a list of arguments (including ``"--"`` prefix) that should - be removed from the returned list. As :py:func:`remove_cmdline_arg` is used internally, an - argument can be specified either by a name or a tuple of argument name and expected number of - values on the command line. Example: + Returns the list of command line arguments that do not belong to the root task. For bool + parameters, such as ``--local-scheduler``, ``"True"`` is inserted if they are used as flags, + i.e., without a parameter value. The returned list is cached. *exclude* can be a list of + arguments (including ``"--"`` prefix) that should be removed from the returned list. As + :py:func:`remove_cmdline_arg` is used internally, an argument can be specified either by a name + or a tuple of argument name and expected number of values on the command line. Example: .. code-block:: python @@ -122,7 +123,17 @@ def global_cmdline_args(exclude=None): if not luigi_parser: return None - _global_cmdline_args = root_task_parser().parse_known_args(luigi_parser.cmdline_args)[1] + _global_cmdline_args = [] + + args = root_task_parser().parse_known_args(luigi_parser.cmdline_args)[1] + + # expand bool flags + for i, arg in enumerate(args): + _global_cmdline_args.append(arg) + if arg.startswith("--"): + is_flag = i == (len(args) - 1) or args[i + 1].startswith("--") + if is_flag: + _global_cmdline_args.append("True") if not exclude: return _global_cmdline_args
Expand bool flags in global_cmdline_args.
riga_law
train
0e6b6864b4176ef75457efccadbf929dfa5d341d
diff --git a/state/allcollections.go b/state/allcollections.go index <HASH>..<HASH> 100644 --- a/state/allcollections.go +++ b/state/allcollections.go @@ -275,6 +275,8 @@ func allCollections() CollectionSchema { Key: []string{"model-uuid", "principal"}, }, { Key: []string{"model-uuid", "machineid"}, + }, { + Key: []string{"model-uuid", "name"}, }}, }, unitStatesC: {
Adds an index to the unit collection making retrieval by name more efficient. This is a hot path for updating unit states.
juju_juju
train
ebb5688fed634a95f76abb7f9a31fa85eea14a18
diff --git a/db/db.go b/db/db.go index <HASH>..<HASH> 100644 --- a/db/db.go +++ b/db/db.go @@ -27,10 +27,7 @@ func (db *DB) Copy() *DB { // Are we connected? func (db *DB) Connected() bool { - if db.connection == nil { - return false - } - return true + return db.connection != nil } // Connect to the backend database diff --git a/db/jobs.go b/db/jobs.go index <HASH>..<HASH> 100644 --- a/db/jobs.go +++ b/db/jobs.go @@ -327,5 +327,5 @@ func (j *Job) Reschedule() error { } func (j *Job) Runnable() bool { - return j.Paused == false && j.NextRun <= time.Now().Unix() + return !j.Paused && j.NextRun <= time.Now().Unix() }
Don't compare bools with bools. It makes Go angry.
starkandwayne_shield
train
cb685beafa618938eaa78e12403f7e82dc1fa478
diff --git a/tests/unit/components/sl-translate-test.js b/tests/unit/components/sl-translate-test.js index <HASH>..<HASH> 100755 --- a/tests/unit/components/sl-translate-test.js +++ b/tests/unit/components/sl-translate-test.js @@ -88,13 +88,13 @@ test( 'Can be used alongside other properties or attribute bindings', function( test( 'On initialization, extractParameterKeys() filters passed parameters', function( assert ) { const component = this.subject({ - key: 'the_key', - pluralKey: 'plural_key', - pluralCount: 'plural_count', - $1: 'a', - 2: 'b', - other: 'c' - }); + key: 'the_key', + pluralKey: 'plural_key', + pluralCount: 'plural_count', + $1: 'a', + 2: 'b', + other: 'c' + }); assert.deepEqual( component.get( 'parameters' ).sort(),
Refactor to conform to linting rules
softlayer_sl-ember-translate
train
5a62dc5c40ab49314b788dd9b68d3daeda6a2c94
diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/StaticMethod/ExistingAtomicStaticCallAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/StaticMethod/ExistingAtomicStaticCallAnalyzer.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/StaticMethod/ExistingAtomicStaticCallAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/StaticMethod/ExistingAtomicStaticCallAnalyzer.php @@ -80,7 +80,7 @@ class ExistingAtomicStaticCallAnalyzer $file_analyzer = $statements_analyzer->getFileAnalyzer(); if ($context->collect_mutations) { - $file_analyzer->getMethodMutations($method_id, $context); + $file_analyzer->getMethodMutations($appearing_method_id, $context); } else { // collecting initializations $local_vars_in_scope = []; @@ -98,14 +98,14 @@ class ExistingAtomicStaticCallAnalyzer } } - if (!isset($context->initialized_methods[(string) $method_id])) { + if (!isset($context->initialized_methods[(string) $appearing_method_id])) { if ($context->initialized_methods === null) { $context->initialized_methods = []; } - $context->initialized_methods[(string) $method_id] = true; + $context->initialized_methods[(string) $appearing_method_id] = true; - $file_analyzer->getMethodMutations($method_id, $context); + $file_analyzer->getMethodMutations($appearing_method_id, $context); foreach ($local_vars_in_scope as $var => $type) { $context->vars_in_scope[$var] = $type; diff --git a/tests/PropertyTypeTest.php b/tests/PropertyTypeTest.php index <HASH>..<HASH> 100644 --- a/tests/PropertyTypeTest.php +++ b/tests/PropertyTypeTest.php @@ -2121,6 +2121,27 @@ class PropertyTypeTest extends TestCase } }' ], + 'skipConstructor' => [ + '<?php + class A { + protected string $s; + + public function __construct() { + $this->s = "hello"; + } + } + + class B extends A {} + + class C extends B { + public function __construct() + { + parent::__construct(); + + echo $this->s; + } + }' + ], ]; }
Fix #<I> - use correct method when simulating property setting
vimeo_psalm
train