hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
eb98e212cb525df1a3d21c75e33cae941d0cbbc3
diff --git a/libnetwork/drivers/bridge/link.go b/libnetwork/drivers/bridge/link.go index <HASH>..<HASH> 100644 --- a/libnetwork/drivers/bridge/link.go +++ b/libnetwork/drivers/bridge/link.go @@ -69,7 +69,7 @@ func linkContainers(action, parentIP, childIP string, ports []netutils.PortBindi return InvalidLinkIPAddrError(childIP) } - chain := iptables.Chain{Name: "DOCKER", Bridge: bridge} + chain := iptables.Chain{Name: DockerChain, Bridge: bridge} for _, port := range ports { err := chain.Link(nfAction, ip1, ip2, int(port.Port), port.Proto.String()) if !ignoreErrors && err != nil {
Reuse existing docker chain constant in link.go - in bridge driver
moby_moby
train
0225b9129df80899e0a1f5d59f3d8eee281573c6
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -25,6 +25,9 @@ var headers = { // Location of token file to generate when user authenticates var tokenFile = __dirname + '/authtoken.txt'; +// Keep track of the number of failed files to change the file break color for readability +var numFailedFiles = 0; + module.exports = function () { // Use Auth Token if present @@ -57,6 +60,10 @@ module.exports = function () { glob.sync(fileGlob).forEach(function (file) { lintMarkdown(fs.readFileSync(file, 'utf8'), file); }); + + if (numFailedFiles > 0) { + process.exit(1); + } }); program @@ -98,6 +105,9 @@ module.exports = function () { glob.sync(command).forEach(function (file) { lintMarkdown(fs.readFileSync(file, 'utf8'), file); }); + if (numFailedFiles > 0) { + process.exit(1); + } } else if (command.indexOf('/') !== -1) { fetchREADME(command); } else { @@ -199,9 +209,6 @@ function parseMarkdown (markdownContent) { // Boolean to keep track if the file break has been logged when discovering multiple errors in a single file var loggedFileBreak; -// Keep track of the number of failed files to change the file break color for readability -var numFailedFiles = 0; - /** * Parses the JavaScript code blocks from the markdown file * @param {String} body Body of markdown file
Added non-zero exit code when local files fail, Fixes #5
ChrisWren_mdlint
train
d6011e6f77e890135f4899b8a30d2a51f70a8734
diff --git a/closure/goog/positioning/positioning_test.js b/closure/goog/positioning/positioning_test.js index <HASH>..<HASH> 100644 --- a/closure/goog/positioning/positioning_test.js +++ b/closure/goog/positioning/positioning_test.js @@ -696,7 +696,15 @@ function testPositionAtAnchorWithResizeHeight() { viewport.toBox()); assertEquals('Status should be HEIGHT_ADJUSTED.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, status); - assertTrue('Popup is within viewport', + + var TOLERANCE = 0.1; + // Adjust the viewport to allow some tolerance for subpixel positioning, + // this is required for this test to pass on IE10,11 + viewport.top -= TOLERANCE; + viewport.left -= TOLERANCE; + + assertTrue('Popup ' + goog.style.getBounds(popup) + + ' not is within viewport' + viewport, viewport.contains(goog.style.getBounds(popup))); }
Add some tolerance for subpixel positioning on IE<I>/<I>. ------------- Created by MOE: <URL>
google_closure-library
train
1ca41ba1e0dd9b3c73d48ff26c321145ea29cdc6
diff --git a/primer3/__init__.py b/primer3/__init__.py index <HASH>..<HASH> 100644 --- a/primer3/__init__.py +++ b/primer3/__init__.py @@ -8,6 +8,15 @@ Current Primer3 version included in package: 2.3.6 Support for both Python 2.7.x and Python 3.x.x ''' +import os +LOCAL_DIR = os.path.dirname(os.path.realpath(__file__)) + +if not os.environ.get('PRIMER3HOME'): + try: + os.environ['PRIMER3HOME'] = os.path.join(LOCAL_DIR, 'src/libprimer3') + except: + raise ImportError('PRIMER3HOME environmental variable is not set.') + from primer3.bindings import (calcHairpin, calcHomodimer, calcHeterodimer, calcHairpinTm, calcHomodimerTm, diff --git a/primer3/bindings.py b/primer3/bindings.py index <HASH>..<HASH> 100644 --- a/primer3/bindings.py +++ b/primer3/bindings.py @@ -16,13 +16,6 @@ import _primer3 # ~~~~~~~ Check to insure that the environment is properly configured ~~~~~~~ # -LOCAL_DIR = os.path.dirname(os.path.realpath(__file__)) - -if not os.environ.get('PRIMER3HOME'): - try: - os.environ['PRIMER3HOME'] = pjoin(LOCAL_DIR, 'src/libprimer3') - except: - raise ImportError('PRIMER3HOME environmental variable is not set.') PRIMER3_HOME = os.environ.get('PRIMER3HOME') diff --git a/primer3/src/analysis2.pyx b/primer3/src/analysis2.pyx index <HASH>..<HASH> 100644 --- a/primer3/src/analysis2.pyx +++ b/primer3/src/analysis2.pyx @@ -36,9 +36,40 @@ cdef extern from "libprimer3/thal.h": int get_thermodynamic_values(const char*, thal_results *) +from cpython.version cimport PY_MAJOR_VERSION + +cdef bytes _bytes(s): + if PY_MAJOR_VERSION > 2 and isinstance(s, str): + # encode to the specific encoding used inside of the module + s = (<str>s).encode('utf8') + return s + else: + return <bytes>s + +def loadThermoParams(): + cdef char* param_path + cdef thal_results thalres + import os + PRIMER3_HOME = os.environ.get('PRIMER3HOME') + ppath = os.path.join(PRIMER3_HOME, 'primer3_config/') + ppath = ppath.encode('utf-8') + param_path = ppath + if get_thermodynamic_values(param_path, &thalres) != 0: + raise IOError("couldn't load config file") +loadThermoParams() + cdef class ThermoResult: cdef thal_results thalres + property temp: + def __get__(self): + return self.thalres.temp + + property dg: + def __get__(self): + return self.thalres.dg + + def __init__(self): self.thalres.no_structure = 0; self.thalres.ds = self.thalres.dh = self.thalres.dg = 0.0 @@ -92,10 +123,8 @@ cdef class ThermoAnalysis: self.salt_correction_method = salt_correction_method # end def - cpdef heterodimer(self, oligo1, oligo2): - cdef char* s1 = oligo1 - cdef char* s2 = oligo2 - tr_obj = ThermoResult() + cdef inline heterodimer_c(ThermoAnalysis self, char* s1, char* s2): + cdef ThermoResult tr_obj = ThermoResult() self.thalargs.dimer = 1 """ @@ -110,3 +139,13 @@ cdef class ThermoAnalysis: <const thal_args *> &(self.thalargs), &(tr_obj.thalres), 0) return tr_obj # end def + + def heterodimer(self, oligo1, oligo2): + oligo1 = _bytes(oligo1) + oligo2 = _bytes(oligo2) + print("oligo1:", type(oligo1)) + print("oligo2:", type(oligo2)) + cdef char* s1 = oligo1 + cdef char* s2 = oligo2 + return ThermoAnalysis.heterodimer_c(<ThermoAnalysis> self, s1, s2) + # end def diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -106,7 +106,7 @@ setup ( 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)' ], packages=['primer3'], - ext_modules=[primer3_ext, analysis_ext], + ext_modules=[primer3_ext], # ext_modules=[primer3_ext] + a2_list, package_data={'primer3': p3_files}, )
cython binding for thermo paramaters proof of concept is done
libnano_primer3-py
train
53bb3b8736a9d90c29caad39690fb194ccde910c
diff --git a/python/vaex/io/colfits.py b/python/vaex/io/colfits.py index <HASH>..<HASH> 100644 --- a/python/vaex/io/colfits.py +++ b/python/vaex/io/colfits.py @@ -45,6 +45,7 @@ def empty(filename, length, column_names, data_types, data_shapes): write("NAXIS", 2, "number of array dimensions") write("NAXIS1", byte_size, "length of dim 1") write("NAXIS2", 1, "length of dim 2") + write("PCOUNT", 0, "number of group parameters") write("TFIELDS", len(column_names), "number of columns") for i, (column_name, type, shape) in enumerate(zip(column_names, data_types, data_shapes)): diff --git a/test/dataset.py b/test/dataset.py index <HASH>..<HASH> 100644 --- a/test/dataset.py +++ b/test/dataset.py @@ -5,6 +5,7 @@ import unittest import vaex as vx import tempfile import vaex.webserver +import astropy.io.fits import vaex.execution a = vaex.execution.buffer_size # will crash if we decide to rename it @@ -294,6 +295,9 @@ class TestDataset(unittest.TestCase): else: path = path_fits export(path, column_names=column_names, shuffle=shuffle, selection=selection) + fitsfile = astropy.io.fits.open(path) + # make sure astropy can read the data + bla = fitsfile[1].data compare = vx.open(path) column_names = column_names or ["x", "y", "z"] self.assertEqual(compare.get_column_names(), column_names + (["random_index"] if shuffle else [])) @@ -307,6 +311,7 @@ class TestDataset(unittest.TestCase): self.assertEqual(sorted(compare.columns[column_name]), sorted(values[indices])) else: self.assertEqual(sorted(compare.columns[column_name]), sorted(values[:length])) + # self.dataset_concat_dup references self.dataset, so set it's active_fraction to 1 again dataset.set_active_fraction(1)
fixed fits export PCOUNT=0, and wrote test to make sure astropy can read it
vaexio_vaex
train
7ca2ed28a18959d35693c11c4528f70bc261ec84
diff --git a/src/main/java/com/github/davidmoten/rx/jdbc/Database.java b/src/main/java/com/github/davidmoten/rx/jdbc/Database.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/davidmoten/rx/jdbc/Database.java +++ b/src/main/java/com/github/davidmoten/rx/jdbc/Database.java @@ -264,12 +264,12 @@ final public class Database { return this; } - public Builder username() { + public Builder username(String username) { this.username = username; return this; } - public Builder password() { + public Builder password(String password) { this.password = password; return this; }
add username and password to parameters that can be passed in Database.Builder
davidmoten_rxjava-jdbc
train
aeecb9cdf54b91f06b328993c64884ec81196bae
diff --git a/breacharbiter_test.go b/breacharbiter_test.go index <HASH>..<HASH> 100644 --- a/breacharbiter_test.go +++ b/breacharbiter_test.go @@ -970,7 +970,7 @@ func TestBreachHandoffSuccess(t *testing.T) { // Send one HTLC to Bob and perform a state transition to lock it in. htlcAmount := lnwire.NewMSatFromSatoshis(20000) htlc, _ := createHTLC(0, htlcAmount) - if _, err := alice.AddHTLC(htlc); err != nil { + if _, err := alice.AddHTLC(htlc, nil); err != nil { t.Fatalf("alice unable to add htlc: %v", err) } if _, err := bob.ReceiveHTLC(htlc); err != nil { @@ -990,7 +990,7 @@ func TestBreachHandoffSuccess(t *testing.T) { // Now send another HTLC and perform a state transition, this ensures // Alice is ahead of the state Bob will broadcast. htlc2, _ := createHTLC(1, htlcAmount) - if _, err := alice.AddHTLC(htlc2); err != nil { + if _, err := alice.AddHTLC(htlc2, nil); err != nil { t.Fatalf("alice unable to add htlc: %v", err) } if _, err := bob.ReceiveHTLC(htlc2); err != nil { @@ -1058,7 +1058,7 @@ func TestBreachHandoffFail(t *testing.T) { // Send one HTLC to Bob and perform a state transition to lock it in. htlcAmount := lnwire.NewMSatFromSatoshis(20000) htlc, _ := createHTLC(0, htlcAmount) - if _, err := alice.AddHTLC(htlc); err != nil { + if _, err := alice.AddHTLC(htlc, nil); err != nil { t.Fatalf("alice unable to add htlc: %v", err) } if _, err := bob.ReceiveHTLC(htlc); err != nil { @@ -1078,7 +1078,7 @@ func TestBreachHandoffFail(t *testing.T) { // Now send another HTLC and perform a state transition, this ensures // Alice is ahead of the state Bob will broadcast. htlc2, _ := createHTLC(1, htlcAmount) - if _, err := alice.AddHTLC(htlc2); err != nil { + if _, err := alice.AddHTLC(htlc2, nil); err != nil { t.Fatalf("alice unable to add htlc: %v", err) } if _, err := bob.ReceiveHTLC(htlc2); err != nil { @@ -1554,7 +1554,7 @@ func forceStateTransition(chanA, chanB *lnwallet.LightningChannel) error { return err } - if _, err := chanA.ReceiveRevocation(bobRevocation); err != nil { + if _, _, _, err := chanA.ReceiveRevocation(bobRevocation); err != nil { return err } if err := chanA.ReceiveNewCommitment(bobSig, bobHtlcSigs); err != nil { @@ -1565,7 +1565,7 @@ func forceStateTransition(chanA, chanB *lnwallet.LightningChannel) error { if err != nil { return err } - if _, err := chanB.ReceiveRevocation(aliceRevocation); err != nil { + if _, _, _, err := chanB.ReceiveRevocation(aliceRevocation); err != nil { return err }
breacharbiter_test: utilize update channel state transition APIs
lightningnetwork_lnd
train
483da57d1789b07cafc52a764919daafc5083e31
diff --git a/core/helpers/Url.php b/core/helpers/Url.php index <HASH>..<HASH> 100644 --- a/core/helpers/Url.php +++ b/core/helpers/Url.php @@ -38,7 +38,7 @@ class Url extends \yii\helpers\Url } /** - * Only stil exists to avoid bc break, fromer known as `to()` us `Url::toRoute(['/module/controller/action', 'arg1' => 'arg1value']);` instead. + * Only stil exists to avoid bc break, former known as `to()`. Use `Url::toRoute(['/module/controller/action', 'arg1' => 'arg1value']);` instead. * Wrapper functions for the createUrl function of the url manager. * * @param string $route diff --git a/core/web/View.php b/core/web/View.php index <HASH>..<HASH> 100644 --- a/core/web/View.php +++ b/core/web/View.php @@ -6,20 +6,24 @@ use Yii; use luya\helpers\Url; /** - * LUYA web view wrapper + * LUYA web view wrapper. * - * @author nadar + * Implements additional helper methods to the Yii web controller. + * + * @author Basil Suter <[email protected]> */ class View extends \yii\web\View { - private $_publicHtml = null; - /** * @var boolean If csrf validation is enabled in the request component, and autoRegisterCsrf is enabled, then * all the meta informations will be auto added to meta tags. */ public $autoRegisterCsrf = true; + /** + * Init view object. Implements auto register csrf meta tokens. + * @see \yii\base\View::init() + */ public function init() { // call parent initializer @@ -32,10 +36,10 @@ class View extends \yii\web\View } /** + * Get the url source for an asset. + * * @todo verify there is already a yii-way solution - * * @param string $assetName - * * @return string */ public function getAssetUrl($assetName) @@ -47,20 +51,18 @@ class View extends \yii\web\View * Removes redundant whitespaces (>1) and new lines (>1). * * @param string $content input string - * * @return string compressed string */ public function compress($content) { - return preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'), array('>', '<', '\\1'), $content); + return preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $content); } /** - * Helper method for convenience. - * - * @param string $route - * @param array $params + * Generate urls helper method. * + * @param string $route The route to create `module/controller/action`. + * @param array $params Optional parameters passed as key value pairing. * @return string */ public function url($route, array $params = []) @@ -89,10 +91,6 @@ class View extends \yii\web\View */ public function getPublicHtml() { - if ($this->_publicHtml === null) { - $this->_publicHtml = Yii::$app->request->baseUrl; - } - - return $this->_publicHtml; + return Yii::$app->request->baseUrl; } }
added docs to web view class, removed privat storage var for public html getter.
luyadev_luya
train
726c3cc74e6db49747e0123d1d81fca0bcc98761
diff --git a/app/User.php b/app/User.php index <HASH>..<HASH> 100644 --- a/app/User.php +++ b/app/User.php @@ -263,8 +263,8 @@ class User { // Don't delete the logs. Database::prepare("UPDATE `##log` SET user_id=NULL WHERE user_id =?")->execute(array($this->user_id)); // Take over the user’s pending changes. (What else could we do with them?) - Database::prepare("DELETE FROM `##change` WHERE user_id=? AND status='accepted'")->execute(array($this->user_id)); - Database::prepare("UPDATE `##change` SET user_id=? WHERE user_id=?")->execute(array($this->user_id, $this->user_id)); + Database::prepare("DELETE FROM `##change` WHERE user_id=? AND status='rejected'")->execute(array($this->user_id)); + Database::prepare("UPDATE `##change` SET user_id=? WHERE user_id=?")->execute(array(Auth::id(), $this->user_id)); Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE user_id=?")->execute(array($this->user_id)); Database::prepare("DELETE FROM `##block` WHERE user_id=?")->execute(array($this->user_id)); Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE user_id=?")->execute(array($this->user_id));
Cannot delete user with pending changes
fisharebest_webtrees
train
e4d0e22a25006fa64c4e098b924fa3d4da9ebd70
diff --git a/pingu/corpus/io/default.py b/pingu/corpus/io/default.py index <HASH>..<HASH> 100644 --- a/pingu/corpus/io/default.py +++ b/pingu/corpus/io/default.py @@ -149,7 +149,7 @@ class DefaultWriter(base.CorpusWriter): utt_issuer_path = os.path.join(path, UTT_ISSUER_FILE_NAME) container_path = os.path.join(path, FEAT_CONTAINER_FILE_NAME) - DefaultWriter.write_files(file_path, corpus) + DefaultWriter.write_files(file_path, corpus, path) DefaultWriter.write_utterances(utterance_path, corpus) DefaultWriter.write_utt_to_issuer_mapping(utt_issuer_path, corpus) DefaultWriter.write_labels(path, corpus) @@ -157,8 +157,8 @@ class DefaultWriter(base.CorpusWriter): DefaultWriter.write_subviews(path, corpus) @staticmethod - def write_files(file_path, corpus): - file_records = [[file.idx, os.path.relpath(file.path, corpus.path)] for file in corpus.files.values()] + def write_files(file_path, corpus, path): + file_records = [[file.idx, os.path.relpath(file.path, path)] for file in corpus.files.values()] textfile.write_separated_lines(file_path, file_records, separator=' ', sort_by_column=0) @staticmethod diff --git a/pingu/corpus/io/kaldi.py b/pingu/corpus/io/kaldi.py index <HASH>..<HASH> 100644 --- a/pingu/corpus/io/kaldi.py +++ b/pingu/corpus/io/kaldi.py @@ -128,7 +128,7 @@ class KaldiWriter(base.CorpusWriter): segments_path = os.path.join(path, SEGMENTS_FILE_NAME) text_path = os.path.join(path, TRANSCRIPTION_FILE_NAME) - default.DefaultWriter.write_files(wav_file_path, corpus) + default.DefaultWriter.write_files(wav_file_path, corpus, path) default.DefaultWriter.write_utterances(segments_path, corpus) default.DefaultWriter.write_utt_to_issuer_mapping(utt2spk_path, corpus) diff --git a/tests/corpus/io/test_default.py b/tests/corpus/io/test_default.py index <HASH>..<HASH> 100644 --- a/tests/corpus/io/test_default.py +++ b/tests/corpus/io/test_default.py @@ -122,14 +122,17 @@ class DefaultWriterTest(unittest.TestCase): assert 'subview_dev.txt' in files def test_save_files(self): - self.writer.save(self.ds, self.path) + out_path = os.path.join(self.path, 'somesubdir') # make sure relative path changes in contrast to self.ds.path + os.makedirs(out_path) + + self.writer.save(self.ds, out_path) - file_1_path = os.path.relpath(resources.get_wav_file_path('wav_1.wav'), self.path) - file_2_path = os.path.relpath(resources.get_wav_file_path('wav_2.wav'), self.path) - file_3_path = os.path.relpath(resources.get_wav_file_path('wav_3.wav'), self.path) - file_4_path = os.path.relpath(resources.get_wav_file_path('wav_4.wav'), self.path) + file_1_path = os.path.relpath(resources.get_wav_file_path('wav_1.wav'), out_path) + file_2_path = os.path.relpath(resources.get_wav_file_path('wav_2.wav'), out_path) + file_3_path = os.path.relpath(resources.get_wav_file_path('wav_3.wav'), out_path) + file_4_path = os.path.relpath(resources.get_wav_file_path('wav_4.wav'), out_path) - with open(os.path.join(self.path, 'files.txt'), 'r') as f: + with open(os.path.join(out_path, 'files.txt'), 'r') as f: file_content = f.read() assert file_content.strip() == 'wav-1 {}\nwav_2 {}\nwav_3 {}\nwav_4 {}'.format(file_1_path,
fix writers to use path from method call not from corpus
ynop_audiomate
train
d20f7fc64ea4f89580e62fc564b6c3734a5e92fe
diff --git a/python/bigdl/dllib/keras/converter.py b/python/bigdl/dllib/keras/converter.py index <HASH>..<HASH> 100644 --- a/python/bigdl/dllib/keras/converter.py +++ b/python/bigdl/dllib/keras/converter.py @@ -20,6 +20,7 @@ import bigdl.nn.layer as BLayer from bigdl.optim.optimizer import L1L2Regularizer as BRegularizer import bigdl.optim.optimizer as boptimizer import bigdl.nn.criterion as bcriterion +import bigdl.util.common as BCommon from bigdl.util.common import get_activation_by_name import keras.optimizers as koptimizers from keras.models import model_from_json @@ -55,16 +56,22 @@ class WeightLoader: @staticmethod def load_weights_from_json_hdf5(def_json, weights_hdf5, by_name=False): - with open(def_json, "r") as jp: - kmodel = model_from_json(jp.read()) + """ + The file path can be stored in a local file system, HDFS, S3, + or any Hadoop-supported file system. + """ bmodel = DefinitionLoader.from_json_path(def_json) + def_value = BCommon.text_from_path(def_json) + kmodel = model_from_json(def_value) WeightLoader.load_weights_from_hdf5(bmodel, kmodel, weights_hdf5, by_name) return bmodel + @staticmethod def load_weights_from_hdf5(bmodel, kmodel, filepath, by_name=False): '''Loads all layer weights from a HDF5 save file. - + filepath can be stored in a local file system, HDFS, S3, + or any Hadoop-supported file system. If `by_name` is False (default) weights are loaded based on the network's execution order topology, meaning layers in the execution seq should be exactly the same @@ -75,7 +82,8 @@ class WeightLoader: for fine-tuning or transfer-learning models where some of the layers have changed. ''' - kmodel.load_weights(filepath=filepath, by_name=by_name) + local_file_path = BCommon.get_local_file(filepath) + kmodel.load_weights(filepath=local_file_path, by_name=by_name) WeightLoader.load_weights_from_kmodel(bmodel, kmodel) @staticmethod @@ -318,8 +326,12 @@ class DefinitionLoader: @classmethod def from_json_path(cls, json_path): - with open(json_path, "r") as jp: - return DefinitionLoader.from_json_str(jp.read()) + """ + :param json_path: definition path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system. + :return: BigDL Model + """ + json_str = BCommon.text_from_path(json_path) + return DefinitionLoader.from_json_str(json_str) @classmethod def from_json_str(cls, json_str): diff --git a/python/bigdl/dllib/utils/common.py b/python/bigdl/dllib/utils/common.py index <HASH>..<HASH> 100644 --- a/python/bigdl/dllib/utils/common.py +++ b/python/bigdl/dllib/utils/common.py @@ -589,6 +589,25 @@ def create_tmp_path(): return tmp_file.name +def text_from_path(path): + sc = get_spark_context() + return sc.textFile(path).collect()[0] + + +def get_local_file(a_path): + if not is_distributed(a_path): + return a_path + path, data = get_spark_context().binaryFiles(a_path).collect()[0] + local_file_path = create_tmp_path() + with open(local_file_path, 'w') as local_file: + local_file.write(data) + return local_file_path + + +def is_distributed(path): + return "://" in path + + def get_activation_by_name(activation_name, activation_id=None): """ Convert to a bigdl activation layer given the name of the activation as a string """
support hdfs and s3 (#<I>)
intel-analytics_BigDL
train
842090056690a9b0397fc49e43e4accf5c34c8e1
diff --git a/reqres.js b/reqres.js index <HASH>..<HASH> 100644 --- a/reqres.js +++ b/reqres.js @@ -317,7 +317,7 @@ function TChannelOutgoingResponse(id, options) { self.headers = options.headers || {}; self.checksumType = options.checksumType || 0; self.checksum = options.checksum || null; - self.ok = true; + self.ok = self.code === 0; self.sendFrame = options.sendFrame; if (options.streamed) { self.streamed = true;
TChannelOutgoingResponse: init ok correcter
uber_tchannel-node
train
bab12e35dad07df883bfb240af9a1d25952c3048
diff --git a/src/Builder/Delete.php b/src/Builder/Delete.php index <HASH>..<HASH> 100644 --- a/src/Builder/Delete.php +++ b/src/Builder/Delete.php @@ -19,6 +19,12 @@ class Delete extends Builder */ public $table; + /** + * Specifies the table to remove data from + * + * @param string $table The table to remove data from + * @return self + */ public function from(string $table): self { $this->table = $table; @@ -26,11 +32,22 @@ class Delete extends Builder return $this; } + /** + * An alias for \p810\MySQL\Builder\Delete::from() + * + * @param string $table The table to remove data from + * @return self + */ public function delete(string $table): self { return $this->from($table); } + /** + * Compiles the delete from clause + * + * @return string + */ protected function compileFrom(): string { return "delete from $this->table"; diff --git a/src/Builder/Insert.php b/src/Builder/Insert.php index <HASH>..<HASH> 100644 --- a/src/Builder/Insert.php +++ b/src/Builder/Insert.php @@ -37,6 +37,12 @@ class Insert extends Builder */ protected $values; + /** + * Specifies the table that the data should be inserted into + * + * @param string $table The table to insert data into + * @return self + */ public function into(string $table): self { $this->table = $table; @@ -44,11 +50,22 @@ class Insert extends Builder return $this; } + /** + * Compiles the insert into clause + * + * @return string + */ protected function compileInsert(): string { return "insert into $this->table"; } + /** + * Specifies an optional list of columns that corresponds to the inserted values + * + * @param string[] $columns A list of column names + * @return self + */ public function columns(array $columns): self { $this->columns = $columns; @@ -56,6 +73,11 @@ class Insert extends Builder return $this; } + /** + * Compiles the column list + * + * @return null|string + */ protected function compileColumns(): ?string { if (! $this->columns) { @@ -65,6 +87,12 @@ class Insert extends Builder return parentheses($this->columns); } + /** + * Specifies the values to insert into the database + * + * @param array[] $rows An array containing any number of lists of values to insert + * @return self + */ public function values(...$rows): self { foreach ($rows as $row) { @@ -76,6 +104,11 @@ class Insert extends Builder return $this; } + /** + * Compiles the values clause + * + * @return string + */ protected function compileValues(): string { $lists = []; diff --git a/src/Builder/Select.php b/src/Builder/Select.php index <HASH>..<HASH> 100644 --- a/src/Builder/Select.php +++ b/src/Builder/Select.php @@ -41,6 +41,12 @@ class Select extends Builder */ protected $columns = '*'; + /** + * Specifies which columns to return in the result set + * + * @param array|string $columns Either a string or an array; if an array, it can be associative to specify table prefixes + * @return self + */ public function select($columns = '*'): self { if (is_array($columns)) { @@ -58,11 +64,22 @@ class Select extends Builder return $this; } + /** + * Compiles the select clause + * + * @return string + */ protected function compileSelect(): string { return "select $this->columns"; } + /** + * Specifies which table to pull data from + * + * @param string $table The table to get data from + * @return self + */ public function from(string $table): self { $this->table = $table; @@ -70,11 +87,22 @@ class Select extends Builder return $this; } + /** + * Compiles the from clause + * + * @return string + */ protected function compileFrom(): string { return "from $this->table"; } + /** + * Specifies a limit of rows to return in the result set + * + * @param int $limit The maximum number of rows to return + * @return self + */ public function limit(int $limit): self { $this->limit = $limit; @@ -82,6 +110,11 @@ class Select extends Builder return $this; } + /** + * Compiles the limit clause + * + * @return null|string + */ protected function compileLimit(): ?string { if (! $this->limit) { diff --git a/src/Builder/Update.php b/src/Builder/Update.php index <HASH>..<HASH> 100644 --- a/src/Builder/Update.php +++ b/src/Builder/Update.php @@ -28,6 +28,12 @@ class Update extends Builder */ public $table; + /** + * Specifies the table to update data in + * + * @param string $table The table to update + * @return self + */ public function update(string $table): self { $this->table = $table; @@ -35,16 +41,36 @@ class Update extends Builder return $this; } + /** + * An alias for \p810\MySQL\Builder\Update::update() + * + * @param string $table The table to update + * @return self + */ public function table(string $table): self { return $this->update($table); } + /** + * Compiles the update from clause + * + * @return string + */ protected function compileUpdate(): string { return "update $this->table"; } + /** + * Specifies which columns to update and what their values should be + * + * This method may take either two arguments, a column and a value, or an associative + * array mapping columns to values + * + * @param array $arguments The columns and values to update + * @return self + */ public function set(...$arguments): self { if (is_array($arguments[0])) { @@ -60,6 +86,11 @@ class Update extends Builder return $this; } + /** + * Compiles the set clause + * + * @return string + */ protected function compileSet(): string { $strings = [];
Adds docblocks to the methods of each builder object
p810_mysql-helper
train
a4f6fbdbf239700826c648587cfc81d1e4062dc1
diff --git a/src/main/javascript/index.js b/src/main/javascript/index.js index <HASH>..<HASH> 100644 --- a/src/main/javascript/index.js +++ b/src/main/javascript/index.js @@ -1,4 +1,4 @@ /*global require, module, BytePushers */ /*jshint -W079 */ -var BytePushers = require('./software.bytepushers.oop'); +var BytePushers = require('./bytepushers-js-oop'); module.exports = BytePushers; \ No newline at end of file
renamed path to required library.
byte-pushers_bytepushers-js-oop
train
1fea2a43b48f42a8480729136d98320d74cd83f3
diff --git a/hazelcast/src/main/java/com/hazelcast/map/impl/operation/KeyBasedMapOperation.java b/hazelcast/src/main/java/com/hazelcast/map/impl/operation/KeyBasedMapOperation.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/impl/operation/KeyBasedMapOperation.java +++ b/hazelcast/src/main/java/com/hazelcast/map/impl/operation/KeyBasedMapOperation.java @@ -90,7 +90,7 @@ public abstract class KeyBasedMapOperation extends MapOperation @Override protected void writeInternal(ObjectDataOutput out) throws IOException { - out.writeUTF(name); + super.writeInternal(out); out.writeData(dataKey); out.writeLong(threadId); out.writeData(dataValue); @@ -103,7 +103,7 @@ public abstract class KeyBasedMapOperation extends MapOperation @Override protected void readInternal(ObjectDataInput in) throws IOException { - name = in.readUTF(); + super.readInternal(in); dataKey = in.readData(); threadId = in.readLong(); dataValue = in.readData(); diff --git a/hazelcast/src/main/java/com/hazelcast/map/impl/operation/ReadonlyKeyBasedMapOperation.java b/hazelcast/src/main/java/com/hazelcast/map/impl/operation/ReadonlyKeyBasedMapOperation.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/impl/operation/ReadonlyKeyBasedMapOperation.java +++ b/hazelcast/src/main/java/com/hazelcast/map/impl/operation/ReadonlyKeyBasedMapOperation.java @@ -52,14 +52,14 @@ public abstract class ReadonlyKeyBasedMapOperation extends MapOperation implemen @Override protected void writeInternal(ObjectDataOutput out) throws IOException { - out.writeUTF(name); + super.writeInternal(out); out.writeData(dataKey); out.writeLong(threadId); } @Override protected void readInternal(ObjectDataInput in) throws IOException { - name = in.readUTF(); + super.readInternal(in); dataKey = in.readData(); threadId = in.readLong(); }
Read and write 'name' field on the level where it's defined (#<I>) Fixes: hazelcast/hazelcast#<I>
hazelcast_hazelcast
train
087e68c7917d97f561526e2189535c3ad680915d
diff --git a/ext_emconf.php b/ext_emconf.php index <HASH>..<HASH> 100644 --- a/ext_emconf.php +++ b/ext_emconf.php @@ -31,7 +31,7 @@ $EM_CONF[$_EXTKEY] = array( 'suggests' => array( 'typo3' => '4.7.1-0.0.0', 't3jquery' => '1.8.0-0.0.0', - 'nkwgok' => '2.0.0-0.0.0', + 'nkwgok' => '2.2.0-0.0.0', ), ), 'dependencies' => 'extbase,fluid',
depend on nkwgok <I> if it is used
subugoe_typo3-pazpar2
train
2caecd0b75c5b65e00f2580eee7014a99bf7ed16
diff --git a/mongoctl/objects/mongod.py b/mongoctl/objects/mongod.py index <HASH>..<HASH> 100644 --- a/mongoctl/objects/mongod.py +++ b/mongoctl/objects/mongod.py @@ -96,9 +96,9 @@ class MongodServer(server.Server): if self.is_shard_server(): cmd_options["shardsvr"] = True - # remove wiredTigerCacheSizeGB if specified since we set it in runtime parameter wiredTigerEngineRuntimeConfig - # if it was specified - if "wiredTigerCacheSizeGB" in cmd_options and self.get_cmd_option("wiredTigerCacheSizeGB") < 1: + # remove wiredTigerCacheSizeGB if its not an int since we set it in runtime parameter + # wiredTigerEngineRuntimeConfig in this case + if "wiredTigerCacheSizeGB" in cmd_options and not isinstance(self.get_cmd_option("wiredTigerCacheSizeGB"), int): del cmd_options["wiredTigerCacheSizeGB"] return cmd_options @@ -337,7 +337,7 @@ class MongodServer(server.Server): def verify_runtime_parameters(self): log_info("Verifying runtime params...") wtcs_gb = self.get_cmd_option("wiredTigerCacheSizeGB") - if wtcs_gb is not None and wtcs_gb < 1: + if wtcs_gb is not None and isinstance(wtcs_gb, float): wtcs_bytes = int(wtcs_gb * 1024 * 1024 * 1024) server_status = self.server_status() if not(server_status and "wiredTiger" in server_status and "cache" in server_status["wiredTiger"] and
disregard wiredTigerCacheSizeGB if it was not a float
mongolab_mongoctl
train
e38d56228909eada704982cdd6390dbca4533ec3
diff --git a/src/Array.js b/src/Array.js index <HASH>..<HASH> 100644 --- a/src/Array.js +++ b/src/Array.js @@ -8,7 +8,9 @@ function extend (Y) { this._model = _model // Array of all the neccessary content this._content = _content + this._debugEvents = [] // TODO: remove!! this.eventHandler = new Y.utils.EventHandler((op) => { + this._debugEvents.push(JSON.parse(JSON.stringify(op))) if (op.struct === 'Insert') { let pos // we check op.left only!, @@ -71,7 +73,7 @@ function extend (Y) { for (delLength = 1; delLength < op.length && i + delLength < this._content.length && Y.utils.inDeletionRange(op, this._content[i + delLength].id); delLength++) {} - // last operation thas will be deleted + // last operation that will be deleted c = this._content[i + delLength - 1] // update delete operation op.length -= c.id[1] - op.target[1] + 1 diff --git a/src/Array.spec.js b/src/Array.spec.js index <HASH>..<HASH> 100644 --- a/src/Array.spec.js +++ b/src/Array.spec.js @@ -22,11 +22,11 @@ function compareArrayValues (arrays) { } } -var numberOfYArrayTests = 50 -var repeatArrayTests = 5 +var numberOfYArrayTests = 10 +var repeatArrayTests = 5000 for (let database of databases) { - // if (database === 'memory') continue // TODO: REMOVE + if (database !== 'memory') continue // TODO: REMOVE describe(`Array Type (DB: ${database})`, function () { var y1, y2, y3, yconfig1, yconfig2, yconfig3, flushAll @@ -619,12 +619,12 @@ for (let database of databases) { expect(this.arrays.length).toEqual(this.users.length) done() })) - it(`succeed after ${numberOfYArrayTests} actions, no GC, no disconnect`, async(function * (done) { + iit(`succeed after ${numberOfYArrayTests} actions, no GC, no disconnect`, async(function * (done) { yield applyRandomTransactionsNoGCNoDisconnect(this.users, this.arrays, randomArrayTransactions, numberOfYArrayTests) yield flushAll() yield Promise.all(this.arrays.map(fixAwaitingInType)) - yield compareArrayValues(this.arrays) yield compareAllUsers(this.users) + yield compareArrayValues(this.arrays) done() })) it(`succeed after ${numberOfYArrayTests} actions, no GC, all users disconnecting/reconnecting`, async(function * (done) {
more debugging. Need to copy for my other working place
y-js_y-array
train
babecb6d4925215f6143b2ffcec79543e2eea080
diff --git a/plugins/inputs/mesos/mesos.go b/plugins/inputs/mesos/mesos.go index <HASH>..<HASH> 100644 --- a/plugins/inputs/mesos/mesos.go +++ b/plugins/inputs/mesos/mesos.go @@ -7,6 +7,7 @@ import ( "log" "net" "net/http" + "strconv" "strings" "sync" @@ -16,7 +17,7 @@ import ( ) type Mesos struct { - Timeout string + Timeout int Servers []string MetricsCol []string `toml:"metrics_collection"` } @@ -225,7 +226,7 @@ func masterBlocks(g string) []string { ret, ok := m[g] if !ok { - log.Println("Unkown metrics group: ", g) + log.Println("[mesos] Unkown metrics group: ", g) return []string{} } @@ -234,7 +235,7 @@ func masterBlocks(g string) []string { var sampleConfig = ` # Timeout, in ms. - timeout = 2000 + timeout = 100 # A list of Mesos masters. e.g. master1:5050, master2:5080, etc. # The port can be skipped if using the default (5050) # Default value is localhost:5050. @@ -244,7 +245,7 @@ var sampleConfig = ` metrics_collection = ["resources","master","system","slaves","frameworks","messages","evqueue","registrar"] ` -// removeGroup(), remove blacklisted groups +// removeGroup(), remove unwanted groups func (m *Mesos) removeGroup(j *map[string]interface{}) { var ok bool @@ -273,8 +274,14 @@ func (m *Mesos) gatherMetrics(a string, acc telegraf.Accumulator) error { "server": host, } - // TODO: Use Timeout - resp, err := http.Get("http://" + a + "/metrics/snapshot") + if m.Timeout == 0 { + log.Println("[mesos] Missing timeout value, setting default value (100ms)") + m.Timeout = 100 + } + + ts := strconv.Itoa(m.Timeout) + "ms" + + resp, err := http.Get("http://" + a + "/metrics/snapshot?timeout=" + ts) if err != nil { return err @@ -290,9 +297,7 @@ func (m *Mesos) gatherMetrics(a string, acc telegraf.Accumulator) error { return errors.New("Error decoding JSON response") } - //if len(m.Blacklist) > 0 { - // m.removeGroup(&jsonOut) - //} + m.removeGroup(&jsonOut) jf := internal.JSONFlattener{} diff --git a/plugins/inputs/mesos/mesos_test.go b/plugins/inputs/mesos/mesos_test.go index <HASH>..<HASH> 100644 --- a/plugins/inputs/mesos/mesos_test.go +++ b/plugins/inputs/mesos/mesos_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "os" + "reflect" "testing" "github.com/influxdata/telegraf/testutil" @@ -86,9 +87,6 @@ func TestMesosMaster(t *testing.T) { } func TestRemoveGroup(t *testing.T) { - //t.Skip("needs refactoring") - // FIXME: removeGroup() behavior is the opposite as it was, - // this test has to be refactored generateMetrics() m := Mesos{ @@ -111,3 +109,42 @@ func TestRemoveGroup(t *testing.T) { } } } + +func TestMasterBlocks(t *testing.T) { + a := "wrong_key" + expect := []string{} + got := masterBlocks(a) + + if !reflect.DeepEqual(got, expect) { + t.Errorf("Expected empty string slice, got: %v", got) + } +} + +func TestSampleConfig(t *testing.T) { + expect := ` + # Timeout, in ms. + timeout = 100 + # A list of Mesos masters. e.g. master1:5050, master2:5080, etc. + # The port can be skipped if using the default (5050) + # Default value is localhost:5050. + servers = ["localhost:5050"] + # Metrics groups to be collected. + # Default, all enabled. + metrics_collection = ["resources","master","system","slaves","frameworks","messages","evqueue","registrar"] +` + + got := new(Mesos).SampleConfig() + + if expect != got { + t.Errorf("Got %s", got) + } +} + +func TestDescription(t *testing.T) { + expect := "Telegraf plugin for gathering metrics from N Mesos masters" + got := new(Mesos).Description() + + if expect != got { + t.Errorf("Got %s", got) + } +}
feat(timeout): Use timeout setting * Use timeout as parameter in the http request * A bit of cleanup * More tests
influxdata_telegraf
train
415ae71cb24a40bf3ee2af83f985ca5051461b93
diff --git a/tofu/tests/tests02_data/test_04_core_new.py b/tofu/tests/tests02_data/test_04_core_new.py index <HASH>..<HASH> 100644 --- a/tofu/tests/tests02_data/test_04_core_new.py +++ b/tofu/tests/tests02_data/test_04_core_new.py @@ -11,9 +11,6 @@ import warnings import numpy as np import matplotlib.pyplot as plt -# Nose-specific -from nose import with_setup # optional - # tofu-specific from tofu import __version__ import tofu.data as tfd
[#<I>] Removed nose dependency
ToFuProject_tofu
train
6469c84c96333f6006a3ee8672ea1829eb88cc23
diff --git a/spec/travis/addons/github_status/event_handler_spec.rb b/spec/travis/addons/github_status/event_handler_spec.rb index <HASH>..<HASH> 100644 --- a/spec/travis/addons/github_status/event_handler_spec.rb +++ b/spec/travis/addons/github_status/event_handler_spec.rb @@ -92,5 +92,13 @@ describe Travis::Addons::GithubStatus::EventHandler do task.expects(:run).with { |_, _, options| options[:tokens]['jdoe'] == 'push-token' } notify end + + it 'does not trigger a task if no tokens are available' do + build.repository.stubs(users_with_permission: []) + Travis.stubs(:run_service).returns(nil) + + task.expects(:run).never + notify + end end end
spec(github-status): add spec testing the no-tokens case This tests the bug that <I>fd6dfe<I>c1ae<I>ca5f4bf8b<I>d<I>c<I> fixed.
travis-ci_travis-core
train
e98b3b68d95aaa3f1e09157f46478ba9d88df81a
diff --git a/geomajas/backend/geomajas-command/src/main/java/org/geomajas/command/configuration/GetMapConfigurationCommand.java b/geomajas/backend/geomajas-command/src/main/java/org/geomajas/command/configuration/GetMapConfigurationCommand.java index <HASH>..<HASH> 100644 --- a/geomajas/backend/geomajas-command/src/main/java/org/geomajas/command/configuration/GetMapConfigurationCommand.java +++ b/geomajas/backend/geomajas-command/src/main/java/org/geomajas/command/configuration/GetMapConfigurationCommand.java @@ -167,6 +167,7 @@ public class GetMapConfigurationCommand implements Command<GetMapConfigurationRe } ClientLayerTreeNodeInfo client = new ClientLayerTreeNodeInfo(); client.setLabel(original.getLabel()); + client.setExpanded(original.isExpanded()); List<ClientLayerInfo> layers = new ArrayList<ClientLayerInfo>(); client.setLayers(layers); for (ClientLayerInfo layer : original.getLayers()) {
Fix MAJ-<I>: layer tree nodes were never expanded in original layer tree view on client In securityClone(ClientLayerTreeNodeInfo original) the "expanded' property was not cloned.
geomajas_geomajas-project-server
train
00aceaae37e60b8e55d8997cc1a6777748a92558
diff --git a/python/ray/tests/test_client.py b/python/ray/tests/test_client.py index <HASH>..<HASH> 100644 --- a/python/ray/tests/test_client.py +++ b/python/ray/tests/test_client.py @@ -1,3 +1,4 @@ +import os import pytest import time import sys @@ -417,15 +418,16 @@ def test_basic_named_actor(ray_start_regular_shared): def test_error_serialization(ray_start_regular_shared): """Test that errors will be serialized properly.""" - with pytest.raises(PermissionError): + fake_path = os.path.join(os.path.dirname(__file__), "not_a_real_file") + with pytest.raises(FileNotFoundError): with ray_start_client_server() as ray: @ray.remote def g(): - with open("/dev/asdf", "w") as f: - f.write("HI") + with open(fake_path, "r") as f: + f.read() - # Raises a PermissionError + # Raises a FileNotFoundError ray.get(g.remote())
[Client] Test Serialization in a platform independent way. (#<I>)
ray-project_ray
train
8f2125581e8f7b3f6e3b9bbe0093232122be5616
diff --git a/lib/appsignal/version.rb b/lib/appsignal/version.rb index <HASH>..<HASH> 100644 --- a/lib/appsignal/version.rb +++ b/lib/appsignal/version.rb @@ -1,5 +1,5 @@ require 'yaml' module Appsignal - VERSION = '0.12.beta.43' + VERSION = '0.12.beta.44' end
Bump to <I>.beta<I> [ci skip]
appsignal_appsignal-ruby
train
afc80cc6d745261ca8134e419bdb1d375aece5a4
diff --git a/build_tools/generate_code.py b/build_tools/generate_code.py index <HASH>..<HASH> 100644 --- a/build_tools/generate_code.py +++ b/build_tools/generate_code.py @@ -93,6 +93,7 @@ DONT_TRACE = { '_weakrefset.py':LIB_FILE, 'linecache.py':LIB_FILE, 'threading.py':LIB_FILE, + 'dis.py':LIB_FILE, #things from pydev that we don't want to trace '_pydev_execfile.py':PYDEV_FILE,
Add `dis` to files for ignoring
fabioz_PyDev.Debugger
train
ff7e3ab4fb67da6ef26a1c143f4f08ed03714bb5
diff --git a/lib/puppetserver/ca/cli.rb b/lib/puppetserver/ca/cli.rb index <HASH>..<HASH> 100644 --- a/lib/puppetserver/ca/cli.rb +++ b/lib/puppetserver/ca/cli.rb @@ -66,8 +66,8 @@ module Puppetserver end values.each do |value| - if value =~ unresolved_setting - @errors << "Could not parse #{$1} in #{value}, " + + if match = value.match(unresolved_setting) + @errors << "Could not parse #{match[0]} in #{value}, " + 'valid settings to be interpolated are ' + '$confdir, $ssldir, $cadir' end @@ -332,6 +332,14 @@ module Puppetserver puppet = PuppetConfig.new(input['config']) puppet.load + unless puppet.errors.empty? + err.puts "Error:" + puppet.errors.each do |message| + err.puts " #{message}" + end + return 1 + end + File.open(puppet.ca_cert_path, 'w') do |f| loader.certs.each do |cert| f.puts cert.to_pem diff --git a/spec/puppetserver/ca/cli_spec.rb b/spec/puppetserver/ca/cli_spec.rb index <HASH>..<HASH> 100644 --- a/spec/puppetserver/ca/cli_spec.rb +++ b/spec/puppetserver/ca/cli_spec.rb @@ -490,12 +490,31 @@ RSpec.describe Puppetserver::Ca::Cli do conf = Puppetserver::Ca::PuppetConfig.new(puppet_conf) conf.load - puts conf.errors + + expect(conf.errors).to be_empty expect(conf.ca_cert_path).to eq('/foo/bar/ca/ca_crt.pem') expect(conf.ca_crl_path).to eq('/fizz/buzz/crl.pem') end end + it 'errs if it cannot resolve dependent settings properly' do + Dir.mktmpdir do |tmpdir| + puppet_conf = File.join(tmpdir, 'puppet.conf') + File.open puppet_conf, 'w' do |f| + f.puts(<<-INI) + [master] + ssldir = $vardir/ssl + INI + end + + conf = Puppetserver::Ca::PuppetConfig.new(puppet_conf) + conf.load + + expect(conf.errors.first).to include('$vardir in $vardir/ssl') + expect(conf.ca_cert_path).to eq('$vardir/ssl/ca/ca_crt.pem') + end + end + it 'actually, honest to god, moves files' do Dir.mktmpdir do |tmpdir| with_files_in tmpdir do |bundle, key, chain, conf|
(SERVER-<I>) Error when parseable settings in conf
puppetlabs_puppetserver-ca-cli
train
12b16e5e3eee26be1aa6fc1e2632da47bc63c706
diff --git a/controllers/login/steamLogin.go b/controllers/login/steamLogin.go index <HASH>..<HASH> 100644 --- a/controllers/login/steamLogin.go +++ b/controllers/login/steamLogin.go @@ -97,12 +97,6 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) { cookie.Expires = time.Time{} http.SetCookie(w, cookie) - referer, ok := r.Header["Referer"] - if ok { - http.Redirect(w, r, referer[0], 303) - return - } - http.Redirect(w, r, config.Constants.LoginRedirectPath, 303) }
Logout: Don't redirect to referer.
TF2Stadium_Helen
train
a0fe68bc07c9b551a7daec87b31f481878f4d450
diff --git a/gitlab/__init__.py b/gitlab/__init__.py index <HASH>..<HASH> 100644 --- a/gitlab/__init__.py +++ b/gitlab/__init__.py @@ -854,7 +854,13 @@ class User(GitlabObject): requiredCreateAttrs = ['email', 'username', 'name'] optionalCreateAttrs = ['password', 'skype', 'linkedin', 'twitter', 'projects_limit', 'extern_uid', 'provider', - 'bio', 'admin', 'can_create_group', 'website_url'] + 'bio', 'admin', 'can_create_group', 'website_url', + 'confirm'] + + def _data_for_gitlab(self, extra_parameters={}): + if hasattr(self, 'confirm'): + self.confirm = str(self.confirm).lower() + return super(User, self)._data_for_gitlab(extra_parameters) def Key(self, id=None, **kwargs): return UserKey._get_list_or_object(self.gitlab, id,
Can bypassing confirm when creating new user
python-gitlab_python-gitlab
train
9ba84c1d7d4b0af19c2b79382940f14005c52c69
diff --git a/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/view/IdolViewServerServiceImpl.java b/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/view/IdolViewServerServiceImpl.java index <HASH>..<HASH> 100644 --- a/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/view/IdolViewServerServiceImpl.java +++ b/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/view/IdolViewServerServiceImpl.java @@ -7,6 +7,7 @@ package com.hp.autonomy.searchcomponents.idol.view; import com.autonomy.aci.client.services.*; import com.autonomy.aci.client.util.AciParameters; +import com.hp.autonomy.aci.content.printfields.PrintFields; import com.hp.autonomy.frontend.configuration.ConfigService; import com.hp.autonomy.frontend.configuration.server.ServerConfig; import com.hp.autonomy.searchcomponents.core.view.ViewServerService; @@ -25,10 +26,12 @@ import com.hp.autonomy.types.idol.responses.Hit; import com.hp.autonomy.types.requests.idol.actions.connector.ConnectorActions; import com.hp.autonomy.types.requests.idol.actions.connector.params.ConnectorViewParams; import com.hp.autonomy.types.requests.idol.actions.query.QueryActions; +import com.hp.autonomy.types.requests.idol.actions.query.params.GetContentParams; import com.hp.autonomy.types.requests.idol.actions.view.ViewActions; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.NotImplementedException; +import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -88,7 +91,16 @@ class IdolViewServerServiceImpl implements IdolViewServerService { */ @Override public void viewDocument(final IdolViewRequest request, final OutputStream outputStream) throws ViewDocumentNotFoundException, IOException { - final Hit document = loadDocument(request.getDocumentReference(), request.getDatabase()); + // Only fetch the minimum necessary information to know if we should use View, Connector, or DRECONTENT rendering. + final PrintFields printFields = new PrintFields(AUTN_IDENTIFIER, AUTN_GROUP); + final ViewConfig viewConfig = configService.getConfig().getViewConfig(); + + final String refField = viewConfig.getReferenceField(); + if(StringUtils.isNotBlank(refField)) { + printFields.append(refField); + } + + final Hit document = loadDocument(request.getDocumentReference(), request.getDatabase(), printFields); final Optional<String> maybeUrl = readViewUrl(document); if (maybeUrl.isPresent()) { @@ -101,7 +113,10 @@ class IdolViewServerServiceImpl implements IdolViewServerService { throw new ViewServerErrorException(request.getDocumentReference(), e); } } else { - final String content = parseFieldValue(document, CONTENT_FIELD).orElse(""); + // We need to fetch the DRECONTENT if we have to use the DRECONTENT rendering fallback. + final Hit docContent = loadDocument(request.getDocumentReference(), request.getDatabase(), new PrintFields(CONTENT_FIELD)); + + final String content = parseFieldValue(docContent, CONTENT_FIELD).orElse(""); final RawDocument rawDocument = RawDocument.builder() .reference(document.getReference()) @@ -120,12 +135,14 @@ class IdolViewServerServiceImpl implements IdolViewServerService { throw new NotImplementedException("Viewing static content promotions on premise is not yet possible"); } - private Hit loadDocument(final String documentReference, final String database) { + private Hit loadDocument(final String documentReference, final String database, final PrintFields printFields) { final ViewConfig viewConfig = configService.getConfig().getViewConfig(); final String referenceField = viewConfig.getReferenceField(); // do a GetContent to check for document visibility and to read out required fields final AciParameters parameters = new AciParameters(QueryActions.GetContent.name()); + parameters.add(GetContentParams.Print.name(), "Fields"); + parameters.add(GetContentParams.PrintFields.name(), printFields); parameterHandler.addGetContentOutputParameters(parameters, database, documentReference, referenceField); final GetContentResponseData queryResponse;
(CORE-<I>) Speed up preview of documents which use connector- or view-based previews. Instead of fetching the entire document in one a=getContent query, we now apply print=fields and printfields to limit to AUTN_IDENTIFIER, AUTN_GROUP and the configured View reference field. This is enough for connector and view based previews; we only need another extra a=getContent query for the DRECONTENT if we have to use the DRECONTENT fallback rendering.
microfocus-idol_haven-search-components
train
b0a66f8dc1bface9c8eb2af986c8d2dd3031744a
diff --git a/util/common.js b/util/common.js index <HASH>..<HASH> 100644 --- a/util/common.js +++ b/util/common.js @@ -4,7 +4,7 @@ * Author: Miklos Maroti */ -define([ "util/assert", "storage/mongo", "storage/cache", "storage/commit", "core/tasync", "core/core", "core/guidcore", "util/sax", "fs", "bin/getconfig", "storage/socketioclient", "core/newcore" ], function (ASSERT, Mongo, Cache, Commit, TASYNC, Core, GuidCore, SAX, FS, CONFIG, Client, NewCore) { +define([ "util/assert", "storage/mongo", "storage/cache", "storage/commit", "core/tasync", "util/sax", "fs", "bin/getconfig", "storage/socketioclient", "core/newcore" ], function (ASSERT, Mongo, Cache, Commit, TASYNC, SAX, FS, CONFIG, Client, Core) { function getParameters (option) { ASSERT(option === null || typeof option === "string" && option.charAt(0) !== "-"); @@ -115,16 +115,7 @@ define([ "util/assert", "storage/mongo", "storage/cache", "storage/commit", "cor project = p; - /*core = new GuidCore(new Core(project, { - autopersist: true - })); - - core.persist = TASYNC.wrap(core.persist); - core.loadByPath = TASYNC.wrap(core.loadByPath); - core.loadRoot = TASYNC.wrap(core.loadRoot); - core.loadChildren = TASYNC.wrap(core.loadChildren); - core.loadPointer = TASYNC.wrap(core.loadPointer);*/ - core = NewCore.syncCore(project,{autopersist:true}); + core = Core.syncCore(project,{autopersist:true}); } function closeProject () {
cleanup core directory finished Former-commit-id: <I>e0bad<I>ef7ff<I>adee<I>b5aada2b<I>
webgme_webgme-engine
train
094faa164a0dbeb9a9062ed57514e85fa3c66c04
diff --git a/in.go b/in.go index <HASH>..<HASH> 100644 --- a/in.go +++ b/in.go @@ -4,10 +4,14 @@ package validation -import "errors" +import ( + "errors" + "reflect" +) // In returns a validation rule that checks if a value can be found in the given list of values. -// Note that the value being checked and the possible range of values must be of the same type. +// reflect.DeepEqual() will be used to determine if two values are equal. +// For more details please refer to https://golang.org/pkg/reflect/#DeepEqual // An empty value is considered valid. Use the Required rule to make sure a value is not empty. func In(values ...interface{}) InRule { return InRule{ @@ -30,7 +34,7 @@ func (r InRule) Validate(value interface{}) error { } for _, e := range r.elements { - if e == value { + if reflect.DeepEqual(e, value) { return nil } } diff --git a/in_test.go b/in_test.go index <HASH>..<HASH> 100644 --- a/in_test.go +++ b/in_test.go @@ -27,6 +27,7 @@ func TestIn(t *testing.T) { {"t5", []interface{}{1, 2}, "1", "must be a valid value"}, {"t6", []interface{}{1, 2}, &v, ""}, {"t7", []interface{}{1, 2}, v2, ""}, + {"t8", []interface{}{[]byte{1}, 1, 2}, []byte{1}, ""}, } for _, test := range tests {
Fixes #<I>: support less restrictive equality comparison by the In rule
go-ozzo_ozzo-validation
train
fd7eb40daf07023ec3c5fce128fc86bad5a47c55
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java @@ -860,7 +860,7 @@ public class AddExchanges @Override public PlanWithProperties visitUnnest(UnnestNode node, PreferredProperties preferredProperties) { - PreferredProperties translatedPreferred = preferredProperties.translate(variable -> node.getReplicateVariables().contains(new Symbol(variable.getName())) ? Optional.of(variable) : Optional.empty()); + PreferredProperties translatedPreferred = preferredProperties.translate(variable -> node.getReplicateVariables().contains(variable) ? Optional.of(variable) : Optional.empty()); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); }
Fix type mismatch in AddExchanges.Rewriter.visitUnnest
prestodb_presto
train
15ee078a8ce7622ca4e7e7a298affa4182674c11
diff --git a/src/Builder/ServerBuilder.php b/src/Builder/ServerBuilder.php index <HASH>..<HASH> 100644 --- a/src/Builder/ServerBuilder.php +++ b/src/Builder/ServerBuilder.php @@ -200,11 +200,11 @@ final class ServerBuilder $this->setupFormats($c); $this->setupTrustDecisionManager($c); - $c[TrustPathValidatorInterface::class] = static function (ServiceContainer $c) { + $c[TrustPathValidatorInterface::class] = static function (ServiceContainer $c): TrustPathValidatorInterface { return new TrustPathValidator($c[ChainValidatorInterface::class]); }; - $c[ChainValidatorInterface::class] = static function (ServiceContainer $c) { + $c[ChainValidatorInterface::class] = static function (ServiceContainer $c): ChainValidatorInterface { // TODO //return new ChainValidator($c[CertificateStatusResolverInterface::class]); return new ChainValidator(null); @@ -228,10 +228,10 @@ final class ServerBuilder if (isset($c[DownloaderInterface::class])) { return; } - $c[DownloaderInterface::class] = static function (ServiceContainer $c) { + $c[DownloaderInterface::class] = static function (ServiceContainer $c): DownloaderInterface { return new Downloader($c[Client::class]); }; - $c[Client::class] = static function (ServiceContainer $c) { + $c[Client::class] = static function (ServiceContainer $c): Client { $factory = new CachingClientFactory($c[CacheProviderInterface::class]); return $factory->createClient(); }; @@ -242,11 +242,13 @@ final class ServerBuilder if (isset($c[CacheProviderInterface::class])) { return; } - if ($this->cacheDir === null) { + + $cacheDir = $this->cacheDir; + if ($cacheDir === null) { throw new ConfigurationException('No cache directory configured. Use useCacheDirectory or useSystemTempCache.'); } - $c[CacheProviderInterface::class] = function (ServiceContainer $c) { - return new FileCacheProvider($this->cacheDir); + $c[CacheProviderInterface::class] = static function (ServiceContainer $c) use ($cacheDir) { + return new FileCacheProvider($cacheDir); }; } @@ -287,11 +289,6 @@ final class ServerBuilder return new WebAuthnServer($c[PolicyInterface::class], $c[CredentialStoreInterface::class]); } - private function getRelyingParty(): RelyingPartyInterface - { - return $this->rp; - } - public function addMetadataSource(MetadataSourceInterface $metadataSource): self { $this->metadataSources[] = $metadataSource; @@ -353,7 +350,7 @@ final class ServerBuilder private function setupFormats(ServiceContainer $c) { $c[PackedAttestationVerifier::class] = static function () { - return new AndroidSafetyNetAttestationVerifier(); + return new PackedAttestationVerifier(); }; $c[FidoU2fAttestationVerifier::class] = static function () { return new FidoU2fAttestationVerifier(); diff --git a/src/Remote/Downloader.php b/src/Remote/Downloader.php index <HASH>..<HASH> 100644 --- a/src/Remote/Downloader.php +++ b/src/Remote/Downloader.php @@ -13,7 +13,7 @@ class Downloader implements DownloaderInterface */ private $client; - public function __construct(Client $client) // TODO use clientfactory + public function __construct(Client $client) // TODO use clientfactory and ClientInterface { $this->client = $client; } diff --git a/src/Server/Authentication/AuthenticationContext.php b/src/Server/Authentication/AuthenticationContext.php index <HASH>..<HASH> 100644 --- a/src/Server/Authentication/AuthenticationContext.php +++ b/src/Server/Authentication/AuthenticationContext.php @@ -29,8 +29,6 @@ class AuthenticationContext extends AbstractContext implements RequestContext /** * @internal TODO: do not include here? - * - * @return static */ public static function create(PublicKeyCredentialRequestOptions $options, PolicyInterface $policy): self {
Bugfix packed attestation wrong verififer and other small fixes
madwizard-thomas_webauthn-server
train
4a1c331423d40a9475e67085112c184aa7e149f4
diff --git a/core/src/main/java/com/dtolabs/client/utils/HttpClientChannel.java b/core/src/main/java/com/dtolabs/client/utils/HttpClientChannel.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/dtolabs/client/utils/HttpClientChannel.java +++ b/core/src/main/java/com/dtolabs/client/utils/HttpClientChannel.java @@ -113,6 +113,12 @@ abstract class HttpClientChannel implements BaseHttpClient { logger.debug("creating connection object to URL: " + requestUrl); httpc = new HttpClient(); + if (null != System.getProperty("http.proxyPort") && null != System.getProperty("http.proxyHost")) { + Integer port = Integer.getInteger("http.proxyPort"); + if (null != port) { + httpc.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), port); + } + } } private static final HashSet validMethodTypes= new HashSet();
Support system properties http.proxyPort/http.proxyPort for CLI tools
rundeck_rundeck
train
9590336c499047ff186248401331c8122c9ab9ae
diff --git a/PHPCI/Builder.php b/PHPCI/Builder.php index <HASH>..<HASH> 100644 --- a/PHPCI/Builder.php +++ b/PHPCI/Builder.php @@ -215,15 +215,6 @@ class Builder implements LoggerAwareInterface $this->pluginExecutor->executePlugins($this->config, 'failure'); $this->buildLogger->logFailure(Lang::get('build_failed')); } - - // Clean up: - $this->buildLogger->log(Lang::get('removing_build')); - - $cmd = 'rm -Rf "%s"'; - if (IS_WIN) { - $cmd = 'rmdir /S /Q "%s"'; - } - $this->executeCommand($cmd, rtrim($this->buildPath, '/')); } catch (\Exception $ex) { $this->build->setStatus(Build::STATUS_FAILED); $this->buildLogger->logFailure(Lang::get('exception') . $ex->getMessage()); @@ -233,6 +224,11 @@ class Builder implements LoggerAwareInterface // Update the build in the database, ping any external services, etc. $this->build->sendStatusPostback(); $this->build->setFinished(new \DateTime()); + + // Clean up: + $this->buildLogger->log(Lang::get('removing_build')); + $this->build->removeBuildDirectory(); + $this->store->save($this->build); } @@ -287,7 +283,7 @@ class Builder implements LoggerAwareInterface */ protected function setupBuild() { - $this->buildPath = PHPCI_DIR . 'PHPCI/build/' . $this->build->getId() . '/'; + $this->buildPath = $this->build->getBuildPath() . '/'; $this->build->currentBuildPath = $this->buildPath; $this->interpolator->setupInterpolationVars( diff --git a/PHPCI/Command/RunCommand.php b/PHPCI/Command/RunCommand.php index <HASH>..<HASH> 100644 --- a/PHPCI/Command/RunCommand.php +++ b/PHPCI/Command/RunCommand.php @@ -166,7 +166,7 @@ class RunCommand extends Command $build->setStatus(Build::STATUS_FAILED); $build->setFinished(new \DateTime()); $store->save($build); - $this->removeBuildDirectory($build); + $build->removeBuildDirectory(); continue; } @@ -175,19 +175,4 @@ class RunCommand extends Command return $rtn; } - - protected function removeBuildDirectory($build) - { - $buildPath = PHPCI_DIR . 'PHPCI/build/' . $build->getId() . '/'; - - if (is_dir($buildPath)) { - $cmd = 'rm -Rf "%s"'; - - if (IS_WIN) { - $cmd = 'rmdir /S /Q "%s"'; - } - - shell_exec($cmd); - } - } } diff --git a/PHPCI/Model/Build.php b/PHPCI/Model/Build.php index <HASH>..<HASH> 100644 --- a/PHPCI/Model/Build.php +++ b/PHPCI/Model/Build.php @@ -217,4 +217,28 @@ class Build extends BuildBase { return array($builder, $file, $line, $message); } + + /** + * Return the path to run this build into. + * + * @return string + */ + public function getBuildPath() + { + return PHPCI_BUILD_ROOT_DIR . $this->getId(); + } + + /** + * Removes the build directory. + */ + public function removeBuildDirectory() + { + $buildPath = $this->getBuildPath(); + + if (!is_dir($buildPath)) { + return; + } + + exec(sprintf(IS_WIN ? 'rmdir /S /Q "%s"' : 'rm -Rf "%s"', $buildPath)); + } } diff --git a/PHPCI/Service/BuildService.php b/PHPCI/Service/BuildService.php index <HASH>..<HASH> 100644 --- a/PHPCI/Service/BuildService.php +++ b/PHPCI/Service/BuildService.php @@ -112,6 +112,7 @@ class BuildService */ public function deleteBuild(Build $build) { + $build->removeBuildDirectory(); return $this->buildStore->delete($build); } } diff --git a/vars.php b/vars.php index <HASH>..<HASH> 100644 --- a/vars.php +++ b/vars.php @@ -16,6 +16,11 @@ if (!defined('PHPCI_BIN_DIR')) { define('PHPCI_BIN_DIR', PHPCI_DIR . 'vendor/bin/'); } +// Define PHPCI_BUILD_ROOT_DIR +if (!defined('PHPCI_BUILD_ROOT_DIR')) { + define('PHPCI_BUILD_ROOT_DIR', PHPCI_DIR . 'PHPCI/build/'); +} + // Should PHPCI run the Shell plugin? if (!defined('ENABLE_SHELL_PLUGIN')) { define('ENABLE_SHELL_PLUGIN', false);
Added a new configuration variable, PHPCI_BUILD_ROOT_DI. This variable allows to change where the build happens. It defaults to PHPCI_DIR.'PHPCI/build/'. Moved build path calculate and build removal into the Build class. Also remove the build directory when deleting the build. Close #<I>
dancryer_PHPCI
train
55ab6b6e5f1536f87ffd6eef065878f6e4946e18
diff --git a/.remarkrc.js b/.remarkrc.js index <HASH>..<HASH> 100644 --- a/.remarkrc.js +++ b/.remarkrc.js @@ -3,5 +3,10 @@ 'use strict'; module.exports = { - plugins: ['@minna-ui/remarklint-config'], + plugins: [ + '@minna-ui/remarklint-config', + + // rules + ['lint-no-file-name-irregular-characters', '\\.a-zA-Z0-9-_'], // need underscore for docs + ], };
Tweak remark lint internal config to suit docs
WeAreGenki_minna-ui
train
a9a27c40fdd61996d21093766b09087c99cf4f5d
diff --git a/internal/descriptor/services.go b/internal/descriptor/services.go index <HASH>..<HASH> 100644 --- a/internal/descriptor/services.go +++ b/internal/descriptor/services.go @@ -248,7 +248,7 @@ func (r *Registry) newParam(meth *Method, path string) (Parameter, error) { if IsWellKnownType(*target.TypeName) { glog.V(2).Infoln("found well known aggregate type:", target) } else { - return Parameter{}, fmt.Errorf("aggregate type %s in parameter of %s.%s: %s", target.Type, meth.Service.GetName(), meth.GetName(), path) + return Parameter{}, fmt.Errorf("%s.%s: %s is a protobuf message type. Protobuf message types cannot be used as path parameters, use a scalar value type (such as string) instead", meth.Service.GetName(), meth.GetName(), path) } } return Parameter{ diff --git a/internal/descriptor/services_test.go b/internal/descriptor/services_test.go index <HASH>..<HASH> 100644 --- a/internal/descriptor/services_test.go +++ b/internal/descriptor/services_test.go @@ -1347,3 +1347,52 @@ func TestExtractServicesWithDeleteBody(t *testing.T) { t.Log(err) } } + +func TestCauseErrorWithPathParam(t *testing.T) { + src := ` + name: "path/to/example.proto", + package: "example" + message_type < + name: "TypeMessage" + field < + name: "message" + type: TYPE_MESSAGE + type_name: 'ExampleMessage' + number: 1, + label: LABEL_OPTIONAL + > + > + service < + name: "ExampleService" + method < + name: "Echo" + input_type: "TypeMessage" + output_type: "TypeMessage" + options < + [google.api.http] < + get: "/v1/example/echo/{message=*}" + > + > + > + > + ` + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { + t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) + } + target := "path/to/example.proto" + reg := NewRegistry() + input := []*descriptorpb.FileDescriptorProto{&fd} + reg.loadFile(fd.GetName(), &protogen.File{ + Proto: &fd, + }) + // switch this field to see the error + wantErr := true + err := reg.loadServices(reg.files[target]) + if got, want := err != nil, wantErr; got != want { + if want { + t.Errorf("loadServices(%q, %q) succeeded; want an error", target, input) + } + t.Errorf("loadServices(%q, %q) failed with %v; want success", target, input, err) + } +}
Reworked Error message in newParam() in services.go (#<I>) * Reworked Error message for newParam() in services.go * Added Test error case for PathParam
grpc-ecosystem_grpc-gateway
train
ad7f20faa353376a4d462975538cb580bf7ee43a
diff --git a/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/fixture/internal/RemoteDriverFactory.java b/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/fixture/internal/RemoteDriverFactory.java index <HASH>..<HASH> 100644 --- a/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/fixture/internal/RemoteDriverFactory.java +++ b/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/fixture/internal/RemoteDriverFactory.java @@ -33,7 +33,7 @@ import java.net.URL; public class RemoteDriverFactory implements DriverFactory { - private static final String SELENIUM_SERVER_URL = "http://lime:4444/wd/hub"; + private static final String SELENIUM_SERVER_URL = "http://ma-selenium:4444/wd/hub"; @Override public WebDriver create() { return initializeDriver();
use ma-selenium (which is OK now) to speed up build
ebi-gene-expression-group_atlas
train
aba28cbafe0bb1cf30fda0edefef7fa5494c3381
diff --git a/mod/forum/view.php b/mod/forum/view.php index <HASH>..<HASH> 100644 --- a/mod/forum/view.php +++ b/mod/forum/view.php @@ -232,7 +232,9 @@ case 'eachuser': if (!empty($forum->intro)) { - print_box(format_text($forum->intro), 'generalbox', 'intro'); + $options = new stdclass; + $options->para = false; + print_box(format_text($forum->intro, FORMAT_MOODLE, $options), 'generalbox', 'intro'); } echo '<p class="mdl-align">'; if (forum_user_can_post_discussion($forum, null, -1, $cm)) { @@ -258,7 +260,9 @@ default: if (!empty($forum->intro)) { - print_box(format_text($forum->intro), 'generalbox', 'intro'); + $options = new stdclass; + $options->para = false; + print_box(format_text($forum->intro, FORMAT_MOODLE, $options), 'generalbox', 'intro'); } echo '<br />'; if (!empty($showall)) {
"FORUM/MDL-<I>, replace p with div in forum summary, merged from <I>"
moodle_moodle
train
47009a01233e727fcc01bd1537a07c61439d4c74
diff --git a/v1/backends/null/null.go b/v1/backends/null/null.go index <HASH>..<HASH> 100644 --- a/v1/backends/null/null.go +++ b/v1/backends/null/null.go @@ -39,13 +39,13 @@ func (e ErrTasknotFound) Error() string { return fmt.Sprintf("Task not found: %v", e.taskUUID) } -// Backend represents an "eager" in-memory result backend +// Backend represents an "null" result backend type Backend struct { common.Backend groups map[string]struct{} } -// New creates EagerBackend instance +// New creates NullBackend instance func New() iface.Backend { return &Backend{ Backend: common.NewBackend(new(config.Config)), @@ -59,7 +59,7 @@ func (b *Backend) InitGroup(groupUUID string, taskUUIDs []string) error { return nil } -// GroupCompleted returns true if all tasks in a group finished +// GroupCompleted returns true (always) func (b *Backend) GroupCompleted(groupUUID string, groupTaskCount int) (bool, error) { _, ok := b.groups[groupUUID] if !ok { @@ -69,7 +69,7 @@ func (b *Backend) GroupCompleted(groupUUID string, groupTaskCount int) (bool, er return true, nil } -// GroupTaskStates returns states of all tasks in the group +// GroupTaskStates returns null states of all tasks in the group func (b *Backend) GroupTaskStates(groupUUID string, groupTaskCount int) ([]*tasks.TaskState, error) { _, ok := b.groups[groupUUID] if !ok { @@ -80,10 +80,7 @@ func (b *Backend) GroupTaskStates(groupUUID string, groupTaskCount int) ([]*task return ret, nil } -// TriggerChord flags chord as triggered in the backend storage to make sure -// chord is never trigerred multiple times. Returns a boolean flag to indicate -// whether the worker should trigger chord (true) or no if it has been triggered -// already (false) +// TriggerChord returns true (always) func (b *Backend) TriggerChord(groupUUID string) (bool, error) { return true, nil } @@ -145,6 +142,5 @@ func (b *Backend) PurgeGroupMeta(groupUUID string) error { } func (b *Backend) updateState(s *tasks.TaskState) error { - // simulate the behavior of json marshal/unmarshal return nil }
CC - Cleanup some comments in null ResultBackend (#<I>)
RichardKnop_machinery
train
1c0a78a4fdb881cb6c14a0a29c2890334974d984
diff --git a/pkg/controller/service/controller.go b/pkg/controller/service/controller.go index <HASH>..<HASH> 100644 --- a/pkg/controller/service/controller.go +++ b/pkg/controller/service/controller.go @@ -804,8 +804,7 @@ func (s *Controller) addFinalizer(service *v1.Service) error { updated.ObjectMeta.Finalizers = append(updated.ObjectMeta.Finalizers, servicehelper.LoadBalancerCleanupFinalizer) klog.V(2).Infof("Adding finalizer to service %s/%s", updated.Namespace, updated.Name) - // TODO(87447) use PatchService from k8s.io/cloud-provider/service/helpers - _, err := patch(s.kubeClient.CoreV1(), service, updated) + _, err := servicehelper.PatchService(s.kubeClient.CoreV1(), service, updated) return err } @@ -820,7 +819,7 @@ func (s *Controller) removeFinalizer(service *v1.Service) error { updated.ObjectMeta.Finalizers = removeString(updated.ObjectMeta.Finalizers, servicehelper.LoadBalancerCleanupFinalizer) klog.V(2).Infof("Removing finalizer from service %s/%s", updated.Namespace, updated.Name) - _, err := patch(s.kubeClient.CoreV1(), service, updated) + _, err := servicehelper.PatchService(s.kubeClient.CoreV1(), service, updated) return err } @@ -846,7 +845,7 @@ func (s *Controller) patchStatus(service *v1.Service, previousStatus, newStatus updated.Status.LoadBalancer = *newStatus klog.V(2).Infof("Patching status for service %s/%s", updated.Namespace, updated.Name) - _, err := patch(s.kubeClient.CoreV1(), service, updated) + _, err := servicehelper.PatchService(s.kubeClient.CoreV1(), service, updated) return err }
Use servicePatch methods from cloud-provider repo in service-controller
kubernetes_kubernetes
train
d5fde6a4b9954d7b3dc4d188e0f7ed6577a5f2b6
diff --git a/lib/request.js b/lib/request.js index <HASH>..<HASH> 100644 --- a/lib/request.js +++ b/lib/request.js @@ -226,7 +226,7 @@ req.param = function(name, defaultValue){ var params = this.params || {}; var body = this.body || {}; var query = this.query || {}; - if (null != params[name]) return params[name]; + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; if (null != body[name]) return body[name]; if (null != query[name]) return query[name]; return defaultValue; diff --git a/test/req.param.js b/test/req.param.js index <HASH>..<HASH> 100644 --- a/test/req.param.js +++ b/test/req.param.js @@ -59,13 +59,13 @@ describe('req', function(){ var app = express(); app.get('/user/:name', function(req, res){ - res.end(req.param('name')); + res.end(req.param('filter') + req.param('name')); }); request(app) .get('/user/tj') .end(function(res){ - res.body.should.equal('tj'); + res.body.should.equal('undefinedtj'); done(); }) })
added test to illustrate req.params as an array
expressjs_express
train
ecf5ba772e99fdbe64405acab644ba1398d27a87
diff --git a/src/components/networked-share.js b/src/components/networked-share.js index <HASH>..<HASH> 100644 --- a/src/components/networked-share.js +++ b/src/components/networked-share.js @@ -357,7 +357,7 @@ AFRAME.registerComponent('networked-share', { if (elComponents.hasOwnProperty(element)) { var name = element; var elComponent = elComponents[name]; - compsWithData[name] = elComponent.getData(); + compsWithData[name] = elComponent.data; } } else { var childKey = naf.utils.childSchemaToKey(element); @@ -365,7 +365,7 @@ AFRAME.registerComponent('networked-share', { if (child) { var comp = child.components[element.component]; if (comp) { - var data = element.property ? comp.data[element.property] : comp.getData(); + var data = element.property ? comp.data[element.property] : comp.data; compsWithData[childKey] = data; } else { naf.log.write('Could not find component ' + element.component + ' on child ', child, child.components); @@ -394,7 +394,7 @@ AFRAME.registerComponent('networked-share', { continue; } compKey = schema; - newCompData = newComps[schema].getData(); + newCompData = newComps[schema].data; } else { // is child component @@ -408,7 +408,7 @@ AFRAME.registerComponent('networked-share', { continue; } compKey = naf.utils.childSchemaToKey(schema); - newCompData = childEl.components[compName].getData(); + newCompData = childEl.components[compName].data; if (propName) { newCompData = newCompData[propName]; } } diff --git a/src/components/networked.js b/src/components/networked.js index <HASH>..<HASH> 100644 --- a/src/components/networked.js +++ b/src/components/networked.js @@ -165,7 +165,7 @@ AFRAME.registerComponent('networked', { if (elComponents.hasOwnProperty(element)) { var name = element; var elComponent = elComponents[name]; - compsWithData[name] = elComponent.getData(); + compsWithData[name] = elComponent.data; } } else { var childKey = naf.utils.childSchemaToKey(element); @@ -173,7 +173,7 @@ AFRAME.registerComponent('networked', { if (child) { var comp = child.components[element.component]; if (comp) { - var data = element.property ? comp.data[element.property] : comp.getData(); + var data = element.property ? comp.data[element.property] : comp.data; compsWithData[childKey] = data; } else { naf.log.write('Could not find component ' + element.component + ' on child ', child, child.components); @@ -202,7 +202,7 @@ AFRAME.registerComponent('networked', { continue; } compKey = schema; - newCompData = newComps[schema].getData(); + newCompData = newComps[schema].data; } else { // is child component @@ -216,7 +216,7 @@ AFRAME.registerComponent('networked', { continue; } compKey = naf.utils.childSchemaToKey(schema); - newCompData = childEl.components[compName].getData(); + newCompData = childEl.components[compName].data; if (propName) { newCompData = newCompData[propName]; } }
component getData() --> component.data now that optimizations removed the function
networked-aframe_networked-aframe
train
31dbabc28354736feb86845ef0112dfb5673b196
diff --git a/src/core/components/files.js b/src/core/components/files.js index <HASH>..<HASH> 100644 --- a/src/core/components/files.js +++ b/src/core/components/files.js @@ -184,10 +184,15 @@ class AddStreamDuplex extends Duplex { super(Object.assign({ objectMode: true }, options)) this._pullStream = pullStream this._pushable = push + this._waitingPullFlush = [] } _read () { this._pullStream(null, (end, data) => { + while (this._waitingPullFlush.length) { + const cb = this._waitingPullFlush.shift() + cb() + } if (end) { if (end instanceof Error) { this.emit('error', end) @@ -199,7 +204,7 @@ class AddStreamDuplex extends Duplex { } _write (chunk, encoding, callback) { + this._waitingPullFlush.push(callback) this._pushable.push(chunk) - callback() } }
fix: added backpressure to the add stream (#<I>) * fix: added backpressure to the add stream
ipfs_js-ipfs
train
18b07efaf49c6e7c9d85c71aa1996b79f86bb3e6
diff --git a/enrol/authorize/localfuncs.php b/enrol/authorize/localfuncs.php index <HASH>..<HASH> 100644 --- a/enrol/authorize/localfuncs.php +++ b/enrol/authorize/localfuncs.php @@ -49,7 +49,7 @@ function prevent_double_paid($course) } if (isset($SESSION->ccpaid)) { unset($SESSION->ccpaid); - redirect($CFG->wwwroot . '/login/logout.php'); + redirect($CFG->wwwroot . '/login/logout.php?sesskey='.sesskey()); return; } } diff --git a/lang/en_utf8/moodle.php b/lang/en_utf8/moodle.php index <HASH>..<HASH> 100644 --- a/lang/en_utf8/moodle.php +++ b/lang/en_utf8/moodle.php @@ -824,6 +824,7 @@ $string['loginstepsnone'] = '<p>Hi!</p> $string['loginto'] = 'Login to $a'; $string['loginusing'] = 'Login here using your username and password'; $string['logout'] = 'Logout'; +$string['logoutconfirm'] = 'Do you really want to logout?'; $string['logs'] = 'Logs'; $string['logtoomanycourses'] = '[ <a href=\"$a->url\">more</a> ]'; $string['logtoomanyusers'] = '[ <a href=\"$a->url\">more</a> ]'; diff --git a/lib/weblib.php b/lib/weblib.php index <HASH>..<HASH> 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -2748,7 +2748,7 @@ function user_login_string($course=NULL, $user=NULL) { href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)'; } else { $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '. - " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php\">".get_string('logout').'</a>)'; + " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)'; } } else { $loggedinas = get_string('loggedinnot', 'moodle'). diff --git a/login/logout.php b/login/logout.php index <HASH>..<HASH> 100644 --- a/login/logout.php +++ b/login/logout.php @@ -10,6 +10,15 @@ $wwwroot = $CFG->wwwroot; } + $sesskey = optional_param('sesskey', '__notpresent__', PARAM_RAW); // we want not null default to prevent required sesskey warning + + if (!confirm_sesskey($sesskey)) { + print_header($SITE->fullname, $SITE->fullname, 'home'); + notice_yesno(get_string('logoutconfirm'), 'logout.php', $CFG->wwwroot.'/', array('sesskey'=>sesskey()), null, 'post', 'get'); + print_footer(); + die; + } + require_logout(); redirect("$wwwroot/");
sesskey added to logout.php MDL-<I>
moodle_moodle
train
828b003d9fcddf5445577481e9e96b443f6cd302
diff --git a/medoo.php b/medoo.php index <HASH>..<HASH> 100644 --- a/medoo.php +++ b/medoo.php @@ -11,7 +11,7 @@ class medoo { protected $database_type = 'mysql'; - // For MySQL, MSSQL, Sybase + // For MySQL, Mariadb, MSSQL, Sybase, PostgreSQL, Oracle protected $server = 'localhost'; protected $username = 'username'; @@ -87,6 +87,10 @@ class medoo $commands[] = $set_charset; break; + case 'oracle': + $dsn = 'oci:host=' . $this->server . (isset($port) ? ';port=' . $port : '') . ';dbname=' . $this->database_name . ';charset=' . $this->charset; + break; + case 'mssql': $dsn = strpos(PHP_OS, 'WIN') !== false ? 'sqlsrv:server=' . $this->server . (isset($port) ? ',' . $port : '') . ';database=' . $this->database_name :
[feature] Add support for Oracle database
catfan_Medoo
train
020f8f88f3343f5a3aac0ae25b80cd2fcbc98718
diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java index <HASH>..<HASH> 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/collection/implementation/TopLevelModifiableResourcesImpl.java @@ -76,7 +76,7 @@ public abstract class TopLevelModifiableResourcesImpl< @Override public Observable<String> deleteByIdsAsync(Collection<String> ids) { - if (ids == null) { + if (ids == null || ids.isEmpty()) { return Observable.empty(); }
minor bug fix in deleteByIdsAsync
Azure_azure-sdk-for-java
train
6a2ea6f506a87c6ec31baa573a061749b63ec5e4
diff --git a/src/Block/Service/AbstractBlockService.php b/src/Block/Service/AbstractBlockService.php index <HASH>..<HASH> 100644 --- a/src/Block/Service/AbstractBlockService.php +++ b/src/Block/Service/AbstractBlockService.php @@ -69,7 +69,7 @@ abstract class AbstractBlockService implements BlockServiceInterface { return [ 'block_id' => $block->getId(), - 'updated_at' => null !== $block->getUpdatedAt() ? $block->getUpdatedAt()->format('U') : strtotime('now'), + 'updated_at' => null !== $block->getUpdatedAt() ? $block->getUpdatedAt()->format('U') : null, ]; }
Remove current timestamp from cache key
sonata-project_SonataBlockBundle
train
0979c9953478d8d78a35210c4d8ae811e5f4111b
diff --git a/mp3/decoder.go b/mp3/decoder.go index <HASH>..<HASH> 100644 --- a/mp3/decoder.go +++ b/mp3/decoder.go @@ -58,6 +58,7 @@ func (d *Decoder) Duration() (time.Duration, error) { return 0, errors.New("can't calculate the duration of a nil pointer") } fr := &Frame{} + var frameDuration time.Duration var duration time.Duration var err error for { @@ -69,7 +70,10 @@ func (d *Decoder) Duration() (time.Duration, error) { } break } - duration += fr.Duration() + frameDuration = fr.Duration() + if frameDuration > 0 { + duration += frameDuration + } d.NbrFrames++ } if err == io.EOF || err == io.ErrUnexpectedEOF || err == io.ErrShortBuffer { @@ -103,8 +107,7 @@ func (d *Decoder) Next(f *Frame) error { // so we need to read the rest. buf := make([]byte, 124) // TODO: parse the actual header - n, err := io.ReadFull(d.r, buf) - if err != nil || n != 124 { + if _, err := io.ReadAtLeast(d.r, buf, 124); err != nil { return ErrInvalidHeader } buf = append(f.buf, buf...) diff --git a/mp3/frame.go b/mp3/frame.go index <HASH>..<HASH> 100644 --- a/mp3/frame.go +++ b/mp3/frame.go @@ -35,7 +35,12 @@ func (f *Frame) Duration() time.Duration { return 0 } ms := (1000 / float64(f.Header.SampleRate())) * float64(f.Header.Samples()) - return time.Duration(int(float64(time.Millisecond) * ms)) + dur := time.Duration(int(float64(time.Millisecond) * ms)) + if dur < 0 { + // we have bad data, let's ignore it + dur = 0 + } + return dur } // CRC returns the CRC word stored in this frame
mp3: better catch of bad data
mattetti_audio
train
2ce9a1f59de384476399be5d858be01c859172e1
diff --git a/tag/manage.php b/tag/manage.php index <HASH>..<HASH> 100644 --- a/tag/manage.php +++ b/tag/manage.php @@ -116,7 +116,7 @@ switch($action) { foreach ( $new_otags as $new_otag ) { if ( $new_otag_id = tag_get_id($new_otag) ) { // tag exists, change the type - tag_set_type($new_otag_id, 'official'); + tag_type_set($new_otag_id, 'official'); } else { require_capability('moodle/tag:create', get_context_instance(CONTEXT_SYSTEM)); tag_add($new_otag, 'official');
MDL-<I>: typo in function name - wrong call meant tag type was set incorrectly (merge from <I>)
moodle_moodle
train
5f5125ad93e0a0eb60ee7be67faecd8ffcaf9124
diff --git a/lib/megam/api/version.rb b/lib/megam/api/version.rb index <HASH>..<HASH> 100644 --- a/lib/megam/api/version.rb +++ b/lib/megam/api/version.rb @@ -1,5 +1,5 @@ module Megam class API - VERSION = "0.14" + VERSION = "0.15" end end
<I> common yml
megamsys_megam_api
train
fac564c04840a78f04af44d814748c95b7d1a342
diff --git a/mapchete/log.py b/mapchete/log.py index <HASH>..<HASH> 100644 --- a/mapchete/log.py +++ b/mapchete/log.py @@ -18,11 +18,64 @@ all_mapchete_packages = set( ) ) +key_value_replace_patterns = { + "AWS_ACCESS_KEY_ID": "***", + "AWS_SECRET_ACCESS_KEY": "***", +} + + +class KeyValueFilter(logging.Filter): + """ + This filter looks for dictionaries passed on to log messages and replaces its values + with a replacement if key matches the pattern. + + Examples + -------- + >>> stream_handler.addFilter( + ... KeyValueFilter( + ... key_value_replace={ + ... "AWS_ACCESS_KEY_ID": "***", + ... "AWS_SECRET_ACCESS_KEY": "***", + ... } + ... ) + ... ) + """ + + def __init__(self, key_value_replace=None): + super(KeyValueFilter, self).__init__() + self._key_value_replace = key_value_replace or {} + + def filter(self, record): + record.msg = self.redact(record.msg) + if isinstance(record.args, dict): + for k, v in record.args.items(): + record.args[k] = self.redact({k: v})[k] + else: + record.args = tuple(self.redact(arg) for arg in record.args) + return True + + def redact(self, msg): + if isinstance(msg, dict): + out_msg = {} + for k, v in msg.items(): + if isinstance(v, dict): + v = self.redact(v) + else: + for k_replace, v_replace in self._key_value_replace.items(): + v = v_replace if k == k_replace else v + out_msg[k] = v + else: + out_msg = msg + + return out_msg + + # lower stream output log level formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) stream_handler.setLevel(logging.WARNING) +stream_handler.addFilter(KeyValueFilter(key_value_replace=key_value_replace_patterns)) for i in all_mapchete_packages: logging.getLogger(i).addHandler(stream_handler)
add custom log filter to replace secrets (#<I>)
ungarj_mapchete
train
6f008ac0637a7236e1752d84c6d9bde5b523dc7d
diff --git a/src/sap.ui.unified/src/sap/ui/unified/calendar/MonthRenderer.js b/src/sap.ui.unified/src/sap/ui/unified/calendar/MonthRenderer.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.unified/src/sap/ui/unified/calendar/MonthRenderer.js +++ b/src/sap.ui.unified/src/sap/ui/unified/calendar/MonthRenderer.js @@ -292,7 +292,7 @@ sap.ui.define(['jquery.sap.global', 'sap/ui/unified/calendar/CalendarUtils', 'sa oRm.addClass("sapUiCalItemOtherMonth"); mAccProps["disabled"] = true; } - if (oDay.getUTCMonth() == oHelper.oToday.getMonth() && oDay.getUTCFullYear() == oHelper.oToday.getFullYear() && oDay.getUTCDate() == oHelper.oToday.getDate()) { + if (oDay.getUTCMonth() == oHelper.oToday.getUTCMonth() && oDay.getUTCFullYear() == oHelper.oToday.getUTCFullYear() && oDay.getUTCDate() == oHelper.oToday.getUTCDate()) { oRm.addClass("sapUiCalItemNow"); mAccProps["label"] = oHelper.sToday + " "; }
[FIX] sap.ui.uinified.Calendar current day is wrong displayed for some time zones Change-Id: Ifef<I>d<I>a2a<I>dc0c5f<I>da5ea6d7c BCP: <I>
SAP_openui5
train
05ca10ed4ed50b3c518f41ec7b9d2ea91dcf1386
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -26,7 +26,9 @@ module.exports = function(source) { } return value; } - entries(vars).map(([key, value]) => { + entries(vars).map((entry) => { + const key = entry[0]; + const value = entry[1]; vars[key] = followVar(value); }); }
fix: deconstruction does not work in Node 5
joscha_less-vars-loader
train
45f3608269d3aa9e47fe6b924730d9122815f9e1
diff --git a/dallinger/prolific.py b/dallinger/prolific.py index <HASH>..<HASH> 100644 --- a/dallinger/prolific.py +++ b/dallinger/prolific.py @@ -53,12 +53,34 @@ class ProlificService: the study on Prolific. If we get there first, there will be an error because the submission hasn't happened yet. """ + status = self.get_participant_session(session_id)["status"] + if status != "AWAITING REVIEW": + # This will trigger a retry from the decorator + raise ProlificServiceException("Prolific session not yet submitted.") + return self._req( method="POST", endpoint=f"/submissions/{session_id}/transition/", json={"action": "APPROVE"}, ) + def get_participant_session(self, session_id: str) -> dict: + """Retrieve details of a participant Session + + This is roughly equivalent to an Assignment on MTurk. + + Example return value: + + { + "id": "60d9aadeb86739de712faee0", + "study_id": "60aca280709ee40ec37d4885", + "participant": "60bf9310e8dec401be6e9615", + "started_at": "2021-05-20T11:03:00.457Z", + "status": "ACTIVE" + } + """ + return self._req(method="GET", endpoint=f"/submissions/{session_id}/") + def create_published_study( self, completion_code: str, @@ -151,6 +173,12 @@ class ProlificService: This needs to happen in two steps: 1. Define the payments as a record on Prolific 2. Trigger the execution of the payments, using the ID from step 1. + + + Note: We currently rely on Dallinger's execution order to ensure that the + study has already been submitted and approved by the time we are called. If + this were not the case, it's possible that payment would fail, but I have + not verified this. - `Jesse Snyder <https://github.com/jessesnyder/>__` Feb 1 2022 """ amount_str = "{:.2f}".format(amount) payload = {
Make sure the participant has submitted their session/assignment before trying to approve it
Dallinger_Dallinger
train
04e6913056e5bdc2261fb2d37e16b1892f50bf2b
diff --git a/elasticutils/__init__.py b/elasticutils/__init__.py index <HASH>..<HASH> 100644 --- a/elasticutils/__init__.py +++ b/elasticutils/__init__.py @@ -13,7 +13,7 @@ log = logging.getLogger('elasticutils') # Note: Don't change these--they're not part of the API. -DEFAULT_URLS = ['http://localhost:9200'] +DEFAULT_URLS = ['localhost'] DEFAULT_DOCTYPES = None DEFAULT_INDEXES = None DEFAULT_TIMEOUT = 5 @@ -122,7 +122,7 @@ def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings): # Returns a new Elasticsearch object es = get_es(force_new=True) - es = get_es(urls=['localhost:9200']) + es = get_es(urls=['localhost']) es = get_es(urls=['localhost:9200'], timeout=10, max_retries=3)
By default connect to localhost, not localhost:<I> <I> is http port that would break if thrift was requested for example
mozilla_elasticutils
train
d6634c20269b0f9f6d8616d71616140057f8cf53
diff --git a/web/src/main/webapp/js/views.js b/web/src/main/webapp/js/views.js index <HASH>..<HASH> 100644 --- a/web/src/main/webapp/js/views.js +++ b/web/src/main/webapp/js/views.js @@ -168,14 +168,14 @@ App.FormSelect = App.FormField.extend({ requiredBinding: 'parentView.required', attributeBindings: ['required'] }), - willInsertElement: function(asdf) { + willInsertElement: function() { if(this.get('optionsPath')) { this.set('options', this.get(this.get('optionsPath'))); } else { this.set('options', this.get('content')); } var options = this.get('options'); - if(typeof options === "object") { //Allow a map object to be used for select options + if(!$.isArray(options)) { //Allow a map object to be used for select options var opsArray = []; for(var option in options) { opsArray.push({name: option, value: options[option]});
Bug fix Fixed bug in App.FormSelect in views.js
crawljax_crawljax
train
23a60cfeb6f67d36d01c00993b32079dbba8fa93
diff --git a/src/shared/js/ch.AutoComplete.js b/src/shared/js/ch.AutoComplete.js index <HASH>..<HASH> 100644 --- a/src/shared/js/ch.AutoComplete.js +++ b/src/shared/js/ch.AutoComplete.js @@ -1,37 +1,31 @@ -/** -* AutoComplete lets you suggest anything from an input element. Use a suggestion service or use a collection with the suggestions. -* @name AutoComplete -* @class AutoComplete -* @augments ch.Controls -* @see ch.Controls -* @memberOf ch -* @param {Object} [conf] Object with configuration properties. -* @param {String} conf.url The url pointing to the suggestions's service. -* @param {String} [conf.content] It represent the text when no options are shown. -* @param {Array} [conf.suggestions] The suggestions's collection. If a URL is set at conf.url parametter this will be omitted. -* @returns itself -* @factorized -* @exampleDescription Create a new autoComplete with configuration. -* @example -* var widget = $(".example").autoComplete({ -* "url": "http://site.com/mySuggestions?q=", -* "message": "Write..." -* }); -*/ (function (window, $, ch) { 'use strict'; if (window.ch === undefined) { throw new window.Error('Expected ch namespace defined.'); } - + /** + * AutoComplete widget shows a list of suggestions when for a HTMLInputElement. + * @memberof ch + * @constructor + * @augments ch.Widget + * @param {Object} [conf] Object with configuration properties. + * @param {String} [options.side] The side option where the target element will be positioned. Its value can be: left, right, top, bottom or center (default). + * @param {String} [options.align] The align options where the target element will be positioned. Its value can be: left, right, top, bottom or center (default). + * @param {Number} [options.offsetX] The offsetX option specifies a distance to displace the target horitontally. Its value by default is 0. + * @param {Number} [options.offsetY] The offsetY option specifies a distance to displace the target vertically. Its value by default is 0. + * @param {String} [options.positioned] The positioned option specifies the type of positioning used. Its value can be: absolute or fixed (default). + * @returns {Object} + * @example + * // Create a new autoComplete with configuration. + * var widget = $('.example').autoComplete(); + */ function AutoComplete($el, options) { /** * Reference to a internal component instance, saves all the information and configuration properties. * @private * @name ch.AutoComplete#that - * @type object */ var that = this; @@ -39,12 +33,10 @@ /** * Triggers when the component is ready to use (Since 0.8.0). - * @name ch.AutoComplete#ready - * @event - * @public - * @exampleDescription Following the first example, using <code>widget</code> as autoComplete's instance controller: + * @event ch.AutoComplete#ready * @example - * widget.on("ready",function () { + * // Following the first example, using <code>widget</code> as autoComplete's instance controller: + * widget.on('ready',function () { * this.show(); * }); */ @@ -61,9 +53,23 @@ $document = $(document), parent = ch.util.inherits(AutoComplete, ch.Widget); + /** + * The name of the widget. A new instance is saved into the $el parameter. + * @memberof! ch.AutoComplete.prototype + * @type {String} + * @expample + * // You can reach the instance associated. + * var widget = $(selector).data('autoComplete'); + */ AutoComplete.prototype.name = 'autoComplete'; - AutoComplete.prototype.constructor = AutoComplete; + /** + * Returns a reference to the Constructor function that created the instance's prototype. + * @memberof! ch.AutoComplete.prototype + * @constructor + * @private + */ + AutoComplete.prototype._constructor = AutoComplete; AutoComplete.prototype._defaults = { 'loadingClass': 'ch-autoComplete-loading', @@ -71,9 +77,17 @@ 'align': 'left', 'keystrokesTime': 1000, 'hiddenby': 'none', - 'html': false + 'html': false, + 'side': 'bottom', + 'align': 'left' }; + /** + * Initialize the instance and merges the user options with defaults options. + * @memberof! ch.AutoComplete.prototype + * @function + * @returns {instance} Returns an instance of ch.AutoComplete. + */ AutoComplete.prototype.init = function ($el, options) { var that = this, ESC = ch.onkeyesc + '.' + this.name, // UI @@ -94,7 +108,7 @@ /** * The component who shows the suggestions. - * @public + * @private * @type Object * @name ch.AutoComplete#_popover */
GH-<I> added side and align to the defaults object configuration
mercadolibre_chico
train
93dab7966150b3f2fdd7fd8b1d546e017111d10f
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -131,11 +131,14 @@ var getInstance = function () { */ user.prototype.initApplication = function(app) { var self = this; + if(molecuel.config && molecuel.config.user.secret) { // Initialize Passport! Also use passport.session() middleware, to support // persistent login sessions (recommended). app.use(passport.initialize()); + app.use(self.initUser); + //app.use(passport.session()); //@todo replace with app.post('/login/jwt', passport.authenticate('local', { session: false }), function (req, res) //app.post('/login/jwt', function (req, res) { @@ -166,12 +169,10 @@ user.prototype.debugHeader = function debugHeader(req, res, next) { user.prototype._defaultSchemaPlugin = function _defaultSchemaPlugin(schema) { schema.add({ createdby: { - _id: {type: elements.ObjectId, ref: 'user', form: {hidden: true, label: 'Created by id'}}, - username: {type: String, form: {hidden: true, label: 'Created by username'}} + type: elements.ObjectId, ref: 'user', form: {readonly: true, label: 'Created by'} }, lastchangedby: { - _id: {type: elements.ObjectId, ref: 'user', form: {hidden: true, label: 'Last changed by id'}}, - username: {type: String, form: {hidden: true, label: 'Last changed by username'}} + type: elements.ObjectId, ref: 'user', form: {readonly: true, label: 'Last changed by'} } }); }; @@ -343,8 +344,10 @@ user.prototype._checkRole = function _checkRole(role, permission) { user.prototype._postApiHandler = function(doc, req, callback) { //var user = getInstance(); if(req.user) { - doc.createdby = req.user; - doc.lastchangedby = req.user; + if(!doc.createdby) { + doc.createdby = req.user._id; //mongoose creates ObjectIDs Cast errors if object reference is a simple object + } + doc.lastchangedby = req.user._id; callback(); } else { callback(new Error('No valid user found')); @@ -352,6 +355,29 @@ user.prototype._postApiHandler = function(doc, req, callback) { }; /** + * Middleware function to register the current user on the request + * @todo: Is this the right place? + * @param req + * @param res + * @param next + */ +user.prototype.initUser = function(req, res, next) { + var self = this; + if(req.headers.authorization) { + jwt.verify(req.headers.authorization, molecuel.config.user.secret, function(err, decoded) { + if(err && !decoded) { + console.log("ERROR USER " + err); + next(); + } else { + req.user = decoded; + next(); + } + }); + } else { + next(); + } +} +/** * Middleware function to check if the user has the correct permissions * @param item * @param req
fixed mlcl_elements integration with generic created by and lastchangedby references
molecuel_mlcl_user
train
18294270c20c640c7aba7a34d2efe84718f41008
diff --git a/schema_salad/codegen.py b/schema_salad/codegen.py index <HASH>..<HASH> 100644 --- a/schema_salad/codegen.py +++ b/schema_salad/codegen.py @@ -90,7 +90,13 @@ def codegen(lang, # type: str cg.declare_field(fieldpred, tl, f.get("doc"), optional) - cg.end_class(rec["name"]) + field_names = [] + for f in rec.get("fields", []): + jld = f.get("jsonldPredicate") + name = f["name"] + field_names.append(shortname(name)) + + cg.end_class(rec["name"], field_names) rootType = list(documentRoots) rootType.append({ diff --git a/schema_salad/codegen_base.py b/schema_salad/codegen_base.py index <HASH>..<HASH> 100644 --- a/schema_salad/codegen_base.py +++ b/schema_salad/codegen_base.py @@ -38,8 +38,8 @@ class CodeGenBase(object): # type: (Text, List[Text], Text, bool) -> None raise NotImplementedError() - def end_class(self, classname): - # type: (Text) -> None + def end_class(self, classname, field_names): + # type: (Text, List[Text]) -> None raise NotImplementedError() def type_loader(self, t): diff --git a/schema_salad/java_codegen.py b/schema_salad/java_codegen.py index <HASH>..<HASH> 100644 --- a/schema_salad/java_codegen.py +++ b/schema_salad/java_codegen.py @@ -68,7 +68,7 @@ public class {cls}Impl implements {cls} {{ void Load() { """) - def end_class(self, classname): + def end_class(self, classname, field_names): with open(os.path.join(self.outdir, "%s.java" % self.current_class), "a") as f: f.write(""" } diff --git a/schema_salad/python_codegen.py b/schema_salad/python_codegen.py index <HASH>..<HASH> 100644 --- a/schema_salad/python_codegen.py +++ b/schema_salad/python_codegen.py @@ -88,18 +88,27 @@ class PythonCodeGen(CodeGenBase): r = {} """) - def end_class(self, classname): - # type: (Text) -> None + def end_class(self, classname, field_names): + # type: (Text, List[Text]) -> None if self.current_class_is_abstract: return self.out.write(""" + for k in doc.keys(): + if k not in self.attrs: + errors.append(SourceLine(doc, k, str).makeError("invalid field `%s`, expected one of: {attrstr}" % (k))) + break + if errors: - raise ValidationException(\"Trying '%s'\\n\"+\"\\n\".join(errors)) -""" % self.safe_name(classname)) + raise ValidationException(\"Trying '{class_}'\\n\"+\"\\n\".join(errors)) +""". + format(attrstr=", ".join(["`%s`" % f for f in field_names]), + class_=self.safe_name(classname))) + self.serializer.write(" return r\n\n") + + self.serializer.write(" attrs = frozenset({attrs})\n".format(attrs=field_names)) - self.serializer.write(" return r\n") self.out.write(self.serializer.getvalue()) self.out.write("\n\n")
Add checks for redundant fields in codegen-ed code (#<I>) * Move attrs to a class variable in codegen
common-workflow-language_schema_salad
train
cbed8dd59684a31e69c3a4a96c42723a2be7e57b
diff --git a/brainpy/__init__.py b/brainpy/__init__.py index <HASH>..<HASH> 100644 --- a/brainpy/__init__.py +++ b/brainpy/__init__.py @@ -5,4 +5,6 @@ A Python Implementation of the Baffling Recursive Algorithm for Isotopic cluster __author__ = "Joshua Klein & Han Hu" -from brainpy import isotopic_variants, IsotopicDistribution, periodic_table, max_variants, calculate_mass +from brainpy import (isotopic_variants, IsotopicDistribution, periodic_table, + max_variants, calculate_mass, neutral_mass, mass_charge_ratio, + PROTON) diff --git a/brainpy/brainpy.py b/brainpy/brainpy.py index <HASH>..<HASH> 100644 --- a/brainpy/brainpy.py +++ b/brainpy/brainpy.py @@ -40,7 +40,7 @@ def mass_charge_ratio(neutral_mass, z, charge_carrier=PROTON): def give_repr(cls): r"""Patch a class to give it a generic __repr__ method - that works by inspecting the instance dictionary. This + that works by inspecting the instance dictionary. Parameters ---------- @@ -256,7 +256,7 @@ def _isotopes_of(element): periodic_table = {k: Element(k) for k in nist_mass} -periodic_table = {k: e for k, e in periodic_table.items() if e.max_neutron_shift() != 0 and e.min_neutron_shift() >= 0} +# periodic_table = {k: e for k, e in periodic_table.items() if e.max_neutron_shift() != 0 and e.min_neutron_shift() >= 0} periodic_table["H+"] = Element("H+") @@ -382,6 +382,19 @@ class Peak(object): self.intensity = intensity self.charge = charge + def __eq__(self, other): + equal = all( + abs(self.mz - other.mz) < 1e-10, + abs(self.intensity - other.intensity) < 1e-10, + self.charge == other.charge) + return equal + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.mz) + @give_repr class IsotopicDistribution(object): @@ -521,7 +534,7 @@ class IsotopicDistribution(object): average_mass /= total self.average_mass = average_mass peak_set.sort(key=mz_getter) - return peak_set + return tuple(peak_set) def isotopic_variants(composition, n_peaks=None, charge=0): diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='brainpy', - version='1.0.6', + version='1.0.8', packages=find_packages(), description="Fast and efficient theoretical isotopic profile generation", long_description='''
Expose more massing tools in __init__
mobiusklein_brainpy
train
dad837d6490dcef2baa5ffccf5db6455e55d8eaf
diff --git a/scripts/generateSkillMeta.js b/scripts/generateSkillMeta.js index <HASH>..<HASH> 100644 --- a/scripts/generateSkillMeta.js +++ b/scripts/generateSkillMeta.js @@ -3,6 +3,7 @@ const { promisify } = require('util'); const fs = require('fs'); const path = require('path'); const { Grammar, Parser } = require('nearley'); +const stripBom = require('strip-bom'); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); @@ -18,10 +19,8 @@ const txt_file = path.join( ); const json_file = path.join(__dirname, '../src/translate', 'skill_meta.json'); -const raw = fs.readFileSync(txt_file, { encoding: 'utf8' }); - -readFile(txt_file, { encoding: 'utf8' }) - .then(raw => { +readFile(txt_file, { encoding: 'utf16le' }) + .then(raw => stripBom(raw)).then(raw => { const parser = new Parser(grammar); parser.feed(raw); const [results] = parser.results;
Fixed encoding issues similar to <I>fd3b0f<I>f5fb7e<I>c<I>ff<I>ece4
eps1lon_poe-i18n
train
903305b9ccbc350b0f6d3806a2cb1710442dbe00
diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -248,7 +248,7 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate */ public function some($key, $operator = null, $value = null) { - return $this->contains($key, $operator, $value); + return $this->contains(...func_get_args()); } /** diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index <HASH>..<HASH> 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1842,6 +1842,44 @@ class SupportCollectionTest extends TestCase })); } + public function testSome() + { + $c = new Collection([1, 3, 5]); + + $this->assertTrue($c->some(1)); + $this->assertFalse($c->some(2)); + $this->assertTrue($c->some(function ($value) { + return $value < 5; + })); + $this->assertFalse($c->some(function ($value) { + return $value > 5; + })); + + $c = new Collection([['v' => 1], ['v' => 3], ['v' => 5]]); + + $this->assertTrue($c->some('v', 1)); + $this->assertFalse($c->some('v', 2)); + + $c = new Collection(['date', 'class', (object) ['foo' => 50]]); + + $this->assertTrue($c->some('date')); + $this->assertTrue($c->some('class')); + $this->assertFalse($c->some('foo')); + + $c = new Collection([['a' => false, 'b' => false], ['a' => true, 'b' => false]]); + + $this->assertTrue($c->some->a); + $this->assertFalse($c->some->b); + + $c = new Collection([ + null, 1, 2, + ]); + + $this->assertTrue($c->some(function ($value) { + return is_null($value); + })); + } + public function testContainsStrict() { $c = new Collection([1, 3, 5, '02']);
[<I>] fix bug when using 'some' alias for the 'contains' method (#<I>) * fix bug when using 'some' alias for the 'contains' method * remove array_filter 'cause it doesnt solve the problem
laravel_framework
train
1ec47d9f087f4bdf5e4422463802342ed38d77b1
diff --git a/seleniumbase/fixtures/base_case.py b/seleniumbase/fixtures/base_case.py index <HASH>..<HASH> 100755 --- a/seleniumbase/fixtures/base_case.py +++ b/seleniumbase/fixtures/base_case.py @@ -1706,6 +1706,22 @@ class BaseCase(unittest.TestCase): except Exception: pass + def choose_file(self, selector, file_path, by=By.CSS_SELECTOR, + timeout=settings.LARGE_TIMEOUT): + """ This method is used to choose a file to upload to a website. + It works by populating a file-chooser "input" field of type="file". + A relative file_path will get converted into an absolute file_path. + + Example usage: + self.choose_file('input[type="file"], "my_dir/my_file.txt") + """ + if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: + timeout = self.__get_new_timeout(timeout) + if page_utils.is_xpath_selector(selector): + by = By.XPATH + abs_path = os.path.abspath(file_path) + self.add_text(selector, abs_path, by=by, timeout=timeout) + def save_element_as_image_file(self, selector, file_name, folder=None): """ Take a screenshot of an element and save it as an image file. If no folder is specified, will save it to the current folder. """
Add the choose_file() method for uploading a file
seleniumbase_SeleniumBase
train
edcb529531029187b2a3a001fa2c631fd9693316
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -23,6 +23,11 @@ module.exports = function (fileName, globalOptions) { options = extend({}, globalOptions || {}); options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []); + // Resolve include paths to baseDir + if(options.baseDir) { + options.includePaths = options.includePaths.map(function (p) { return path.dirname(path.resolve(options.baseDir, p)); }); + } + options.data = inputString; options.includePaths.unshift(path.dirname(fileName));
Handle baseDir option to resolve include paths before rendering;
davidguttman_sassify
train
c59c5f9b923ab5b4c40bb9993774517a4126651a
diff --git a/pythran/tests/test_pep8.py b/pythran/tests/test_pep8.py index <HASH>..<HASH> 100644 --- a/pythran/tests/test_pep8.py +++ b/pythran/tests/test_pep8.py @@ -1,9 +1,10 @@ import unittest import pythran import pep8 -import inspect +import glob import os + class TestPEP8(unittest.TestCase): ''' Enable automatic pep8 compliance testing @@ -13,18 +14,25 @@ class TestPEP8(unittest.TestCase): pass -def generic_test_package(self, mod): - base, _ = os.path.splitext(mod.__file__) - mod_file = base + '.py' # takes care of .pyc or .pyo +def generic_test_package(self, mod_file): chk = pep8.Checker(mod_file) - chk.report._ignore_code = lambda s: s in ('E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127', 'E128', 'E129') + chk.report._ignore_code = lambda s: s in ('E121', 'E122', 'E123', 'E124', + 'E125', 'E126', 'E127', 'E128', + 'E129') failed = chk.check_all() self.assertEqual(failed, 0) -def add_module_pep8_test(module_name): - module = getattr(pythran, module_name) - if inspect.ismodule(module): - setattr(TestPEP8, 'test_' + module_name, - lambda self: generic_test_package(self, module)) +# Get Pythran install path from import +path = os.path.dirname(pythran.__file__) + +# Check all py +files = glob.glob(os.path.join(path, "*.py")) + +# Exclude autogenerated file +files.remove(os.path.join(path, "parsetab.py")) -map(add_module_pep8_test, dir(pythran)) +# Add the "magic" test method that fit unittest framework +for modfile in files: + module_name, _ = os.path.splitext(os.path.basename(modfile)) + setattr(TestPEP8, 'test_' + module_name, + lambda self: generic_test_package(self, modfile))
Fixup pep8 unittest. Use glob(*.py) on Pythran install dir Exclude parsetab.py because it is autogenerated
serge-sans-paille_pythran
train
24d5690130798dd590a236cc4b0b95064232bdbb
diff --git a/src/utilities/extendSchema.js b/src/utilities/extendSchema.js index <HASH>..<HASH> 100644 --- a/src/utilities/extendSchema.js +++ b/src/utilities/extendSchema.js @@ -705,16 +705,16 @@ export function extendSchemaImpl( } function concatMaybeArrays<X>( - ...arrays: $ReadOnlyArray<?$ReadOnlyArray<X>> + maybeArrayA: ?$ReadOnlyArray<X>, + maybeArrayB: ?$ReadOnlyArray<X>, ): ?$ReadOnlyArray<X> { - // eslint-disable-next-line no-undef-init - let result = undefined; - for (const maybeArray of arrays) { - if (maybeArray) { - result = result === undefined ? maybeArray : result.concat(maybeArray); - } + if (maybeArrayA == null) { + return maybeArrayB; + } + if (maybeArrayB == null) { + return maybeArrayA; } - return result; + return maybeArrayA.concat(maybeArrayB); } const stdTypeMap = keyMap(
Simplify 'concatMaybeArrays' (#<I>)
graphql_graphql-js
train
f4122dd7cfa47b19486c1481af1bccfe25383634
diff --git a/chacha/chachaAVX2_amd64.go b/chacha/chachaAVX2_amd64.go index <HASH>..<HASH> 100644 --- a/chacha/chachaAVX2_amd64.go +++ b/chacha/chachaAVX2_amd64.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a license that can be // found in the LICENSE file. -// +build amd64, go1.7, !gccgo, !appengine, !go1.6 +// +build ignore package chacha diff --git a/chacha/chachaAVX2_amd64.s b/chacha/chachaAVX2_amd64.s index <HASH>..<HASH> 100644 --- a/chacha/chachaAVX2_amd64.s +++ b/chacha/chachaAVX2_amd64.s @@ -2,7 +2,7 @@ // Use of this source code is governed by a license that can be // found in the LICENSE file. -// +build amd64, go1.7, !gccgo, !appengine, !go1.6 +// +build ignore #include "textflag.h" diff --git a/chacha/chachaSSE_amd64.go b/chacha/chachaSSE_amd64.go index <HASH>..<HASH> 100644 --- a/chacha/chachaSSE_amd64.go +++ b/chacha/chachaSSE_amd64.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a license that can be // found in the LICENSE file. -// +build amd64, go1.6, !gccgo, !appengine +// +build amd64, !gccgo, !appengine package chacha
Disable AVX2 again - Version dependend compilation needs investigation
aead_chacha20
train
af53f010875bfbefcd3d5a614817f702295b5b93
diff --git a/shutit_pexpect.py b/shutit_pexpect.py index <HASH>..<HASH> 100644 --- a/shutit_pexpect.py +++ b/shutit_pexpect.py @@ -1771,7 +1771,10 @@ class ShutItPexpectSession(object): lines = filter(lambda x: x.find('\x08') == -1, lines) before = '\n'.join(lines) # Remove the command we ran in from the output. - before = before.strip(send) + # First, strip whitespace from the start of 'before', and the send: + before = before.strip() + send = send.strip() + shutit_global.shutit_global_object.log('send_and_get_output "before": ' + before + ', send_and_get_output send was: ' + send, level=logging.DEBUG) if strip: # cf: http://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]') @@ -1781,26 +1784,31 @@ class ShutItPexpectSession(object): # Strip out \rs to make it output the same as a typical CL. This could be optional. string_without_termcodes_stripped_no_cr = string_without_termcodes.replace('\r','') if preserve_newline: - ret = string_without_termcodes_stripped_no_cr + '\n' + before = string_without_termcodes_stripped_no_cr + '\n' else: - ret = string_without_termcodes_stripped_no_cr + before = string_without_termcodes_stripped_no_cr else: - ret = before + before = before + if before.startswith(send): + before = before[len(send):] + # Strip whitespace again + before = before.strip() + shutit_global.shutit_global_object.log('send_and_get_output "before" after startswith check: ' + before, level=logging.DEBUG) # Too chatty, but kept here in case useful for debugging - #shutit_global.shutit_global_object.log('send_and_get_output got:\n' + ret, level=logging.DEBUG) + shutit_global.shutit_global_object.log('send_and_get_output got:\n' + before, level=logging.DEBUG) # Leave this debug in in case there are any strange characters to consider. - #shutit_global.shutit_global_object.log('send_and_get_output returning in base64:\n' + base64.b64encode(ret), level=logging.DEBUG) + shutit_global.shutit_global_object.log('send_and_get_output returning in base64:\n' + base64.b64encode(before), level=logging.DEBUG) ## In rare cases a bell has been seen - can't see why we'd want a bell so simply remove them all. - #ret = ret.replace('\x07','') + before = before.replace('\x07','') # If there happens to be an escape character in there, it's likely a # problem - see IWT-4812. - ret = ret.split('\x1b')[0].strip() + before = before.split('\x1b')[0].strip() if PY3: - shutit_global.shutit_global_object.log('send_and_get_output returning in base64: ' + str(base64.b64encode(bytes(ret,'utf-8'))), level=logging.DEBUG) + shutit_global.shutit_global_object.log('send_and_get_output returning in base64: ' + str(base64.b64encode(bytes(before,'utf-8'))), level=logging.DEBUG) else: - shutit_global.shutit_global_object.log('send_and_get_output returning in base64: ' + base64.b64encode(bytes(ret)), level=logging.DEBUG) + shutit_global.shutit_global_object.log('send_and_get_output returning in base64: ' + base64.b64encode(bytes(before)), level=logging.DEBUG) shutit.handle_note_after(note=note) - return ret + return before def get_env_pass(self,user=None,msg=None,note=None):
Tidied up long-standing issue with stripping send_and_get_ooutput
ianmiell_shutit
train
fa5ca179baf54561b7a999bda5c037b07fd0556d
diff --git a/cas-server-webapp-config/src/main/java/org/apereo/cas/config/CasWebflowContextConfiguration.java b/cas-server-webapp-config/src/main/java/org/apereo/cas/config/CasWebflowContextConfiguration.java index <HASH>..<HASH> 100644 --- a/cas-server-webapp-config/src/main/java/org/apereo/cas/config/CasWebflowContextConfiguration.java +++ b/cas-server-webapp-config/src/main/java/org/apereo/cas/config/CasWebflowContextConfiguration.java @@ -5,6 +5,8 @@ import com.google.common.collect.ImmutableList; import org.apereo.cas.CipherExecutor; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.web.flow.CasDefaultFlowUrlHandler; +import org.apereo.cas.web.flow.CasWebflowConfigurer; +import org.apereo.cas.web.flow.DefaultWebflowConfigurer; import org.apereo.cas.web.flow.LogoutConversionService; import org.apereo.cas.web.flow.SelectiveFlowHandlerAdapter; import org.apereo.spring.webflow.plugin.ClientFlowExecutionRepository; @@ -14,6 +16,7 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.binding.convert.ConversionService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.ApplicationContext; @@ -86,7 +89,7 @@ public class CasWebflowContextConfiguration { final WebFlowSpringELExpressionParser parser = new WebFlowSpringELExpressionParser( new SpelExpressionParser(), logoutConversionService()); - + return parser; } @@ -158,7 +161,6 @@ public class CasWebflowContextConfiguration { @RefreshScope @Bean public CipherBean loginFlowCipherBean() { - try { return new CipherBean() { @Override @@ -196,7 +198,6 @@ public class CasWebflowContextConfiguration { @RefreshScope @Bean public FlowBuilderServices builder() { - final FlowBuilderServicesBuilder builder = new FlowBuilderServicesBuilder(this.applicationContext); builder.setViewFactoryCreator(viewFactoryCreator()); builder.setExpressionParser(expressionParser()); @@ -291,7 +292,6 @@ public class CasWebflowContextConfiguration { * * @return the flow definition registry */ - @RefreshScope @Bean public FlowDefinitionRegistry logoutFlowRegistry() { final FlowDefinitionRegistryBuilder builder = new FlowDefinitionRegistryBuilder(this.applicationContext, builder()); @@ -305,10 +305,10 @@ public class CasWebflowContextConfiguration { * * @return the flow definition registry */ - @RefreshScope @Bean public FlowDefinitionRegistry loginFlowRegistry() { - final FlowDefinitionRegistryBuilder builder = new FlowDefinitionRegistryBuilder(this.applicationContext, builder()); + final FlowDefinitionRegistryBuilder builder = + new FlowDefinitionRegistryBuilder(this.applicationContext, builder()); builder.setBasePath(BASE_CLASSPATH_WEBFLOW); builder.addFlowLocationPattern("/login/*-webflow.xml"); return builder.build(); @@ -321,20 +321,20 @@ public class CasWebflowContextConfiguration { */ @RefreshScope @Bean - public FlowExecutorImpl loginFlowExecutor() { + public FlowExecutor loginFlowExecutor() { final FlowDefinitionRegistry loginFlowRegistry = loginFlowRegistry(); - + if (casProperties.getWebflow().getSession().isStorage()) { final SessionBindingConversationManager conversationManager = new SessionBindingConversationManager(); conversationManager.setLockTimeoutSeconds(casProperties.getWebflow().getSession().getLockTimeout()); conversationManager.setMaxConversations(casProperties.getWebflow().getSession().getMaxConversations()); - + final FlowExecutionImplFactory executionFactory = new FlowExecutionImplFactory(); - + final SerializedFlowExecutionSnapshotFactory flowExecutionSnapshotFactory = new SerializedFlowExecutionSnapshotFactory(executionFactory, loginFlowRegistry()); flowExecutionSnapshotFactory.setCompress(casProperties.getWebflow().getSession().isCompress()); - + final DefaultFlowExecutionRepository repository = new DefaultFlowExecutionRepository(conversationManager, flowExecutionSnapshotFactory); executionFactory.setExecutionKeyFactory(repository); @@ -350,5 +350,15 @@ public class CasWebflowContextConfiguration { repository.setFlowExecutionFactory(factory); return new FlowExecutorImpl(loginFlowRegistry, factory, repository); } + + @ConditionalOnMissingBean(name = "defaultWebflowConfigurer") + @Bean + public CasWebflowConfigurer defaultWebflowConfigurer() { + final DefaultWebflowConfigurer c = new DefaultWebflowConfigurer(); + c.setLoginFlowDefinitionRegistry(loginFlowRegistry()); + c.setLogoutFlowDefinitionRegistry(logoutFlowRegistry()); + c.setFlowBuilderServices(builder()); + return c; + } }
Refactored web flow APIs
apereo_cas
train
f52cd3d70927270e04ce9d199900a88af6f7ed8a
diff --git a/src/adapt/epub.js b/src/adapt/epub.js index <HASH>..<HASH> 100644 --- a/src/adapt/epub.js +++ b/src/adapt/epub.js @@ -1943,12 +1943,9 @@ adapt.epub.OPFView.prototype.getPageViewItem = function(spineIndex) { const style = store.getStyleForDoc(xmldoc); const customRenderer = self.makeCustomRenderer(xmldoc); let viewport = self.viewport; - const viewportSize = style.sizeViewport(viewport.width, viewport.height, viewport.fontSize); + const viewportSize = style.sizeViewport(viewport.width, viewport.height, viewport.fontSize, self.pref); if (viewportSize.width != viewport.width || viewportSize.height != viewport.height || viewportSize.fontSize != viewport.fontSize) { - if (self.pref.spreadView) { - viewportSize.width *= 2; - } viewport = new adapt.vgen.Viewport(viewport.window, viewportSize.fontSize, viewport.root, viewportSize.width, viewportSize.height); } diff --git a/src/adapt/ops.js b/src/adapt/ops.js index <HASH>..<HASH> 100644 --- a/src/adapt/ops.js +++ b/src/adapt/ops.js @@ -118,9 +118,10 @@ adapt.ops.Style = function(store, rootScope, pageScope, cascade, rootBox, * @param {number} viewportWidth * @param {number} viewportHeight * @param {number} fontSize + * @param {adapt.expr.Preferences=} pref * @return {{width:number, height:number, fontSize:number}} */ -adapt.ops.Style.prototype.sizeViewport = function(viewportWidth, viewportHeight, fontSize) { +adapt.ops.Style.prototype.sizeViewport = function(viewportWidth, viewportHeight, fontSize, pref) { if (this.viewportProps.length) { const context = new adapt.expr.Context(this.rootScope, viewportWidth, viewportHeight, fontSize); @@ -142,7 +143,8 @@ adapt.ops.Style.prototype.sizeViewport = function(viewportWidth, viewportHeight, const widthVal = adapt.css.toNumber(width.evaluate(context, "width"), context); const heightVal = adapt.css.toNumber(height.evaluate(context, "height"), context); if (widthVal > 0 && heightVal > 0) { - return {width:widthVal, height:heightVal, fontSize}; + const spreadWidth = pref && pref.spreadView ? (widthVal + pref.pageBorder) * 2 : widthVal; + return {width:spreadWidth, height:heightVal, fontSize}; } } }
Fix again #<I> considering spread page border and special case where specified viewport size equals to natural viewport size
vivliostyle_vivliostyle.js
train
6b70374b1f0b0762d89bc9973ef58e81d945c47b
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -5,13 +5,22 @@ var evalRule = require('./evalRule'); var queryRulesetFn = require('./queryRulesetFn'); var selectRulesToEval = require('./selectRulesToEval'); -var rulesets = { - 'rid1x0': require('./rulesets/hello_world'), - 'rid2x0': require('./rulesets/store_name'), - 'rid3x0': require('./rulesets/raw'), - 'rid4x0': require('./rulesets/event_ops') +var rulesets = {}; +var installRuleset = function(rid, path){ + var rs = require('./rulesets/' + path); + rs.rid = rid; + _.each(rs.rules, function(rule, rule_name){ + rule.rid = rid; + rule.rule_name = rule_name; + }); + rulesets[rid] = rs; }; +installRuleset('rid1x0', 'hello_world'); +installRuleset('rid2x0', 'store_name'); +installRuleset('rid3x0', 'raw'); +installRuleset('rid4x0', 'event_ops'); + module.exports = function(conf){ var db = DB(conf.db); @@ -25,7 +34,7 @@ module.exports = function(conf){ selectRulesToEval(pico, rulesets, event, function(err, to_eval){ if(err) return callback(err); - λ.map(to_eval, function(e, callback){ + λ.map(to_eval, function(rule, callback){ var ctx = { pico: pico, @@ -33,14 +42,14 @@ module.exports = function(conf){ vars: {}, event: event, meta: { - rule_name: e.rule_name, + rule_name: rule.rule_name, txn_id: 'TODO',//TODO transactions - rid: e.rid, + rid: rule.rid, eid: event.eid } }; - evalRule(e.rule, ctx, callback); + evalRule(rule, ctx, callback); }, function(err, responses){ if(err) return callback(err); diff --git a/src/selectRulesToEval.js b/src/selectRulesToEval.js index <HASH>..<HASH> 100644 --- a/src/selectRulesToEval.js +++ b/src/selectRulesToEval.js @@ -4,23 +4,17 @@ var λ = require('contra'); module.exports = function(pico, rulesets, event, callback){ //TODO optimize using the salience graph - var all_rules = []; - _.each(rulesets, function(rs, rid){ - if(!_.has(pico && pico.ruleset, rid)){ - return; - } - _.each(rs.rules, function(rule, rule_name){ - all_rules.push({ - rid: rid, - rule_name: rule_name, - rule: rule - }); - }); - }); + var all_rules = _.flatten(_.map(rulesets, function(rs){ + return _.values(rs.rules); + })); var ctx = {event: event}; - λ.filter(all_rules, function(r, next){ - r.rule.select(ctx, next); + λ.filter(all_rules, function(rule, next){ + if(!_.has(pico && pico.ruleset, rule.rid)){ + next(undefined, false); + return; + } + rule.select(ctx, next); }, callback); };
adjusting how rulesets are managed
Picolab_pico-engine
train
5e1ed2533ff73da33b366d4da71595542271abfe
diff --git a/.happo.js b/.happo.js index <HASH>..<HASH> 100644 --- a/.happo.js +++ b/.happo.js @@ -16,9 +16,6 @@ module.exports = { targets: { 'chrome': new RemoteBrowserTarget('chrome', { viewport: '800x600' - }), - 'internet explorer': new RemoteBrowserTarget('internet explorer', { - viewport: '800x600' }) },
test(happo): Remove IE from visual regression tests * Testing in IE increases test duration and currently provides little value.
mineral-ui_mineral-ui
train
81dc1dc844047f93c161a0cbb6bb4e426b67cfb5
diff --git a/ethtool.go b/ethtool.go index <HASH>..<HASH> 100644 --- a/ethtool.go +++ b/ethtool.go @@ -59,7 +59,7 @@ const ( // MAX_GSTRINGS maximum number of stats entries that ethtool can // retrieve currently. const ( - MAX_GSTRINGS = 200 + MAX_GSTRINGS = 1000 ) type ifreq struct {
Increase max_gstrings Bumping the value to <I> to resolve this error with some room. "map[] ethtool currently doesn't support more than <I> entries, received <I>"
safchain_ethtool
train
e43e548a3472671eef89f44a28634ba01732042d
diff --git a/infoschema/tables.go b/infoschema/tables.go index <HASH>..<HASH> 100644 --- a/infoschema/tables.go +++ b/infoschema/tables.go @@ -797,6 +797,28 @@ func dataForColumnsInTable(schema *model.DBInfo, tbl *model.TableInfo) [][]types if colLen == types.UnspecifiedLength { colLen = defaultFlen } + if col.Tp == mysql.TypeSet { + // Example: In MySQL set('a','bc','def','ghij') has length 13, because + // len('a')+len('bc')+len('def')+len('ghij')+len(ThreeComma)=13 + // Reference link: https://bugs.mysql.com/bug.php?id=22613 + colLen = 0 + for _, ele := range col.Elems { + colLen += len(ele) + } + if len(col.Elems) != 0 { + colLen += (len(col.Elems) - 1) + } + } else if col.Tp == mysql.TypeEnum { + // Example: In MySQL enum('a', 'ab', 'cdef') has length 4, because + // the longest string in the enum is 'cdef' + // Reference link: https://bugs.mysql.com/bug.php?id=22613 + colLen = 0 + for _, ele := range col.Elems { + if len(ele) > colLen { + colLen = len(ele) + } + } + } if decimal == types.UnspecifiedLength { decimal = defaultDecimal } diff --git a/infoschema/tables_test.go b/infoschema/tables_test.go index <HASH>..<HASH> 100644 --- a/infoschema/tables_test.go +++ b/infoschema/tables_test.go @@ -77,6 +77,16 @@ func (s *testSuite) TestDataForTableRowsCountField(c *C) { tk.MustExec("create user xxx") tk.MustExec("flush privileges") + // Test for length of enum and set + tk.MustExec("drop table if exists t") + tk.MustExec("create table t ( s set('a','bc','def','ghij') default NULL, e1 enum('a', 'ab', 'cdef'), s2 SET('1','2','3','4','1585','ONE','TWO','Y','N','THREE'))") + tk.MustQuery("select column_name, character_maximum_length from information_schema.columns where table_schema=Database() and table_name = 't' and column_name = 's'").Check( + testkit.Rows("s 13")) + tk.MustQuery("select column_name, character_maximum_length from information_schema.columns where table_schema=Database() and table_name = 't' and column_name = 's2'").Check( + testkit.Rows("s2 30")) + tk.MustQuery("select column_name, character_maximum_length from information_schema.columns where table_schema=Database() and table_name = 't' and column_name = 'e1'").Check( + testkit.Rows("e1 4")) + tk1 := testkit.NewTestKit(c, store) tk1.MustExec("use test") c.Assert(tk1.Se.Auth(&auth.UserIdentity{
infoschema: fix bug of column size of set and enum type (#<I>)
pingcap_tidb
train
5b236c948964f8a9917c5d08197272a33917bf18
diff --git a/src/Sylius/Bundle/CoreBundle/DataFixtures/ORM/LoadOrdersData.php b/src/Sylius/Bundle/CoreBundle/DataFixtures/ORM/LoadOrdersData.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/CoreBundle/DataFixtures/ORM/LoadOrdersData.php +++ b/src/Sylius/Bundle/CoreBundle/DataFixtures/ORM/LoadOrdersData.php @@ -71,15 +71,7 @@ class LoadOrdersData extends DataFixture } while ('UK' === $isoName); $country = $this->getReference('Sylius.Country.'.$isoName); - $province = null; - - if ($country->hasProvinces()) { - $provinceKey = $this->faker->randomNumber( - 0, - $country->getProvinces()->count() - ); - $province = $country->getProvinces()->get($provinceKey); - }; + $province = $country->hasProvinces() ? $this->faker->randomElement($country->getProvinces()->toArray()) : null; $address->setCountry($country); $address->setProvince($province);
Fix: Sometimes you have not to find the hardest solution...
Sylius_Sylius
train
9e008355ae6a815ac9ab8b0f63a8d4686de57f2c
diff --git a/EventListener/UploadDoctrineListener.php b/EventListener/UploadDoctrineListener.php index <HASH>..<HASH> 100644 --- a/EventListener/UploadDoctrineListener.php +++ b/EventListener/UploadDoctrineListener.php @@ -37,7 +37,7 @@ class UploadDoctrineListener implements EventSubscriber ]; } - public function onPrePersist(LifecycleEventArgs $args): void + public function prePersist(LifecycleEventArgs $args): void { $entity = $args->getEntity();
[UploadBundle] Fixed the prePersist method name.
ruvents_ruwork-upload-bundle
train
544e19aa80bfd7ea145b4d1ca22121ccaf1cb740
diff --git a/lang/ja/README b/lang/ja/README index <HASH>..<HASH> 100644 --- a/lang/ja/README +++ b/lang/ja/README @@ -1,7 +1,7 @@ MOODLE JAPANESE TRANSLATION ---------------------------------------------------------------------- STARTED : November 21, 2002 -LAST MODIFIED : July 26, 2005 +LAST MODIFIED : July 27, 2005 Thanks to everyone who have supported our translation project! diff --git a/lang/ja/admin.php b/lang/ja/admin.php index <HASH>..<HASH> 100644 --- a/lang/ja/admin.php +++ b/lang/ja/admin.php @@ -1,9 +1,12 @@ <?PHP // $Id$ - // admin.php - created with Moodle 1.6 development (2005060201) + // admin.php - created with Moodle 1.6 development (2005072200) $string['adminseesallevents'] = '�����Ԥ����ƤΥ��٥�Ȥ�ɽ��'; $string['adminseesownevents'] = '�����Ԥ�¾�Υ桼����Ʊ��'; +$string['backgroundcolour'] = '�طʿ�'; +$string['badwordsconfig'] = '����ޤǶ��ڤ�줿���Ѷػ��Ѹ�����Ϥ��Ƥ���������'; +$string['badwordslist'] = '���Ѷػ��Ѹ����'; $string['blockinstances'] = '���󥹥���'; $string['blockmultiple'] = 'ʣ��'; $string['cachetext'] = '�ƥ����ȥ���å�����¸����'; @@ -90,7 +93,8 @@ $string['configvariables'] = ' $string['configwarning'] = '�ְ�ä�����ϥȥ�֥�θ����ˤʤ�ޤ��Τǡ�������������ѹ�����������դ��Ƥ���������'; $string['configzip'] = 'ZIP�ץ������ξ�����ꤷ�Ƥ������� ( UNIX�Τߡ�Ǥ�� )�������ZIP��ˤ򥵡�����Ǻ������뤿���ɬ�פǤ�������ˤ�����硢Moodle�������롼�������Ѥ��ޤ�'; $string['confirmation'] = '��ǧ'; -$string['cronwarning'] = '<a href=\"cron.php\">cron.php���ƥʥ󥹥�����ץ�</a>�����ʤ��Ȥ�24���ֲ�ư���Ƥ��ޤ���<br />cron.php�μ�ư���˴ؤ���<a href=\"../doc/?frame=install.html&sub=cron\">���󥹥ȡ���ɥ������</a>��������������'; +$string['cronwarning'] = '<a href=\"cron.php\">cron.php���ƥʥ󥹥�����ץ�</a>�����ʤ��Ȥ�24���ֲ�ư���Ƥ��ޤ���<br />cron.php�μ�ư���˴ؤ���<a href=\"../doc/?frame=install.html��=cron\">���󥹥ȡ���ɥ������</a>��������������'; +$string['density'] = '̩��'; $string['edithelpdocs'] = '�إ��ʸ����Խ�'; $string['editstrings'] = '�������ȥ�󥰤��Խ�'; $string['filterall'] = '���Ƥ�ʸ����ե��륿����'; @@ -107,6 +111,8 @@ $string['importtimezones'] = ' $string['importtimezonescount'] = '$a->source ��� $a->count �Υ���ȥ꤬����ݡ��Ȥ���ޤ�����'; $string['importtimezonesfailed'] = '�����������Ĥ���ޤ���Ǥ���!'; $string['incompatibleblocks'] = '�ߴ������ʤ��֥��å�'; +$string['latexpreamble'] = 'LaTeX�ץꥢ��֥�'; +$string['latexsettings'] = 'LaTeX��������'; $string['optionalmaintenancemessage'] = '���ץ���󡦥��ƥʥ󥹥�å�����'; $string['pleaseregister'] = '���Υܥ����ä��ˤϡ����ʤ��Υ����Ȥ���Ͽ���Ƥ���������'; $string['sitemaintenance'] = '���Υ����Ȥϥ��ƥʥ���Ǥ������ߤ����Ѥ��������ޤ���'; diff --git a/lang/ja_utf8/admin.php b/lang/ja_utf8/admin.php index <HASH>..<HASH> 100644 --- a/lang/ja_utf8/admin.php +++ b/lang/ja_utf8/admin.php @@ -1,9 +1,12 @@ <?PHP // $Id$ - // admin.php - created with Moodle 1.6 development (2005060201) + // admin.php - created with Moodle 1.6 development (2005072200) $string['adminseesallevents'] = '管理者に全てのイベントを表示'; $string['adminseesownevents'] = '管理者は他のユーザと同じ'; +$string['backgroundcolour'] = '背景色'; +$string['badwordsconfig'] = 'コンマで区切られた使用禁止用語を入力してください。'; +$string['badwordslist'] = '使用禁止用語一覧'; $string['blockinstances'] = 'インスタンス'; $string['blockmultiple'] = '複数'; $string['cachetext'] = 'テキストキャッシュ保存時間'; @@ -90,7 +93,8 @@ $string['configvariables'] = '詳細設定'; $string['configwarning'] = '間違った設定はトラブルの原因になりますので、これらの設定を変更する場合は注意してください。'; $string['configzip'] = 'ZIPプログラムの場所を指定してください ( UNIXのみ、任意 )。これはZIP書庫をサーバ内で作成するために必要です。空白にした場合、Moodleは内部ルーチンを使用します'; $string['confirmation'] = '確認'; -$string['cronwarning'] = '<a href=\"cron.php\">cron.phpメンテナンススクリプト</a>が少なくとも24時間稼動していません。<br />cron.phpの自動化に関して<a href=\"../doc/?frame=install.html&sub=cron\">インストールドキュメント</a>をご覧ください。'; +$string['cronwarning'] = '<a href=\"cron.php\">cron.phpメンテナンススクリプト</a>が少なくとも24時間稼動していません。<br />cron.phpの自動化に関して<a href=\"../doc/?frame=install.html⊂=cron\">インストールドキュメント</a>をご覧ください。'; +$string['density'] = '密度'; $string['edithelpdocs'] = 'ヘルプ文書の編集'; $string['editstrings'] = '翻訳ストリングの編集'; $string['filterall'] = '全ての文字をフィルタする'; @@ -107,6 +111,8 @@ $string['importtimezones'] = 'タイムゾーンリストの更新'; $string['importtimezonescount'] = '$a->source より $a->count のエントリがインポートされました。'; $string['importtimezonesfailed'] = 'ソースが見つかりませんでした!'; $string['incompatibleblocks'] = '互換性がないブロック'; +$string['latexpreamble'] = 'LaTeXプリアンブル'; +$string['latexsettings'] = 'LaTeXレンダ設定'; $string['optionalmaintenancemessage'] = 'オプション・メンテナンスメッセージ'; $string['pleaseregister'] = 'このボタンを消すには、あなたのサイトを登録してください。'; $string['sitemaintenance'] = 'このサイトはメンテナンス中です。現在ご利用いただけません。';
translated some new strings for admin.php.
moodle_moodle
train
1d15602dad1909a2cc6346870cd329869d8ccc2d
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/TransactionApplicationData.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/TransactionApplicationData.java index <HASH>..<HASH> 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/TransactionApplicationData.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/TransactionApplicationData.java @@ -16,6 +16,7 @@ */ package org.mobicents.servlet.sip.message; +import java.io.Serializable; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; @@ -30,7 +31,10 @@ import org.mobicents.servlet.sip.proxy.ProxyBranchImpl; * *@author mranga */ -public class TransactionApplicationData { +public class TransactionApplicationData implements Serializable { + + private static final long serialVersionUID = 1L; + private transient ProxyBranchImpl proxyBranch; private transient SipServletMessageImpl sipServletMessage; private transient Set<SipServletResponseImpl> sipServletResponses;
making it Serializable again, was removed during the findbugs bug fixing git-svn-id: <URL>
RestComm_sip-servlets
train
ad617184194ae2bb5a020e8f4a9facdd1f97c3a3
diff --git a/time_wizard/mixins.py b/time_wizard/mixins.py index <HASH>..<HASH> 100644 --- a/time_wizard/mixins.py +++ b/time_wizard/mixins.py @@ -41,4 +41,7 @@ class TimeWizardMixin(models.Model): @property def is_published(self): - return self.time_wizard.is_published + if self.time_wizard_id: + return self.time_wizard.is_published + else: + return False
Fix server error when no referenced time_wizard-instance is given
wfehr_django-time-wizard
train
60ec4aef7b7b15f847425bab8fa5d3cf0511ff5e
diff --git a/lib/rspec-puppet.rb b/lib/rspec-puppet.rb index <HASH>..<HASH> 100644 --- a/lib/rspec-puppet.rb +++ b/lib/rspec-puppet.rb @@ -1,9 +1,15 @@ require 'puppet' require 'rspec' +require 'fileutils' +require 'tmpdir' require 'rspec-puppet/matchers' require 'rspec-puppet/example' require 'rspec-puppet/setup' +if Integer(Puppet.version.split('.').first) >= 3 + Puppet.initialize_settings +end + RSpec.configure do |c| c.add_setting :module_path, :default => '/etc/puppet/modules' c.add_setting :manifest_dir, :default => nil diff --git a/lib/rspec-puppet/example/class_example_group.rb b/lib/rspec-puppet/example/class_example_group.rb index <HASH>..<HASH> 100644 --- a/lib/rspec-puppet/example/class_example_group.rb +++ b/lib/rspec-puppet/example/class_example_group.rb @@ -8,6 +8,9 @@ module RSpec::Puppet end def catalogue + vardir = Dir.mktmpdir + Puppet[:vardir] = vardir + Puppet[:hiera_config] = File.join(vardir, "hiera.yaml") if Puppet[:hiera_config] == "/dev/null" Puppet[:modulepath] = self.respond_to?(:module_path) ? module_path : RSpec.configuration.module_path Puppet[:manifestdir] = self.respond_to?(:manifest_dir) ? manifest_dir : RSpec.configuration.manifest_dir Puppet[:manifest] = self.respond_to?(:manifest) ? manifest : RSpec.configuration.manifest @@ -49,7 +52,9 @@ module RSpec::Puppet } facts_val.merge!(munge_facts(facts)) if self.respond_to?(:facts) - build_catalog(nodename, facts_val, code) + catalogue = build_catalog(nodename, facts_val, code) + FileUtils.rm_rf(vardir) if File.directory?(vardir) + catalogue end end end diff --git a/lib/rspec-puppet/example/define_example_group.rb b/lib/rspec-puppet/example/define_example_group.rb index <HASH>..<HASH> 100644 --- a/lib/rspec-puppet/example/define_example_group.rb +++ b/lib/rspec-puppet/example/define_example_group.rb @@ -10,6 +10,8 @@ module RSpec::Puppet def catalogue define_name = self.class.top_level_description.downcase + vardir = Dir.mktmpdir + Puppet[:vardir] = vardir Puppet[:modulepath] = self.respond_to?(:module_path) ? module_path : RSpec.configuration.module_path Puppet[:manifestdir] = self.respond_to?(:manifest_dir) ? manifest_dir : RSpec.configuration.manifest_dir Puppet[:manifest] = self.respond_to?(:manifest) ? manifest : RSpec.configuration.manifest @@ -51,7 +53,9 @@ module RSpec::Puppet } facts_val.merge!(munge_facts(facts)) if self.respond_to?(:facts) - build_catalog(nodename, facts_val, code) + catalogue = build_catalog(nodename, facts_val, code) + FileUtils.rm_rf(vardir) if File.directory?(vardir) + catalogue end end end diff --git a/lib/rspec-puppet/example/host_example_group.rb b/lib/rspec-puppet/example/host_example_group.rb index <HASH>..<HASH> 100644 --- a/lib/rspec-puppet/example/host_example_group.rb +++ b/lib/rspec-puppet/example/host_example_group.rb @@ -8,6 +8,8 @@ module RSpec::Puppet end def catalogue + vardir = Dir.mktmpdir + Puppet[:vardir] = vardir Puppet[:modulepath] = self.respond_to?(:module_path) ? module_path : RSpec.configuration.module_path Puppet[:manifestdir] = self.respond_to?(:manifest_dir) ? manifest_dir : RSpec.configuration.manifest_dir Puppet[:manifest] = self.respond_to?(:manifest) ? manifest : RSpec.configuration.manifest @@ -24,7 +26,9 @@ module RSpec::Puppet } facts_val.merge!(munge_facts(facts)) if self.respond_to?(:facts) - build_catalog(nodename, facts_val, code) + catalogue = build_catalog(nodename, facts_val, code) + FileUtils.rm_rf(vardir) if File.directory?(vardir) + catalogue end end end diff --git a/spec/functions/split_spec.rb b/spec/functions/split_spec.rb index <HASH>..<HASH> 100644 --- a/spec/functions/split_spec.rb +++ b/spec/functions/split_spec.rb @@ -6,6 +6,6 @@ describe 'split' do it { should_not run.with_params('foo').and_raise_error(Puppet::DevError) } it 'something' do - expect { subject.call('foo') }.to raise_error(Puppet::ParseError) + expect { subject.call('foo') }.to raise_error(ArgumentError) end end
Preliminary Puppet <I> support
rodjek_rspec-puppet
train
c4b81a1b8319375445ce62edff1f0e43e3a976ed
diff --git a/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/InstanceName.java b/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/InstanceName.java index <HASH>..<HASH> 100644 --- a/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/InstanceName.java +++ b/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/InstanceName.java @@ -211,9 +211,9 @@ public class InstanceName implements ResourceName { } private Builder(InstanceName instanceName) { - project = instanceName.project; - location = instanceName.location; - instance = instanceName.instance; + this.project = instanceName.project; + this.location = instanceName.location; + this.instance = instanceName.instance; } public InstanceName build() { diff --git a/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/LocationName.java b/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/LocationName.java index <HASH>..<HASH> 100644 --- a/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/LocationName.java +++ b/java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/LocationName.java @@ -181,8 +181,8 @@ public class LocationName implements ResourceName { } private Builder(LocationName locationName) { - project = locationName.project; - location = locationName.location; + this.project = locationName.project; + this.location = locationName.location; } public LocationName build() { diff --git a/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/InstanceName.java b/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/InstanceName.java index <HASH>..<HASH> 100644 --- a/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/InstanceName.java +++ b/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/InstanceName.java @@ -211,9 +211,9 @@ public class InstanceName implements ResourceName { } private Builder(InstanceName instanceName) { - project = instanceName.project; - location = instanceName.location; - instance = instanceName.instance; + this.project = instanceName.project; + this.location = instanceName.location; + this.instance = instanceName.instance; } public InstanceName build() { diff --git a/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/LocationName.java b/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/LocationName.java index <HASH>..<HASH> 100644 --- a/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/LocationName.java +++ b/java-memcache/proto-google-cloud-memcache-v1beta2/src/main/java/com/google/cloud/memcache/v1beta2/LocationName.java @@ -181,8 +181,8 @@ public class LocationName implements ResourceName { } private Builder(LocationName locationName) { - project = locationName.project; - location = locationName.location; + this.project = locationName.project; + this.location = locationName.location; } public LocationName build() { diff --git a/java-memcache/synth.metadata b/java-memcache/synth.metadata index <HASH>..<HASH> 100644 --- a/java-memcache/synth.metadata +++ b/java-memcache/synth.metadata @@ -4,23 +4,23 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-memcache.git", - "sha": "8b82a782fec0b91a0826a103e396175edced1327" + "sha": "f423fabe90a87fe5cc38e0753150ac26d1973026" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "08c4eeb531c01ad031134dca94b18e3f7dd35902", - "internalRef": "378718217" + "sha": "551681f25e36b11829e87e580281350461f4f3f5", + "internalRef": "379784268" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "08c4eeb531c01ad031134dca94b18e3f7dd35902", - "internalRef": "378718217" + "sha": "551681f25e36b11829e87e580281350461f4f3f5", + "internalRef": "379784268" } }, {
chore: release gapic-generator-java <I> (#<I>) This PR was generated using Autosynth. :rainbow: Synth log will be available here: <URL> PiperOrigin-RevId: <I> Source-Link: <URL>
googleapis_google-cloud-java
train
254528dfa4b00b33ed63f36085844ea13702a3e7
diff --git a/src/main/java/com/threerings/gwt/ui/Bindings.java b/src/main/java/com/threerings/gwt/ui/Bindings.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/threerings/gwt/ui/Bindings.java +++ b/src/main/java/com/threerings/gwt/ui/Bindings.java @@ -24,6 +24,7 @@ package com.threerings.gwt.ui; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FocusWidget; +import com.google.gwt.user.client.ui.ToggleButton; import com.google.gwt.user.client.ui.Widget; import com.threerings.gwt.util.Value; @@ -68,6 +69,25 @@ public class Bindings } /** + * Binds the specified toggle button to the supplied boolean value. The binding will work both + * ways: interactive changes to the toggle button will update the value and changes to the + * value will update the state of the toggle button. + */ + public static void bindDown (final ToggleButton toggle, final Value<Boolean> value) + { + toggle.addClickHandler(new ClickHandler() { + public void onClick (ClickEvent event) { + value.update(toggle.isDown()); + } + }); + value.addListenerAndTrigger(new Value.Listener<Boolean>() { + public void valueChanged (Boolean value) { + toggle.setDown(value); + } + }); + } + + /** * Returns a click handler that toggles the supplied boolean value when clicked. */ public static ClickHandler makeToggler (final Value<Boolean> value)
Utility for binding the down state of a toggle button to a value.
threerings_gwt-utils
train
f7c02c1eb2e39fe1179fc970a5b5d2a39d0608e3
diff --git a/marv/_aggregate.py b/marv/_aggregate.py index <HASH>..<HASH> 100644 --- a/marv/_aggregate.py +++ b/marv/_aggregate.py @@ -61,7 +61,7 @@ def object_pairs_hook(pairs): key = pairs[0][0] value = pairs[0][1] if key == '$datetime': - return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f') + return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f' if '.' in value else '%Y-%m-%dT%H:%M:%S') elif key == '$timedelta': return timedelta(0, value) return Mapping(pairs) @@ -80,7 +80,7 @@ def object_pairs_hook2(pairs): key = pairs[0][0] value = pairs[0][1] if key == '$datetime': - return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f') + return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f' if '.' in value else '%Y-%m-%dT%H:%M:%S') elif key == '$timedelta': return timedelta(0, value) return dict(pairs)
workaround for timestamps without fraction
ternaris_marv
train
429b4df886930775b2ed8c100225b24579a7a4c7
diff --git a/src/Formatters/LogstashFormatter.php b/src/Formatters/LogstashFormatter.php index <HASH>..<HASH> 100644 --- a/src/Formatters/LogstashFormatter.php +++ b/src/Formatters/LogstashFormatter.php @@ -8,12 +8,17 @@ class LogstashFormatter extends NormalizerFormatter * @var string */ private $applicationName; + /** + * @var string|null + */ + private $environment; - public function __construct($applicationName) + public function __construct($applicationName, $environment = null) { parent::__construct('Y-m-d\TH:i:s.uP'); $this->applicationName = $applicationName; + $this->environment = $environment; } public function format(array $record) @@ -23,7 +28,7 @@ class LogstashFormatter extends NormalizerFormatter $log['timestamp'] = $record['datetime']; $log['message'] = $record['message']; $log['app_name'] = $this->applicationName; - $log['environment'] = $record['channel']; + $log['environment'] = $this->environment ?: $record['channel']; $log['host_container_id'] = gethostname(); $log['level'] = [ 'code' => $record['level'],
Add configurable environment for LogstashFormatter
ordercloud_ordercloud-php-monolog
train
55f659b8a4d99c4b74899b3b156a0d7c9a801523
diff --git a/streamparser.py b/streamparser.py index <HASH>..<HASH> 100644 --- a/streamparser.py +++ b/streamparser.py @@ -21,8 +21,8 @@ Knownness.__doc__ = """Level of knowledge associated with a lexical unit. """ -Reading = namedtuple('Reading', ['baseform', 'tags']) -Reading.__doc__ = """A single subreading of an analysis of a token. +SReading = namedtuple('SReading', ['baseform', 'tags']) +SReading.__doc__ = """A single subreading of an analysis of a token. Fields: baseform (str): The base form (lemma, lexical form, citation form) of the reading. tags (list of str): The morphological tags associated with the reading. @@ -49,7 +49,7 @@ class LexicalUnit: Attributes: lexicalUnit (str): The lexical unit in Apertium stream format. wordform (str): The word form (surface form) of the lexical unit. - readings (list of list of Reading): The analyses of the lexical unit with sublists containing all subreadings. + readings (list of list of SReading): The analyses of the lexical unit with sublists containing all subreadings. knownness (Knownness): The level of knowledge of the lexical unit. """ @@ -72,7 +72,7 @@ class LexicalUnit: baseform = subreading[0].lstrip('+') tags = re.findall(r'<([^>]+)>', subreading[1]) - subreadings.append(Reading(baseform=baseform, tags=tags)) + subreadings.append(SReading(baseform=baseform, tags=tags)) self.readings.append(subreadings) else:
Reading→SReading, more honest
apertium_streamparser
train
879ab3a6f1074f922bbba25b5f788eb72dab9444
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ setup( "py-moneyed>=0.6.0,<2.0", # version limited to be installable with django-money "django-money>=0.9.1", "django-import-export>=0.5.0", - "babel>=2.5.1", + "babel>=2.9.1", 'openpyxl<=2.6;python_version<"3.5"', ], )
require babel at least <I>
adamcharnock_django-hordak
train
dab4a8f69ad8b7745fb69b489810d198c5b3e980
diff --git a/mythril/laser/ethereum/call.py b/mythril/laser/ethereum/call.py index <HASH>..<HASH> 100644 --- a/mythril/laser/ethereum/call.py +++ b/mythril/laser/ethereum/call.py @@ -10,7 +10,7 @@ import mythril.laser.ethereum.util as util from mythril.laser.ethereum import natives from mythril.laser.ethereum.instruction_data import calculate_native_gas from mythril.laser.ethereum.state.account import Account -from mythril.laser.ethereum.natives import PRECOMPILE_COUNT +from mythril.laser.ethereum.natives import PRECOMPILE_COUNT, PRECOMPILE_FUNCTIONS from mythril.laser.ethereum.state.calldata import ( BaseCalldata, SymbolicCalldata, @@ -249,11 +249,10 @@ def native_call( log.debug("CALL with symbolic start or offset not supported") return [global_state] - contract_list = ["ecrecover", "sha256", "ripemd160", "identity"] call_address_int = int(callee_address, 16) native_gas_min, native_gas_max = calculate_native_gas( global_state.mstate.calculate_extension_size(mem_out_start, mem_out_sz), - contract_list[call_address_int - 1], + PRECOMPILE_FUNCTIONS[call_address_int - 1].__name__, ) global_state.mstate.min_gas_used += native_gas_min global_state.mstate.max_gas_used += native_gas_max @@ -263,7 +262,11 @@ def native_call( except natives.NativeContractException: for i in range(mem_out_sz): global_state.mstate.memory[mem_out_start + i] = global_state.new_bitvec( - contract_list[call_address_int - 1] + "(" + str(call_data) + ")", 8 + PRECOMPILE_FUNCTIONS[call_address_int - 1].__name__ + + "(" + + str(call_data) + + ")", + 8, ) return [global_state] diff --git a/mythril/laser/ethereum/instruction_data.py b/mythril/laser/ethereum/instruction_data.py index <HASH>..<HASH> 100644 --- a/mythril/laser/ethereum/instruction_data.py +++ b/mythril/laser/ethereum/instruction_data.py @@ -199,7 +199,7 @@ def calculate_native_gas(size: int, contract: str): :param contract: :return: """ - gas_value = None + gas_value = 0 word_num = ceil32(size) // 32 if contract == "ecrecover": gas_value = opcodes.GECRECOVER @@ -210,7 +210,9 @@ def calculate_native_gas(size: int, contract: str): elif contract == "identity": gas_value = opcodes.GIDENTITYBASE + word_num * opcodes.GIDENTITYWORD else: - raise ValueError("Unknown contract type {}".format(contract)) + # TODO: Add gas for other precompiles, computation should be shifted to natives.py + # as some data isn't available here + pass return gas_value, gas_value diff --git a/mythril/laser/ethereum/natives.py b/mythril/laser/ethereum/natives.py index <HASH>..<HASH> 100644 --- a/mythril/laser/ethereum/natives.py +++ b/mythril/laser/ethereum/natives.py @@ -213,9 +213,10 @@ def native_contracts(address: int, data: BaseCalldata) -> List[int]: :return: """ - if isinstance(data, ConcreteCalldata): - concrete_data = data.concrete(None) - else: + if not isinstance(data, ConcreteCalldata): raise NativeContractException() - - return PRECOMPILE_FUNCTIONS[address - 1](concrete_data) + concrete_data = data.concrete(None) + try: + return PRECOMPILE_FUNCTIONS[address - 1](concrete_data) + except TypeError: + raise NativeContractException
Fix/natives (#<I>) * Fix precompiles * Fix black * Deal with TypeError
ConsenSys_mythril-classic
train
9512c1a851489a83c8d52aef0074d7c800017cca
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index <HASH>..<HASH> 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -1105,7 +1105,9 @@ class PeriodIndex(Int64Index): def __unicode__(self): output = self.__class__.__name__ output += u'(' - output += '[{0}]'.format(', '.join(map("u'{0}'".format, self))) + prefix = '' if py3compat.PY3 else 'u' + mapper = "{0}'{{0}}'".format(prefix) + output += '[{0}]'.format(', '.join(map(mapper.format, self))) output += ", freq='{0}'".format(self.freq) output += ')' return output
fix for <I> which does not accept unicode literal prefix
pandas-dev_pandas
train
2ae426b69b5a5be869bda01c7548818f8a4cfea5
diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index <HASH>..<HASH> 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -198,7 +198,7 @@ class BaseArrayHelper $key = substr($key, $pos + 1); } - if (is_object($array) && isset($array->$key)) { + if (is_object($array) && property_exists($array, $key)) { return $array->$key; } elseif (is_array($array)) { return array_key_exists($key, $array) ? $array[$key] : $default;
#<I>: changed behavior of ArrayHelper::getValue() according to @azureru suggestion
yiisoft_yii-core
train
1023cf1d72a3bfe56cbbf8ef89ad96725639e066
diff --git a/src/core.js b/src/core.js index <HASH>..<HASH> 100644 --- a/src/core.js +++ b/src/core.js @@ -1125,13 +1125,15 @@ jQuery.extend({ return (text || "").replace( /^\s+|\s+$/g, "" ); }, + // NOTE: Due to the conflict with Scriptaculous (http://dev.jquery.com/ticket/3248) + // We remove support for functions since jQuery 1.3 makeArray: function( array ) { var ret = []; if( array != null ){ var i = array.length; - //the window, strings and functions also have 'length' - if( i == null || array.split || array.setInterval || array.call ) + // The window, strings (and functions) also have 'length' + if( i == null || array.split || array.setInterval ) ret[0] = array; else while( i ) diff --git a/test/unit/core.js b/test/unit/core.js index <HASH>..<HASH> 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -1684,7 +1684,7 @@ test("contents()", function() { }); test("jQuery.makeArray", function(){ - expect(15); + expect(14); equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName, "HEAD", "Pass makeArray a jQuery object" ); @@ -1708,8 +1708,11 @@ test("jQuery.makeArray", function(){ ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" ); - //function, is tricky as it has length - equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" ); + // function, is tricky as it has length + // NOTE: Due to the conflict with Scriptaculous (http://dev.jquery.com/ticket/3248) + // We remove support for functions since jQuery 1.3 + //equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" ); + //window, also has length equals( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
jquery core: closes #<I>, #<I>, #<I>, #<I>, #<I>, #<I>. jQuery.makeArray doesn't support functions anymore. Voiding the conflict with Scriptaculous <I>.x.
jquery_jquery
train
43bfb394b3464a2ab2996b61d1fc4f4330bf1966
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -41,10 +41,5 @@ setup(name='brokit', maintainer_email="[email protected]", url='https://github.com/biocore/brokit', packages=find_packages(), - install_requires=['scikit-bio == 0.0.0-dev'], - dependency_links=[ - 'https://github.com/biocore/scikit-bio/archive/master.zip#egg=scikit-bio-0.0.0-dev' - ], - extras_require={}, - classifiers=classifiers - ) + install_requires=['scikit-bio == 0.1.1'], + classifiers=classifiers)
Update to skbio <I>
biocore_burrito-fillings
train
0da4a08bdfea28a0cc881ca5831aadfcf8a3b7eb
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -51,6 +51,8 @@ module ActiveRecord sc.execute(binds, klass, conn) do |record| set_inverse_instance record end.first + rescue RangeError + nil end def replace(record) diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -1062,6 +1062,20 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal 1, parent.reload.children_count end + def test_belongs_to_with_out_of_range_value_assigning + model = Class.new(Comment) do + def self.name; "Temp"; end + validates :post, presence: true + end + + comment = model.new + comment.post_id = 10_000_000_000 + + assert_nil comment.post + assert_not comment.valid? + assert_equal [{ error: :blank }], comment.errors.details[:post] + end + def test_polymorphic_with_custom_primary_key toy = Toy.create! sponsor = Sponsor.create!(sponsorable: toy)
Prevent `RangeError` for `belongs_to` associations Currently to access `belongs_to` associations raises a `RangeError` if foreign key attribute has out of range value. It should return a nil value rather than raising a `RangeError`. Fixes #<I>.
rails_rails
train
cde7dc231d78bf3b35f1e006046c81d30e446d65
diff --git a/androguard/core/bytecodes/apk.py b/androguard/core/bytecodes/apk.py index <HASH>..<HASH> 100644 --- a/androguard/core/bytecodes/apk.py +++ b/androguard/core/bytecodes/apk.py @@ -904,7 +904,11 @@ class APK(object): """ # TODO: figure out if both android:name and name tag exist which one to give preference - return tag.get(self._ns(attribute)) or tag.get(attribute) + value = tag.get(self._ns(attribute)) + if value is None: + log.warning("Failed to get the attribute with namespace") + value = tag.get(attribute) + return value def find_tags(self, tag_name, **attribute_filter): """ @@ -958,7 +962,10 @@ class APK(object): return True for attr, value in attribute_filter.items(): # TODO: figure out if both android:name and name tag exist which one to give preference - _value = tag.get(self._ns(attr)) or tag.get(attr) + _value = tag.get(self._ns(attr)) + if _value is None: + log.warning("Failed to get the attribute with namespace") + _value = tag.get(attr) if _value != value: return False return True
added warning if the namespace parsing fails. One can catch the warning and decide for now
androguard_androguard
train
ab3c67dc4c7ab83acfd7fd2e2909fa2456a622cb
diff --git a/overpass/cli.py b/overpass/cli.py index <HASH>..<HASH> 100644 --- a/overpass/cli.py +++ b/overpass/cli.py @@ -10,20 +10,20 @@ import overpass @click.option('--timeout', default=25, help='Timeout in seconds.') @click.option('--endpoint', default='http://overpass-api.de/api/interpreter', help='URL of your prefered API.') [email protected]('--format', default='geojson', help="""Format to save the data. [email protected]('--responseformat', default='geojson', help="""Format to save the data. Options are 'geojson' and 'osm'. Default format is geojson.""") @click.argument('query', type=str) @click.argument('output_file', type=click.Path()) -def cli(timeout, endpoint, format, query, output_file): +def cli(timeout, endpoint, responseformat, query, output_file): """Run query and save the result in output_file""" api = overpass.API(timeout=timeout, endpoint=endpoint) - if format not in api.SUPPORTED_FORMATS: + if responseformat not in api.SUPPORTED_FORMATS: print("format {} not supported. Supported formats: {}".format( - format, + responseformat, api.SUPPORTED_FORMATS.join(", "))) - result = api.Get(query, responseformat=format) + result = api.Get(query, responseformat=responseformat) with open(output_file, 'w') as f: if responseformat=="geojson": geojson.dump(result, f, indent=2, sort_keys=True)
change format to responseformat (format is a reserved word in Python)
mvexel_overpass-api-python-wrapper
train
32b8d009cfb3e8a945b7dab7b8cad1434dcc43aa
diff --git a/src/Formatter/ResponseFormatter.php b/src/Formatter/ResponseFormatter.php index <HASH>..<HASH> 100644 --- a/src/Formatter/ResponseFormatter.php +++ b/src/Formatter/ResponseFormatter.php @@ -173,6 +173,7 @@ class ResponseFormatter implements ResponseFormatterInterface private function processRestEltType($elts, $columns, $idx) { + print_r($elts); if (isset($elts[0])) { foreach ($elts as $elt) { $this->processRestEltType($elt, $columns, $idx); diff --git a/src/Formatter/Result.php b/src/Formatter/Result.php index <HASH>..<HASH> 100644 --- a/src/Formatter/Result.php +++ b/src/Formatter/Result.php @@ -172,7 +172,7 @@ class Result public function get($identifier) { if (!array_key_exists($identifier, $this->identifiers)) { - throw new \InvalidArgumentException(sprintf('The identifier %s is not defined', $identifier)); + return null; } if (count($this->identifiers[$identifier]) === 1) {
when identifier does not exist, it should return null instead of throwing exception
neoxygen_neo4j-neoclient
train
7062333c94cbcb6ab3cc5663c918e00adbff47ca
diff --git a/cobald_tests/daemon/test_service.py b/cobald_tests/daemon/test_service.py index <HASH>..<HASH> 100644 --- a/cobald_tests/daemon/test_service.py +++ b/cobald_tests/daemon/test_service.py @@ -98,17 +98,17 @@ class TestServiceRunner(object): runner = ServiceRunner(accept_delay=0.1) run_in_thread(runner.accept, name='test_execute') # do not pass in values - receive default - assert runner.execute(sub_pingpong, flavour=threading) is None - assert runner.execute(co_pingpong, flavour=trio) is None - assert runner.execute(co_pingpong, flavour=asyncio) is None + assert runner.adopt(sub_pingpong, flavour=threading) is None + assert runner.adopt(co_pingpong, flavour=trio) is None + assert runner.adopt(co_pingpong, flavour=asyncio) is None # pass in positional arguments - assert runner.execute(sub_pingpong, 1, flavour=threading) is None - assert runner.execute(co_pingpong, 2, flavour=trio) is None - assert runner.execute(co_pingpong, 3, flavour=asyncio) is None + assert runner.adopt(sub_pingpong, 1, flavour=threading) is None + assert runner.adopt(co_pingpong, 2, flavour=trio) is None + assert runner.adopt(co_pingpong, 3, flavour=asyncio) is None # pass in keyword arguments - assert runner.execute(sub_pingpong, what=4, flavour=threading) is None - assert runner.execute(co_pingpong, what=5, flavour=trio) is None - assert runner.execute(co_pingpong, what=6, flavour=asyncio) is None + assert runner.adopt(sub_pingpong, what=4, flavour=threading) is None + assert runner.adopt(co_pingpong, what=5, flavour=trio) is None + assert runner.adopt(co_pingpong, what=6, flavour=asyncio) is None for _ in range(10): time.sleep(0.05) if len(reply_store) == 9:
fixed test for runtime.adopt
MatterMiners_cobald
train
2739d6fea8ffb4a1291d0c6f976b5781daea1cdf
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,5 +1,4 @@ /* global module */ - module.exports = function(grunt) { 'use strict'; @@ -100,7 +99,6 @@ module.exports = function(grunt) { singlerun: {}, saucelabs: { options: { - configFile: "tests/protractor.conf.js", args: { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY diff --git a/tests/protractor.conf.js b/tests/protractor.conf.js index <HASH>..<HASH> 100644 --- a/tests/protractor.conf.js +++ b/tests/protractor.conf.js @@ -1,64 +1,30 @@ exports.config = { - // ----- How to setup Selenium ----- - // - // There are three ways to specify how to use Selenium. Specify one of the - // following: - // - // 1. seleniumServerJar - to start Selenium Standalone locally. - // 2. seleniumAddress - to connect to a Selenium server which is already running. - // 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs. - - // The location of the selenium standalone server .jar file. - //seleniumServerJar: '../node_modules/protractor/selenium/selenium-server-standalone-2.41.0.jar', - // The port to start the selenium server on, or null if the server should - // find its own unused port. - //seleniumPort: null, - // Chromedriver location is used to help the selenium standalone server - // find chromedriver. This will be passed to the selenium jar as - // the system property webdriver.chrome.driver. If null, selenium will - // attempt to find chromedriver using PATH. - //chromeDriver: '../node_modules/protractor/selenium/chromedriver', - // Additional command line options to pass to selenium. For example, - // if you need to change the browser timeout, use - // seleniumArgs: ['-browserTimeout=60'], - //seleniumArgs: [], - + // Locally, we should just use the default standalone Selenium server + // In Travis, we set up the Selenium serving via Sauce Labs sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, - //seleniumAddress: 'http://localhost:4444/wd/hub', - - // ----- What tests to run ----- - // - // Spec patterns are relative to the location of this config. + // Tests to run specs: [ './protractor/**/*.spec.js' ], - // ----- Capabilities to be passed to the webdriver instance ---- - // - // For a full list of available capabilities, see - // https://code.google.com/p/selenium/wiki/DesiredCapabilities - // and - // https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js + // Capabilities to be passed to the webdriver instance + // For a full list of available capabilities, see https://code.google.com/p/selenium/wiki/DesiredCapabilities capabilities: { 'browserName': 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, - 'name': 'AngularFire Protractor Tests Build' + process.env.TRAVIS_BUILD_NUMBER + 'name': 'AngularFire Protractor Tests Build ' + process.env.TRAVIS_BUILD_NUMBER }, - // A base URL for your application under test. Calls to protractor.get() - // with relative paths will be prepended with this. - //baseUrl: 'http://localhost:' + (process.env.HTTP_PORT || '3030') + '/tests/protractor/', - //baseUrl: 'http://0.0.0.0:3030/tests/protractor/', + // Calls to protractor.get() with relative paths will be prepended with the baseUrl baseUrl: 'http://localhost:3030/tests/protractor/', - // Selector for the element housing the angular app - this defaults to - // body, but is necessary if ng-app is on a descendant of <body> + // Selector for the element housing the angular app rootElement: 'body', - // ----- Options to be passed to minijasminenode ----- + // Options to be passed to minijasminenode jasmineNodeOpts: { // onComplete will be called just before the driver quits. onComplete: null,
Cleaned up code now that everything is working
firebase_angularfire
train
9736d803e05451f1c9da48dfde86387b14695392
diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -1,8 +1,8 @@ var tape = require('tape') var electron = require('../') -var fs = require('fs') +var pathExists = require('path-exists') tape('has binary', function(t) { - t.ok(fs.existsSync(electron), 'electron was downloaded') + t.ok(pathExists.sync(electron), 'electron was downloaded') t.end() -}) \ No newline at end of file +})
fs.existsSync() is depreciated in io.js
RnbWd_electron-bin
train
2f4d9b479e198892f833f1cd29ab3c71f6cf897a
diff --git a/lib/pork.rb b/lib/pork.rb index <HASH>..<HASH> 100644 --- a/lib/pork.rb +++ b/lib/pork.rb @@ -18,11 +18,23 @@ module Pork module API module_function - def describe desc, &suite + def describe desc=:default, &suite Pork.stats.start Executor.execute(self, desc, &suite) Pork.stats.tests += 1 end + + def copy desc=:default, &suite + mutex.synchronize{ stash[desc] = suite } + end + + # Search for current context first, then the top-level context (API) + def paste desc=:default + instance_eval(&[stash, API.stash].find{ |s| s[desc] }[desc]) + end + + def mutex; @mutex ||= Mutex.new; end + def stash; @stash ||= {} ; end end class Executor < Struct.new(:name) @@ -34,7 +46,7 @@ module Pork }.module_eval(&suite) end - def self.would name, &test + def self.would name=:default, &test assertions = Pork.stats.assertions context = new(name) run_before(context) diff --git a/test/test_bacon.rb b/test/test_bacon.rb index <HASH>..<HASH> 100644 --- a/test/test_bacon.rb +++ b/test/test_bacon.rb @@ -285,35 +285,35 @@ Pork::API.describe "before/after" do end end -# shared "a shared context" do -# it "gets called where it is included" do -# true.should.be.true -# end -# end - -# shared "another shared context" do -# it "can access data" do -# @magic.should.be.equal 42 -# end -# end - -# describe "shared/behaves_like" do -# behaves_like "a shared context" - -# ctx = self -# it "raises NameError when the context is not found" do -# lambda { -# ctx.behaves_like "whoops" -# }.should.raise NameError -# end - -# behaves_like "a shared context" - -# before { -# @magic = 42 -# } -# behaves_like "another shared context" -# end +Pork::API.copy "a shared context" do + would "get called where it is included" do + true.should.eq true + end +end + +Pork::API.copy "another shared context" do + would "access data" do + @magic.should.eq 42 + end +end + +Pork::API.describe "shared/behaves_like" do + paste "a shared context" + + ctx = self + would "raise NameError when the context is not found" do + lambda { + ctx.paste "whoops" + }.should.raise NameError + end + + paste "a shared context" + + before { + @magic = 42 + } + paste "another shared context" +end Pork::API.describe "Methods" do def the_meaning_of_life
implement copy and paste (shared and behaves_like) TODO: nested copy and paste
godfat_pork
train