hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3ff51793c9e726d9201ddb22adfebcb25f956b6b
diff --git a/sporniket-core-io/src/test/java/test/sporniket/libre/io/TestPropertyParser.java b/sporniket-core-io/src/test/java/test/sporniket/libre/io/TestPropertyParser.java index <HASH>..<HASH> 100644 --- a/sporniket-core-io/src/test/java/test/sporniket/libre/io/TestPropertyParser.java +++ b/sporniket-core-io/src/test/java/test/sporniket/libre/io/TestPropertyParser.java @@ -114,7 +114,7 @@ public class TestPropertyParser extends TestCase private static final String[] TEST_DESCRIPTION__MULTIPLE_LINE_PROPERIES__PROPERTY_VALUE__SOURCE = { - " line 1 ", " line 2." + "\t line 1 ", " line 2." }; private static final String[] TEST_DESCRIPTION__MULTIPLE_LINE_PROPERTIES__LEFT_TRIM = @@ -248,14 +248,15 @@ public class TestPropertyParser extends TestCase public final void testErrorManagement() { final LineByLinePropertyParser _parser = new LineByLinePropertyParser(); - - final String[] _correctLines = { + + final String[] _correctLines = + { TEST_DESCRIPTION__EMPTY_LINE[0], TEST_DESCRIPTION__COMMENT__NO_SPACES[0], TEST_DESCRIPTION__SINGLE_LINE_PROPERTIES__EMPTY_VALUE[0], TEST_DESCRIPTION__SINGLE_LINE_PROPERTIES__LEFT_TRIM__EMPTY_VALUE[0] }; - for (String _correctLine:_correctLines) + for (String _correctLine : _correctLines) { doTestCorrectLine(_parser, _correctLine); } @@ -451,6 +452,10 @@ public class TestPropertyParser extends TestCase String _got = dumpStringArray(_listener.myParsedValue); fail("Property value does not match : \nexpected=\n" + _expected + "\ngot=\n" + _got + "\n"); } + String _expected = String.join("\n", expectedValue); + String _got = String.join("\n", _listener.myParsedValue); + assertEquals(_expected, _got); + } private final void doTestSingleLine(String lineToParse, String expectedName, String expectedValue)
fixed : test of multiline property parsing was incomplete
sporniket_core
train
75cfa7ca25516c2c4eb1e189f0467974632d4570
diff --git a/lib/browser/graph.js b/lib/browser/graph.js index <HASH>..<HASH> 100644 --- a/lib/browser/graph.js +++ b/lib/browser/graph.js @@ -1,5 +1,5 @@ require.define('lib/browser/graph', function (require, module) { - var renderer = require('lib/browser/graph/renderer').renderer; + var renderer = require('./graph/renderer').renderer; function drawGraph() { var deps = window.deps,
`browser-require` supports relative pathing.
brentlintner_arctor
train
74855666df9632e0a186fb4b97e79127ead0f594
diff --git a/parameters/__init__.py b/parameters/__init__.py index <HASH>..<HASH> 100644 --- a/parameters/__init__.py +++ b/parameters/__init__.py @@ -165,9 +165,8 @@ class Parameters(object): logger.info('adding %s to configuration files', file_name) - self.configuration_files[file_name] = SafeConfigParser() - if os.access(file_name, os.R_OK): + self.configuration_files[file_name] = SafeConfigParser() self.configuration_files[file_name].read(file_name) else: logger.warn('could not read %s', file_name)
Don't add files to state unless they are accessible. If we can't access a file and read it why would we add it to our list of files to parse?
alunduil_crumbs
train
adedbef33506971f5aafe61f091b518a62f03e0e
diff --git a/cloudcast/iscm/cfninit.py b/cloudcast/iscm/cfninit.py index <HASH>..<HASH> 100644 --- a/cloudcast/iscm/cfninit.py +++ b/cloudcast/iscm/cfninit.py @@ -202,12 +202,16 @@ class CfnInitISCM(object): iscm.iscm_ud_append( "\n".join([ +# r'PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/aws/bin', r'[ -z "`which python`" ] && FATAL 1 "Unable to find python"', r'[ -z "`which pip`" ] && [ ! -x /usr/local/bin/pip ] && { curl -L %s | python; }' % self.get_pip_url, r'PIP_PATH=`which pip`', r'PIP_PATH=${PIP_PATH:-/usr/local/bin/pip}', r'[ ! -x "$PIP_PATH" ] && FATAL 1 "Unable to find/install pip, which is required"', - r'$PIP_PATH install %s || FATAL 1 "Unable to install cfn-init tools"' % self.aws_cfn_bootstrap_url, + r'[ -z "`which cfn-get-metadata`" ] && [ ! -x /usr/local/bin/cfn-get-metadata ] && $PIP_PATH install %s' % self.aws_cfn_bootstrap_url, + r'CFN_GETMETA_PATH=`which cfn-get-metadata`', + r'CFN_GETMETA_PATH=${CFN_GETMETA_PATH:-/usr/local/bin/cfn-get-metadata}', + r'[ ! -x "$CFN_GETMETA_PATH" ] && FATAL 1 "Unable to find cfn-init tools"', ]), "\n", 'export AWS__STACK_NAME="', AWS.StackName ,'" ', diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ from setuptools import setup, find_packages setup( name = "cloudcast", - version = "0.0.8", + version = "0.0.9", packages = find_packages(), package_data = { # Script files that contain initial bootstrap sequences
install cfn tools on bootstrap only if needed - <I>
tuxpiper_cloudcast
train
3e490d6178bd8b01463b6302127d5dd9f028bf1d
diff --git a/includes/session.php b/includes/session.php index <HASH>..<HASH> 100644 --- a/includes/session.php +++ b/includes/session.php @@ -55,7 +55,7 @@ if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCO define ('WT_USE_GOOGLE_API', false); if (WT_USE_GOOGLE_API) { define('WT_JQUERY_URL', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); - define('WT_JQUERYUI_URL', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js'); + define('WT_JQUERYUI_URL', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.19/jquery-ui.min.js'); } else { define('WT_JQUERY_URL', WT_STATIC_URL.'js/jquery/jquery.min.js'); define('WT_JQUERYUI_URL', WT_STATIC_URL.'js/jquery/jquery-ui.min.js');
Update jQuery via CDN to <I>
fisharebest_webtrees
train
020836752b23fc7d6a8fb06382b95767910e7e2a
diff --git a/src/PackageJsonSynchronizer.php b/src/PackageJsonSynchronizer.php index <HASH>..<HASH> 100644 --- a/src/PackageJsonSynchronizer.php +++ b/src/PackageJsonSynchronizer.php @@ -207,7 +207,7 @@ class PackageJsonSynchronizer return null; } - foreach (['/assets', '/Resources/assets'] as $subdir) { + foreach (['/assets', '/Resources/assets', '/src/Resources/assets'] as $subdir) { $packageJsonPath = $packageDir.$subdir.'/package.json'; if (!file_exists($packageJsonPath)) {
Look into vendor's src/Resources/assets for package.json
symfony_flex
train
89789e8210221cb31b5d3d212652a43b510961d5
diff --git a/decidim-core/app/packs/src/decidim/input_character_counter.js b/decidim-core/app/packs/src/decidim/input_character_counter.js index <HASH>..<HASH> 100644 --- a/decidim-core/app/packs/src/decidim/input_character_counter.js +++ b/decidim-core/app/packs/src/decidim/input_character_counter.js @@ -95,6 +95,9 @@ export default class InputCharacterCounter { if (remaining === 1) { message = MESSAGES.charactersLeft.one; } + this.$input[0].dispatchEvent( + new CustomEvent("characterCounter", {detail: {remaining: remaining}}) + ); showMessages.push(message.replace(COUNT_KEY, remaining)); } @@ -118,4 +121,4 @@ $(() => { }); }); -export { InputCharacterCounter, createCharacterCounter }; +export {InputCharacterCounter, createCharacterCounter}; diff --git a/decidim-core/app/packs/src/decidim/input_emoji.js b/decidim-core/app/packs/src/decidim/input_emoji.js index <HASH>..<HASH> 100644 --- a/decidim-core/app/packs/src/decidim/input_emoji.js +++ b/decidim-core/app/packs/src/decidim/input_emoji.js @@ -1,4 +1,4 @@ -import { EmojiButton } from "@joeattardi/emoji-button"; +import {EmojiButton} from "@joeattardi/emoji-button"; // eslint-disable-next-line require-jsdoc export default function addInputEmoji() { @@ -37,9 +37,24 @@ export default function addInputEmoji() { // belong to for Foundation Abide to show them automatically. parent.querySelectorAll(".form-error").forEach((el) => wrapper.appendChild(el)); - btnContainer.addEventListener("click", () => picker.togglePicker(btnContainer)) + let handlerPicker = function () { + picker.togglePicker(btnContainer); + } + + btnContainer.addEventListener("click", handlerPicker); + + elem.addEventListener("characterCounter", (event) => { + if (event.detail.remaining >= 4) { + btnContainer.addEventListener("click", handlerPicker); + btnContainer.removeAttribute("style"); + } else { + btnContainer.removeEventListener("click", handlerPicker); + btnContainer.setAttribute("style", "color:lightgrey"); + } + }); + - picker.on("emoji", ({ emoji }) => { + picker.on("emoji", ({emoji}) => { elem.value += ` ${emoji} ` const event = new Event("emoji.added"); diff --git a/decidim-core/lib/decidim/core/test/shared_examples/comments_examples.rb b/decidim-core/lib/decidim/core/test/shared_examples/comments_examples.rb index <HASH>..<HASH> 100644 --- a/decidim-core/lib/decidim/core/test/shared_examples/comments_examples.rb +++ b/decidim-core/lib/decidim/core/test/shared_examples/comments_examples.rb @@ -132,6 +132,33 @@ shared_examples "comments" do end end end + + it "let the emoji button works properly when there are not too much characters" do + if component.present? + component.update!(settings: { comments_max_length: 100 }) + visit current_path + + within ".add-comment form" do + find(:css, "textarea:enabled").set("toto") + expect(page).not_to have_selector(".emoji-picker__wrapper") + find("svg").click + end + expect(page).to have_selector(".emoji-picker__wrapper") + end + end + + it "deactivate the emoji button when there are less than 4 characters left" do + if component.present? + component.update!(settings: { comments_max_length: 30 }) + visit current_path + + within ".add-comment form" do + find(:css, "textarea:enabled").set("0123456789012345678901234567") + find("svg").click + expect(page).not_to have_selector(".emoji-picker__wrapper") + end + end + end end end
Fix character counter with emoji picker close to maximum characters (#<I>)
decidim_decidim
train
80025072963e4151d48b2b58f5b0060c4466b6d3
diff --git a/geos/mapsource.py b/geos/mapsource.py index <HASH>..<HASH> 100644 --- a/geos/mapsource.py +++ b/geos/mapsource.py @@ -4,6 +4,7 @@ import os from pprint import pprint from geos.geometry import GeographicBB import re +import random F_SEP = "/" # folder separator in mapsources (not necessarily == os.sep) @@ -110,6 +111,7 @@ class MapLayer(object): self.tile_url = tile_url self.min_zoom = min_zoom self.max_zoom = max_zoom + self.server_parts = [] def get_tile_url(self, zoom, x, y): """ @@ -119,8 +121,21 @@ class MapLayer(object): >>> ms.layers[0].get_tile_url(42, 43, 44) 'http://tile.openstreetmap.org/42/43/44.png' """ - return self.tile_url.format(**{"$z": zoom, "$x": x, "$y": y}) + if(len(self.server_parts) == 0): + return self.tile_url.format(**{"$z": zoom, "$x": x, "$y": y}) + else: + return self.tile_url.format(**{"$z": zoom, "$x": x, "$y": y, "$serverpart": random.choice(self.server_parts)}) + @property + def get_tile_urls(self): + if(len(self.server_parts) == 0): + return self.tile_url.replace("$", "") + else: + cur_tile_url = [] + for s in self.server_parts: + cur_tile_url.append(self.tile_url.replace("{$serverpart}", s).replace("$", "")) + return cur_tile_url + def __repr__(self): return "<MapLayer: url:{}, min_zoom:{}, max_zoom:{}>".format( self.tile_url, self.min_zoom, self.max_zoom) @@ -247,6 +262,8 @@ class MapSource(object): map_layer.min_zoom = int(elem.text) elif elem.tag == 'maxZoom': map_layer.max_zoom = int(elem.text) + elif elem.tag == 'serverParts': + map_layer.server_parts += str(elem.text).split() except ValueError: raise MapSourceException("minZoom/maxZoom must be an integer. ") diff --git a/geos/server.py b/geos/server.py index <HASH>..<HASH> 100644 --- a/geos/server.py +++ b/geos/server.py @@ -44,7 +44,7 @@ def maps_json(): { "min_zoom": layer.min_zoom, "max_zoom": layer.max_zoom, - "tile_url": layer.tile_url.replace("$", ""), + "tile_url": layer.get_tile_urls, } for layer in map_source.layers ] diff --git a/geos/static/custom.js b/geos/static/custom.js index <HASH>..<HASH> 100644 --- a/geos/static/custom.js +++ b/geos/static/custom.js @@ -313,7 +313,7 @@ function activateMap(mapSource) { $.each(mapSource.layers, function (i, tileLayer) { tmpLayer = new ol.layer.Tile({ source: new ol.source.XYZ({ - url: tileLayer.tile_url, + urls: tileLayer.tile_url, crossOrigin: null, minZoom: tileLayer.min_zoom, maxZoom: tileLayer.max_zoom
Support serverParts (multiple urls for a map layer) in customMapSource for kml and OpenLayers
grst_geos
train
69eca983e8dadae33346dabcabf818caf5d8fd21
diff --git a/trump/orm.py b/trump/orm.py index <HASH>..<HASH> 100644 --- a/trump/orm.py +++ b/trump/orm.py @@ -1543,7 +1543,7 @@ class SymbolHandle(Base, ReprMixin): symbol = relationship("Symbol") - def __init__(self, chkpnt_settings={}, sym=None): + def __init__(self, chkpnt_settings=None, sym=None): """ Parameters @@ -1560,7 +1560,8 @@ class SymbolHandle(Base, ReprMixin): self.concatenation = rbd or BitFlag(['raise']) self.aggregation = rbd or BitFlag(['stdout']) self.validity_check = rbd or BitFlag(['report']) - + + chkpnt_settings = chkpnt_settings or {} # override with anything passed in settings for checkpoint in chkpnt_settings: if checkpoint in SymbolHandle.__table__.columns: @@ -1590,13 +1591,14 @@ class Index(Base, ReprMixin): kwargs = relationship("IndexKwarg", lazy="dynamic", cascade=ADO) - def __init__(self, name, indimp, case=None, kwargs={}, sym=None): + def __init__(self, name, indimp, case=None, kwargs=None, sym=None): set_symbol_or_symname(self, sym) self.name = name self.indimp = indimp self.case = case or "asis" + kwargs = kwargs or {} self.setkwargs(**kwargs) def setkwargs(self, **kwargs): @@ -2147,7 +2149,7 @@ class FeedHandle(Base, ReprMixin): [Feed.symname, Feed.fnum]) __table_args__ = (fkey, {}) - def __init__(self, chkpnt_settings={}, feed=None): + def __init__(self, chkpnt_settings=None, feed=None): """ :param chkpnt_settings: dict A dictionary with keys matchin names of the handle points @@ -2163,7 +2165,9 @@ class FeedHandle(Base, ReprMixin): self.index_property_problem = rbd or BitFlag(['stdout']) self.data_type_problem = rbd or BitFlag(['stdout', 'report']) self.monounique = rbd or BitFlag(['raise']) - + + chkpnt_settings = chkpnt_settings or {} + # override with anything passed in settings for checkpoint in chkpnt_settings: if checkpoint in FeedHandle.__table__.columns:
Fix default dicts in 3 spots, close GH#<I>
Equitable_trump
train
fc7ca1a10688cb355a69b2db68c428f3841ad7a7
diff --git a/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java b/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java index <HASH>..<HASH> 100644 --- a/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java +++ b/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java @@ -60,6 +60,7 @@ import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.api.model.PodSpecBuilder; import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.QuantityBuilder; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.SecretVolumeSource; @@ -304,6 +305,11 @@ class KubernetesDockerRunner implements DockerRunner { .withName(KEEPALIVE_CONTAINER_NAME) // Use the k8s pause container image. It sleeps forever until terminated. .withImage("k8s.gcr.io/pause:3.1") + .withNewResources() + .addToRequests("cpu", new QuantityBuilder() + .withAmount("0") + .build()) + .endResources() .build(); }
request 0 cpu for keepalive container
spotify_styx
train
277d72fbb022d7afb05dff12dceb3912be282120
diff --git a/src/main/java/org/jcodec/containers/mp4/QTTimeUtil.java b/src/main/java/org/jcodec/containers/mp4/QTTimeUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jcodec/containers/mp4/QTTimeUtil.java +++ b/src/main/java/org/jcodec/containers/mp4/QTTimeUtil.java @@ -92,7 +92,7 @@ public class QTTimeUtil { * @return */ public static long mediaToEdited(TrakBox trak, long mediaTv, int movieTimescale) { - if (trak.getEdits() == null) + if (trak.getEdits() == null || trak.getEdits().isEmpty()) return mediaTv; long accum = 0; for (Edit edit : trak.getEdits()) { diff --git a/src/main/java/org/jcodec/containers/mp4/boxes/MovieBox.java b/src/main/java/org/jcodec/containers/mp4/boxes/MovieBox.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jcodec/containers/mp4/boxes/MovieBox.java +++ b/src/main/java/org/jcodec/containers/mp4/boxes/MovieBox.java @@ -124,18 +124,17 @@ public class MovieBox extends NodeBox { } public TrakBox importTrack(MovieBox movie, TrakBox track) { - TrakBox newTrack = (TrakBox) NodeBox.cloneBox(track, 1024 * 1024, factory); + TrakBox newTrack = (TrakBox) NodeBox.cloneBox(track, track.estimateSize() * 2, factory); List<Edit> edits = newTrack.getEdits(); - - ArrayList<Edit> result = new ArrayList<Edit>(); - if (edits != null) { + if (edits != null && !edits.isEmpty()) { + ArrayList<Edit> result = new ArrayList<Edit>(); for (Edit edit : edits) { result.add(new Edit(rescale(edit.getDuration(), movie.getTimescale()), edit.getMediaTime(), edit .getRate())); } + newTrack.setEdits(result); } - newTrack.setEdits(result); return newTrack; }
[mp4] fixing bug with edits and importTrack
jcodec_jcodec
train
1c72d033473165ade8a126ba64180d76a9212dcd
diff --git a/decoder.go b/decoder.go index <HASH>..<HASH> 100644 --- a/decoder.go +++ b/decoder.go @@ -90,7 +90,7 @@ func (d *Decoder) Decode(dst interface{}, src map[string][]string) error { return d.checkRequired(t, src, "") } -// checkRequired checks whether requred field empty +// checkRequired checks whether required fields are empty // // check type t recursively if t has struct fields, and prefix is same as parsePath: in dotted notation //
fixed typo (#<I>)
gorilla_schema
train
6ca16ae675d70106cf831078dcd88b523b863a5c
diff --git a/epitopes/download.py b/epitopes/download.py index <HASH>..<HASH> 100644 --- a/epitopes/download.py +++ b/epitopes/download.py @@ -1,16 +1,17 @@ -from os import (environ, makedirs, remove) -from os.path import (join, exists, isdir) -from shutil import move import gzip +from os import (environ, makedirs, remove) +from os.path import (join, exists, isdir, splitext) +from shutil import move, rmtree, copyfileobj +from tempfile import NamedTemporaryFile import zipfile - try: - from urllib2 import urlretrieve + from urllib2 import urlretrieve, urlopen except ImportError: - from urllib import urlretrieve + from urllib import urlretrieve, urlopen import appdirs import pandas as pd +from progressbar import ProgressBar DATA_DIR = environ.get("EPITOPES_DATA", appdirs.user_cache_dir("epitopes")) @@ -19,18 +20,29 @@ def fetch_data(filename, download_url): makedirs(DATA_DIR) full_path = join(DATA_DIR, filename) if not exists(full_path): - print "Downloading %s" % download_url + print "Downloading %s" % download_url + + base_name, ext = splitext(filename) + tmp_file = NamedTemporaryFile( + suffix='.' + ext, + prefix = base_name, + delete = False) + tmp_path = tmp_file.name + in_stream = urlopen(download_url) + copyfileobj(in_stream, tmp_file) + in_stream.close() + tmp_file.close() + #tmp_path, _ = urlretrieve(download_url)#, reporthook = report_hook) + if download_url.endswith(("csv", "hdf", "txt")): - urlretrieve(download_url, full_path) + move(tmp_path, full_path) elif download_url.endswith("zip"): - tmp_path, _ = urlretrieve(download_url) print "Decompressing..." with zipfile.ZipFile(tmp_path) as z: extract_path = z.extract(filename) move(extract_path, full_path) remove(tmp_path) elif download_url.endswith("gz"): - tmp_path, _ = urlretrieve(download_url) print "Decompressing..." with gzip.GzipFile(tmp_path) as src: contents = src.read() @@ -38,6 +50,9 @@ def fetch_data(filename, download_url): with open(full_path, 'w') as dst: dst.write(contents) elif download_url.endswith(("html", "htm")): - df = pd.read_html(download_url, header=0, infer_types=False)[0] + df = pd.read_html(tmp_path, header=0, infer_types=False)[0] df.to_csv(full_path, sep=',', index=False, encoding='utf-8') return full_path + +def clear_cache(): + rmtree(DATA_DIR) diff --git a/epitopes/reference.py b/epitopes/reference.py index <HASH>..<HASH> 100644 --- a/epitopes/reference.py +++ b/epitopes/reference.py @@ -1,6 +1,12 @@ +from collections import Counter + +import Bio.SeqIO +import pandas as pd +from progressbar import ProgressBar + from download import fetch_data -def load_reference_peptides(): +def load_peptide_counts(peptide_lengths = [8,9,10,11]): """ List of all reference peptides encoded in a reference human exome """ @@ -10,5 +16,21 @@ def load_reference_peptides(): gz_name = fasta_name + ".gz" full_url = base_url + ftp_dir + gz_name local_path = fetch_data(fasta_name, full_url) + epitope_counts = Counter() with open(local_path, 'r') as f: - print f.read() \ No newline at end of file + seqs = [str(record.seq) for record in Bio.SeqIO.parse(f, "fasta")] + print "Generating substrings" + pbar = ProgressBar(maxval = len(seqs)).start() + for seq_num, seq in enumerate(seqs): + for size in peptide_lengths: + for i in range(len(seq) - size + 1): + epitope_counts[seq[i:i+size]] += 1 + pbar.update(seq_num+1) + pbar.finish() + return pd.DataFrame( + epitopes.most_common(), + columns=["Peptide", "Count"]) + +def load_peptides(peptide_lengths = [8,9,10,11]): + df = load_peptide_counts(peptide_lengths) + return set(df.Peptide) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -51,6 +51,8 @@ if __name__ == '__main__': 'pandas(>=0.13.1)', 'scikit.learn(>=0.14.1)', 'appdirs', + 'progressbar', + 'biopython', ], long_description=readme, packages=['epitopes'],
added progressbars, fixed download, generating substrings for reference
openvax_pepdata
train
a0e02ed974bd127c8ffb586009eb7c049765801d
diff --git a/lib/fakefs/file_test.rb b/lib/fakefs/file_test.rb index <HASH>..<HASH> 100644 --- a/lib/fakefs/file_test.rb +++ b/lib/fakefs/file_test.rb @@ -7,5 +7,9 @@ module FakeFS def self.directory?(file_name) File.directory?(file_name) end + + def self.file?(file_name) + File.file?(file_name) + end end end diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index <HASH>..<HASH> 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -1584,6 +1584,18 @@ class FakeFSTest < Test::Unit::TestCase assert !FileTest.directory?('/path/to/somedir') end + def test_filetest_file_returns_correct_values + path = '/path/to/file.txt' + File.open(path, 'w') { |f| f.write "Yatta!" } + assert FileTest.file?(path) + + FileUtils.rm path + assert !FileTest.file?(path) + + FileUtils.mkdir_p '/path/to/somedir' + assert !FileTest.file?('/path/to/somedir') + end + def test_pathname_exists_returns_correct_value FileUtils.touch "foo" assert Pathname.new("foo").exist?
Added fake FileTest.file? (Closes #<I>)
fakefs_fakefs
train
94b02c8ac3863eacace0abbf182b5ed3c8fa7a16
diff --git a/src/Shell/SendInvoicesShell.php b/src/Shell/SendInvoicesShell.php index <HASH>..<HASH> 100644 --- a/src/Shell/SendInvoicesShell.php +++ b/src/Shell/SendInvoicesShell.php @@ -118,7 +118,9 @@ class SendInvoicesShell extends AppShell $tableData = ''; $sumPrice = 0; + foreach ($manufacturers as $manufacturer) { + $sendInvoice = $this->Manufacturer->getOptionSendInvoice($manufacturer->send_invoice); $invoiceNumber = $this->Manufacturer->Invoices->getNextInvoiceNumber($manufacturer->invoices); $invoiceLink = '/admin/lists/getInvoice?file=' . str_replace( @@ -126,7 +128,9 @@ class SendInvoicesShell extends AppShell $manufacturer->name, $manufacturer->id_manufacturer, Configure::read('app.timeHelper')->formatToDbFormatDate($this->cronjobRunDay), $invoiceNumber ) ); + if (!empty($manufacturer->current_order_count)) { + $price = $manufacturer->order_detail_price_sum; $sumPrice += $price; $variableMemberFeeAsString = ''; @@ -156,13 +160,14 @@ class SendInvoicesShell extends AppShell ); $tableData .= '</td>'; $tableData .= '</tr>'; - $i ++; - } - if (!empty($manufacturer->current_order_count) && $sendInvoice) { + $url = $this->browser->adminPrefix . '/manufacturers/sendInvoice?manufacturerId=' . $manufacturer->id_manufacturer . '&dateFrom=' . $dateFrom . '&dateTo=' . $dateTo; $this->browser->get($url); + $i ++; + } } + if ($tableData != '') { $outString .= '<table class="list no-clone-last-row">'; $outString .= '<tr>';
generate invoices even though they are not sent to manufacturer
foodcoopshop_foodcoopshop
train
350f548e312b7e21511627bdca23e2b9f6dd602a
diff --git a/lib/mixpanel/tracker.rb b/lib/mixpanel/tracker.rb index <HASH>..<HASH> 100644 --- a/lib/mixpanel/tracker.rb +++ b/lib/mixpanel/tracker.rb @@ -20,7 +20,7 @@ module Mixpanel def append_person_event(properties = {}) # evaluate symbols and rewrite - special_properties = %w{email created_at} + special_properties = %w{email created} special_properties.each do |key| symbolized_key = key.to_sym if properties.has_key?(symbolized_key)
fixed special property name in people api
zevarito_mixpanel
train
0b613256e8f66f798d6fd04ed231c1aaa6500e21
diff --git a/src/Pux/RouteRequest.php b/src/Pux/RouteRequest.php index <HASH>..<HASH> 100644 --- a/src/Pux/RouteRequest.php +++ b/src/Pux/RouteRequest.php @@ -14,6 +14,16 @@ use Universal\Http\Request; class RouteRequest implements RouteRequestMatcher { + static $httpHeaderMapping = array( + 'HTTP_ACCEPT' => 'Accept', + 'HTTP_ACCEPT_CHARSET' => 'Accept-Charset', + 'HTTP_ACCEPT_ENCODING' => 'Accept-Encoding', + 'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language', + 'HTTP_CONNECTION' => 'Connection', + 'HTTP_HOST' => 'Host', + 'HTTP_REFERER' => 'Referer', + 'HTTP_USER_AGENT' => 'User-Agent', + ); /** * @var array $headers @@ -230,11 +240,10 @@ class RouteRequest implements RouteRequestMatcher public static function createHeadersFromServerGlobal($server) { $headers = array(); - foreach ($server as $key => $value) { - // we only convert the fields that are with HTTP_ prefix - if (substr($key, 0, 5) == 'HTTP_') { - $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))))] = $value; - } + foreach (self::$httpHeaderMapping as $serverKey => $headerKey) { + if (isset($server[$serverKey])) { + $headers[$headerKey] = $server[$serverKey]; + } } return $headers; }
Define $httpHeaderMapping to reduce key translation and travse
c9s_Pux
train
1e59e50ae48a9f02d00580f173f481e723888c88
diff --git a/tar_transformer.go b/tar_transformer.go index <HASH>..<HASH> 100644 --- a/tar_transformer.go +++ b/tar_transformer.go @@ -136,6 +136,11 @@ func transformZipToTar(path, destPath string) (int64, error) { return 0, err } + err = zr.Close() + if err != nil { + return 0, err + } + err = os.Remove(path) if err != nil { return 0, err
Windows likes its files closed before removing them.
cloudfoundry_cacheddownloader
train
11137f435b6ad9acc51a58005fc3db6dd5cf8c00
diff --git a/models/classes/ExtendedStateService.php b/models/classes/ExtendedStateService.php index <HASH>..<HASH> 100644 --- a/models/classes/ExtendedStateService.php +++ b/models/classes/ExtendedStateService.php @@ -102,7 +102,7 @@ class ExtendedStateService /** * Gets the timer delay * @param string $testSessionId - * @return bool|float + * @return float * @throws \common_exception_InconsistentData */ public function getTimerDelay($testSessionId) @@ -110,7 +110,7 @@ class ExtendedStateService $extra = $this->getExtra($testSessionId); return isset($extra['timer_delay']) ? floatval($extra['timer_delay']) - : false; + : 0; } /** diff --git a/models/classes/runner/QtiRunnerService.php b/models/classes/runner/QtiRunnerService.php index <HASH>..<HASH> 100644 --- a/models/classes/runner/QtiRunnerService.php +++ b/models/classes/runner/QtiRunnerService.php @@ -22,6 +22,8 @@ namespace oat\taoQtiTest\models\runner; +use alroniks\dtms\DateInterval; +use alroniks\dtms\DateTime; use oat\oatbox\service\ConfigurableService; use oat\taoDelivery\model\execution\DeliveryExecution; use oat\taoQtiItem\model\QtiJsonItemCompiler; @@ -971,24 +973,23 @@ class QtiRunnerService extends ConfigurableService implements RunnerService public function updateTimers(RunnerServiceContext $context, $duration) { if ($context instanceof QtiRunnerServiceContext) { + /* @var AssessmentTestSession $session */ $session = $context->getTestSession(); $sessionId = $session->getSessionId(); if($duration > 0){ + $extendedStateService = \taoQtiTest_helpers_TestRunnerUtils::getExtendedStateService(); + $duration += $extendedStateService->getTimerDelay($sessionId); + $delay = fmod($duration, 1); + $duration = floor($duration); + $extendedStateService->setTimerDelay($sessionId, $delay); + $places = AssessmentTestPlace::TEST_PART | AssessmentTestPlace::ASSESSMENT_TEST | AssessmentTestPlace::ASSESSMENT_SECTION; $constraints = $session->getTimeConstraints($places); - foreach ($constraints as $constraint) { - $placeId = $constraint->getSource()->getIdentifier(); $placeDuration = $session[ $placeId . '.duration' ]; if($placeDuration instanceof \qtism\common\datatypes\Duration){ - $extendedStateService = \taoQtiTest_helpers_TestRunnerUtils::getExtendedStateService(); - $delay = $extendedStateService->getTimerDelay($sessionId); - $duration += $delay; - $delay = fmod($duration, 1); - $extendedStateService->setTimerDelay($sessionId, $delay); - //here the duration means: the time spent by a user, so we subtract the given time $placeDuration->sub(new \qtism\common\datatypes\Duration('PT' . $duration . 'S')); }
TestRunner: fix timer delay storage
oat-sa_extension-tao-testqti
train
7dd8e2fe1f4174a8296947b6a12885eec08d7497
diff --git a/src/Weew/HttpClient/Drivers/Curl/ResponseBuilder.php b/src/Weew/HttpClient/Drivers/Curl/ResponseBuilder.php index <HASH>..<HASH> 100644 --- a/src/Weew/HttpClient/Drivers/Curl/ResponseBuilder.php +++ b/src/Weew/HttpClient/Drivers/Curl/ResponseBuilder.php @@ -51,12 +51,6 @@ class ResponseBuilder { $headers = $this->parser->getHeaders($this->response); $content = $this->parser->getContent($this->response); - if (array_get($headers, 'set-cookie')) { - var_dump($this->response); - // foo - var_dump($headers); - } - $httpResponse = new HttpResponse( $this->resource->getOption(CURLINFO_HTTP_CODE), $content,
Done tracking a bug from the php-curl-wrapper package.
weew_http-client
train
8576317cf8ecf0aae1c2280faba6252504c65ccf
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -4,9 +4,10 @@ var React = require('react'); var invariant = require('react/lib/invariant'); var pattern = require('url-pattern'); -function createRouter(component) { +function createRouter(component, environment) { return React.createClass({ + mixins: [environment], propTypes: { path: React.PropTypes.string, @@ -28,8 +29,7 @@ function createRouter(component) { }, navigate: function(path, cb) { - window.history.pushState({}, '', path); - var path = window.location.pathname; + this.updatePath(path); this.setState({match: this.matchPath(path)}, cb); }, @@ -44,7 +44,7 @@ function createRouter(component) { ); path = this.props.path || match.match._[0]; } else { - path = this.props.path || window.location.pathname; + path = this.props.path || this.getPath(); } if (path[0] !== '/') { @@ -56,22 +56,6 @@ function createRouter(component) { }; }, - componentDidMount: function() { - window.addEventListener('popstate', this.onPopState); - }, - - componentWillUnmount: function() { - window.removeEventListener('popstate', this.onPopState); - }, - - onPopState: function(e) { - var path = window.location.pathname; - - if (this.state.match.path !== path) { - this.setState({match: this.matchPath(path)}); - } - }, - getMatch: function() { return this.state.match; }, @@ -132,6 +116,80 @@ function getChildren() { } /** + * Router environment mixin for routers which handles History API. + */ +var HistoryAPIRouterEnvironment = { + + getPath: function() { + return window.location.pathname; + }, + + updatePath: function(path) { + window.history.pushState({}, '', path); + }, + + componentDidMount: function() { + window.addEventListener('popstate', this.onPopState); + }, + + componentWillUnmount: function() { + window.removeEventListener('popstate', this.onPopState); + }, + + onPopState: function(e) { + var path = window.location.pathname; + + if (this.state.match.path !== path) { + this.setState({match: this.matchPath(path)}); + } + } +}; + +/** + * Router environment mixin for routers which handles hashchange event. + */ +var HashChangeRouterEnvironment = { + + getPath: function() { + return window.location.hash; + }, + + updatePath: function(path) { + window.location.hash = path; + }, + + componentDidMount: function() { + window.addEventListener('hashchange', this.onHashChange); + }, + + componentWillUnmount: function() { + window.removeEventListener('hashchange', this.onHashChange); + }, + + onHashChange: function() { + var path = window.location.hash; + + if (this.state.match.path !== path) { + this.setState({match: this.matchPath(path)}); + } + } +}; + +function Route(props, handler) { + invariant( + typeof props.handler === 'function' || typeof handler === 'function', + "Route handler should be a template"); + return {path: props.path, handler: props.handler || handler}; +} + +function NotFound(props, handler) { + invariant( + typeof props.handler === 'function' || typeof handler === 'function', + "NotFound handler should be a template"); + return {path: null, handler: props.handler || handler}; +} + +/** * A component which can navigate to a different route. */ var NavigatableMixin = { @@ -145,6 +203,11 @@ var NavigatableMixin = { } }; +/** + * A basic navigatable component which renders into <a> DOM element and handles + * onClick event by transitioning onto different route (defined by + * this.props.href). + */ var Link = React.createClass({ mixins: [NavigatableMixin], @@ -164,26 +227,23 @@ var Link = React.createClass({ } }); -function Route(props, handler) { - invariant( - typeof props.handler === 'function' || typeof handler === 'function', - "Route handler should be a template"); - return {path: props.path, handler: props.handler || handler}; -} +module.exports = { -function NotFound(props, handler) { - invariant( - typeof props.handler === 'function' || typeof handler === 'function', - "NotFound handler should be a template"); - return {path: null, handler: props.handler || handler}; -} + HashChange: { + Pages: createRouter(React.DOM.body, HashChangeRouterEnvironment), + Page: Route, -module.exports = { + Locations: createRouter(React.DOM.div, HashChangeRouterEnvironment), + Location: Route, + + NotFound: NotFound, + Link: Link + }, - Pages: createRouter(React.DOM.body), + Pages: createRouter(React.DOM.body, HistoryAPIRouterEnvironment), Page: Route, - Locations: createRouter(React.DOM.div), + Locations: createRouter(React.DOM.div, HistoryAPIRouterEnvironment), Location: Route, NotFound: NotFound,
Move History API out to a mixin Also add support for hashchange router.
STRML_react-router-component
train
d7c43bedc5144917d1a3f1e5514f614d67a61596
diff --git a/templates/client/html/catalog/filter/tree-partial.php b/templates/client/html/catalog/filter/tree-partial.php index <HASH>..<HASH> 100644 --- a/templates/client/html/catalog/filter/tree-partial.php +++ b/templates/client/html/catalog/filter/tree-partial.php @@ -100,7 +100,7 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] ); <?php $params = array_merge( $this->get( 'params', [] ), ['f_name' => $item->getName( 'url' ), 'f_catid' => $item->getId()] ) ?> <div class="cat-item catid-<?= $enc->attr( $item->getId() . - ( $item->hasChildren() ? ' withchild' : ' nochild' ) . + ( !$item->getChildren()->isEmpty() ? ' withchild' : ' nochild' ) . ( $this->get( 'path', map() )->has( $item->getId() ) ? ' active' : '' ) . ' catcode-' . $item->getCode() . ' ' . $item->getConfigValue( 'css-class' ) ) ?>" data-id="<?= $item->getId() ?>"> @@ -109,7 +109,7 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] ); <a class="col-10 name" href="<?= $enc->attr( $this->url( $item->getTarget() ?: $target, $controller, $action, $params, [], $config ) ) ?>"> <?= $enc->html( $item->getName(), $enc::TRUST ) ?> </a> - <?php if( $item->hasChildren() ) : ?> + <?php if( !$item->getChildren()->isEmpty() ) : ?> <div class="col-2 next" data-submenu="<?= $enc->attr( $item->getId() ) ?>" title="<?= $enc->attr( $this->translate( 'client', 'Open submenu' ) ) ?>"> </div> @@ -135,7 +135,7 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] ); <div id="<?= $enc->attr( $item->getId() ) ?>" class="submenu <?= $enc->attr( ( $this->get( 'path', map() )->has( $item->getId() ) ? ' active opened' : '' ) ) . - ( $item->hasChildren() ? ' withchild' : ' nochild' ) ?>" + ( !$item->getChildren()->isEmpty() ? ' withchild' : ' nochild' ) ?>" data-id="<?= $item->getId() ?>"> <div class="row header">
Avoid wrong styling if not sub-categories are available in catalog filter tree
aimeos_ai-client-html
train
26200929c16d6fc831d8a39843b581fbb7e774e3
diff --git a/command/agent/config.go b/command/agent/config.go index <HASH>..<HASH> 100644 --- a/command/agent/config.go +++ b/command/agent/config.go @@ -815,7 +815,7 @@ func (c *Config) HTTPAddrs() ([]ProtoAddr, error) { } addrs = append(addrs, ProtoAddr{"http", a.Network(), a.String()}) } - if c.Ports.HTTPS > 0 { + if c.Ports.HTTPS > 0 && c.CertFile != "" && c.KeyFile != "" { a, err := c.ClientListener(c.Addresses.HTTPS, c.Ports.HTTPS) if err != nil { return nil, err
agent: start HTTPS only if there is a cert and key
hashicorp_consul
train
da7e85ff009308e316b478c14be99ed06af4b91d
diff --git a/template/template.go b/template/template.go index <HASH>..<HASH> 100644 --- a/template/template.go +++ b/template/template.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io" - "os" "strings" "time" "unicode" @@ -75,8 +74,8 @@ func toDatetime(timestamp float64, layout, zone string) string { } loc, err := time.LoadLocation(zone) if err != nil { - fmt.Printf("Error parsing timezone. %s\n", err) - os.Exit(1) + fmt.Printf("Error parsing timezone, defaulting to local timezone. %s\n", err) + return time.Unix(int64(timestamp), 0).Local().Format(layout) } return time.Unix(int64(timestamp), 0).In(loc).Format(layout) }
defaulting to local timezone if one cannot be found or parsed
drone_drone-go
train
c04b68b1b6ad11447a518869a7a9ba04212a32d7
diff --git a/lib/OpenLayers/Map.js b/lib/OpenLayers/Map.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Map.js +++ b/lib/OpenLayers/Map.js @@ -105,8 +105,8 @@ OpenLayers.Map.prototype = { /** * APIProperty: baseLayer - * {<OpenLayers.Layer>} The currently selected base layer - this determines - * min/max zoom level, projection, etc. + * {<OpenLayers.Layer>} The currently selected base layer. This determines + * min/max zoom level, projection, etc. */ baseLayer: null,
replace hyphen with period in comments - ND is greedy about hyphens. This fixes the doc bit for map.baseLayer git-svn-id: <URL>
openlayers_openlayers
train
ec8b10ad980949e8743b51b44963dc0c15ebf1ea
diff --git a/src/Methods/CopyMethod.php b/src/Methods/CopyMethod.php index <HASH>..<HASH> 100644 --- a/src/Methods/CopyMethod.php +++ b/src/Methods/CopyMethod.php @@ -24,6 +24,10 @@ class CopyMethod implements ExposeMethod public function exposeDirectory($source, $target) { + // Skip if symlink + if ($this->filesystem->isSymlinkedDirectory($target)) { + return; + } if (!$this->filesystem->copy($source, $target)) { throw new RuntimeException("Could not write to directory $target"); } diff --git a/src/Methods/SymlinkMethod.php b/src/Methods/SymlinkMethod.php index <HASH>..<HASH> 100644 --- a/src/Methods/SymlinkMethod.php +++ b/src/Methods/SymlinkMethod.php @@ -26,7 +26,13 @@ class SymlinkMethod implements ExposeMethod { $parent = dirname($target); $this->filesystem->ensureDirectoryExists($parent); - if (!$this->filesystem->relativeSymlink($target, $source)) { + + // Delete target if exists + if (file_exists($target)) { + $this->filesystem->removeDirectory($target); + } + // Ensure symlink exists + if (!$this->filesystem->relativeSymlink($source, $target)) { throw new RuntimeException("Could not create symlink at $target"); } }
Fix symlinking and copying logic
silverstripe_vendor-plugin
train
1653f85edbe22bdccb6f4822b4678d6f8c431eb7
diff --git a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/AvailabilityHandler.java b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/AvailabilityHandler.java index <HASH>..<HASH> 100644 --- a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/AvailabilityHandler.java +++ b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/AvailabilityHandler.java @@ -186,8 +186,10 @@ public class AvailabilityHandler extends MetricsServiceHandler implements IMetri @DELETE @Path("/{id}") - @ApiOperation(value = "Deletes the metric and associated data points, and updates internal indexes." - + " Note: compressed data will not be deleted and still be accessible.") + @ApiOperation(value = "Deletes the metric and associated uncompressed data points, and updates internal indexes." + + " Note: compressed data will not be deleted immediately. It is deleted as part of the normal" + + " data expiration as defined by the data retention settings. Consequently, compressed data will" + + " be accessible until it automatically expires.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric deletion was successful."), @ApiResponse(code = 500, message = "Unexpected error occurred trying to delete the metric.") diff --git a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java index <HASH>..<HASH> 100644 --- a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java +++ b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java @@ -193,8 +193,10 @@ public class CounterHandler extends MetricsServiceHandler implements IMetricsHan @DELETE @Path("/{id}") - @ApiOperation(value = "Deletes the metric and associated data points, and updates internal indexes." - + " Note: compressed data will not be deleted and still be accessible.") + @ApiOperation(value = "Deletes the metric and associated uncompressed data points, and updates internal indexes." + + " Note: compressed data will not be deleted immediately. It is deleted as part of the normal" + + " data expiration as defined by the data retention settings. Consequently, compressed data will" + + " be accessible until it automatically expires.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric deletion was successful."), @ApiResponse(code = 500, message = "Unexpected error occurred trying to delete the metric.") diff --git a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/GaugeHandler.java b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/GaugeHandler.java index <HASH>..<HASH> 100644 --- a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/GaugeHandler.java +++ b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/GaugeHandler.java @@ -192,8 +192,10 @@ public class GaugeHandler extends MetricsServiceHandler implements IMetricsHandl @DELETE @Path("/{id}") - @ApiOperation(value = "Deletes the metric and associated data points, and updates internal indexes." - + " Note: compressed data will not be deleted and still be accessible.") + @ApiOperation(value = "Deletes the metric and associated uncompressed data points, and updates internal indexes." + + " Note: compressed data will not be deleted immediately. It is deleted as part of the normal" + + " data expiration as defined by the data retention settings. Consequently, compressed data will" + + " be accessible until it automatically expires.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric deletion was successful."), @ApiResponse(code = 500, message = "Unexpected error occurred trying to delete the metric.") diff --git a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/StringHandler.java b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/StringHandler.java index <HASH>..<HASH> 100644 --- a/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/StringHandler.java +++ b/api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/StringHandler.java @@ -174,8 +174,10 @@ public class StringHandler extends MetricsServiceHandler implements IMetricsHand @DELETE @Path("/{id}") - @ApiOperation(value = "Deletes the metric and associated data points, and updates internal indexes." - + " Note: compressed data will not be deleted and still be accessible.") + @ApiOperation(value = "Deletes the metric and associated uncompressed data points, and updates internal indexes." + + " Note: compressed data will not be deleted immediately. It is deleted as part of the normal" + + " data expiration as defined by the data retention settings. Consequently, compressed data will" + + " be accessible until it automatically expires.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric deletion was successful."), @ApiResponse(code = 500, message = "Unexpected error occurred trying to delete the metric.")
[HWKMETRICS-<I>] Make further clarifications about the deletion of compressed data.
hawkular_hawkular-metrics
train
c8519ad540580c2693557f4d27439a226ccb42a8
diff --git a/modules/custom/openy_calc/js/openy_calc.js b/modules/custom/openy_calc/js/openy_calc.js index <HASH>..<HASH> 100644 --- a/modules/custom/openy_calc/js/openy_calc.js +++ b/modules/custom/openy_calc/js/openy_calc.js @@ -15,4 +15,15 @@ } }; + /** + * To close the alert Modals dialog. + */ + Drupal.behaviors.openyAlertModalsClose = { + attach: function (context, settings) { + $('.alert-modal .close').on('click', function (e) { + e.preventDefault(); + $(this).closest('.alert-modal').remove(); + }); + } + }; })(jQuery);
[MAINTAIN-<I>] fixed issue with not working modal dialog on membership (/join) page on Carnation theme
ymcatwincities_openy
train
6235bd825b9951fae07afbd5c836a5c761dd7ec6
diff --git a/cmd/data-usage-cache.go b/cmd/data-usage-cache.go index <HASH>..<HASH> 100644 --- a/cmd/data-usage-cache.go +++ b/cmd/data-usage-cache.go @@ -528,7 +528,7 @@ type objectIO interface { // Only backend errors are returned as errors. // If the object is not found or unable to deserialize d is cleared and nil error is returned. func (d *dataUsageCache) load(ctx context.Context, store objectIO, name string) error { - r, err := store.GetObjectNInfo(ctx, dataUsageBucket, name, nil, http.Header{}, noLock, ObjectOptions{}) + r, err := store.GetObjectNInfo(ctx, dataUsageBucket, name, nil, http.Header{}, readLock, ObjectOptions{}) if err != nil { switch err.(type) { case ObjectNotFound:
Grab read lock while reading usage cache (#<I>)
minio_minio
train
f361d443b7d4e77a3da22112b5ab6426bec4f6f4
diff --git a/registry/proxy/proxyblobstore.go b/registry/proxy/proxyblobstore.go index <HASH>..<HASH> 100644 --- a/registry/proxy/proxyblobstore.go +++ b/registry/proxy/proxyblobstore.go @@ -72,13 +72,8 @@ func (pbs *proxyBlobStore) serveLocal(ctx context.Context, w http.ResponseWriter return false, nil } - if err == nil { - proxyMetrics.BlobPush(uint64(localDesc.Size)) - return true, pbs.localStore.ServeBlob(ctx, w, r, dgst) - } - - return false, nil - + proxyMetrics.BlobPush(uint64(localDesc.Size)) + return true, pbs.localStore.ServeBlob(ctx, w, r, dgst) } func (pbs *proxyBlobStore) storeLocal(ctx context.Context, dgst digest.Digest) error {
clean up code because err is always nil
docker_distribution
train
036bd8fb5ca56085bee656a1ede23a4f608f89ac
diff --git a/server.js b/server.js index <HASH>..<HASH> 100644 --- a/server.js +++ b/server.js @@ -98,61 +98,73 @@ app.get('/', (req, res) => { app.get('/components/:component', (req, res) => { const glob = `consumables/html/components/${req.params.component}/**/*.html`; - Promise.all([getContent(glob), allLinks]) - .then(results => { - if (typeof results[0] === 'undefined') { - res.status(404).end(); - } else { - res.render('demo-all', { - html: results[0], - links: results[1] - }); - } - }) - .catch((error) => { - console.error(error.stack); // eslint-disable-line no-console - res.status(500).end(); - }); + if (path.relative('consumables/html/components', glob).substr(0, 2) === '..') { + res.status(404).end(); + } else { + Promise.all([getContent(glob), allLinks]) + .then(results => { + if (typeof results[0] === 'undefined') { + res.status(404).end(); + } else { + res.render('demo-all', { + html: results[0], + links: results[1] + }); + } + }) + .catch((error) => { + console.error(error.stack); // eslint-disable-line no-console + res.status(500).end(); + }); + } }); app.get('/base-elements/:component', (req, res) => { const glob = `consumables/html/base-elements/${req.params.component}/**/*.html`; - Promise.all([getContent(glob), allLinks]) - .then(results => { - if (typeof results[0] === 'undefined') { - res.status(404).end(); - } else { - res.render('demo-all', { - html: results[0], - links: results[1] - }); - } - }) - .catch((error) => { - console.error(error.stack); // eslint-disable-line no-console - res.status(500).end(); - }); + if (path.relative('consumables/html/base-elements', glob).substr(0, 2) === '..') { + res.status(404).end(); + } else { + Promise.all([getContent(glob), allLinks]) + .then(results => { + if (typeof results[0] === 'undefined') { + res.status(404).end(); + } else { + res.render('demo-all', { + html: results[0], + links: results[1] + }); + } + }) + .catch((error) => { + console.error(error.stack); // eslint-disable-line no-console + res.status(500).end(); + }); + } }); app.get('/global/:component', (req, res) => { const glob = `consumables/html/global/${req.params.component}/**/*.html`; - Promise.all([getContent(glob), allLinks]) - .then(results => { - if (typeof results[0] === 'undefined') { - res.status(404).end(); - } else { - res.render('demo-all', { - html: results[0], - links: results[1] - }); - } - }) - .catch((error) => { - console.error(error.stack); // eslint-disable-line no-console - res.status(500).end(); - }); + if (path.relative('consumables/html/global', glob).substr(0, 2) === '..') { + res.status(404).end(); + } else { + Promise.all([getContent(glob), allLinks]) + .then(results => { + if (typeof results[0] === 'undefined') { + res.status(404).end(); + } else { + res.render('demo-all', { + html: results[0], + links: results[1] + }); + } + }) + .catch((error) => { + console.error(error.stack); // eslint-disable-line no-console + res.status(500).end(); + }); + } }); app.listen(port, () => {
Prevent request for component test page not in the directory for that. (#<I>)
carbon-design-system_carbon-components
train
515d7548cba62ded398b1687945091430d9d3d65
diff --git a/src/main/java/io/github/classgraph/ClassGraph.java b/src/main/java/io/github/classgraph/ClassGraph.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/classgraph/ClassGraph.java +++ b/src/main/java/io/github/classgraph/ClassGraph.java @@ -86,7 +86,7 @@ public class ClassGraph { * * @return the ClassGraph version, or "unknown" if it could not be determined. */ - public static final String getVersion() { + public static String getVersion() { return VersionFinder.getVersion(); } diff --git a/src/main/java/io/github/classgraph/utils/VersionFinder.java b/src/main/java/io/github/classgraph/utils/VersionFinder.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/classgraph/utils/VersionFinder.java +++ b/src/main/java/io/github/classgraph/utils/VersionFinder.java @@ -105,7 +105,7 @@ public class VersionFinder { /** * @return the version number of ClassGraph. */ - public static final synchronized String getVersion() { + public static synchronized String getVersion() { // Try to get version number from pom.xml (available when running in Eclipse) final Class<?> cls = ClassGraph.class; try {
final static When a static method is overridden in a subclass it can still be accessed via the super class, making a final declaration not very necessary. Declaring a static method final does prevent subclasses from defining a static method with the same signature.
classgraph_classgraph
train
1e8ef0f4285d86de7aba8a74fe00562745c9f8b4
diff --git a/src/forms/UserFormFactory.php b/src/forms/UserFormFactory.php index <HASH>..<HASH> 100644 --- a/src/forms/UserFormFactory.php +++ b/src/forms/UserFormFactory.php @@ -46,6 +46,8 @@ class UserFormFactory public function create($userId) { $defaults = []; + $user = null; + if (isset($userId)) { $user = $this->userRepository->find($userId); $defaults = $user->toArray(); @@ -92,7 +94,7 @@ class UserFormFactory /** @var UserFormDataProviderInterface[] $providers */ $providers = $this->dataProviderManager->getProviders('users.dataprovider.user_form', UserFormDataProviderInterface::class); foreach ($providers as $sorting => $provider) { - $form = $provider->provide(['form' => $form]); + $form = $provider->provide(['form' => $form, 'user' => $user]); } $form->addGroup($this->translator->translate('users.admin.user_form.other'));
Finalizing extraction of invoices from user form remp/crm#<I>
remp2020_crm-users-module
train
a126b06a1dcbc3eacd519278b3007b04660f5606
diff --git a/executor/ddl_test.go b/executor/ddl_test.go index <HASH>..<HASH> 100644 --- a/executor/ddl_test.go +++ b/executor/ddl_test.go @@ -1526,3 +1526,14 @@ func (s *testRecoverTable) TestRenameMultiTables(c *C) { tk.MustExec("drop database rename2") tk.MustExec("drop database rename3") } + +// See https://github.com/pingcap/tidb/issues/24582 +func (s *testSuite6) TestDuplicatedEntryErr(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1;") + tk.MustExec("create table t1(a int, b varchar(20), primary key(a,b(3)) clustered);") + tk.MustExec("insert into t1 values(1,'aaaaa');") + _, err := tk.Exec("insert into t1 values(1,'aaaaa');") + c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-aaa' for key 'PRIMARY'") +} diff --git a/store/driver/txn/error.go b/store/driver/txn/error.go index <HASH>..<HASH> 100644 --- a/store/driver/txn/error.go +++ b/store/driver/txn/error.go @@ -94,6 +94,9 @@ func extractKeyExistsErrFromHandle(key kv.Key, value []byte, tblInfo *model.Tabl if err != nil { return genKeyExistsError(name, key.String(), err) } + if col.Length > 0 { + str = str[:col.Length] + } valueStr = append(valueStr, str) } return genKeyExistsError(name, strings.Join(valueStr, "-"), nil)
ddl: the clustered index primary key conflict prompt information is not an index value (#<I>)
pingcap_tidb
train
782ca9b9e90578b4b08b1c2e332b949ace45259a
diff --git a/test/representer_computer_test.rb b/test/representer_computer_test.rb index <HASH>..<HASH> 100644 --- a/test/representer_computer_test.rb +++ b/test/representer_computer_test.rb @@ -96,7 +96,7 @@ class RepresenterComputerTest < MiniTest::Spec it "returns nil when not present" do skip "not sure what to do when format is unknown" - subject.for(:xml, Object.new, "bands").must_equal nil + subject.for(:xml, Class.new.new, "bands").must_equal nil end end end \ No newline at end of file
make test break when format is unknown.
apotonick_roar-rails
train
9eb1ef132f57a311e7ae0a8a529c499b6550404d
diff --git a/core-bundle/src/Resources/contao/library/Contao/User.php b/core-bundle/src/Resources/contao/library/Contao/User.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/Resources/contao/library/Contao/User.php +++ b/core-bundle/src/Resources/contao/library/Contao/User.php @@ -553,7 +553,7 @@ abstract class User extends \System { $time = time(); - // Regenerate a new session id to harden against session fixation attacks. + // Regenerate the session id to harden against session fixation attacks session_regenerate_id(); // Generate the cookie hash
[Core] Fix a comment.
contao_contao
train
02a092876f0b6e83ddeec43b3987afc1b16da549
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ setup( "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development", ],
Updated python version in classifiers
pydanny_cookiecutter-django
train
81a07602a9303fddb1763641e945026b76661f93
diff --git a/Excel/Reader.php b/Excel/Reader.php index <HASH>..<HASH> 100644 --- a/Excel/Reader.php +++ b/Excel/Reader.php @@ -1676,7 +1676,7 @@ class sb_Excel_Reader extends sb_Excel_ReaderBackend{ $val = $this->val($row,$col,$sheet); if ($val=='') { $val="&nbsp;"; } else { - $val = htmlentities($val); + $link = $this->hyperlink($row,$col,$sheet); if ($link!='') { $val = "<a href=\"$link\">$val</a>";
no longer uses htmlentities when dumping
surebert_surebert-framework
train
1a0842a79068887928b164c6adfbe5527fb66248
diff --git a/spec/controllers/no_response_if_performed_spec.rb b/spec/controllers/no_response_if_performed_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/no_response_if_performed_spec.rb +++ b/spec/controllers/no_response_if_performed_spec.rb @@ -3,46 +3,34 @@ require File.expand_path(File.join(File.dirname(__FILE__), '../spec_helper')) module NoResponseIfPerformedSpec # example setup class TheController < ActionController::Base - before_filter :redirect + before_filter :do_redirect response_for :an_action do |format| - format.html { in_response_for } + format.html { render :text => "in response for" } end protected - def redirect + def do_redirect redirect_to 'http://redirected.from.before_filter' end - - def in_response_for; end end describe TheController do - describe "when before_filter redirects, GET :an_action" do - it "should redirect to 'http://redirected.from.before_filter'" do + describe "(when before_filter redirects)" do + it "GET :an_action should redirect to 'http://redirected.from.before_filter'" do get :an_action response.should redirect_to('http://redirected.from.before_filter') end - - it "should not execute inside response_for" do - @controller.should_not_receive :in_response_for - get :an_action - end end - describe "when before_filter doesn't redirect, GET :an_action" do + describe "(when before_filter doesn't redirect)" do before do - @controller.stub!(:redirect) - end - - it "should execute inside response for" do - @controller.should_receive :in_response_for - get :an_action + @controller.stub!(:do_redirect) end - it "should render :an_action" do + it "GET :an_action should execute inside response for" do get :an_action - response.should render_template(:an_action) + response.body.should == 'in response for' end end end
Simplify spec, less method tracing, more response checking
ianwhite_response_for
train
1b3f7edb82d61cd7b523f7434b7ce5dfdb5c06fa
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -10,7 +10,7 @@ module.exports = function (object, path, defaultValue) { // A) If the path is an array, we can just use that // B) If the path is a string, convert it into an array using migrating // array-style `[foo]` accessors into object-style `.foo` accessors - const cleanPath = Object(path) === path + const cleanPath = Array.isArray(path) ? path : path.replace(regexCloseSquareBracket, '').replace(regexOpenSquareBracket, '.').split('.')
Use Array.isArray (~<I>% speed improvement for strings)
queicherius_fast-get
train
f9097027af2a912555c429e85fd0fbf442678d20
diff --git a/therapist/cli.py b/therapist/cli.py index <HASH>..<HASH> 100644 --- a/therapist/cli.py +++ b/therapist/cli.py @@ -67,7 +67,7 @@ def install(**kwargs): colorama.init(strip=kwargs.get('no_color')) stdout = subprocess.check_output('which therapist', shell=True) - therapist_bin = stdout.split()[0] + therapist_bin = stdout.decode('utf-8').split()[0] git_dir = current_git_dir()
Fix encoding issue in Py3
rehandalal_therapist
train
8fbe92052894b73fff48c23d55515ed2d0c880c3
diff --git a/src/main/java/org/thymeleaf/dom/NestableNode.java b/src/main/java/org/thymeleaf/dom/NestableNode.java index <HASH>..<HASH> 100755 --- a/src/main/java/org/thymeleaf/dom/NestableNode.java +++ b/src/main/java/org/thymeleaf/dom/NestableNode.java @@ -217,7 +217,16 @@ public abstract class NestableNode extends Node { } newChild.parent = this; - + + if (getProcessTextNodes()) { + // If we are already processing text nodes, we must make sure the new child also does + newChild.setProcessTextNodes(getProcessTextNodes()); + } + if (getProcessCommentNodes()) { + // If we are already processing comment nodes, we must make sure the new child also does + newChild.setProcessCommentNodes(getProcessCommentNodes()); + } + } } @@ -283,7 +292,16 @@ public abstract class NestableNode extends Node { } newChild.parent = this; - + + if (getProcessTextNodes()) { + // If we are already processing text nodes, we must make sure the new child also does + newChild.setProcessTextNodes(getProcessTextNodes()); + } + if (getProcessCommentNodes()) { + // If we are already processing comment nodes, we must make sure the new child also does + newChild.setProcessCommentNodes(getProcessCommentNodes()); + } + } }
Fixes #<I>. Flags for processing text and comment nodes not being correctly propagated to new children.
thymeleaf_thymeleaf
train
47ca5dd4fe4ef74499fab0fd1900d8ce040c964c
diff --git a/lib/refile/file.rb b/lib/refile/file.rb index <HASH>..<HASH> 100644 --- a/lib/refile/file.rb +++ b/lib/refile/file.rb @@ -83,6 +83,16 @@ module Refile @io = nil end + # Prevent from exposing secure information unexpectedly + # + # @return [Hash] + def as_json(options={}) + { + id: id, + backend: backend.to_s + } + end + private def io
Prevent from exposing secure information unexpectedly
refile_refile
train
de57e13285c173e1d93d77ccc5e8056c34185588
diff --git a/billy/utils/__init__.py b/billy/utils/__init__.py index <HASH>..<HASH> 100644 --- a/billy/utils/__init__.py +++ b/billy/utils/__init__.py @@ -109,7 +109,7 @@ def textual_diff(l1, l2): # fixing bill ids _bill_id_re = re.compile(r'([A-Z]*)\s*0*([-\d]+)') -_mi_bill_id_re = re.compile(r'(SJR|HJR)\s*(\w+)') +_mi_bill_id_re = re.compile(r'(SJR|HJR)\s*([A-Z]+)') def fix_bill_id(bill_id): bill_id = bill_id.replace('.', '')
limit MI regex a bit more
openstates_billy
train
9d678a5a2db9357c240e4b10270835fdf42e7393
diff --git a/src/com/mebigfatguy/fbcontrib/utils/OpcodeUtils.java b/src/com/mebigfatguy/fbcontrib/utils/OpcodeUtils.java index <HASH>..<HASH> 100644 --- a/src/com/mebigfatguy/fbcontrib/utils/OpcodeUtils.java +++ b/src/com/mebigfatguy/fbcontrib/utils/OpcodeUtils.java @@ -122,7 +122,7 @@ public class OpcodeUtils implements Constants { } public static boolean isReturn(int seen) { - return ((seen == ARETURN) || (seen == IRETURN) || (seen == LRETURN) || (seen == FRETURN) || (seen == DRETURN)); + return ((seen == ARETURN) || (seen == IRETURN) || (seen == LRETURN) || (seen == FRETURN) || (seen == DRETURN) || (seen == RETURN)); } }
fix isReturn, to include plain RETURN
mebigfatguy_fb-contrib
train
667e9651024c2b0991538aac6ebd2b8766ee7093
diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index <HASH>..<HASH> 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -1730,8 +1730,8 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err // Setting the encryption key type to "Service" in PUT. The following GET will not return the queue/table in the service list of its response. // So defaults to setting the encryption key type to "Service" if it is absent in the GET response. Also, define the default value as "Service" in the schema. var ( - queueEncryptionKeyType = "Service" - tableEncryptionKeyType = "Service" + queueEncryptionKeyType = string(storage.KeyTypeService) + tableEncryptionKeyType = string(storage.KeyTypeService) ) if encryption := props.Encryption; encryption != nil && encryption.Services != nil { if encryption.Services.Queue != nil {
Update internal/services/storage/storage_account_resource.go
terraform-providers_terraform-provider-azurerm
train
78ee4b9a7e30690b65b293800c9fdb660dc3a6eb
diff --git a/app/models/mercator_mesonic/webartikel.rb b/app/models/mercator_mesonic/webartikel.rb index <HASH>..<HASH> 100644 --- a/app/models/mercator_mesonic/webartikel.rb +++ b/app/models/mercator_mesonic/webartikel.rb @@ -44,7 +44,7 @@ module MercatorMesonic @product = webartikel.import_and_return_product if @product.save JobLogger.info("Saving Product " + @product.id.to_s + " " + - @product.number + "succeeded.") + @product.number + " succeeded.") else JobLogger.error("Saving Product " + @product.number + " failed: " + @product.errors.first.to_s) @@ -73,7 +73,7 @@ module MercatorMesonic @inventories = Inventory.all end @inventories.each do |inventory| - if Webartikel.where(Artikelnummer: inventory.number).count == 0 + if Webartikel.where(Artikelnummer: [inventory.number, inventory.product.number]).count == 0 inventory.destroy \ or JobLogger.error("Deleting Inventory failed: " + inventory.errors.first) end
bugfix if inventory number <> product number, check both for removing orphans
informatom_mercator_mesonic
train
d56d8ae62ee2c2aa0e7f3d25419f86a5fe986d0c
diff --git a/lib/components/narrative/default/default-itinerary.js b/lib/components/narrative/default/default-itinerary.js index <HASH>..<HASH> 100644 --- a/lib/components/narrative/default/default-itinerary.js +++ b/lib/components/narrative/default/default-itinerary.js @@ -8,10 +8,11 @@ import FieldTripGroupSize from '../../admin/field-trip-itinerary-group-size' import NarrativeItinerary from '../narrative-itinerary' import ItineraryBody from '../line-itin/connected-itinerary-body' import SimpleRealtimeAnnotation from '../simple-realtime-annotation' +import { getTotalFare } from '../../../util/state' import ItinerarySummary from './itinerary-summary' -const { calculateFares, isBicycle, isMicromobility, isTransit } = coreUtils.itinerary +const { isBicycle, isMicromobility, isTransit } = coreUtils.itinerary /** * Obtains the description of an itinerary in the given locale. @@ -125,14 +126,12 @@ const ITINERARY_ATTRIBUTES = [ id: 'cost', order: 2, render: (itinerary, options) => { - // Get unformatted transit fare portion only (in cents). - const { transitFare } = calculateFares(itinerary) return ( <FormattedNumber currency={options.currency} currencyDisplay='narrowSymbol' style='currency' - value={transitFare / 100} + value={getTotalFare(itinerary, options.configCosts) / 100} /> ) } @@ -194,6 +193,7 @@ class DefaultItinerary extends NarrativeItinerary { render () { const { active, + configCosts, currency, expanded, itinerary, @@ -246,6 +246,7 @@ class DefaultItinerary extends NarrativeItinerary { } options.LegIcon = LegIcon options.timeFormat = use24HourFormat ? 'H:mm' : 'h:mm a' + options.configCosts = configCosts options.currency = currency return ( <li className={`${attribute.id}${isSelected ? ' main' : ''}`} key={attribute.id}> @@ -276,6 +277,7 @@ class DefaultItinerary extends NarrativeItinerary { const mapStateToProps = (state, ownProps) => { return { + configCosts: state.otp.config.itinerary?.costs, // The configured (ambient) currency is needed for rendering the cost // of itineraries whether they include a fare or not, in which case // we show $0.00 or its equivalent in the configured currency and selected locale. diff --git a/lib/util/state.js b/lib/util/state.js index <HASH>..<HASH> 100644 --- a/lib/util/state.js +++ b/lib/util/state.js @@ -289,8 +289,9 @@ function sortItineraries (type, direction, a, b, config) { if (direction === 'ASC') return a.duration - b.duration else return b.duration - a.duration case 'COST': - const aTotal = getTotalFare(a, config) - const bTotal = getTotalFare(b, config) + const configCosts = config.itinerary?.costs + const aTotal = getTotalFare(a, configCosts) + const bTotal = getTotalFare(b, configCosts) if (direction === 'ASC') return aTotal - bTotal else return bTotal - aTotal default: @@ -329,7 +330,7 @@ function calculateItineraryCost (itinerary, config = {}) { // If config contains values to override defaults, apply those. const configWeights = config.itinerary && config.itinerary.weights if (configWeights) Object.assign(weights, configWeights) - return getTotalFare(itinerary, config) * weights.fareFactor + + return getTotalFare(itinerary, config.itinerary?.costs) * weights.fareFactor + itinerary.duration * weights.durationFactor + itinerary.walkDistance * weights.walkReluctance + getDriveTime(itinerary) * weights.driveReluctance + @@ -368,13 +369,12 @@ const DEFAULT_COSTS = { * FIXME: Move to otp-ui? * TODO: Add GBFS fares */ -function getTotalFare (itinerary, config = {}) { +export function getTotalFare (itinerary, configCosts = {}) { // Get transit/TNC fares. const {maxTNCFare, transitFare} = calculateFares(itinerary) // Start with default cost values. const costs = DEFAULT_COSTS // If config contains values to override defaults, apply those. - const configCosts = config.itinerary && config.itinerary.costs if (configCosts) Object.assign(costs, configCosts) // Calculate total cost from itinerary legs. let drivingCost = 0
fix(itinerary): calculate and display non-transit fares in batch mode Fixes potential regression in <URL>
opentripplanner_otp-react-redux
train
600cd22b0fc476d47bfd0b963948122b8bdc33ae
diff --git a/reportbuilder/classes/table/custom_report_table.php b/reportbuilder/classes/table/custom_report_table.php index <HASH>..<HASH> 100644 --- a/reportbuilder/classes/table/custom_report_table.php +++ b/reportbuilder/classes/table/custom_report_table.php @@ -218,7 +218,7 @@ class custom_report_table extends base_report_table { * * @return column[] */ - private function get_active_columns(): array { + protected function get_active_columns(): array { return $this->report->get_active_columns(); } diff --git a/reportbuilder/classes/table/custom_report_table_view.php b/reportbuilder/classes/table/custom_report_table_view.php index <HASH>..<HASH> 100644 --- a/reportbuilder/classes/table/custom_report_table_view.php +++ b/reportbuilder/classes/table/custom_report_table_view.php @@ -36,6 +36,11 @@ class custom_report_table_view extends custom_report_table { * Override printed headers, to use those of grandparent class */ public function print_headers() { + $columns = $this->get_active_columns(); + if (empty($columns)) { + return; + } + base_report_table::print_headers(); }
MDL-<I> reportbuilder: check for presence of active column headers.
moodle_moodle
train
ec6b4aa19bf1874fc247d554c4a92e842af5f07c
diff --git a/src/component.js b/src/component.js index <HASH>..<HASH> 100644 --- a/src/component.js +++ b/src/component.js @@ -49,10 +49,7 @@ export function tanokComponent(target) { const stream = this.props.tanokStream || this.props.eventStream; - if (metadata !== null) { - return stream && stream.subWithMeta(name, metadata); - } - return stream && stream.subs[name]; + return stream && stream.subWithMeta(`${stream.streamName}.${name}`, metadata); }; return target; diff --git a/src/components/subcomponent.js b/src/components/subcomponent.js index <HASH>..<HASH> 100644 --- a/src/components/subcomponent.js +++ b/src/components/subcomponent.js @@ -18,11 +18,7 @@ export class Subcomponent extends React.Component { }, }; - if (metadata !== null) { - this[streamKey] = stream && stream.subWithMeta(name, metadata); - } else { - this[streamKey] = stream && stream.subs[name]; - } + this[streamKey] = stream && stream.subWithMeta(`${stream.streamName}.${name}`, metadata); } getChildContext() { diff --git a/src/fxs.js b/src/fxs.js index <HASH>..<HASH> 100644 --- a/src/fxs.js +++ b/src/fxs.js @@ -6,24 +6,15 @@ export function rethrowFx(action, payload) { export function subcomponentFx(subName, dispatchSub) { return function (stream) { - stream.subStream(subName, dispatchSub) + stream.subStream(`${stream.streamName}.${subName}`, dispatchSub); } } export function childFx(effect, streamName, metadata = null) { return (streamWrapper) => { - let substream; - if (metadata !== null) { - substream = streamWrapper.subWithMeta(streamName, metadata); - } else { - substream = streamWrapper.subs[streamName]; - } - if (!substream) { - throw new Error(`No such substream '${streamName}'`) - } - - return effect - ? effect(substream) - : Rx.helpers.noop; + const substream = streamWrapper.subWithMeta(`${streamWrapper.streamName}.${streamName}`, metadata); + return effect + ? effect(substream) + : Rx.helpers.noop; }; } diff --git a/src/helpers.js b/src/helpers.js index <HASH>..<HASH> 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -1,6 +1,6 @@ export function actionIs(actionName) { return function () { - return this.filter(({action}) => action === actionName); + return this.filter(({ action, streamName }) => action === `${streamName}.${actionName}`); }; }
Fixed subStreamMeta with null metadata in child compnent, fixed child streamName chaining
brabadu_tanok
train
d0b35aad75c6fa65cb2ea69455e8f8a69fbf2be9
diff --git a/build/es6now.js b/build/es6now.js index <HASH>..<HASH> 100644 --- a/build/es6now.js +++ b/build/es6now.js @@ -8429,7 +8429,7 @@ var Replacer = _es6now.Class(function(__super) { return { wrapComputed: function(node, text) { if (node.computedNames) - return "_es6now.computed(" + (text || this.stringify(node)) + ", " + node.computedNames.join(",") + ")"; + return "_es6now.computed(" + (text || this.stringify(node)) + ", " + node.computedNames.join(", ") + ")"; }, addTempVar: function(node, value) { diff --git a/src/Replacer.js b/src/Replacer.js index <HASH>..<HASH> 100644 --- a/src/Replacer.js +++ b/src/Replacer.js @@ -858,7 +858,7 @@ export class Replacer { wrapComputed(node, text) { if (node.computedNames) - return "_es6now.computed(" + (text || this.stringify(node)) + ", " + node.computedNames.join(",") + ")"; + return "_es6now.computed(" + (text || this.stringify(node)) + ", " + node.computedNames.join(", ") + ")"; } addTempVar(node, value) { diff --git a/test/translate/computed-names.js b/test/translate/computed-names.js index <HASH>..<HASH> 100644 --- a/test/translate/computed-names.js +++ b/test/translate/computed-names.js @@ -3,7 +3,8 @@ }); ({ - ["x"]: 1 + ["x"]: 1, + ["y"]: 2 }); class C { diff --git a/test/translate/computed-names.out.js b/test/translate/computed-names.out.js index <HASH>..<HASH> 100644 --- a/test/translate/computed-names.out.js +++ b/test/translate/computed-names.out.js @@ -3,8 +3,9 @@ }, "x")); (_es6now.computed({ - __$0: 1 -}, "x")); + __$0: 1, + __$1: 2 +}, "x", "y")); var C = _es6now.Class(function(__super) { return _es6now.computed({
Fix whitespace in computed names translation.
zenparsing_esdown
train
4bce582f66fc4fb2d84bcf8ce7333000a5765d13
diff --git a/src/Model/Project.php b/src/Model/Project.php index <HASH>..<HASH> 100644 --- a/src/Model/Project.php +++ b/src/Model/Project.php @@ -32,7 +32,7 @@ class Project extends Resource */ public function getSubscriptionId() { - if ($this->hasProperty('subscription_id')) { + if ($this->hasProperty('subscription_id', false)) { return $this->getProperty('subscription_id'); }
Avoid reloading a project in getSubscriptionId()
platformsh_platformsh-client-php
train
f48c63ffb4471c7be25bee5511ca369ad0292d50
diff --git a/source/resource/Base.php b/source/resource/Base.php index <HASH>..<HASH> 100644 --- a/source/resource/Base.php +++ b/source/resource/Base.php @@ -464,7 +464,7 @@ class GenericResource { $not = array('primary_method', 'lastUpdate', 'subfunctions', 'client'); // we only need key value foreach ($proto as $k => $p) { - if (is_object($p) || in_array($k, $not)) { + if (in_array($k, $not)) { unset($proto[$k]); } }
toArray/0: update only ignore known keys in serializing
Bandwidth_php-bandwidth
train
bb28941b8b7d6566e1b244b651fe3f46e7a2dfe8
diff --git a/src/main/java/com/couchbase/lite/Database.java b/src/main/java/com/couchbase/lite/Database.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/couchbase/lite/Database.java +++ b/src/main/java/com/couchbase/lite/Database.java @@ -3657,6 +3657,42 @@ public final class Database { * @exclude */ @InterfaceAudience.Private + public String getLastSequenceStored(String checkpointId, boolean push) { + + if (!push) { + throw new RuntimeException("need to unhardcode push = 1 before it will work with pull replications"); + } + + String sql = "SELECT last_sequence FROM replicators " + + "WHERE remote = ? AND push = 1 "; + String[] args = {checkpointId}; + Cursor cursor = null; + RevisionList changes = null; + String lastSequence = null; + + try { + + cursor = database.rawQuery(sql, args); + cursor.moveToNext(); + while(!cursor.isAfterLast()) { + lastSequence = cursor.getString(0); + cursor.moveToNext(); + } + } catch (SQLException e) { + Log.e(Database.TAG, "Error", e); + } finally { + if(cursor != null) { + cursor.close(); + } + } + + return lastSequence; + } + + /** + * @exclude + */ + @InterfaceAudience.Private public static String quote(String string) { return string.replace("'", "''"); }
Issue #<I> - add method so the unit test can get the last sequence stored. <URL>
couchbase_couchbase-lite-java-core
train
f93eeb799bf6f230be7bdeb1bd6540a8d312a775
diff --git a/lib/plugins/index.js b/lib/plugins/index.js index <HASH>..<HASH> 100644 --- a/lib/plugins/index.js +++ b/lib/plugins/index.js @@ -1,4 +1,4 @@ -const {isArray, isObject, omit, castArray, isUndefined} = require('lodash'); +const {isPlainObject, omit, castArray, isUndefined} = require('lodash'); const AggregateError = require('aggregate-error'); const getError = require('../get-error'); const PLUGINS_DEFINITIONS = require('../definitions/plugins'); @@ -15,7 +15,7 @@ module.exports = (options, pluginsPath, logger) => { pluginConfs = def; } else { // If an object is passed and the path is missing, set the default one for single plugins - if (isObject(options[pluginType]) && !options[pluginType].path && !isArray(def)) { + if (isPlainObject(options[pluginType]) && !options[pluginType].path && castArray(def).length === 1) { options[pluginType].path = def; } if (config && !config.validator(options[pluginType])) { diff --git a/test/plugins/plugins.test.js b/test/plugins/plugins.test.js index <HASH>..<HASH> 100644 --- a/test/plugins/plugins.test.js +++ b/test/plugins/plugins.test.js @@ -116,11 +116,20 @@ test.serial('Export plugins loaded from the dependency of a shareable config fil }); test('Use default when only options are passed for a single plugin', t => { - const plugins = getPlugins({generateNotes: {}, analyzeCommits: {}}, {}, t.context.logger); + const analyzeCommits = {}; + const success = () => {}; + const fail = [() => {}]; + + const plugins = getPlugins({analyzeCommits, success, fail}, {}, t.context.logger); // Verify the module returns a function for each plugin - t.is(typeof plugins.generateNotes, 'function'); t.is(typeof plugins.analyzeCommits, 'function'); + t.is(typeof plugins.success, 'function'); + t.is(typeof plugins.fail, 'function'); + + // Verify only the plugins defined as an object with no `path` are set to the default value + t.falsy(success.path); + t.falsy(fail.path); }); test('Merge global options with plugin options', async t => {
fix: do not set `path` to plugin config defined as a Function or an Array If a plugin hook was defined as a `Function` or an `Array` the `path` property would be set to the default value. Even if this bug had no actual negative impact, it should be fixed so the code would perform as intended.
semantic-release_semantic-release
train
291a5fdc494ed92b53db4d32f11dfa05c4d3a63b
diff --git a/lib/utils.js b/lib/utils.js index <HASH>..<HASH> 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -270,12 +270,14 @@ Utils.generate = function(args) { var code = ''; - // get the class name of the target - var moduleLocation = target.moduleLocation ? target.moduleLocation : target.constructor ? target.constructor.moduleLocation : null; - if (moduleLocation) { - var targetClassName = typeof target == 'object' ? target.constructor.name : target.name; + // For static calls, we need to make sure we generate the require for the class. + if (type == 'staticMethodCall') { + var moduleLocation = target.moduleLocation ? target.moduleLocation : target.constructor ? target.constructor.moduleLocation : null; + if (moduleLocation) { + var targetClassName = typeof target == 'object' ? target.constructor.name : target.name; - code += generateRequires([{name: targetClassName, moduleLocation: moduleLocation}]); + code += generateRequires([{name: targetClassName, moduleLocation: moduleLocation}]); + } } if (callArgs) {
Only generate a require() when calling a method statically.
EclairJS_eclairjs
train
3acec994fd2367a8d641c22ab0cdc76de2bf7772
diff --git a/lib/lwm2m-common.js b/lib/lwm2m-common.js index <HASH>..<HASH> 100644 --- a/lib/lwm2m-common.js +++ b/lib/lwm2m-common.js @@ -870,7 +870,6 @@ export class LwM2MClientProxy extends EventEmitter { export class LwM2MObjectStore { constructor(opts) { - this.repoFileName = `lwm2m_${opts.clientName}_${opts.serverHost}_${opts.serverPort}.json`; this.repo = null; this.propagator = opts; this.updatedUris = []; diff --git a/lib/lwm2m.js b/lib/lwm2m.js index <HASH>..<HASH> 100644 --- a/lib/lwm2m.js +++ b/lib/lwm2m.js @@ -18,8 +18,6 @@ 'use strict'; import 'source-map-support/register'; -import fs from 'fs'; -import path from 'path'; import { ResourceRepositoryBuilder, LwM2MClientProxy, LwM2MObjectStore } from './lwm2m-common'; @@ -74,35 +72,21 @@ export default function(RED) { this.client = new LwM2MClientProxy(this, this.objectStore); this.operations = { init() { - return new Promise((resolve) => { - fs.readFile(path.join(RED.settings.userDir, - self.objectStore.repoFileName), (err, data) => { - self.objectStore.repo = {}; - if (err || process.env.LWM2M_RESET === 'true') { - return resolve(); - } else { - try { - return resolve(JSON.parse(data)); - } catch (_) { - } - } - resolve(); - }); - }).then((json={}) => { - if (Array.isArray(json)) { - self.warn(`stored objects JSON must be Object rather than Array`); - json = {}; + let json = {}; + if (Array.isArray(json)) { + self.warn(`stored objects JSON must be Object rather than Array`); + json = {}; + } + let initialObjects = {}; + try { + initialObjects = JSON.parse(self.objects); + if (Array.isArray(initialObjects)) { + self.warn(`'Objects' property must be Object rather than Array`); + initialObjects = {}; } - let initialObjects = {}; - try { - initialObjects = JSON.parse(self.objects); - if (Array.isArray(initialObjects)) { - self.warn(`'Objects' property must be Object rather than Array`); - initialObjects = {}; - } - } catch (_) {} - return new ResourceRepositoryBuilder([json, initialObjects]).build(self.hideSensitiveInfo); - }).then((repo) => { + } catch (_) {} + return new ResourceRepositoryBuilder( + [json, initialObjects]).build(self.hideSensitiveInfo).then((repo) => { self.objectStore.repo = repo; }).catch((err) => { if (err instanceof Error) { @@ -154,15 +138,9 @@ export default function(RED) { this.operations.init().then(() => { this.operations.startClient(); }); - this.on('close', (done) => { + this.on('close', () => { this.client.shutdown(); delete lwm2mClients[key]; - fs.writeFile(path.join(RED.settings.userDir, - this.objectStore.repoFileName), - this.objectStore.repo.toJSONString(), (err) => { - this.log(`Repository data has been saved to ${this.objectStore.repoFileName}`); - return done(err); - }); }); } }
Remove repository persistence support Object persistence should be implemented in NR flow rather than this node as the requirement differs depending on expected use cases.
CANDY-LINE_node-red-contrib-lwm2m
train
10ea613134d81daf00581b87df2eb57812169568
diff --git a/util.go b/util.go index <HASH>..<HASH> 100644 --- a/util.go +++ b/util.go @@ -192,16 +192,9 @@ func downloadFile(url, destFile string) error { } func writeToFile(source io.Reader, destFile string, mode os.FileMode) error { - fh, err := os.Create(destFile) + fh, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) if err != nil { - Log.Error("Could not write to %s", destFile) - return err - } - defer fh.Close() - - err = fh.Chmod(mode) - if err != nil { - Log.Error("Could not set file mode for %s", destFile) + Log.Error("Could not create %s", destFile) return err } defer fh.Close() diff --git a/util_test.go b/util_test.go index <HASH>..<HASH> 100644 --- a/util_test.go +++ b/util_test.go @@ -4,6 +4,7 @@ import ( "io/ioutil" "os" "path/filepath" + "syscall" bp "github.com/cloudfoundry/libbuildpack" . "github.com/onsi/ginkgo" @@ -125,6 +126,7 @@ var _ = Describe("Util", func() { err error fileInfo os.FileInfo oldMode os.FileMode + oldUmask int ) BeforeEach(func() { var fh *os.File @@ -144,6 +146,8 @@ var _ = Describe("Util", func() { err = fh.Chmod(0742) Expect(err).To(BeNil()) + oldUmask = syscall.Umask(0000) + }) AfterEach(func() { var fh *os.File @@ -158,6 +162,8 @@ var _ = Describe("Util", func() { err = os.RemoveAll(tmpdir) Expect(err).To(BeNil()) + + syscall.Umask(oldUmask) }) Context("with a valid source file", func() {
Create file with proper permissions instead of using chmod - Fixes a problem where the go os.Chmod function doesn't work on Windows See: <URL>
cloudfoundry_libbuildpack
train
1435af084dcda0640e216c1ef6106736dbad8d63
diff --git a/webapps/webapp/Gruntfile.js b/webapps/webapp/Gruntfile.js index <HASH>..<HASH> 100644 --- a/webapps/webapp/Gruntfile.js +++ b/webapps/webapp/Gruntfile.js @@ -426,7 +426,7 @@ module.exports = function(grunt) { dist: { options: { - cleancss: true + compress: true }, files: { 'target/webapp/assets/css/common.css': 'src/main/webapp/assets/styles/common.less',
fix(cockpit): fix the color of layout splitter
camunda_camunda-bpm-platform
train
59fea890433ee1789a9883a203019dd1b0d0a74f
diff --git a/src/Rammbock/synchronization.py b/src/Rammbock/synchronization.py index <HASH>..<HASH> 100644 --- a/src/Rammbock/synchronization.py +++ b/src/Rammbock/synchronization.py @@ -15,8 +15,8 @@ def synchronized(f, *args, **kw): class SynchronizedType(type): - def __new__(cls, name, bases, local): + def __new__(cls, clsname, bases, local): for name, item in local.items(): if callable(item) and not name.startswith("_"): local[name] = synchronized(item) - return type.__new__(cls, name, bases, local) + return type.__new__(cls, clsname, bases, local)
fixed class name bug from syncrhonization metaclass. This prevented pickling.
robotframework_Rammbock
train
4d9629b2abf1b430f93b561064a659de339ba5ea
diff --git a/src/geometry/LineString.js b/src/geometry/LineString.js index <HASH>..<HASH> 100644 --- a/src/geometry/LineString.js +++ b/src/geometry/LineString.js @@ -70,6 +70,61 @@ Z.LineString = Z.Polyline = Z.Vector.extend(/** @lends maptalks.LineString.proto return this._coordinates; }, + animateShow: function (options) { + if (!options) { + options = {}; + } + var coordinates = this.getCoordinates(); + var duration = options['duration'] || 1000; + var length = this.getLength(); + var easing = options['easing'] || 'out'; + this.setCoordinates([]); + var player = Z.Animation.animate({'t' : duration}, {'speed' : duration, 'easing' : easing}, Z.Util.bind(function (frame) { + this._drawAnimFrame(frame.styles.t, duration, length, coordinates); + }, this)); + player.play(); + return this; + }, + + _drawAnimFrame: function (t, duration, length, coordinates) { + if (t === 0) { + this.setCoordinates([]); + return; + } + var map = this.getMap(); + var targetLength = t / duration * length; + if (!this._animIdx) { + this._animIdx = 0; + this._animLenSoFar = 0; + this.show(); + } + var i, l; + var segLen = 0; + for (i = this._animIdx, l = coordinates.length; i < l - 1; i++) { + segLen = map.computeLength(coordinates[i], coordinates[i + 1]); + if (this._animLenSoFar + segLen > targetLength) { + break; + } + this._animLenSoFar += segLen; + } + this._animIdx = i; + if (this._animIdx >= l - 1) { + this.setCoordinates(coordinates); + return; + } + var idx = this._animIdx; + var p1 = coordinates[idx], p2 = coordinates[idx + 1], + span = targetLength - this._animLenSoFar, + r = span / segLen; + var x = p1.x + (p2.x - p1.x) * r, + y = p1.y + (p2.y - p1.y) * r, + targetCoord = new maptalks.Coordinate(x, y); + var animCoords = coordinates.slice(0, this._animIdx + 1); + animCoords.push(targetCoord); + + this.setCoordinates(animCoords); + }, + _computeGeodesicLength:function (measurer) { return Z.GeoUtil._computeLength(this.getCoordinates(), measurer); },
[feat] add animateShow for LineString
maptalks_maptalks.js
train
806563f5987202897d6e8d0118d63e0ca28cee5b
diff --git a/src/org/mozilla/javascript/ScriptOrFnNode.java b/src/org/mozilla/javascript/ScriptOrFnNode.java index <HASH>..<HASH> 100644 --- a/src/org/mozilla/javascript/ScriptOrFnNode.java +++ b/src/org/mozilla/javascript/ScriptOrFnNode.java @@ -46,27 +46,18 @@ public class ScriptOrFnNode extends Node { public final String getSourceName() { return sourceName; } public final void setSourceName(String sourceName) { - // One time action - if (sourceName == null || this.sourceName != null) - Context.codeBug(); this.sourceName = sourceName; } public final String getEncodedSource() { return encodedSource; } public final void setEncodedSource(String encodedSource) { - // One time action - if (encodedSource == null || this.encodedSource != null) - Context.codeBug(); this.encodedSource = encodedSource; } public final String getOriginalSource() { return originalSource; } public final void setOriginalSource(String originalSource) { - // One time action - if (originalSource == null || this.originalSource != null) - Context.codeBug(); this.originalSource = originalSource; }
Allow to set null for sourceName, encodedSource and originalSource
mozilla_rhino
train
a3d46690e07bf7f523f856b947b6a21d002e6ed4
diff --git a/demo/simple/package.json b/demo/simple/package.json index <HASH>..<HASH> 100644 --- a/demo/simple/package.json +++ b/demo/simple/package.json @@ -7,6 +7,6 @@ "dependencies": { "express": "3.1.0", - "object-sugar": "0.2.0" + "object-sugar": "0.2.1" } } diff --git a/lib/rest-sugar.js b/lib/rest-sugar.js index <HASH>..<HASH> 100644 --- a/lib/rest-sugar.js +++ b/lib/rest-sugar.js @@ -1,5 +1,6 @@ var async = require('async'); var funkit = require('funkit'); +var otozip = funkit.functional.otozip; var is = require('is-js'); @@ -15,9 +16,19 @@ function init(app, prefix, apis, queries) { app.get(prefix, initHandler('', handlers.pre, function(req, res) { var api = {}; - for(var k in apis) api[k] = queries.getMeta(apis[k]); + async.parallel(otozip(apis).map(function(v) { + return function(cb) { + queries.getMeta(v[1], function(err, d) { + if(err) return console.error(err); - res.json(api); + api[v[0]] = d; + + cb(); + }); + }; + }), function() { + res.json(api); + }); })); for(var k in apis) initAPI(app, prefix, k, apis[k], queries, handlers); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "devDependencies": { "request": "2.14.0", - "object-sugar": "0.2.0" + "object-sugar": "0.2.1" }, "main": "./lib/rest-sugar.js", diff --git a/tests/queries.js b/tests/queries.js index <HASH>..<HASH> 100644 --- a/tests/queries.js +++ b/tests/queries.js @@ -9,7 +9,25 @@ var utils = require('./utils'); // TODO: tidy up and make the API consistent +function getMeta(r, extra, check) { + extra = extra || {}; + + return function(cb) { + request.get({url: r, json: true, qs: extra}, function(err, d, body) { + if(err) return console.error(err); + + if(check) check(err, d, body); + else assert.ok(body); + + cb(err, d, body); + }); + }; +} +exports.getMeta = getMeta; + function get(r, extra, check) { + extra = extra || {}; + return function(cb) { request.get({url: r, json: true, qs: extra}, function(err, d, body) { if(err) return console.error(err); diff --git a/tests/test_rest.js b/tests/test_rest.js index <HASH>..<HASH> 100644 --- a/tests/test_rest.js +++ b/tests/test_rest.js @@ -11,7 +11,8 @@ var queries = require('./queries'); function tests(done) { - var resource = conf.host + ':' + conf.port + conf.prefix + 'authors'; + var apiRoot = conf.host + ':' + conf.port + conf.prefix; + var resource = apiRoot + 'authors'; var app = serve(conf); var api = rest.init(app, conf.prefix, { authors: models.Author @@ -37,6 +38,7 @@ function tests(done) { if(err) return console.error(err); utils.runTests([ + queries.getMeta(apiRoot), queries.get(resource), queries.getViaId(resource), queries.create(resource),
Make getMeta work ok again The definition of getMeta had changed so had to update rest-sugar accordingly.
sugarjs_rest-sugar
train
94902dbefe1950da6bb09419fe296f46b7efbbf4
diff --git a/Util/ParserUtil.php b/Util/ParserUtil.php index <HASH>..<HASH> 100755 --- a/Util/ParserUtil.php +++ b/Util/ParserUtil.php @@ -225,7 +225,7 @@ class ParserUtil static function validateUrl($url) { if(!filter_var($url, FILTER_VALIDATE_URL)) { - throw new \Exception('Invalid URL'); + return false; } return true;
if url is not valid, it should be simply return false
CampaignChain_core
train
e37c28acee8886f30e6060c63553730b918b6f2e
diff --git a/bika/lims/skins/bika/bika_widgets/reflexrulewidget.js b/bika/lims/skins/bika/bika_widgets/reflexrulewidget.js index <HASH>..<HASH> 100644 --- a/bika/lims/skins/bika/bika_widgets/reflexrulewidget.js +++ b/bika/lims/skins/bika/bika_widgets/reflexrulewidget.js @@ -533,6 +533,7 @@ jQuery(function($){ local_id = create_local_id(selection); $(action_div).find("input[id^='ReflexRules-an_result_id-']") .first().val(local_id); + populate_analysis_selection(local_id); } else{ $(action_div).find("input[id^='ReflexRules-an_result_id-']") @@ -545,6 +546,7 @@ jQuery(function($){ local_id = create_local_id(selection); $(action_div).find("input[id^='ReflexRules-an_result_id-']") .first().val(local_id); + populate_analysis_selection(local_id); } } @@ -716,4 +718,20 @@ jQuery(function($){ } return array; } + + function populate_analysis_selection(local_id) { + /** + This function adds the recently created 'local_id' to the analysis + services selection lists. + */ + // Getting the selectors from the containers + var selectors = $('td.rulescontainer').slice(1).find("select[id^='ReflexRules-analysisservice-']"); + // Add the new local-id as a new the options + $.each($(selectors), function(index, element){ + $(element).append( + '<option value="' + local_id + + '">' + local_id + '</option>' + ); + }); + } });
populate selection lists with the new local id
senaite_senaite.core
train
435d9945a34ceedc97d5219b2bbb7cc88c9ac8e8
diff --git a/pre_commit/languages/ruby.py b/pre_commit/languages/ruby.py index <HASH>..<HASH> 100644 --- a/pre_commit/languages/ruby.py +++ b/pre_commit/languages/ruby.py @@ -118,7 +118,7 @@ def install_environment( ) helpers.run_setup_cmd( prefix, - ('gem', 'install', '--no-ri', '--no-rdoc') + + ('gem', 'install', '--no-document') + prefix.star('.gem') + additional_dependencies, )
Switch from deprecated docs-off args to --no-document
pre-commit_pre-commit
train
3e4ddbb05d023358a65491c1553ab928431fb5f0
diff --git a/src/StringUtils.php b/src/StringUtils.php index <HASH>..<HASH> 100644 --- a/src/StringUtils.php +++ b/src/StringUtils.php @@ -133,9 +133,9 @@ class StringUtils '~[^a-z^\d]+~i', '_', preg_replace( - '~([a-z\d])([A-Z]|\d)~', + '~([a-z\d+])([A-Z])~', '\1_\2', - preg_replace('~([A-Z]|\d+)([A-Z][a-z]|\d)~', '\1_\2', $word) + preg_replace('~([A-Z]+)([A-Z][a-z])~', '\1_\2', $word) ) ), '_' diff --git a/test/StringUtilsTest.php b/test/StringUtilsTest.php index <HASH>..<HASH> 100644 --- a/test/StringUtilsTest.php +++ b/test/StringUtilsTest.php @@ -109,7 +109,7 @@ class StringUtilsTest extends \PHPUnit_Framework_TestCase 'original' => 'this is just a string 123', 'startsWith' => 'this is', 'endsWith' => 'string 123', - 'underscored' => 'this_is_just_a_string_1_2_3', + 'underscored' => 'this_is_just_a_string_123', 'camelCased' => 'ThisIsJustAString123' ]], [[ @@ -138,6 +138,18 @@ class StringUtilsTest extends \PHPUnit_Framework_TestCase 'endsWith' => 'not lie', 'underscored' => 'i_like_camel_case_and_cannot_lie', 'camelCased' => 'ILikeCamelCaseAndCannotLie', + ]], [[ + 'original' => '12_3_4_56', + 'startsWith' => '12_3_', + 'endsWith' => '4_56', + 'underscored' => '12_3_4_56', + 'camelCased' => '123456', + ]], [[ + 'original' => '__-__', + 'startsWith' => '__-', + 'endsWith' => '-__', + 'underscored' => '', + 'camelCased' => '-', ]], ]; }
WSNL-<I>:: removed some vague code
webservices-nl_utils
train
ba497f3433d5ed1e1c3a60dbf952c3002d9630fe
diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/ServiceProvider.php +++ b/src/ServiceProvider.php @@ -239,11 +239,28 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider return new CompilerEngine($this->app['Bkwld\LaravelPug\Pug' . ucfirst(ltrim($subExtension, '.')) . 'Compiler']); }); - // Add extensions - $this->app['view']->addExtension('pug' . $subExtension, 'pug' . $subExtension); - $this->app['view']->addExtension('pug' . $subExtension . '.php', 'pug' . $subExtension); - $this->app['view']->addExtension('jade' . $subExtension, 'pug' . $subExtension); - $this->app['view']->addExtension('jade' . $subExtension . '.php', 'pug' . $subExtension); + $mainExtension = 'pug' . $subExtension; + $extensions = array( + // Pug extensions + $mainExtension, + $mainExtension . '.php', + // Legacy jade extensions + 'jade' . $subExtension, + 'jade' . $subExtension . '.php', + ); + + if ($subExtension !== '') { + $subExtensionPrefix = substr($subExtension, 1) . '.'; + + $extensions[] = $subExtensionPrefix . 'pug'; + $extensions[] = $subExtensionPrefix . 'pug.php'; + $extensions[] = $subExtensionPrefix . 'jade'; + $extensions[] = $subExtensionPrefix . 'jade.php'; + } + + foreach ($extensions as $extension) { + $this->app['view']->addExtension($extension, $mainExtension); + } } /** @@ -257,7 +274,7 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider } /** - * Get the configuration, which is keyed differently in L5 vs l4. + * Get the configuration, which is keyed differently in L5 vs L4. * * @return array */ diff --git a/tests/BladeDirectivesTest.php b/tests/BladeDirectivesTest.php index <HASH>..<HASH> 100644 --- a/tests/BladeDirectivesTest.php +++ b/tests/BladeDirectivesTest.php @@ -185,6 +185,10 @@ class BladeDirectivesTest extends TestCase self::assertSame( [ + 'blade.jade.php' => 'pug.blade', + 'blade.jade' => 'pug.blade', + 'blade.pug.php' => 'pug.blade', + 'blade.pug' => 'pug.blade', 'jade.blade.php' => 'pug.blade', 'jade.blade' => 'pug.blade', 'pug.blade.php' => 'pug.blade', diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/ServiceProviderTest.php +++ b/tests/ServiceProviderTest.php @@ -344,7 +344,7 @@ class ServiceProviderTest extends TestCase $this->provider->boot(); self::assertArraySubset( - ['pug', 'pug.php', 'jade', 'jade.php', 'pug.blade', 'pug.blade.php', 'jade.blade', 'jade.blade.php'], + ['pug', 'pug.php', 'jade', 'jade.php', 'pug.blade', 'pug.blade.php', 'jade.blade', 'jade.blade.php', 'blade.pug', 'blade.pug.php', 'blade.jade', 'blade.jade.php'], array_keys($view->getExtensions()) ); self::assertSame('bkwld/laravel-pug', $this->provider->getCurrentPackage());
Implement #<I> Add reverted extensions blade.pug and jade.pug
BKWLD_laravel-pug
train
74da4d4f4429dc160f2c36e73810d359871909fc
diff --git a/tests/FrameTest.php b/tests/FrameTest.php index <HASH>..<HASH> 100644 --- a/tests/FrameTest.php +++ b/tests/FrameTest.php @@ -6,7 +6,7 @@ use Char0n\FFMpegPHP\Movie; use Char0n\FFMpegPHP\Frame; use PHPUnit\Framework\TestCase; -class FFmpegFrameTest extends TestCase +class FrameTest extends TestCase { protected static $moviePath; diff --git a/tests/OutputProviders/FFMpegProviderTest.php b/tests/OutputProviders/FFMpegProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/OutputProviders/FFMpegProviderTest.php +++ b/tests/OutputProviders/FFMpegProviderTest.php @@ -5,7 +5,7 @@ use PHPUnit\Framework\TestCase; use SebastianBergmann\Timer\Timer; use Char0n\FFMpegPHP\OutputProviders\FFMpegProvider; -class FFmpegProviderTest extends TestCase +class FFMpegProviderTest extends TestCase { protected static $moviePath; diff --git a/tests/OutputProviders/FFProbeProviderTest.php b/tests/OutputProviders/FFProbeProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/OutputProviders/FFProbeProviderTest.php +++ b/tests/OutputProviders/FFProbeProviderTest.php @@ -5,7 +5,7 @@ use PHPUnit\Framework\TestCase; use SebastianBergmann\Timer\Timer; use Char0n\FFMpegPHP\OutputProviders\FFProbeProvider; -class FFProbeOutputProviderTest extends TestCase +class FFProbeProviderTest extends TestCase { protected static $moviePath;
test: fix tests class names (#<I>)
char0n_ffmpeg-php
train
d4dacab0671f9aedbf3924d3df2a4a95c8c11a87
diff --git a/cors.go b/cors.go index <HASH>..<HASH> 100644 --- a/cors.go +++ b/cors.go @@ -415,6 +415,7 @@ func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool { for _, h := range c.allowedHeaders { if h == header { found = true + break } } if !found {
Add early break on allowedHeaders match found (#<I>)
rs_cors
train
82a44852cb3a5c8c7836dc64ee98c89619aae504
diff --git a/lib/IDS/Converter.php b/lib/IDS/Converter.php index <HASH>..<HASH> 100644 --- a/lib/IDS/Converter.php +++ b/lib/IDS/Converter.php @@ -126,6 +126,29 @@ class IDS_Converter { return $value; } + + /** + * Check for comments and erases them if available + * + * @return string $value + */ + public static function convertFromCommented($value) { + + + if (preg_match('/(?:\<!-|-->|\/\*|\*\/|\/\/\W*\w+\s*$)|(?:(?:#|--|{)\s*$)/Ds', $value)) { + + $pattern = array('/(?:(?:<!)(?:(?:--(?:[^-]*(?:-[^-]+)*)--\s*)*)(?:>))/Ds', + '/(?:(?:\/\*\/*[^\/\*]*)+\*\/)/Ds', + '/(?:(?:\/\/|--|#|{).*)/Ds' + ); + + $converted = preg_replace($pattern, null, $value); + + $value .= ' [' . $converted . '] '; + } + + return $value; + } } /* diff --git a/lib/IDS/Monitor.php b/lib/IDS/Monitor.php index <HASH>..<HASH> 100644 --- a/lib/IDS/Monitor.php +++ b/lib/IDS/Monitor.php @@ -169,6 +169,7 @@ class IDS_Monitor { $value = IDS_Converter::convertFromUTF7($value); $value = IDS_Converter::convertFromJSCharcode($value); + $value = IDS_Converter::convertFromCommented($value); return $filter->match($value); } diff --git a/lib/default_filter.xml b/lib/default_filter.xml index <HASH>..<HASH> 100644 --- a/lib/default_filter.xml +++ b/lib/default_filter.xml @@ -157,7 +157,7 @@ <impact>5</impact> </filter> <filter> - <rule><![CDATA[(?:(?:alert|msgbox|prompt|confirm|dialog|expression|urn|fromCharcode|decodeURIComponent|eval|toString|substr|Execute|window)[\s]?[(;\[])]]></rule> + <rule><![CDATA[(?:(?:alert|msgbox|prompt|confirm|dialog|expression|urn|decodeURIComponent|eval|toString|Execute|window)[\s]?[(;\[])]]></rule> <description>detects possible includes and typical script methods</description> <tags> <tag>xss</tag> @@ -168,6 +168,39 @@ <impact>5</impact> </filter> <filter> + <rule><![CDATA[(?:(?:hash|host|hostname|href|pathname|port|protocol|search|replace|back|forward|go|innerhtml|innertext|outerhtml)[\s]?[(;\[])]]></rule> + <description>detects javascript script object properties and methods</description> + <tags> + <tag>xss</tag> + <tag>csrf</tag> + <tag>id</tag> + <tag>rfe</tag> + </tags> + <impact>4</impact> + </filter> + <filter> + <rule><![CDATA[(?:(?:concat|join|pop|push|reverse|shift|slice|splice|sort|unshift)[\s]?[(;\[])]]></rule> + <description>detects javascript script array properties and methods</description> + <tags> + <tag>xss</tag> + <tag>csrf</tag> + <tag>id</tag> + <tag>rfe</tag> + </tags> + <impact>4</impact> + </filter> + <filter> + <rule><![CDATA[(?:(?:charat|charcodeat|concat|fromcharcode|indexof|lastindexof|match|replace|search|slice|split|substr|substring)[\s]?[(;\[])]]></rule> + <description>detects javascript script string properties and methods</description> + <tags> + <tag>xss</tag> + <tag>csrf</tag> + <tag>id</tag> + <tag>rfe</tag> + </tags> + <impact>4</impact> + </filter> + <filter> <rule><![CDATA[(?:with\s*\(\s*.+\s*\)\s*\w+\s*\()]]></rule> <description>detects self contained xss via with()</description> <tags> diff --git a/tests/IDS/MonitorTest.php b/tests/IDS/MonitorTest.php index <HASH>..<HASH> 100644 --- a/tests/IDS/MonitorTest.php +++ b/tests/IDS/MonitorTest.php @@ -84,17 +84,17 @@ class IDS_MonitorTest extends PHPUnit_Framework_TestCase { ); $result = $test->run(); $this->assertTrue($result->hasEvent(1)); - $this->assertEquals(22, $result->getImpact()); + $this->assertEquals(26, $result->getImpact()); } public function testSQLIList() { $test = new IDS_Monitor( - array('" OR 1=1#', '; DROP table Users --'), + array('" OR 1=1#', '; DROP table Users --', '/**/S/**/E/**/L/**/E/**/C/**/T * FROM users WHERE 1 = 1'), $this->storage ); $result = $test->run(); $this->assertTrue($result->hasEvent(1)); - $this->assertEquals(8, $result->getImpact()); + $this->assertEquals(12, $result->getImpact()); } public function testDTList(){
added new converter function to check for comments and attach the prefiltered string (to eliminate the problem with comment obfuscation), fixed the tests, modified the monitor to make use of the new converter function
PHPIDS_PHPIDS
train
88fa8ba96879bc64854bd4cd5162f85b0af16c35
diff --git a/lib/announce/adapters/shoryuken_adapter.rb b/lib/announce/adapters/shoryuken_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/announce/adapters/shoryuken_adapter.rb +++ b/lib/announce/adapters/shoryuken_adapter.rb @@ -25,7 +25,7 @@ module Announce def configure_publishing (options[:publish] || {}).each do |subject, actions| Array(actions).each do |action| - Announce::Adapter::ShoryukenAdapter::Topic(subject, action, options).create + ShoryukenAdapter::Topic.new(subject, action, options).create end end end @@ -33,8 +33,8 @@ module Announce def configure_subscribing (options[:subscribe] || {}).each do |subject, actions| Array(actions).each do |action| - topic = Announce::Adapter::ShoryukenAdapter::Topic(subject, action, options) - queue = Announce::Adapter::ShoryukenAdapter::Queue(subject, action, options) + topic = ShoryukenAdapter::Topic.new(subject, action, options) + queue = ShoryukenAdapter::Queue.new(subject, action, options) topic.create queue.create topic.subscribe(queue)
fix class name issue, and missing `new` call
PRX_announce
train
6156680c0e52331f16295262c932f451174c79cb
diff --git a/gbdxtools/images/catalog_image.py b/gbdxtools/images/catalog_image.py index <HASH>..<HASH> 100644 --- a/gbdxtools/images/catalog_image.py +++ b/gbdxtools/images/catalog_image.py @@ -6,8 +6,8 @@ Contact: chris.helm@digitalglobe.com from __future__ import print_function from gbdxtools import WV01, WV02, WV03_SWIR, WV03_VNIR, LandsatImage, IkonosImage, GE01, QB02, Sentinel2 from gbdxtools.images.ipe_image import IpeImage, GraphMeta -from gbdxtools.vectors import Vectors from gbdxtools.ipe.error import UnsupportedImageType +from gbdxtools.images.util.image import vector_services_query from shapely import wkt from shapely.geometry import box @@ -49,11 +49,9 @@ class CatalogImage(object): return IpeImage(GraphMeta(**kwargs)) except KeyError: raise ValueError("Catalog Images must be initiated by a Catalog Id or an RDA Graph Id") - vectors = Vectors() - aoi = wkt.dumps(box(-180, -90, 180, 90)) query = "item_type:GBDXCatalogRecord AND attributes.catalogID:{}".format(cat_id) query += " AND NOT item_type:IDAHOImage AND NOT item_type:DigitalGlobeAcquisition" - result = vectors.query(aoi, query=query, count=1) + result = vector_services_query(query, count=1) if len(result) == 0: raise Exception('Could not find a catalog entry for the given id: {}'.format(cat_id)) else: diff --git a/gbdxtools/images/util/image.py b/gbdxtools/images/util/image.py index <HASH>..<HASH> 100644 --- a/gbdxtools/images/util/image.py +++ b/gbdxtools/images/util/image.py @@ -23,11 +23,11 @@ def vendor_id(rec): _id = rec['properties']['attributes']['vendorDatasetIdentifier'] return _id.split(':')[1].split('_')[0] -def vector_services_query(query, aoi=None): +def vector_services_query(query, aoi=None, **kwargs): vectors = Vectors() if not aoi: aoi = wkt.dumps(box(-180, -90, 180, 90)) - _parts = sorted(vectors.query(aoi, query=query), key=lambda x: x['properties']['id']) + _parts = sorted(vectors.query(aoi, query=query, **kwargs), key=lambda x: x['properties']['id']) return _parts
using updated vector_services_query in CatalogImage
DigitalGlobe_gbdxtools
train
4ca9fcd73225af9cb1dc2acc99bb494dc5f8926a
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index <HASH>..<HASH> 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -154,7 +154,7 @@ Indexing - When called with a null slice (e.g. ``df.iloc[:]``), the ``.iloc`` and ``.loc`` indexers return a shallow copy of the original object. Previously they returned the original object. (:issue:`13873`). - When called on an unsorted ``MultiIndex``, the ``loc`` indexer now will raise ``UnsortedIndexError`` only if proper slicing is used on non-sorted levels (:issue:`16734`). - +- Fixes regression in 0.20.3 when indexing with a string on a ``TimedeltaIndex`` (:issue:`16896`). I/O ^^^ diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index <HASH>..<HASH> 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -392,13 +392,15 @@ def is_timedelta64_dtype(arr_or_dtype): False >>> is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) True + >>> is_timedelta64_dtype('0 days') + False """ if arr_or_dtype is None: return False try: tipo = _get_dtype_type(arr_or_dtype) - except ValueError: + except: return False return issubclass(tipo, np.timedelta64) diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index <HASH>..<HASH> 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -199,12 +199,17 @@ def test_is_datetime64tz_dtype(): def test_is_timedelta64_dtype(): assert not com.is_timedelta64_dtype(object) + assert not com.is_timedelta64_dtype(None) assert not com.is_timedelta64_dtype([1, 2, 3]) assert not com.is_timedelta64_dtype(np.array([], dtype=np.datetime64)) + assert not com.is_timedelta64_dtype('0 days') + assert not com.is_timedelta64_dtype("0 days 00:00:00") + assert not com.is_timedelta64_dtype(["0 days 00:00:00"]) + assert not com.is_timedelta64_dtype("NO DATE") + assert com.is_timedelta64_dtype(np.timedelta64) assert com.is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) - - assert not com.is_timedelta64_dtype("0 days 00:00:00") + assert com.is_timedelta64_dtype(pd.to_timedelta(['0 days', '1 days'])) def test_is_period_dtype(): diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index <HASH>..<HASH> 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -66,6 +66,9 @@ class TestTimedeltaIndex(DatetimeLike): for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: assert idx.get_loc('1 day 1 hour', method) == loc + # GH 16896 + assert idx.get_loc('0 days') == 0 + def test_get_loc_nat(self): tidx = TimedeltaIndex(['1 days 01:00:00', 'NaT', '2 days 01:00:00']) diff --git a/pandas/tests/indexing/test_timedelta.py b/pandas/tests/indexing/test_timedelta.py index <HASH>..<HASH> 100644 --- a/pandas/tests/indexing/test_timedelta.py +++ b/pandas/tests/indexing/test_timedelta.py @@ -5,7 +5,6 @@ from pandas.util import testing as tm class TestTimedeltaIndexing(object): - def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) @@ -40,3 +39,11 @@ class TestTimedeltaIndexing(object): dtype="int64") tm.assert_frame_equal(expected, df) + + def test_string_indexing(self): + # GH 16896 + df = pd.DataFrame({'x': range(3)}, + index=pd.to_timedelta(range(3), unit='days')) + expected = df.iloc[0] + sliced = df.loc['0 days'] + tm.assert_series_equal(sliced, expected)
Fixes for #<I>(TimedeltaIndex indexing regression for strings) (#<I>)
pandas-dev_pandas
train
d0390cf8e2319b5e1e8f352751addc96f2e029e6
diff --git a/mod/feedback/edit_item.php b/mod/feedback/edit_item.php index <HASH>..<HASH> 100644 --- a/mod/feedback/edit_item.php +++ b/mod/feedback/edit_item.php @@ -120,6 +120,9 @@ print_header_simple(format_string($feedback->name), "", $navigation, "", "", true, $buttontext, navmenu($course, $cm)); + /// print the tabs + include('tabs.php'); + /// Print the main part of the page /////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
adding the tab-row in edit_item.php
moodle_moodle
train
4a01091f5c18932ca179b2609f06ab7ff4aac0ed
diff --git a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementRule.java b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementRule.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementRule.java +++ b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementRule.java @@ -506,6 +506,7 @@ public class AgreementRule extends Rule { private static final Set<String> VIELE_WENIGE_LOWERCASE = new HashSet<>(Arrays.asList( "sämtlicher", "etliche", + "etlicher", "viele", "vieler", "wenige",
[de] prevent another false alarm in DE_AGREEMENT
languagetool-org_languagetool
train
a51c7d45f67db35ec838909b10147bbd097cea28
diff --git a/lib/melodiest/generator.rb b/lib/melodiest/generator.rb index <HASH>..<HASH> 100644 --- a/lib/melodiest/generator.rb +++ b/lib/melodiest/generator.rb @@ -61,7 +61,7 @@ module Melodiest File.open "#{@destination}/#{@app_name}.rb", "w" do |f| f.write(content[:yaml]) f.write("class #{app_class_name} < Melodiest::Application\n") - f.write(" setup #{SecureRandom.hex(32)}\n\n") + f.write(" setup '#{SecureRandom.hex(32)}'\n\n") f.write(" set :app_file, __FILE__\n") f.write(" set :views, Proc.new { File.join(root, \"app/views\") }\n\n") f.write(" use Rack::Csrf, raise: true\n\n") diff --git a/spec/melodiest/generator_spec.rb b/spec/melodiest/generator_spec.rb index <HASH>..<HASH> 100644 --- a/spec/melodiest/generator_spec.rb +++ b/spec/melodiest/generator_spec.rb @@ -98,7 +98,7 @@ describe Melodiest::Generator do expected_file_content = <<DOC class MyApp < Melodiest::Application - setup #{secret} + setup '#{secret}' set :app_file, __FILE__ set :views, Proc.new { File.join(root, "app/views") } @@ -137,7 +137,7 @@ DOC require 'yaml' class MyApp < Melodiest::Application - setup #{secret} + setup '#{secret}' set :app_file, __FILE__ set :views, Proc.new { File.join(root, "app/views") }
oops.. forgot to add single quote
kuntoaji_sinator
train
05dacbd0729f4ebf0074bd21c50f3bf813ad7fab
diff --git a/lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/topbar/TopBarController.java b/lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/topbar/TopBarController.java index <HASH>..<HASH> 100644 --- a/lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/topbar/TopBarController.java +++ b/lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/topbar/TopBarController.java @@ -1,6 +1,7 @@ package com.reactnativenavigation.viewcontrollers.topbar; import android.content.Context; +import android.os.Build; import android.support.v4.view.ViewPager; import android.view.View; @@ -10,12 +11,14 @@ import com.reactnativenavigation.views.topbar.TopBar; public class TopBarController { + private static final int INITIAL_ELEVATION = 0; private TopBar topBar; public View createView(Context context, StackLayout stackLayout) { if (topBar == null) { topBar = createTopBar(context, stackLayout); topBar.setId(CompatUtils.generateViewId()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) topBar.setElevation(INITIAL_ELEVATION); } return topBar; } diff --git a/lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/TopBarControllerTest.java b/lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/TopBarControllerTest.java index <HASH>..<HASH> 100644 --- a/lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/TopBarControllerTest.java +++ b/lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/TopBarControllerTest.java @@ -2,7 +2,6 @@ package com.reactnativenavigation.viewcontrollers; import android.app.Activity; import android.content.Context; -import android.support.annotation.NonNull; import com.reactnativenavigation.BaseTest; import com.reactnativenavigation.viewcontrollers.topbar.TopBarController; @@ -20,31 +19,38 @@ import static org.mockito.Mockito.verify; public class TopBarControllerTest extends BaseTest { private TopBarController uut; + private TitleBar titleBar; + private TopBar topBar; + private Activity activity; @Override public void beforeEach() { - uut = new TopBarController(); - } - - @Test - public void clear() { - final TitleBar[] titleBar = new TitleBar[1]; + activity = newActivity(); uut = new TopBarController() { - @NonNull @Override protected TopBar createTopBar(Context context, StackLayout stackLayout) { - return new TopBar(context, stackLayout) { + topBar = spy(new TopBar(context, stackLayout) { @Override protected TitleBar createTitleBar(Context context) { - titleBar[0] = spy(super.createTitleBar(context)); - return titleBar[0]; + titleBar = spy(super.createTitleBar(context)); + return titleBar; } - }; + }); + return topBar; } }; - Activity activity = newActivity(); + } + + @Test + public void createView_setElevationToCancelDefaultElevationAnimationWhichMightConflictWithElevationValueFromDefaultOptions() { + uut.createView(activity, Mockito.mock(StackLayout.class)); + verify(topBar).setElevation(0); + } + + @Test + public void clear() { uut.createView(activity, Mockito.mock(StackLayout.class)); uut.clear(); - verify(titleBar[0], times(1)).clear(); + verify(titleBar, times(1)).clear(); } }
Set elevation 0 when creating TopBar Apparently TopBar elevation property is animated. Meaning that if 4dp elevation is set, when the view appears its elevation is animated from 0dp to 4dp. This resulted in rare race condition where the onAnimationEnd callback was called after we set the desired elevation value, and an unexpected elevation value was set.
wix_react-native-navigation
train
e69eaacaaa1456d0e4688594ee6d2b860de084c4
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -57,7 +57,9 @@ "doctrine/doctrine-fixtures-bundle": "^3.4", "phpstan/extension-installer": "^1.0", "phpstan/phpstan": "^0.12.52", + "phpstan/phpstan-phpunit": "^0.12.18", "phpstan/phpstan-symfony": "^0.12.10", + "psalm/plugin-phpunit": "^0.15.1", "psalm/plugin-symfony": "^2.0", "sonata-project/block-bundle": "^4.2", "sonata-project/entity-audit-bundle": "^1.1", @@ -87,5 +89,13 @@ "psr-4": { "Sonata\\DoctrineORMAdminBundle\\Tests\\": "tests/" } + }, + "scripts": { + "post-install-cmd": [ + "[ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/simple-phpunit install" + ], + "post-update-cmd": [ + "[ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/simple-phpunit install" + ] } } diff --git a/phpstan.neon.dist b/phpstan.neon.dist index <HASH>..<HASH> 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,5 +1,8 @@ parameters: level: 2 + bootstrapFiles: + - vendor/bin/.phpunit/phpunit/vendor/autoload.php paths: - src + - tests treatPhpDocTypesAsCertain: false diff --git a/psalm.xml b/psalm.xml index <HASH>..<HASH> 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,9 +1,14 @@ <?xml version="1.0" encoding="UTF-8"?> -<psalm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" errorLevel="7" resolveFromConfigFile="true" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" errorBaseline="psalm-baseline.xml"> +<psalm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" errorLevel="7" resolveFromConfigFile="true" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" autoloader="vendor/bin/.phpunit/phpunit/vendor/autoload.php" errorBaseline="psalm-baseline.xml"> <projectFiles> <directory name="src"/> + <directory name="tests"/> <ignoreFiles> <directory name="vendor"/> </ignoreFiles> </projectFiles> + <plugins> + <pluginClass class="Psalm\SymfonyPsalmPlugin\Plugin"/> + <pluginClass class="Psalm\PhpUnitPlugin\Plugin"/> + </plugins> </psalm> diff --git a/tests/App/Entity/Command.php b/tests/App/Entity/Command.php index <HASH>..<HASH> 100644 --- a/tests/App/Entity/Command.php +++ b/tests/App/Entity/Command.php @@ -29,7 +29,7 @@ class Command /** * @ORM\Column(type="datetime") * - * @param \DateTime + * @var \DateTime */ private $createdAt; diff --git a/tests/Filter/FilterTestCase.php b/tests/Filter/FilterTestCase.php index <HASH>..<HASH> 100644 --- a/tests/Filter/FilterTestCase.php +++ b/tests/Filter/FilterTestCase.php @@ -154,6 +154,6 @@ class TestQueryBuilder extends QueryBuilder /** @var string[] */ public $query = []; - /** @var string[] */ + /** @var mixed[] */ public $queryParameters = []; } diff --git a/tests/Fixtures/DoctrineType/ProductIdType.php b/tests/Fixtures/DoctrineType/ProductIdType.php index <HASH>..<HASH> 100644 --- a/tests/Fixtures/DoctrineType/ProductIdType.php +++ b/tests/Fixtures/DoctrineType/ProductIdType.php @@ -22,9 +22,9 @@ final class ProductIdType extends Type { const NAME = 'ProductId'; - public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string + public function getSQLDeclaration(array $column, AbstractPlatform $platform): string { - return $platform->getIntegerTypeDeclarationSQL($fieldDeclaration); + return $platform->getIntegerTypeDeclarationSQL($column); } public function requiresSQLCommentHint(AbstractPlatform $platform): bool diff --git a/tests/Fixtures/DoctrineType/ValueObjectWithToStringImpl.php b/tests/Fixtures/DoctrineType/ValueObjectWithToStringImpl.php index <HASH>..<HASH> 100644 --- a/tests/Fixtures/DoctrineType/ValueObjectWithToStringImpl.php +++ b/tests/Fixtures/DoctrineType/ValueObjectWithToStringImpl.php @@ -24,7 +24,7 @@ final class ValueObjectWithToStringImpl public function getValue() { - return (string) $this; + return (string) $this->uuid; } public function toString()
Run phpstan and psalm on tests
sonata-project_SonataDoctrineORMAdminBundle
train
4f7f18e92e1b0e15dfad6a9de6cbfeed0b5fb315
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Description.php b/lib/Alchemy/Phrasea/Controller/Admin/Description.php index <HASH>..<HASH> 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Description.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Description.php @@ -54,15 +54,16 @@ class Description implements ControllerProviderInterface 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfAtime', 'namespace' => 'Phraseanet' ), + 'tfbasename' => array( + 'tagname' => 'TfBasename', + 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfBasename', + 'namespace' => 'Phraseanet' + ), 'tfbits' => array( 'tagname' => 'TfBits', 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfBits', 'namespace' => 'Phraseanet' ), - 'tfbasename' => array( - 'tagname' => 'TfBasename', - 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfBasename', - 'namespace' => 'Phraseanet'), 'tfchannels' => array( 'tagname' => 'TfChannels', 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfChannels', @@ -73,6 +74,11 @@ class Description implements ControllerProviderInterface 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfCtime', 'namespace' => 'Phraseanet' ), + 'tfdirname' => array( + 'tagname' => 'TfDirname', + 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfDirname', + 'namespace' => 'Phraseanet' + ), 'tfduration' => array( 'tagname' => 'TfDuration', 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfDuration', @@ -113,9 +119,9 @@ class Description implements ControllerProviderInterface 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfMtime', 'namespace' => 'Phraseanet' ), - 'tfdirname' => array( - 'tagname' => 'TfDirname', - 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfDirname', + 'tfquarantine' => array( + 'tagname' => 'TfQuarantine', + 'classname' => '\\Alchemy\\Phrasea\\Metadata\\Tag\\TfQuarantine', 'namespace' => 'Phraseanet' ), 'tfrecordid' => array(
Add Tf-Quarantine to proposed Phraseanet TF-Fields
alchemy-fr_Phraseanet
train
efe032099e1996ef97df6f36618e6fbdbfcb8bc8
diff --git a/lib/discordrb/cache.rb b/lib/discordrb/cache.rb index <HASH>..<HASH> 100644 --- a/lib/discordrb/cache.rb +++ b/lib/discordrb/cache.rb @@ -1,3 +1,5 @@ +require 'discordrb/api' + module Discordrb module Cache # Initializes this cache
Make sure the Cache has access to the API
meew0_discordrb
train
c862518ff4830c0deaf84ef47d5b2d1def24ac6b
diff --git a/app/controllers/com/controller/admin.rb b/app/controllers/com/controller/admin.rb index <HASH>..<HASH> 100644 --- a/app/controllers/com/controller/admin.rb +++ b/app/controllers/com/controller/admin.rb @@ -94,7 +94,9 @@ module Com if self.class.private_method_defined?("#{model_name}_params") || self.class.method_defined?("#{model_name}_params") send "#{model_name}_params" else - params.fetch(model_name, {}).permit(*permit_keys) + p = params.fetch(model_name, {}).permit(*permit_keys) + p.merge! default_form_params if model_object.respond_to?(:organ_id) + p end end
auto responde to organ id
work-design_rails_com
train
0bdc57cd755b70291812ce7744b9c45376f94470
diff --git a/tools/bt-run.py b/tools/bt-run.py index <HASH>..<HASH> 100644 --- a/tools/bt-run.py +++ b/tools/bt-run.py @@ -66,6 +66,10 @@ def runstrat(): for strat, kwargs in strategies: cerebro.addstrategy(strat, **kwargs) + inds = getobjects(args.indicators, bt.Indicator, bt.indicators) + for ind, kwargs in inds: + cerebro.addindicator(ind, **kwargs) + obs = getobjects(args.observers, bt.Observer, bt.observers) for ob, kwargs in obs: cerebro.addobserver(ob, **kwargs) @@ -281,7 +285,7 @@ def parse_args(): 'strategy_name from the given module_path\n' '\n' 'module_path will load the module and return ' - 'the first available strategy in the module\n' + 'the 1st available strategy in the module\n' '\n' ':strategy_name will load the given strategy ' 'from the set of built-in strategies' @@ -306,16 +310,16 @@ def parse_args(): 'observer_name from the given module_path\n' '\n' 'module_path will load the module and return ' - 'all available observers in the module\n' + 'the 1st observer in the module\n' '\n' - ':observer_name will load the given strategy ' + ':observer_name will load the given observer ' 'from the set of built-in observers' '\n' 'To pass kwargs to the observer do it like this' '\n' 'module:observer:name=value,name2=value2')) - # Anaylzers + # Analyzers group = parser.add_argument_group(title='Analyzers') group.add_argument('--analyzer', '-an', dest='analyzers', action='append', required=False, @@ -325,18 +329,43 @@ def parse_args(): 'module_path:analzyer_name.\n' '\n' 'module_path:analyzer_name will load ' - 'observer_name from the given module_path\n' + 'analyzer_name from the given module_path\n' '\n' 'module_path will load the module and return ' - 'all available analyzers in the module\n' + 'the 1st analyzer in the module\n' '\n' - ':anaylzer_name will load the given strategy ' - 'from the set of built-in strategies' + ':analyzer_name will load the given analyzer ' + 'from the set of built-in analyzers' '\n' 'To pass kwargs to the analyzer do it like this' '\n' 'module:analyzer:name=value,name2=value2')) + # Analyzers + group = parser.add_argument_group(title='Indicators') + group.add_argument('--indicator', '-ind', dest='indicators', + action='append', required=False, + help=('This option can be specified multiple times.\n' + '\n' + 'The specified indicators will be injected in the' + 'loaded strategies' + '\n\n' + 'Module and indicator to load with format ' + 'module_path:indicator_name.\n' + '\n' + 'module_path:indicator_name will load ' + 'indicator_name from the given module_path\n' + '\n' + 'module_path will load the module and return ' + 'the 1st available indicator in the module\n' + '\n' + ':indicator_name will load the given indicator ' + 'from the set of built-in indicators' + '\n' + 'To pass kwargs to the analyzer do it like this' + '\n' + 'module:indicators:name=value,name2=value2')) + # Broker/Commissions group = parser.add_argument_group(title='Cash and Commission Scheme Args') group.add_argument('--cash', '-cash', required=False, type=float,
bt-run support for indicator injection into strategies
backtrader_backtrader
train
f583d878260e49ed5d52f50492a4bbfe0cfbb736
diff --git a/src/main/groovy/util/GroovyScriptEngine.java b/src/main/groovy/util/GroovyScriptEngine.java index <HASH>..<HASH> 100644 --- a/src/main/groovy/util/GroovyScriptEngine.java +++ b/src/main/groovy/util/GroovyScriptEngine.java @@ -181,12 +181,15 @@ public class GroovyScriptEngine implements ResourceConnector { StringSetMap cache = localCache.get(); cache.makeTransitiveHull(); long time = System.currentTimeMillis(); + Set<String> entryNames = new HashSet<String>(); for (Map.Entry<String,Set<String>> entry: cache.entrySet()) { String className = entry.getKey(); Class clazz = getClassCacheEntry(className); if (clazz==null) continue; String entryName = getPath(clazz); + if(entryNames.contains(entryName)) continue; + entryNames.add(entryName); Set<String> value = convertToPaths(entry.getValue()); ScriptCacheEntry cacheEntry = new ScriptCacheEntry(clazz,time,value); scriptCache.put(entryName,cacheEntry); diff --git a/src/main/org/codehaus/groovy/tools/gse/StringSetMap.java b/src/main/org/codehaus/groovy/tools/gse/StringSetMap.java index <HASH>..<HASH> 100644 --- a/src/main/org/codehaus/groovy/tools/gse/StringSetMap.java +++ b/src/main/org/codehaus/groovy/tools/gse/StringSetMap.java @@ -15,12 +15,12 @@ */ package org.codehaus.groovy.tools.gse; -import java.util.HashMap; -import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; -public class StringSetMap extends HashMap<String,Set<String>> { +public class StringSetMap extends LinkedHashMap<String,Set<String>> { public StringSetMap() { super(); @@ -36,7 +36,7 @@ public class StringSetMap extends HashMap<String,Set<String>> { String name = (String) o; Set<String> set = super.get(name); if (set==null) { - set = new HashSet(); + set = new LinkedHashSet<String>(); put(name,set); } return set; diff --git a/src/test/groovy/util/GroovyScriptEngineTest.groovy b/src/test/groovy/util/GroovyScriptEngineTest.groovy index <HASH>..<HASH> 100644 --- a/src/test/groovy/util/GroovyScriptEngineTest.groovy +++ b/src/test/groovy/util/GroovyScriptEngineTest.groovy @@ -18,8 +18,9 @@ class GroovyScriptEngineTest extends GroovyTestCase { private File helperIntf private File helper private File bug4013 + private File bug4234 - private List allFiles = [currentDir, srcDir, script, company, util, makeMeSuper, makeMe, helperIntf, helper, bug4013] + private List allFiles = [currentDir, srcDir, script, company, util, makeMeSuper, makeMe, helperIntf, helper, bug4013, bug4234] /** * Here we have inheritance and delegation-- where the delegate implements an @@ -108,6 +109,18 @@ class GroovyScriptEngineTest extends GroovyTestCase { } } """ + + bug4234 = new File(srcDir, "Groovy4234Helper.groovy") + bug4234.delete() + bug4234 << """ + class Foo4234 { + static main(args){ + println "Running Foo4234 -> main()" + } + } + + class Bar4234 { } + """ } public void tearDown(){ @@ -184,6 +197,22 @@ class GroovyScriptEngineTest extends GroovyTestCase { assert klazz.name == 'Groovy4013Helper' // we should still get the outer class, not inner one } + //GROOVY-4234 + void testGSERunningAScriptThatHasMultipleClasses() { + def klazz, gse + + String[] roots = new String[1] + roots[0] = srcDir.getAbsolutePath() + + gse = new GroovyScriptEngine(roots) + + println "testGSELoadingAScriptThatHasMultipleClasses - Run 1" + gse.run("Groovy4234Helper.groovy", new Binding()) + + println "testGSELoadingAScriptThatHasMultipleClasses - Run 2" + gse.run("Groovy4234Helper.groovy", new Binding()) + } + /* * The script passes the className of the class it's supposed to * instantiate to this method, expecting a newly instantiated object
GROOVY-<I> GSE failed to execute a script that had multiple classes. Fixed it. git-svn-id: <URL>
groovy_groovy-core
train
ca91c26b680c0163d7827f421619c6dbff6e76ee
diff --git a/bakery_lint/fonttests/test_ttf.py b/bakery_lint/fonttests/test_ttf.py index <HASH>..<HASH> 100644 --- a/bakery_lint/fonttests/test_ttf.py +++ b/bakery_lint/fonttests/test_ttf.py @@ -62,20 +62,6 @@ class TTFTestCase(TestCase): if std.getvalue(): self.fail('FontForge prints STDERR') - @autofix('bakery_cli.fixers.CharacterSymbolsFixer') - def test_check_names_are_ascii_only(self): - """ Is there any non-ascii character in NAME or CFF tables? """ - font = Font.get_ttfont(self.operator.path) - - for name in font.names: - # Items with NameID > 18 are expressly for localising - # the ASCII-only IDs into Hindi / Arabic / etc. - if name.nameID >= 0 and name.nameID <= 18: - string = Font.bin2unistring(name) - marks = CharacterSymbolsFixer.unicode_marks(string) - if marks: - self.fail('Contains {}'.format(marks)) - @autofix('bakery_cli.fixers.OpentypeFamilyNameFixer') def test_check_opentype_familyname(self): """ FamilyName matches Windows-only Opentype-specific FamilyName? """
delete old implementation of test_check_names_are_ascii_only
googlefonts_fontbakery
train
5e1da1a285b47edf32a5cfad5143c0bdc2d0c9e8
diff --git a/samples/DatePickerSample.js b/samples/DatePickerSample.js index <HASH>..<HASH> 100644 --- a/samples/DatePickerSample.js +++ b/samples/DatePickerSample.js @@ -1,13 +1,13 @@ enyo.kind({ name: "onyx.sample.DatePickerSample", kind: "FittableRows", - classes: "onyx onyx-sample", + classes: "onyx enyo-fit", handlers: { onSelect: "updateDateValues" }, components: [ {kind: "onyx.Toolbar", content:$L("Dates")}, - {kind: "FittableColumns", components:[ + {kind: "FittableColumns", style: "padding: 10px", components:[ {components: [ {content:$L("Choose Locale:"), classes:"onyx-sample-divider"}, {kind: "onyx.PickerDecorator", style:"padding:10px;", onSelect: "pickerHandler", components: [ @@ -32,7 +32,7 @@ enyo.kind({ {kind:"onyx.Button",content:"Get Dates", style:"margin:10px;", ontap:"getDates"}, {kind:"onyx.Button",content:"Reset Dates", ontap:"resetDates"}, {style:"width:100%;height:5px;background-color:black;margin-bottom:5px;"}, - {caption: "Dates", components: [ + {caption: "Dates", style: "padding: 10px", components: [ {content:"DATE",classes:"onyx-sample-divider"}, {classes: "onyx-toolbar-inline", components: [ {name:"datePicker1", kind:"onyx.DatePicker"} diff --git a/samples/TimePickerSample.js b/samples/TimePickerSample.js index <HASH>..<HASH> 100644 --- a/samples/TimePickerSample.js +++ b/samples/TimePickerSample.js @@ -1,13 +1,13 @@ enyo.kind({ name: "onyx.sample.TimePickerSample", kind: "FittableRows", - classes: "onyx onyx-sample", + classes: "onyx enyo-fit", handlers: { onSelect: "updateTimeValues" }, components: [ {kind: "onyx.Toolbar", content:$L("Times")}, - {kind: "FittableColumns", components:[ + {kind: "FittableColumns", style: "padding: 10px", components:[ {components: [ {content:$L("Choose Locale:"), classes:"onyx-sample-divider"}, {kind: "onyx.PickerDecorator", style:"padding:10px;", onSelect: "pickerHandler", components: [ @@ -34,7 +34,7 @@ enyo.kind({ {kind:"onyx.Button",content:"Reset Times", ontap:"resetTimes"}, {style:"width:100%;height:5px;background-color:black;margin-bottom:5px;"}, - {caption: "Dates", components: [ + {caption: "Dates", style: "padding: 10px", components: [ {content:"TIME",classes:"onyx-sample-divider"}, {classes: "onyx-toolbar-inline", components: [ {name:"timePicker1", kind:"onyx.TimePicker"}
Removing margin from date/time picker samples Enyo-DCO-<I>-
enyojs_onyx
train
e809c9c42ce76bb8581369a7e74d6ff8fe7a4438
diff --git a/Curl/Wrapper.php b/Curl/Wrapper.php index <HASH>..<HASH> 100644 --- a/Curl/Wrapper.php +++ b/Curl/Wrapper.php @@ -197,7 +197,7 @@ class Wrapper } if ($headers !== null && count($headers) > 0) { - $params['http']['header'] = $headers; + $cparams['http']['header'] = $headers; } $context = stream_context_create($cparams);
fopen alternative, proper response object with headers POST confirmed to be working
synaq_SynaqCurlBundle
train
40beb9fe926ef1dd0d29084fc27eaf7f40552078
diff --git a/jmock2/src/org/jmock/Mockery.java b/jmock2/src/org/jmock/Mockery.java index <HASH>..<HASH> 100644 --- a/jmock2/src/org/jmock/Mockery.java +++ b/jmock2/src/org/jmock/Mockery.java @@ -86,13 +86,22 @@ public class Mockery { } /** - * Specifies expectations on the context during the test. + * Specifies the expected invocations that the object under test will perform upon + * objects in its context during the test. */ public void expects(ExpectationBuilder builder) { builder.setDefaultAction(defaultAction); - expectation = builder.toExpectation(); - capture = null; + expects(builder.toExpectation()); } + + /** + * Specifies the expected invocations that the object under test will perform upon + * objects in its context during the test. + */ + public void expects(Expectation newExpectation) { + expectation = newExpectation; + capture = null; + } /** * Fails if the test if there are any expectations that have not been met.
Pulled out a public expects(Expectation) method to avoid being buried under a sugar coating. Some more javadoccery.
jmock-developers_jmock-library
train
1016d177ebde96fbf0a0a5ad14aea5b6fd78e83b
diff --git a/sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_version.py b/sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_version.py index <HASH>..<HASH> 100644 --- a/sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_version.py +++ b/sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_version.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -VERSION = "4.0.0b3" +VERSION = "4.0.0b4" diff --git a/sdk/keyvault/azure-keyvault-keys/azure/keyvault/keys/_version.py b/sdk/keyvault/azure-keyvault-keys/azure/keyvault/keys/_version.py index <HASH>..<HASH> 100644 --- a/sdk/keyvault/azure-keyvault-keys/azure/keyvault/keys/_version.py +++ b/sdk/keyvault/azure-keyvault-keys/azure/keyvault/keys/_version.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -VERSION = "4.0.0b3" +VERSION = "4.0.0b4" diff --git a/sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_version.py b/sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_version.py index <HASH>..<HASH> 100644 --- a/sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_version.py +++ b/sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_version.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -VERSION = "4.0.0b3" +VERSION = "4.0.0b4"
Increment Key Vault versions (#<I>)
Azure_azure-sdk-for-python
train
2d177e909d047f2c716e9d048da27893a8c5be6f
diff --git a/lib/puppet/provider/service/init.rb b/lib/puppet/provider/service/init.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/provider/service/init.rb +++ b/lib/puppet/provider/service/init.rb @@ -97,6 +97,7 @@ Puppet::Type.type(:service).provide :init, :parent => :base do fullpath = File.join(path, name) next if name =~ /^\./ next if exclude.include? name + next if FileTest.directory?(fullpath) next if not FileTest.executable?(fullpath) next if not is_init?(fullpath) instances << new(:name => name, :path => path, :hasstatus => true) diff --git a/spec/unit/provider/service/gentoo_spec.rb b/spec/unit/provider/service/gentoo_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/service/gentoo_spec.rb +++ b/spec/unit/provider/service/gentoo_spec.rb @@ -52,7 +52,8 @@ describe 'Puppet::Type::Service::Provider::Gentoo', end it "should get a list of services from /etc/init.d but exclude helper scripts" do - expect(FileTest).to receive(:directory?).with('/etc/init.d').and_return(true) + allow(FileTest).to receive(:directory?).and_call_original + allow(FileTest).to receive(:directory?).with('/etc/init.d').and_return(true) expect(Dir).to receive(:entries).with('/etc/init.d').and_return(initscripts) (initscripts - helperscripts).each do |script| expect(FileTest).to receive(:executable?).with("/etc/init.d/#{script}").and_return(true) diff --git a/spec/unit/provider/service/init_spec.rb b/spec/unit/provider/service/init_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/service/init_spec.rb +++ b/spec/unit/provider/service/init_spec.rb @@ -85,7 +85,8 @@ describe 'Puppet::Type::Service::Provider::Init', @services = ['one', 'two', 'three', 'four', 'umountfs'] allow(Dir).to receive(:entries).and_call_original allow(Dir).to receive(:entries).with('tmp').and_return(@services) - expect(FileTest).to receive(:directory?).with('tmp').and_return(true) + allow(FileTest).to receive(:directory?).and_call_original + allow(FileTest).to receive(:directory?).with('tmp').and_return(true) allow(FileTest).to receive(:executable?).and_return(true) end @@ -93,6 +94,11 @@ describe 'Puppet::Type::Service::Provider::Init', expect(provider_class.instances.map(&:name)).to eq(@services) end + it "should omit directories from the service list" do + expect(FileTest).to receive(:directory?).with('tmp/four').and_return(true) + expect(provider_class.instances.map(&:name)).to eq(@services - ['four']) + end + it "should omit an array of services from exclude list" do exclude = ['two', 'four'] expect(provider_class.get_services(provider_class.defpath, exclude).map(&:name)).to eq(@services - exclude) diff --git a/spec/unit/provider/service/openwrt_spec.rb b/spec/unit/provider/service/openwrt_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/service/openwrt_spec.rb +++ b/spec/unit/provider/service/openwrt_spec.rb @@ -50,7 +50,8 @@ describe 'Puppet::Type::Service::Provider::Openwrt', before :each do allow(Dir).to receive(:entries).and_call_original allow(Dir).to receive(:entries).with('/etc/init.d').and_return(services) - allow(FileTest).to receive(:directory?).and_return(true) + allow(FileTest).to receive(:directory?).and_call_original + allow(FileTest).to receive(:directory?).with('/etc/init.d').and_return(true) allow(FileTest).to receive(:executable?).and_return(true) end diff --git a/spec/unit/provider/service/redhat_spec.rb b/spec/unit/provider/service/redhat_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/service/redhat_spec.rb +++ b/spec/unit/provider/service/redhat_spec.rb @@ -50,7 +50,8 @@ describe 'Puppet::Type::Service::Provider::Redhat', @services = ['one', 'two', 'three', 'four', 'kudzu', 'functions', 'halt', 'killall', 'single', 'linuxconf', 'boot', 'reboot'] @not_services = ['functions', 'halt', 'killall', 'single', 'linuxconf', 'reboot', 'boot'] allow(Dir).to receive(:entries).and_return(@services) - allow(FileTest).to receive(:directory?).and_return(true) + allow(FileTest).to receive(:directory?).and_call_original + allow(FileTest).to receive(:directory?).with('/etc/init.d').and_return(true) allow(FileTest).to receive(:executable?).and_return(true) end
(PUP-<I>) Prevent puppet from executing directories Currently puppet is trying to execute directories which have the x-bit. This results in a lot of error messages like `Debug: Executing: '/etc/init.d/rc0.d status'` With this check these error messages won't appear. Fixes PUP-<I>
puppetlabs_puppet
train
879dd58df0cecc6f46acfae649b3913c8cc7c5d0
diff --git a/pysyncthru/language.py b/pysyncthru/language.py index <HASH>..<HASH> 100644 --- a/pysyncthru/language.py +++ b/pysyncthru/language.py @@ -15,13 +15,22 @@ class State(Enum): READY = 4 UNKNOWN = 5 PRINTING = 6 + SCANNING = 7 + CALIBRATING = 8 +# Translating all variations of status messages to their meaning RAW_TO_INTERNAL = { "EN": { ' Sleeping... ': State.SLEEPING, ' Ready to Copy ': State.READY, ' Warming Up ': State.WARMING_UP, + 'Sleeping....': State.SLEEPING, + 'Ready To Copy': State.READY, + 'Warming up. Please wait': State.WARMING_UP, + 'Printing': State.PRINTING, + 'Scanning': State.SCANNING, + 'Calibrating... Please Wait': State.CALIBRATING, }, "DE": { ' Sparbetrieb... ': State.SLEEPING, @@ -35,6 +44,38 @@ RAW_TO_INTERNAL = { } } +# Adds menue items that are mapped to "Ready" state +_MENUE_ITEMS = { + "EN": [ + 'Basic Copy', + 'Auto Fit Copy', + 'Custom Copy', + 'ID Copy', + 'N-Up Copy', + 'Book Copy', + 'Local PC', + 'Network PC', + 'FTP', + 'SMB', + 'Email', + 'USB', + 'Shared Folder', + 'Memory Send', + 'On Hook Dial', + 'Delayed Send', + 'Redial', + 'Group Dial Send', + 'Speed Dial Send', + 'Edit Home', + 'Machine Setup', + 'Admin Setup', + ] +} +for lang, items in _MENUE_ITEMS.items(): + for raw in items: + RAW_TO_INTERNAL[lang][raw] = State.READY + + ANY_LANGUAGE = {} for mapping in RAW_TO_INTERNAL.values(): ANY_LANGUAGE.update(mapping) @@ -47,6 +88,8 @@ INTERNAL_TO_HUMAN = { State.READY: 'Ready', State.UNKNOWN: 'Unknown', State.PRINTING: 'Printing', + State.SCANNING: 'Scanning', + State.CALIBRATING: 'Calibrating', }, "DE": { State.SLEEPING: 'Sparbetrieb', @@ -55,6 +98,8 @@ INTERNAL_TO_HUMAN = { State.READY: 'Bereit', State.UNKNOWN: 'Unbekannt', State.PRINTING: 'Drucken', + State.SCANNING: 'Scannen', + State.CALIBRATING: 'Kalibrieren', }, "RU": { State.SLEEPING: 'Oжидaниe', @@ -63,5 +108,7 @@ INTERNAL_TO_HUMAN = { State.READY: 'Гoтoв', State.UNKNOWN: 'Неизвестно', State.PRINTING: 'Идeт пeчaть', + State.SCANNING: 'сканирование', + State.CALIBRATING: 'калибровочный', }, }
Add more states for multi-skilled printer
nielstron_pysyncthru
train
ec4f6b6d587243bac785afd280f50bd8ba567710
diff --git a/src/Rocketeer/Services/Connections/ConnectionsHandler.php b/src/Rocketeer/Services/Connections/ConnectionsHandler.php index <HASH>..<HASH> 100644 --- a/src/Rocketeer/Services/Connections/ConnectionsHandler.php +++ b/src/Rocketeer/Services/Connections/ConnectionsHandler.php @@ -11,6 +11,7 @@ namespace Rocketeer\Services\Connections; use Illuminate\Support\Arr; use Illuminate\Support\Str; +use Rocketeer\Exceptions\ConnectionException; use Rocketeer\Traits\HasLocator; /** @@ -256,6 +257,8 @@ class ConnectionsHandler * Set the active connections * * @param string|string[] $connections + * + * @throws ConnectionException */ public function setConnections($connections) { @@ -264,11 +267,13 @@ class ConnectionsHandler } // Sanitize and set connections - $connections = array_filter($connections, [$this, 'isValidConnection']); - if ($connections) { - $this->connections = $connections; - $this->handle = null; + $filtered = array_filter($connections, [$this, 'isValidConnection']); + if (!$filtered) { + throw new ConnectionException('Invalid connection(s): '.implode(', ', $connections)); } + + $this->connections = $filtered; + $this->handle = null; } /** diff --git a/tests/Services/Connections/ConnectionsHandlerTest.php b/tests/Services/Connections/ConnectionsHandlerTest.php index <HASH>..<HASH> 100644 --- a/tests/Services/Connections/ConnectionsHandlerTest.php +++ b/tests/Services/Connections/ConnectionsHandlerTest.php @@ -182,7 +182,7 @@ class ConnectionsHandlerTest extends RocketeerTestCase public function testValidatesConnectionOnMultiset() { - $this->connections->setConnections(['foo', 'bar']); + $this->connections->setConnections(['production', 'bar']); $this->assertEquals(['production'], $this->connections->getConnections()); } @@ -220,6 +220,13 @@ class ConnectionsHandlerTest extends RocketeerTestCase $this->assertArrayNotHasKey(2, $this->connections->getConnectionCredentials('production')); } + public function testThrowsExceptionWhenTryingToSetInvalidConnection() + { + $this->setExpectedException('Rocketeer\Exceptions\ConnectionException', 'Invalid connection(s): foo, bar'); + + $this->connections->setConnections('foo,bar'); + } + //////////////////////////////////////////////////////////////////// //////////////////////////////// HELPERS /////////////////////////// ////////////////////////////////////////////////////////////////////
Close #<I> - Throw exception on invalid connections, instead of falling back to last valid one
rocketeers_rocketeer
train
46f7e8bb075036c92695b15a1ddb6971c751e585
diff --git a/src/DocBlock/Tags/Method.php b/src/DocBlock/Tags/Method.php index <HASH>..<HASH> 100644 --- a/src/DocBlock/Tags/Method.php +++ b/src/DocBlock/Tags/Method.php @@ -98,8 +98,8 @@ final class Method extends BaseTag implements Factory\StaticMethod (?:[\w\|_\\\\]+) # array notation (?:\[\])* - ) - )? + )* + ) \s+ )? # Legacy method name (not captured) diff --git a/tests/unit/DocBlock/Tags/MethodTest.php b/tests/unit/DocBlock/Tags/MethodTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/DocBlock/Tags/MethodTest.php +++ b/tests/unit/DocBlock/Tags/MethodTest.php @@ -15,6 +15,7 @@ namespace phpDocumentor\Reflection\DocBlock\Tags; use Mockery as m; use phpDocumentor\Reflection\DocBlock\Description; use phpDocumentor\Reflection\DocBlock\DescriptionFactory; +use phpDocumentor\Reflection\Fqsen; use phpDocumentor\Reflection\TypeResolver; use phpDocumentor\Reflection\Types\Array_; use phpDocumentor\Reflection\Types\Compound; @@ -469,6 +470,16 @@ class MethodTest extends \PHPUnit_Framework_TestCase $this->assertSame($description, $fixture->getDescription()); } + /** + * @covers ::create + * @uses \phpDocumentor\Reflection\DocBlock\Tags\Method::<public> + * @uses \phpDocumentor\Reflection\DocBlock\DescriptionFactory + * @uses \phpDocumentor\Reflection\TypeResolver + * @uses \phpDocumentor\Reflection\DocBlock\Description + * @uses \phpDocumentor\Reflection\Fqsen + * @uses \phpDocumentor\Reflection\Types\Context + * @uses \phpDocumentor\Reflection\Types\Void_ + */ public function testCreateWithoutReturnType() { $descriptionFactory = m::mock(DescriptionFactory::class); @@ -492,4 +503,44 @@ class MethodTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf(Void_::class, $fixture->getReturnType()); $this->assertSame($description, $fixture->getDescription()); } + + /** + * @covers ::create + * @uses \phpDocumentor\Reflection\DocBlock\Tags\Method::<public> + * @uses \phpDocumentor\Reflection\DocBlock\DescriptionFactory + * @uses \phpDocumentor\Reflection\TypeResolver + * @uses \phpDocumentor\Reflection\DocBlock\Description + * @uses \phpDocumentor\Reflection\Fqsen + * @uses \phpDocumentor\Reflection\Types\Context + * @uses \phpDocumentor\Reflection\Types\Array_ + * @uses \phpDocumentor\Reflection\Types\Compound + * @uses \phpDocumentor\Reflection\Types\Integer + * @uses \phpDocumentor\Reflection\Types\Object_ + */ + public function testCreateWithMixedReturnTypes() + { + $descriptionFactory = m::mock(DescriptionFactory::class); + $resolver = new TypeResolver(); + $context = new Context(''); + + $descriptionFactory->shouldReceive('create')->andReturn(new Description('')); + + $fixture = Method::create( + 'MyClass[]|int[] myMethod()', + $resolver, + $descriptionFactory, + $context + ); + + $this->assertSame('\MyClass[]|int[] myMethod()', (string)$fixture); + $this->assertSame('myMethod', $fixture->getMethodName()); + $this->assertEquals([], $fixture->getArguments()); + + $this->assertEquals( + new Compound([ + new Array_(new Object_(new Fqsen('\MyClass'))), + new Array_(new Integer()), + ]) + , $fixture->getReturnType()); + } }
Allows usage of compound array types fixes #<I>
phpDocumentor_ReflectionDocBlock
train
edeb3cb0121b70d931da87f30e558746d1500d10
diff --git a/views/js/qtiCommonRenderer/renderers/interactions/ExtendedTextInteraction.js b/views/js/qtiCommonRenderer/renderers/interactions/ExtendedTextInteraction.js index <HASH>..<HASH> 100755 --- a/views/js/qtiCommonRenderer/renderers/interactions/ExtendedTextInteraction.js +++ b/views/js/qtiCommonRenderer/renderers/interactions/ExtendedTextInteraction.js @@ -22,8 +22,8 @@ * @author Bertrand Chevrier <bertrand@taotesting.com> */ define([ - 'lodash', 'jquery', + 'lodash', 'i18n', 'tpl!taoQtiItem/qtiCommonRenderer/tpl/interactions/extendedTextInteraction', 'taoQtiItem/qtiCommonRenderer/helpers/container', @@ -31,7 +31,7 @@ define([ 'ckeditor', 'taoQtiItem/qtiCreator/editor/ckEditor/ckConfigurator', 'polyfill/placeholders' -], function(_, $, __, tpl, containerHelper, instructionMgr, ckEditor ,ckConfigurator){ +], function($, _, __, tpl, containerHelper, instructionMgr, ckEditor ,ckConfigurator){ 'use strict'; /** @@ -120,7 +120,7 @@ define([ } else { $el.bind('keyup change', function(e) { - Helper.triggerResponseChangeEvent(interaction, {}); + containerHelper.triggerResponseChangeEvent(interaction, {}); }); } @@ -334,7 +334,7 @@ define([ }; var _ckEditorData = function(interaction) { - return Helper.getContainer(interaction).data('editor').getData(); + return containerHelper.get(interaction).data('editor').getData(); }; var _getFormat = function(interaction) { @@ -382,10 +382,9 @@ define([ var $container = containerHelper.getContainer(interaction); $container.find('input, textarea').attr('disabled', 'disabled'); -if (interaction.attr('format') === 'xhtml' && $container.data('editor')) { + if (interaction.attr('format') === 'xhtml' && $container.data('editor')) { $container.data('editor').destroy(); } - } }; var clearText = function(interaction) { @@ -402,7 +401,6 @@ if (interaction.attr('format') === 'xhtml' && $container.data('editor')) { $container.find('textarea').val(text); } }; -<<<<<<< HEAD /** * Clean interaction destroy
fix wrong merge in extended text renderer
oat-sa_extension-tao-itemqti
train
5e2cdb48d45af795d2901659bc28aee6d770c681
diff --git a/command/helper_stats.go b/command/helper_stats.go index <HASH>..<HASH> 100644 --- a/command/helper_stats.go +++ b/command/helper_stats.go @@ -1,6 +1,8 @@ package command import ( + "fmt" + "github.com/hashicorp/nomad/api" ) @@ -28,3 +30,17 @@ func buildDeviceStatsSummaryMap(host *api.HostStats) map[string]*api.StatValue { return r } + +func formatDeviceStats(stat *api.StatObject, keyPrefix string, result *[]string) { + if keyPrefix != "" { + keyPrefix = keyPrefix + "." + } + + for n, stat := range stat.Attributes { + *result = append(*result, fmt.Sprintf("%s%s|%s", keyPrefix, n, stat)) + } + + for k, o := range stat.Nested { + formatDeviceStats(o, keyPrefix+k, result) + } +} diff --git a/command/helper_stats_test.go b/command/helper_stats_test.go index <HASH>..<HASH> 100644 --- a/command/helper_stats_test.go +++ b/command/helper_stats_test.go @@ -1,6 +1,7 @@ package command import ( + "sort" "testing" "github.com/hashicorp/nomad/api" @@ -73,3 +74,58 @@ func TestBuildDeviceStatsSummaryMap(t *testing.T) { require.EqualValues(t, expected, buildDeviceStatsSummaryMap(hostStats)) } + +func TestFormatDeviceStats(t *testing.T) { + statValue := func(v string) *api.StatValue { + return &api.StatValue{ + StringVal: helper.StringToPtr(v), + } + } + + stat := &api.StatObject{ + Attributes: map[string]*api.StatValue{ + "k0": statValue("v0"), + }, + Nested: map[string]*api.StatObject{ + "nested1": &api.StatObject{ + Attributes: map[string]*api.StatValue{ + "k1_0": statValue("v1_0"), + "k1_1": statValue("v1_1"), + }, + Nested: map[string]*api.StatObject{ + "nested1_1": &api.StatObject{ + Attributes: map[string]*api.StatValue{ + "k11_0": statValue("v11_0"), + "k11_1": statValue("v11_1"), + }, + }, + }, + }, + "nested2": &api.StatObject{ + Attributes: map[string]*api.StatValue{ + "k2": statValue("v2"), + }, + }, + }, + } + + result := []string{"preseedkey|pressededvalue"} + formatDeviceStats(stat, "", &result) + + // check array is appended only + require.Equal(t, "preseedkey|pressededvalue", result[0]) + + // check rest of values + sort.Strings(result) + expected := []string{ + "k0|v0", + "nested1.k1_0|v1_0", + "nested1.k1_1|v1_1", + "nested1.nested1_1.k11_0|v11_0", + "nested1.nested1_1.k11_1|v11_1", + "nested2.k2|v2", + "preseedkey|pressededvalue", + } + + require.Equal(t, expected, result) +} diff --git a/command/node_status.go b/command/node_status.go index <HASH>..<HASH> 100644 --- a/command/node_status.go +++ b/command/node_status.go @@ -602,9 +602,8 @@ func (c *NodeStatusCommand) printDeviceStats(hostStats *api.HostStats) { qid := deviceQualifiedID(dg.Vendor, dg.Type, dg.Name, id) attrs := make([]string, 1, len(dinst.Stats.Attributes)+1) attrs[0] = fmt.Sprintf("Device|%s", qid) - for n, stat := range dinst.Stats.Attributes { - attrs = append(attrs, fmt.Sprintf("%s|%s", n, stat)) - } + formatDeviceStats(dinst.Stats, "", &attrs) + c.Ui.Output(formatKV(attrs)) } }
Display StatsObject nested objects as well
hashicorp_nomad
train
b6ff824cd5292b393f9dd5c976a193dc5afd808a
diff --git a/lib/mongodb/connection.js b/lib/mongodb/connection.js index <HASH>..<HASH> 100644 --- a/lib/mongodb/connection.js +++ b/lib/mongodb/connection.js @@ -24,6 +24,7 @@ var Connection = exports.Connection = function(host, port, autoReconnect, option this.buffer = ''; this.stubBuffer = ''; this.connected = false; + this.closedConnectionCount = 0; // Connection pool variables this.pool = []; @@ -200,9 +201,9 @@ var setupConnectionPool = function(self, poolSize, reconnect) { // Add a close listener connection.addListener("close", function() { - // Only emit close once the last connection in the pool closes. - connectedTo = connectedTo - 1; - if (connectedTo === 0) + // Only emit close once all connections in the pool have closed. + // Note that connections which emit an error also emit a close. + if (++self.closedConnectionCount === self.pool.length) self.emit("close"); });
Make connection emit close event even in presence of errors.
mongodb_node-mongodb-native
train
eb4d2976ed3862a4a76dcf2c05ecec788863623d
diff --git a/lib/adhearsion/call_controller/output/formatter.rb b/lib/adhearsion/call_controller/output/formatter.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/call_controller/output/formatter.rb +++ b/lib/adhearsion/call_controller/output/formatter.rb @@ -38,9 +38,7 @@ module Adhearsion def uri?(string) uri = URI.parse string !!uri.scheme - rescue URI::BadURIError - false - rescue URI::InvalidURIError + rescue URI::BadURIError, URI::InvalidURIError false end
[CS] Reduce duplication in error conditions
adhearsion_adhearsion
train
661016672f62739dda9d95630503ceee7d46b99b
diff --git a/salt/returners/mysql.py b/salt/returners/mysql.py index <HASH>..<HASH> 100644 --- a/salt/returners/mysql.py +++ b/salt/returners/mysql.py @@ -80,7 +80,7 @@ log = logging.getLogger(__name__) def __virtual__(): if not HAS_MYSQL: return False - return 'mysql' + return True def _get_options():
Not renaming, return a boolean in `__virtual__()`.
saltstack_salt
train
0d3874474e946e0b47ad54a7a222cd866d810cf1
diff --git a/src/Http/Client/Auth/Oauth.php b/src/Http/Client/Auth/Oauth.php index <HASH>..<HASH> 100644 --- a/src/Http/Client/Auth/Oauth.php +++ b/src/Http/Client/Auth/Oauth.php @@ -220,6 +220,9 @@ class Oauth $credentials['privateKeyPassphrase'] = $passphrase; } $privateKey = openssl_pkey_get_private($credentials['privateKey'], $credentials['privateKeyPassphrase']); + if ($privateKey === false) { + throw new RuntimeException('Could not open privateKey file. Got ' . openssl_error_string()); + } $signature = ''; openssl_sign($baseString, $signature, $privateKey); if (PHP_MAJOR_VERSION < 8) {
Add better error handling for OpenSSL failures Raise errors when OpenSSL cannot read the private key file. Refs #<I>
cakephp_cakephp
train
2def3420c2f0be37e51f677d42084b8ff08b2e3b
diff --git a/nodeconductor/structure/serializers.py b/nodeconductor/structure/serializers.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/serializers.py +++ b/nodeconductor/structure/serializers.py @@ -275,7 +275,7 @@ class CustomerPermissionSerializer(PermissionFieldFilteringMixin, class Meta(object): model = User.groups.through fields = ( - 'url', 'role', + 'url', 'pk', 'role', 'customer', 'customer_name', 'customer_native_name', 'customer_abbreviation', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid', ) @@ -348,7 +348,7 @@ class ProjectPermissionSerializer(PermissionFieldFilteringMixin, class Meta(object): model = User.groups.through fields = ( - 'url', + 'url', 'pk', 'role', 'project', 'project_name', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid', @@ -420,7 +420,7 @@ class ProjectGroupPermissionSerializer(PermissionFieldFilteringMixin, class Meta(object): model = User.groups.through fields = ( - 'url', + 'url', 'pk', 'role', 'project_group', 'project_group_name', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid', diff --git a/nodeconductor/structure/tests/test_customer_permissions.py b/nodeconductor/structure/tests/test_customer_permissions.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/tests/test_customer_permissions.py +++ b/nodeconductor/structure/tests/test_customer_permissions.py @@ -39,7 +39,7 @@ class CustomerPermissionSerializerTest(unittest.TestCase): def test_payload_has_required_fields(self): expected_fields = [ - 'url', 'role', + 'url', 'role', 'pk', 'customer', 'customer_name', 'customer_native_name', 'customer_abbreviation', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid' ] diff --git a/nodeconductor/structure/tests/test_project_groups_permissions.py b/nodeconductor/structure/tests/test_project_groups_permissions.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/tests/test_project_groups_permissions.py +++ b/nodeconductor/structure/tests/test_project_groups_permissions.py @@ -39,7 +39,7 @@ class ProjectGroupPermissionSerializerTest(unittest.TestCase): def test_payload_has_required_fields(self): expected_fields = [ - 'url', 'role', 'project_group', 'project_group_name', + 'url', 'role', 'project_group', 'project_group_name', 'pk', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid' ] self.assertItemsEqual(expected_fields, self.serializer.fields.keys()) diff --git a/nodeconductor/structure/tests/test_project_permissions.py b/nodeconductor/structure/tests/test_project_permissions.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/tests/test_project_permissions.py +++ b/nodeconductor/structure/tests/test_project_permissions.py @@ -39,7 +39,7 @@ class ProjectPermissionSerializerTest(unittest.TestCase): def test_payload_has_required_fields(self): expected_fields = [ - 'url', 'role', 'project', 'project_name', + 'url', 'role', 'project', 'project_name', 'pk', 'user', 'user_full_name', 'user_native_name', 'user_username', 'user_uuid' ] self.assertItemsEqual(expected_fields, self.serializer.fields.keys())
Expose PK of permission endpoints as fields - SAAS-<I> - Simplify the life of REST client builders.
opennode_waldur-core
train