content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
update documentation per suggestions from ostezer
b7e88250f421d34d25f89737c65954150248ee28
<ide><path>docs/sources/installation/centos.md <ide> page_title: Installation on CentOS <del>page_description: This page provides documentation for installing docker on CentOS <add>page_description: Instructions for installing Docker on CentOS <ide> page_keywords: Docker, Docker documentation, requirements, linux, centos, epel, docker.io, docker-io <ide> <ide> # CentOS <ide> page_keywords: Docker, Docker documentation, requirements, linux, centos, epel, <ide> > This is a community contributed installation path. The only `official` <ide> > installation is using the [*Ubuntu*](../ubuntulinux/#ubuntu-linux) <ide> > installation path. This version may be out of date because it depends on <del>> some binaries to be updated and published <add>> some binaries to be updated and published. <ide> <ide> The Docker package is available via the EPEL repository. These instructions work <ide> for CentOS 6 and later. They will likely work for other binary compatible EL6 <ide> or explore and build on the images yourself. <ide> ## Issues? <ide> <ide> If you have any issues - please report them directly in the <del>[CentOS bug tracker]( <del>http://bugs.centos.org). <add>[CentOS bug tracker](http://bugs.centos.org).
1
Python
Python
add `distinct` call in `filter_queryset`
3522b69394d932c8bf8028a456b6d9b64c38b54e
<ide><path>rest_framework/filters.py <ide> def filter_queryset(self, request, queryset, view): <ide> for search_term in self.get_search_terms(request): <ide> or_queries = [models.Q(**{orm_lookup: search_term}) <ide> for orm_lookup in orm_lookups] <del> queryset = queryset.filter(reduce(operator.or_, or_queries)) <add> queryset = queryset.filter(reduce(operator.or_, or_queries)).distinct() <ide> <ide> return queryset <ide>
1
Javascript
Javascript
fix $flowfixme in rtlexample
206ef54aa415e3e2bb0d48111104dfc372b97e0f
<ide><path>RNTester/js/RTLExample.js <ide> class RTLExample extends React.Component<any, State> { <ide> <RNTesterBlock <ide> title={'Controlling Animation'} <ide> description={'Animation direction according to layout'}> <del> {/* $FlowFixMe - Typing ReactNativeComponent revealed errors */} <del> <View Style={styles.view}> <add> <View style={styles.view}> <ide> <AnimationBlock <ide> onPress={this._linearTap} <ide> imgStyle={{
1
Javascript
Javascript
add basic date support
cc097867f49673005d47a7f8f0cbe25f7d5c2163
<ide><path>src/filters.js <ide> foreach({ <ide> }, <ide> <ide> 'date': function(date) { <add> if (date instanceof Date) <add> return date.toLocaleDateString(); <add> else <add> return date; <ide> }, <ide> <ide> 'json': function(object) {
1
Python
Python
fix static checks
95be3eec42cd5ae0ef8c6402f7d1cd87e5d93848
<ide><path>airflow/models/dag.py <ide> def partial_subset( <ide> for t in regex_match + also_include} <ide> <ide> def filter_task_group(group, parent_group): <del> """ <del> Exclude tasks not included in the subdag from the given TaskGroup. <del> """ <add> """Exclude tasks not included in the subdag from the given TaskGroup.""" <ide> copied = copy.copy(group) <ide> copied.used_group_ids = set(copied.used_group_ids) <ide> copied._parent_group = parent_group
1
PHP
PHP
update httpjsonresponsetest.php
5c85962b75f5737f674c3e39b234e1f8c614353c
<ide><path>tests/Http/HttpJsonResponseTest.php <ide> <ide> class HttpJsonResponseTest extends TestCase <ide> { <del> public function testSeAndRetrieveJsonableData() <add> public function testSetAndRetrieveJsonableData() <ide> { <ide> $response = new \Illuminate\Http\JsonResponse(new JsonResponseTestJsonableObject); <ide> $data = $response->getData(); <ide> $this->assertInstanceOf('StdClass', $data); <ide> $this->assertEquals('bar', $data->foo); <ide> } <ide> <del> public function testSeAndRetrieveJsonSerializeData() <add> public function testSetAndRetrieveJsonSerializeData() <ide> { <ide> $response = new \Illuminate\Http\JsonResponse(new JsonResponseTestJsonSerializeObject); <ide> $data = $response->getData(); <ide> $this->assertInstanceOf('StdClass', $data); <ide> $this->assertEquals('bar', $data->foo); <ide> } <ide> <del> public function testSeAndRetrieveArrayableData() <add> public function testSetAndRetrieveArrayableData() <ide> { <ide> $response = new \Illuminate\Http\JsonResponse(new JsonResponseTestArrayableObject); <ide> $data = $response->getData();
1
Ruby
Ruby
fix rubocop warnings
2cf6184735050319a78063111b6f464f2320e2b7
<ide><path>Library/Homebrew/test/test_formula_installer.rb <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> dependent = formula do <ide> url "foo" <ide> version "0.5" <del> depends_on "#{dependency.name}" <add> depends_on dependency.name.to_s <ide> end <ide> <ide> dependency.prefix("0.1").join("bin/a").mkpath
1
Javascript
Javascript
add boxed bigint formatting to util.inspect
893432ad928e25854950c0b5c581dfb3081ed4bb
<ide><path>lib/util.js <ide> function formatValue(ctx, value, recurseTimes, ln) { <ide> if (keyLength === 0) <ide> return ctx.stylize(`[Boolean: ${formatted}]`, 'boolean'); <ide> base = `[Boolean: ${formatted}]`; <add> // eslint-disable-next-line valid-typeof <add> } else if (typeof raw === 'bigint') { <add> // Make boxed primitive BigInts look like such <add> const formatted = formatPrimitive(stylizeNoColor, raw); <add> if (keyLength === 0) <add> return ctx.stylize(`[BigInt: ${formatted}]`, 'bigint'); <add> base = `[BigInt: ${formatted}]`; <ide> } else if (typeof raw === 'symbol') { <ide> const formatted = formatPrimitive(stylizeNoColor, raw); <ide> return ctx.stylize(`[Symbol: ${formatted}]`, 'symbol'); <ide><path>test/parallel/test-util-inspect-bigint.js <ide> const assert = require('assert'); <ide> const { inspect } = require('util'); <ide> <ide> assert.strictEqual(inspect(1n), '1n'); <add>assert.strictEqual(inspect(Object(-1n)), '[BigInt: -1n]'); <add>assert.strictEqual(inspect(Object(13n)), '[BigInt: 13n]');
2
Javascript
Javascript
remove v8forceoptimization calls
3129ba2bae718b4b92d69ba55e64c136eccbb7a0
<ide><path>benchmark/url/whatwg-url-idna.js <ide> function main(conf) { <ide> const input = inputs[conf.input][to]; <ide> const method = to === 'ascii' ? domainToASCII : domainToUnicode; <ide> <del> common.v8ForceOptimization(method, input); <del> <ide> bench.start(); <ide> for (var i = 0; i < n; i++) { <ide> method(input); <ide><path>benchmark/vm/run-in-context.js <ide> function main(conf) { <ide> <ide> const contextifiedSandbox = vm.createContext(); <ide> <del> common.v8ForceOptimization(vm.runInContext, <del> '0', contextifiedSandbox, options); <ide> bench.start(); <ide> for (; i < n; i++) <ide> vm.runInContext('0', contextifiedSandbox, options); <ide><path>benchmark/vm/run-in-this-context.js <ide> function main(conf) { <ide> <ide> var i = 0; <ide> <del> common.v8ForceOptimization(vm.runInThisContext, '0', options); <ide> bench.start(); <ide> for (; i < n; i++) <ide> vm.runInThisContext('0', options);
3
Mixed
Go
return write error
c65de2c0207ac67e5023ada8709490ef4627bd01
<ide><path>api/server/server.go <ide> func writeCorsHeaders(w http.ResponseWriter, r *http.Request) { <ide> } <ide> <ide> func ping(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> w.Write([]byte{'O', 'K'}) <del> return nil <add> _, err := w.Write([]byte{'O', 'K'}) <add> return err <ide> } <ide> <ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion version.Version) http.HandlerFunc { <ide><path>docs/sources/reference/api/docker_remote_api_v1.11.md <ide> Ping the docker server <ide> Status Codes: <ide> <ide> - **200** - no error <add> - **500** - server error <ide> <ide> ### Create a new image from a container's changes <ide>
2
Text
Text
add faq about paths to being a moderator
7b20b654d96fad3df20330a00cdddfd0936e4ed4
<ide><path>docs/FAQ.md <ide> We typically do not assign issues to anyone other than long-time contributors. I <ide> - Did you follow the pull request checklist? <ide> - Did you give your pull request a meaningful title? <ide> <add>### I am interested in being a moderator at freeCodeCamp. Where should I start? <add> <add>Our community moderators are our heroes. Their voluntary contributions make <add>freeCodeCamp a safe and welcoming community. <add> <add>First and foremost, we would need you to be an active participant in the <add>community, and live by our [code of conduct](https://www.freecodecamp.org/news/code-of-conduct/) <add>(not just enforce it). <add> <add>Here are some recommended paths for some of our platforms: <add> <add>- To be a **Discord/Chat** moderator, have an active presence in our chat and <add> have positive engagements with others, while also learning and practicing how <add> to deal with potential conflicts that may arise. <add>- To be a **Forum** moderator, similar to a chat moderator, have an active <add> presence and engage with other forum posters, supporting others in their <add> learning journey, and even given feedback when asked. Take a look at <add> [The Subforum Leader Handbook](https://forum.freecodecamp.org/t/the-subforum-leader-handbook/326326) <add> for more information. <add>- To be a **GitHub** moderator, help process GitHub issues that are brought up <add> to see if they are valid and (ideally) try to propose solutions for these <add> issues to be picked up by others (or yourself). <add> <add>Altogether, be respectful to others. We are humans all around the world. With <add>that in mind, please also consider using encouraging or supportive language and <add>be mindful of cross-cultural communication. <add> <add>If you practice the above **consistently for a while** and our fellow moderator <add>members recommend you, a staff member will reach out and onboard you to the <add>moderators' team. Open source work is voluntary work and our time is limited. <add>We acknowledge that this is probably true in your case as well. So we emphasize <add>being **consistent** rather than engaging in the community 24/7. <add> <add>Take a look at our [Moderator Handbook](https://contribute.freecodecamp.org/#/moderator-handbook) <add>for a more exhaustive list of other responsibilities and expectations we have <add>of our moderators. <add> <ide> ### I am stuck on something that is not included in this documentation. <ide> <ide> **Feel free to ask for help in:**
1
Ruby
Ruby
limit fatal dev tools check to sierra
12aad5c65fee39c5f044e39ca1efcbed58aebd39
<ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> def development_tools_checks <ide> end <ide> <ide> def fatal_development_tools_checks <del> if ENV["TRAVIS"] || ARGV.homebrew_developer? <add> if MacOS.version >= :sierra && ENV["CI"].nil? <ide> %w[ <add> check_xcode_up_to_date <add> check_clt_up_to_date <ide> ] <ide> else <ide> %w[ <del> check_xcode_up_to_date <del> check_clt_up_to_date <ide> ] <ide> end <ide> end
1
PHP
PHP
use no protocol to fetch lato font
8bf428c193475ca95face345a37816239b827daa
<ide><path>resources/views/welcome.blade.php <ide> <html> <ide> <head> <del> <link href='http://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'> <add> <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'> <ide> <ide> <style> <ide> body {
1
Python
Python
add new snapshot features for outscale provider
3f81a899c8b253f0bfa60ccf589878067164fdad
<ide><path>libcloud/compute/drivers/outscale.py <ide> def ex_create_snapshot_export_task( <ide> The copy of the source snapshot is independent and belongs to you. <ide> <ide> :param osu_export_disk_image_format: The format of the export <del> disk (qcow2 | vdi | vmdk). <add> disk (qcow2 | vdi | vmdk). (required) <ide> :type osu_export_disk_image_format: ``str`` <ide> <ide> :param osu_export_api_key_id: The API key of the OSU account <ide> def ex_create_snapshot_export_task( <ide> :type osu_export_api_secret_key : ``str`` <ide> <ide> :param osu_export_bucket: The name of the OSU bucket you want <del> to export the object to. <add> to export the object to. (required) <ide> :type osu_export_bucket : ``str`` <ide> <ide> :param osu_export_manifest_url: The URL of the manifest file. <ide> def ex_create_snapshot_export_task( <ide> object_export_task_id + '.' + disk_image_format. <ide> :type osu_export_prefix : ``str`` <ide> <del> :param snapshot: The ID of the snapshot to export. <add> :param snapshot: The ID of the snapshot to export. (required) <ide> :type snapshot : ``VolumeSnapshot`` <ide> <ide> :param dry_run: If true, checks whether you have the required <ide> def ex_update_snapshot( <ide> the resource is public. If false, the resource is private. <ide> :type perm_to_create_volume_removals_global_perm: ``bool`` <ide> <del> :param snapshot: The ID of the snapshot. <add> :param snapshot: The ID of the snapshot. (required) <ide> :type snapshot: ``VolumeSnapshot`` <ide> <ide> :param dry_run: If true, checks whether you have the required
1
Javascript
Javascript
fix issue with dst transition in chinese locale
7d367f561150926f4fdaa1ce95741f7ee134af27
<ide><path>src/locale/zh-cn.js <ide> export default moment.defineLocale('zh-cn', { <ide> nextWeek : function () { <ide> var startOfWeek, prefix; <ide> startOfWeek = moment().startOf('week'); <del> prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; <add> prefix = this.diff(startOfWeek, 'days') >= 7 ? '[下]' : '[本]'; <ide> return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm'; <ide> }, <ide> lastWeek : function () {
1
Python
Python
update dynet example to use minibatching
ef76c28d70229cb13955cbee654b69810606cda9
<ide><path>examples/spacy_dynet_lstm.py <ide> from collections import defaultdict <ide> from itertools import count <ide> <add>#import _gdynet as dynet <add>#from _gdynet import cg <ide> import dynet <ide> from dynet import cg <ide> <ide> def get_vocab(train, test): <ide> words.append(w) <ide> vw = Vocab.from_corpus([words]) <ide> vt = Vocab.from_corpus([tags]) <del> UNK = vw.w2i["_UNK_"] <ide> return words, tags, wc, vw, vt <ide> <ide> <ide> class BiTagger(object): <del> def __init__(self, nwords, ntags): <add> def __init__(self, vw, vt, nwords, ntags): <add> self.vw = vw <add> self.vt = vt <ide> self.nwords = nwords <ide> self.ntags = ntags <ide> <add> self.UNK = self.vw.w2i["_UNK_"] <add> <ide> self._model = dynet.Model() <ide> self._sgd = dynet.SimpleSGDTrainer(self._model) <ide> <ide> def __init__(self, nwords, ntags): <ide> <ide> self._fwd_lstm = dynet.LSTMBuilder(1, 128, 50, self._model) <ide> self._bwd_lstm = dynet.LSTMBuilder(1, 128, 50, self._model) <add> self._words_batch = [] <add> self._tags_batch = [] <add> self._minibatch_size = 32 <ide> <del> def __call__(self, doc): <add> def __call__(self, words): <ide> dynet.renew_cg() <del> <del> wembs = [self._E[word.rank] for word in doc] <add> word_ids = [self.vw.w2i.get(w, self.UNK) for w in words] <add> wembs = [self._E[w] for w in word_ids] <ide> <ide> f_state = self._fwd_lstm.initial_state() <ide> b_state = self._bwd_lstm.initial_state() <ide> def __call__(self, doc): <ide> H = dynet.parameter(self._pH) <ide> O = dynet.parameter(self._pO) <ide> <add> tags = [] <ide> for i, (f, b) in enumerate(zip(fw, reversed(bw))): <ide> r_t = O * (dynet.tanh(H * dynet.concatenate([f, b]))) <ide> out = dynet.softmax(r_t) <del> doc[i].tag = np.argmax(out.npvalue()) <del> <del> def update(self, doc, gold): <add> tags.append(self.vt.i2w[np.argmax(out.npvalue())]) <add> return tags <add> <add> def update(self, words, tags): <add> self._words_batch.append(words) <add> self._tags_batch.append(tags) <add> if len(self._words_batch) == self._minibatch_size: <add> loss = self.update_batch(self._words_batch, self._tags_batch) <add> self._words_batch = [] <add> self._tags_batch = [] <add> else: <add> loss = 0 <add> return loss <add> <add> def update_batch(self, words_batch, tags_batch): <ide> dynet.renew_cg() <del> wembs = [self._E[word.rank] for word in doc] <add> length = max(len(words) for words in words_batch) <add> word_ids = np.zeros((length, len(words_batch)), dtype='int32') <add> for j, words in enumerate(words_batch): <add> for i, word in enumerate(words): <add> word_ids[i, j] = self.vw.w2i.get(word, self.UNK) <add> tag_ids = np.zeros((length, len(words_batch)), dtype='int32') <add> for j, tags in enumerate(tags_batch): <add> for i, tag in enumerate(tags): <add> tag_ids[i, j] = self.vt.w2i.get(tag, self.UNK) <add> wembs = [dynet.lookup_batch(self._E, word_ids[i]) for i in range(length)] <ide> wembs = [dynet.noise(we, 0.1) for we in wembs] <ide> <ide> f_state = self._fwd_lstm.initial_state() <ide> def update(self, doc, gold): <ide> O = dynet.parameter(self._pO) <ide> <ide> errs = [] <del> for f, b, t in zip(fw, reversed(bw), tags): <add> for i, (f, b) in enumerate(zip(fw, reversed(bw))): <ide> f_b = dynet.concatenate([f,b]) <ide> r_t = O * (dynet.tanh(H * f_b)) <del> err = dynet.pickneglogsoftmax(r_t, t) <del> errs.append(err) <del> <add> err = dynet.pickneglogsoftmax_batch(r_t, tag_ids[i]) <add> errs.append(dynet.sum_batches(err)) <ide> sum_errs = dynet.esum(errs) <ide> squared = -sum_errs # * sum_errs <del> loss += sum_errs.scalar_value() <add> losses = sum_errs.scalar_value() <ide> sum_errs.backward() <del> sgd.update() <add> self._sgd.update() <add> return losses <ide> <ide> <ide> def main(train_loc, dev_loc, model_dir): <ide> def main(train_loc, dev_loc, model_dir): <ide> train = list(read_data((train_loc))) <ide> test = list(read_data(dev_loc)) <ide> <del> tagger = BiTagger(vocab) <add> words, tags, wc, vw, vt = get_vocab(train, test) <ide> <ide> UNK = vw.w2i["_UNK_"] <ide> nwords = vw.size() <ide> ntags = vt.size() <ide> <del> model = dynet.Model() <del> sgd = dynet.SimpleSGDTrainer(model) <del> <del> E = model.add_lookup_parameters((nwords, 128)) <del> p_t1 = model.add_lookup_parameters((ntags, 30)) <del> <del> pH = model.add_parameters((32, 50*2)) <del> pO = model.add_parameters((ntags, 32)) <del> <del> builders=[ <del> dynet.LSTMBuilder(1, 128, 50, model), <del> dynet.LSTMBuilder(1, 128, 50, model), <del> ] <add> tagger = BiTagger(vw, vt, nwords, ntags) <ide> <ide> tagged = loss = 0 <add> <ide> for ITER in xrange(50): <ide> random.shuffle(train) <ide> for i, s in enumerate(train,1): <ide> if i % 5000 == 0: <del> sgd.status() <add> tagger._sgd.status() <ide> print(loss / tagged) <ide> loss = 0 <ide> tagged = 0 <ide> if i % 10000 == 0: <ide> good = bad = 0.0 <ide> for sent in test: <del> word_ids = [vw.w2i.get(w, UNK) for w, t in sent] <del> tags = tagger.tag_sent(word_ids) <add> #word_ids = [vw.w2i.get(w, UNK) for w, t in sent] <add> tags = tagger([w for w, t in sent]) <ide> golds = [t for w, t in sent] <ide> for go, gu in zip(golds, tags): <ide> if go == gu: <ide> good += 1 <ide> else: <ide> bad += 1 <ide> print(good / (good+bad)) <del> ws = [vw.w2i.get(w, UNK) for w,p in s] <del> ps = [vt.w2i[p] for w, p in s] <del> model.update(ws, ps) <add> loss += tagger.update([w for w, t in s], [t for w, t in s]) <add> tagged += len(s) <ide> <ide> <ide> if __name__ == '__main__':
1
Ruby
Ruby
add tests for cyclic deps
fa8b80747ac6e33904b1b6e2b95232aa22bf90d5
<ide><path>Library/Homebrew/test/formula_installer_spec.rb <ide> def temporary_install(formula, **options) <ide> end <ide> end <ide> <del> specify "check installation sanity pinned dependency" do <del> dep_name = "dependency" <del> dep_path = CoreTap.new.formula_dir/"#{dep_name}.rb" <del> dep_path.write <<~RUBY <del> class #{Formulary.class_s(dep_name)} < Formula <del> url "foo" <del> version "0.2" <del> end <del> RUBY <add> describe "#check_install_sanity" do <add> it "raises on direct cyclic dependency" do <add> ENV["HOMEBREW_DEVELOPER"] = "1" <ide> <del> Formulary.cache.delete(dep_path) <del> dependency = Formulary.factory(dep_name) <add> dep_name = "homebrew-test-cyclic" <add> dep_path = CoreTap.new.formula_dir/"#{dep_name}.rb" <add> dep_path.write <<~RUBY <add> class #{Formulary.class_s(dep_name)} < Formula <add> url "foo" <add> version "0.1" <add> depends_on "#{dep_name}" <add> end <add> RUBY <add> Formulary.cache.delete(dep_path) <add> f = Formulary.factory(dep_name) <add> <add> fi = described_class.new(f) <add> <add> expect { <add> fi.check_install_sanity <add> }.to raise_error(CannotInstallFormulaError) <add> end <ide> <del> dependent = formula do <del> url "foo" <del> version "0.5" <del> depends_on dependency.name.to_s <add> it "raises on indirect cyclic dependency" do <add> ENV["HOMEBREW_DEVELOPER"] = "1" <add> <add> formula1_name = "homebrew-test-formula1" <add> formula2_name = "homebrew-test-formula2" <add> formula1_path = CoreTap.new.formula_dir/"#{formula1_name}.rb" <add> formula1_path.write <<~RUBY <add> class #{Formulary.class_s(formula1_name)} < Formula <add> url "foo" <add> version "0.1" <add> depends_on "#{formula2_name}" <add> end <add> RUBY <add> Formulary.cache.delete(formula1_path) <add> formula1 = Formulary.factory(formula1_name) <add> <add> formula2_path = CoreTap.new.formula_dir/"#{formula2_name}.rb" <add> formula2_path.write <<~RUBY <add> class #{Formulary.class_s(formula2_name)} < Formula <add> url "foo" <add> version "0.1" <add> depends_on "#{formula1_name}" <add> end <add> RUBY <add> Formulary.cache.delete(formula2_path) <add> <add> fi = described_class.new(formula1) <add> <add> expect { <add> fi.check_install_sanity <add> }.to raise_error(CannotInstallFormulaError) <ide> end <ide> <del> (dependency.prefix("0.1")/"bin"/"a").mkpath <del> HOMEBREW_PINNED_KEGS.mkpath <del> FileUtils.ln_s dependency.prefix("0.1"), HOMEBREW_PINNED_KEGS/dep_name <add> it "raises on pinned dependency" do <add> dep_name = "homebrew-test-dependency" <add> dep_path = CoreTap.new.formula_dir/"#{dep_name}.rb" <add> dep_path.write <<~RUBY <add> class #{Formulary.class_s(dep_name)} < Formula <add> url "foo" <add> version "0.2" <add> end <add> RUBY <ide> <del> dependency_keg = Keg.new(dependency.prefix("0.1")) <del> dependency_keg.link <add> Formulary.cache.delete(dep_path) <add> dependency = Formulary.factory(dep_name) <ide> <del> expect(dependency_keg).to be_linked <del> expect(dependency).to be_pinned <add> dependent = formula do <add> url "foo" <add> version "0.5" <add> depends_on dependency.name.to_s <add> end <ide> <del> fi = described_class.new(dependent) <add> (dependency.prefix("0.1")/"bin"/"a").mkpath <add> HOMEBREW_PINNED_KEGS.mkpath <add> FileUtils.ln_s dependency.prefix("0.1"), HOMEBREW_PINNED_KEGS/dep_name <ide> <del> expect { <del> fi.check_install_sanity <del> }.to raise_error(CannotInstallFormulaError) <add> dependency_keg = Keg.new(dependency.prefix("0.1")) <add> dependency_keg.link <add> <add> expect(dependency_keg).to be_linked <add> expect(dependency).to be_pinned <add> <add> fi = described_class.new(dependent) <add> <add> expect { <add> fi.check_install_sanity <add> }.to raise_error(CannotInstallFormulaError) <add> end <ide> end <ide> <ide> specify "install fails with BuildError when a system() call fails" do
1
Javascript
Javascript
remove unused var from test-assert.js
686a85ff43471e66b1ba071a4710f362b2ccac0a
<ide><path>test/parallel/test-assert.js <ide> assert.throws(makeBlock(a.deepStrictEqual, new Boolean(true), {}), <ide> function thrower(errorConstructor) { <ide> throw new errorConstructor('test'); <ide> } <del>var aethrow = makeBlock(thrower, a.AssertionError); <del>aethrow = makeBlock(thrower, a.AssertionError); <ide> <ide> // the basic calls work <ide> assert.throws(makeBlock(thrower, a.AssertionError),
1
Python
Python
fix bug when channel=1
06c3a804e7d56cc77f76a28ee34aa67a34daedee
<ide><path>keras/backend/tensorflow_backend.py <ide> def batch_normalization(x, mean, var, beta, gamma, axis=-1, epsilon=1e-3): <ide> # The mean / var / beta / gamma may be processed by broadcast <ide> # so it may have extra axes with 1, it is not needed and should be removed <ide> if ndim(mean) > 1: <del> mean = tf.squeeze(mean) <add> mean = tf.reshape(mean, (-1)) <ide> if ndim(var) > 1: <del> var = tf.squeeze(var) <add> var = tf.reshape(var, (-1)) <ide> if beta is None: <ide> beta = zeros_like(mean) <ide> elif ndim(beta) > 1: <del> beta = tf.squeeze(beta) <add> beta = tf.reshape(beta, (-1)) <ide> if gamma is None: <ide> gamma = ones_like(mean) <ide> elif ndim(gamma) > 1: <del> gamma = tf.squeeze(gamma) <add> gamma = tf.reshape(gamma, (-1)) <ide> y, _, _ = tf.nn.fused_batch_norm( <ide> x, <ide> gamma, <ide><path>tests/keras/layers/normalization_test.py <ide> def test_basic_batchnorm(): <ide> kwargs={'momentum': 0.9, <ide> 'epsilon': 0.1, <ide> 'axis': 1}, <del> input_shape=(3, 4, 2)) <add> input_shape=(1, 4, 1)) <ide> layer_test(normalization.BatchNormalization, <ide> kwargs={'gamma_initializer': 'ones', <ide> 'beta_initializer': 'ones',
2
Python
Python
fix error messages in training.py
8766c22d198be8484ba58bb8ffe4aca8770aa2c0
<ide><path>keras/engine/training.py <ide> def get_layer(self, name=None, index=None): <ide> <ide> if index is not None: <ide> if len(self.layers) <= index: <del> raise ValueError(f'Was asked to retrieve layer at index {str(index)}' <del> f' but model only has {str(len(self.layers))}' <add> raise ValueError(f'Was asked to retrieve layer at index {index}' <add> f' but model only has {len(self.layers)}' <ide> ' layers.') <ide> else: <ide> return self.layers[index] <ide> def get_layer(self, name=None, index=None): <ide> for layer in self.layers: <ide> if layer.name == name: <ide> return layer <del> raise ValueError(f'No such layer: {name}. Existing layers are ' <del> f'{self.layers}.') <add> raise ValueError(f'No such layer: {name}. Existing layers are: ' <add> f'{list(layer.name for layer in self.layers)}.') <ide> raise ValueError('Provide either a layer name or layer index at ' <ide> '`get_layer`.') <ide> <ide> def _check_call_args(self, method_name): <ide> raise ValueError( <ide> f'Models passed to `{method_name}` can only have `training` ' <ide> 'and the first argument in `call()` as positional arguments, ' <del> f'found: {str(extra_args)}.') <add> f'found: {extra_args}.') <ide> <ide> def _validate_compile(self, optimizer, metrics, **kwargs): <ide> """Performs validation checks for the default `compile()`."""
1
Python
Python
add a new hook for google datastore
2fe8f188f64c7144fb7f9e521b827af7d8009be8
<ide><path>airflow/contrib/hooks/datastore_hook.py <add>from apiclient.discovery import build <add>from airflow.contrib.hooks.gc_base_hook import GoogleCloudBaseHook <add> <add>class DatastoreHook(GoogleCloudBaseHook): <add> """ <add> Interact with Google Cloud Datastore. Connections must be defined with an <add> extras JSON field containing: <add> <add> { <add> "project": "<google project ID>", <add> "service_account": "<google service account email>", <add> "key_path": "<p12 key path>" <add> } <add> <add> If you have used ``gcloud auth`` to authenticate on the machine that's <add> running Airflow, you can exclude the service_account and key_path <add> parameters. <add> """ <add> <add> conn_name_attr = 'datastore_conn_id' <add> <add> def __init__(self, <add> scope=['https://www.googleapis.com/auth/datastore', <add> 'https://www.googleapis.com/auth/userinfo.email'], <add> datastore_conn_id='google_cloud_datastore_default', <add> delegate_to=None): <add> super(DatastoreHook, self).__init__(scope, datastore_conn_id, delegate_to) <add> # datasetId is the same as the project name <add> self.datasetId = self._extras_dejson().get('project') <add> <add> def get_conn(self): <add> """ <add> Returns a Google Cloud Storage service object. <add> """ <add> http_authorized = self._authorize() <add> return build('datastore', 'v1beta2', http=http_authorized) <add> <add> def allocate_ids(self, partialKeys): <add> """ <add> Allocate IDs for incomplete keys. <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/allocateIds <add> <add> :param partialKeys: a list of partial keys <add> :return: a list of full keys. <add> """ <add> resp = self.get_conn().datasets().allocateIds(datasetId=self.datasetId, body={'keys': partialKeys}).execute() <add> return resp['keys'] <add> <add> def begin_transaction(self): <add> """ <add> Get a new transaction handle <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/beginTransaction <add> <add> :return: a transaction handle <add> """ <add> resp = self.get_conn().datasets().beginTransaction(datasetId=self.datasetId, body={}).execute() <add> return resp['transaction'] <add> <add> def commit(self, body): <add> """ <add> Commit a transaction, optionally creating, deleting or modifying some entities. <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/commit <add> <add> :param body: the body of the commit request <add> :return: the response body of the commit request <add> """ <add> resp = self.get_conn().datasets().commit(datasetId=self.datasetId, body=body).execute() <add> return resp <add> <add> def lookup(self, keys, read_consistency=None, transaction=None): <add> """ <add> Lookup some entities by key <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/lookup <add> :param keys: the keys to lookup <add> :param read_consistency: the read consistency to use. default, strong or eventual. <add> Cannot be used with a transaction. <add> :param transaction: the transaction to use, if any. <add> :return: the response body of the lookup request. <add> """ <add> body = {'keys': keys} <add> if read_consistency: <add> body['readConsistency'] = read_consistency <add> if transaction: <add> body['transaction'] = transaction <add> return self.get_conn().datasets().lookup(datasetId=self.datasetId, body=body).execute() <add> <add> def rollback(self, transaction): <add> """ <add> Roll back a transaction <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/rollback <add> :param transaction: the transaction to roll back <add> """ <add> self.get_conn().datasets().rollback(datasetId=self.datasetId, body={'transaction': transaction})\ <add> .execute() <add> <add> def run_query(self, body): <add> """ <add> Run a query for entities. <add> see https://cloud.google.com/datastore/docs/apis/v1beta2/datasets/runQuery <add> :param body: the body of the query request <add> :return: the batch of query results. <add> """ <add> resp = self.get_conn().datasets().runQuery(datasetId=self.datasetId, body=body).execute() <add> return resp['batch'] <ide><path>airflow/contrib/hooks/gc_base_hook.py <ide> class GoogleCloudBaseHook(BaseHook): <ide> def __init__(self, scope, conn_id, delegate_to=None): <ide> """ <ide> :param scope: The scope of the hook. <del> :type scope: string <add> :type scope: string or an iterable of strings. <ide> :param conn_id: The connection ID to use when fetching connection info. <ide> :type conn_id: string <ide> :param delegate_to: The account to impersonate, if any. <ide><path>airflow/www/views.py <ide> class ConnectionModelView(wwwutils.SuperUserMixin, AirflowModelView): <ide> form_choices = { <ide> 'conn_type': [ <ide> ('bigquery', 'BigQuery',), <add> ('datastore', 'Google Datastore'), <ide> ('ftp', 'FTP',), <ide> ('google_cloud_storage', 'Google Cloud Storage'), <ide> ('hdfs', 'HDFS',),
3
Javascript
Javascript
upgrade react and react native at the same time
a0f3a93f0ba12df1a1030c4a36e2072eea4b775e
<ide><path>react-native-git-upgrade/cliEntry.js <ide> stdout: ${stdout}`)); <ide> + * - Parsed package.json <ide> + */ <ide> function readPackageFiles() { <del> const nodeModulesPakPath = path.resolve( <add> const reactNativeNodeModulesPakPath = path.resolve( <ide> process.cwd(), <ide> 'node_modules', <ide> 'react-native', <ide> 'package.json' <ide> ); <ide> <add> const reactNodeModulesPakPath = path.resolve( <add> process.cwd(), <add> 'node_modules', <add> 'react', <add> 'package.json' <add> ); <add> <ide> const pakPath = path.resolve( <ide> process.cwd(), <ide> 'package.json' <ide> ); <ide> <ide> try { <del> const nodeModulesPak = JSON.parse(fs.readFileSync(nodeModulesPakPath, 'utf8')); <add> const reactNativeNodeModulesPak = JSON.parse(fs.readFileSync(reactNativeNodeModulesPakPath, 'utf8')); <add> const reactNodeModulesPak = JSON.parse(fs.readFileSync(reactNodeModulesPakPath, 'utf8')); <ide> const pak = JSON.parse(fs.readFileSync(pakPath, 'utf8')); <ide> <del> return {nodeModulesPak, pak}; <add> return {reactNativeNodeModulesPak, reactNodeModulesPak, pak}; <ide> } catch (err) { <ide> throw new Error( <del> 'Unable to find "' + pakPath + '" or "' + nodeModulesPakPath + '". ' + <del> 'Make sure you ran "npm install" and that you are inside a React Native project.' <add> 'Unable to find one of "' + pakPath + '", "' + rnPakPath + '" or "' + reactPakPath + '". ' + <add> 'Make sure you ran "npm install" and that you are inside a React Native project.' <ide> ) <ide> } <ide> } <ide> async function checkForUpdates() { <ide> async function run(requestedVersion, cliArgs) { <ide> const tmpDir = path.resolve(os.tmpdir(), 'react-native-git-upgrade'); <ide> const generatorDir = path.resolve(process.cwd(), 'node_modules', 'react-native', 'local-cli', 'generator'); <add> let projectBackupCreated = false; <ide> <ide> try { <del> let projectBackupCreated = false; <del> <ide> await checkForUpdates(); <ide> <ide> log.info('Read package.json files'); <del> const {nodeModulesPak, pak} = readPackageFiles(); <add> const {reactNativeNodeModulesPak, reactNodeModulesPak, pak} = readPackageFiles(); <ide> const appName = pak.name; <del> const currentVersion = nodeModulesPak.version; <add> const currentVersion = reactNativeNodeModulesPak.version; <add> const currentReactVersion = reactNodeModulesPak.version; <ide> const declaredVersion = pak.dependencies['react-native']; <ide> const declaredReactVersion = pak.dependencies.react; <ide> <ide> async function run(requestedVersion, cliArgs) { <ide> log.info('Check that Git is installed'); <ide> checkGitAvailable(); <ide> <del> log.info('Get react-native version from NPM registry'); <del> const versionOutput = await exec('npm view react-native@' + (requestedVersion || 'latest') + ' version', verbose); <del> const newVersion = semver.clean(versionOutput); <del> log.info('Upgrading to React Native ' + newVersion); <add> log.info('Get information from NPM registry'); <add> const viewCommand = 'npm view react-native@' + (requestedVersion || 'latest') + ' peerDependencies.react version --json'; <add> const viewOutput = await exec(viewCommand, verbose).then(JSON.parse); <add> const newVersion = viewOutput.version; <add> const newReactVersionRange = viewOutput['peerDependencies.react']; <ide> <ide> log.info('Check new version'); <ide> checkNewVersionValid(newVersion, requestedVersion); <ide> async function run(requestedVersion, cliArgs) { <ide> await exec('git commit -m "Old version" --allow-empty', verbose); <ide> <ide> log.info('Install the new version'); <del> await exec('npm install --save react-native@' + newVersion + ' --color=always', verbose); <add> let installCommand = 'npm install --save --color=always'; <add> installCommand += ' react-native@' + newVersion; <add> if (!semver.satisfies(currentReactVersion, newReactVersionRange)) { <add> // Install React as well to avoid unmet peer dependency <add> installCommand += ' react@' + newReactVersionRange; <add> } <add> await exec(installCommand, verbose); <ide> <ide> log.info('Generate new version template'); <ide> await generateTemplates(generatorDir, appName, verbose);
1
Ruby
Ruby
adjust rubocop formatter on ci
9d57bfc9ba34c91817b1740432924e4600d33c5c
<ide><path>Library/Homebrew/style.rb <ide> def run_rubocop(files, output_type, <ide> case output_type <ide> when :print <ide> args << "--debug" if debug <add> <add> if ENV["CI"] <add> # Don't show the default formatter's progress dots on CI. <add> args << "--format" << "clang" <add> end <add> <ide> args << "--color" if Tty.color? <ide> <ide> system cache_env, "rubocop", *args
1
PHP
PHP
fix the definite article on evaluated
b31117aaef08f8432606acdc03dd09813643b63f
<ide><path>src/Illuminate/View/Environment.php <ide> public function __construct(EngineResolver $engines, ViewFinderInterface $finder <ide> } <ide> <ide> /** <del> * Get a evaluated view contents for the given view. <add> * Get the evaluated view contents for the given view. <ide> * <ide> * @param string $view <ide> * @param array $data <ide> protected function parseData($data) <ide> } <ide> <ide> /** <del> * Get a evaluated view contents for a named view. <add> * Get the evaluated view contents for a named view. <ide> * <ide> * @param string $view <ide> * @param mixed $data
1
Text
Text
update text about actions - redux
f1fc7872f4e9d2269be72c47a0baa8f90132c059
<ide><path>guide/portuguese/redux/redux-actions/index.md <ide> title: Redux Actions <ide> localeTitle: Ações do Redux <ide> --- <del>## Ações do Redux <add>## Actions <ide> <del>A ação do Redux é um objeto simples que descreve o tipo de evento que aconteceu em seu aplicativo. Eles podem até conter dados que precisam ser enviados do aplicativo para a loja Redux. A ação pode conter qualquer coisa, mas deve ter um type propriedade que descreve o evento ocorrendo. Uma boa prática é usar constantes ao descrever a ação. <add>Action é um objeto simples que descreve o tipo de evento que aconteceu em seu aplicativo. Eles podem até conter dados que precisam ser enviados do aplicativo para a `store`. Uma action pode conter qualquer coisa, mas deve ter propriedade `type` que descreve o evento ocorrido. Uma boa prática é usar constantes para descrever a ação. <ide> <ide> Por exemplo <ide> <ide> ```javascript <del>const ADD_ITEM = 'ADD_ITEM' <add>const ADD_ITEM = 'ADD_ITEM'; <ide> ``` <ide> <ide> ```javascript <ide> const ADD_ITEM = 'ADD_ITEM' <ide> } <ide> ``` <ide> <del>Podemos enviar essas ações para a loja usando `javascript store.dispatch()` Um aplicativo pode ter diferentes tipos de eventos acontecendo ao mesmo tempo e essas ações ajudam a descrever esses eventos. Sem essas ações, não há como alterar o estado do aplicativo. <add>Podemos enviar essas `actions` para a `store` usando `javascript store.dispatch()`. Um aplicativo pode ter diferentes tipos de eventos acontecendo ao mesmo tempo e as ações ajudam a descrever esses eventos. Sem essas ações, não há como alterar o estado do aplicativo. <ide> <del>Você pode tentar o projeto [redux-actions](https://github.com/redux-utilities/redux-actions) , que reduz muito o clichê, tornando suas ações mais rápidas. <add>Você pode acessar o projeto [redux-actions](https://github.com/redux-utilities/redux-actions), que reduz muito o clichê, tornando suas actions mais rápidas. <ide> <ide> #### Mais Informações: <ide> <del>[Documentos oficiais do Redux de ações](https://redux.js.org/basics/actions) página do projeto github do [redux-actions](https://github.com/redux-utilities/redux-actions) <ide>\ No newline at end of file <add>[Documentos oficiais do Redux de ações](https://redux.js.org/basics/actions) página do projeto github do [redux-actions](https://github.com/redux-utilities/redux-actions)
1
Ruby
Ruby
follow style conventions
a61c4dfa70892d21a96802398605880cfda75c90
<ide><path>activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb <ide> class Simple <ide> # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml <ide> # for details. <ide> def load_translations(*filenames) <del> filenames.each {|filename| load_file filename } <add> filenames.each { |filename| load_file(filename) } <ide> end <ide> <ide> # Stores translations for the given locale in memory. <ide> def store_translations(locale, data) <ide> <ide> def translate(locale, key, options = {}) <ide> raise InvalidLocale.new(locale) if locale.nil? <del> return key.map{|k| translate locale, k, options } if key.is_a? Array <add> return key.map { |k| translate(locale, k, options) } if key.is_a? Array <ide> <ide> reserved = :scope, :default <ide> count, scope, default = options.values_at(:count, *reserved) <ide> options.delete(:default) <del> values = options.reject{|name, value| reserved.include? name } <add> values = options.reject { |name, value| reserved.include?(name) } <ide> <ide> entry = lookup(locale, key, scope) <ide> if entry.nil? <ide> def translate(locale, key, options = {}) <ide> raise(I18n::MissingTranslationData.new(locale, key, options)) <ide> end <ide> end <del> entry = pluralize locale, entry, count <del> entry = interpolate locale, entry, values <add> entry = pluralize(locale, entry, count) <add> entry = interpolate(locale, entry, values) <ide> entry <ide> end <ide> <ide> def interpolate(locale, string, values = {}) <ide> # for all other file extensions. <ide> def load_file(filename) <ide> type = File.extname(filename).tr('.', '').downcase <del> raise UnknownFileType.new(type, filename) unless respond_to? :"load_#{type}" <add> raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}") <ide> data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash <del> data.each{|locale, d| merge_translations locale, d } <add> data.each { |locale, d| merge_translations(locale, d) } <ide> end <ide> <ide> # Loads a plain Ruby translations file. eval'ing the file must yield <ide> # a Hash containing translation data with locales as toplevel keys. <ide> def load_rb(filename) <del> eval IO.read(filename), binding, filename <add> eval(IO.read(filename), binding, filename) <ide> end <ide> <ide> # Loads a YAML translations file. The data must have locales as <ide> # toplevel keys. <ide> def load_yml(filename) <del> YAML::load IO.read(filename) <add> YAML::load(IO.read(filename)) <ide> end <ide> <ide> # Deep merges the given translations hash with the existing translations <ide> # for the given locale <ide> def merge_translations(locale, data) <ide> locale = locale.to_sym <ide> translations[locale] ||= {} <del> data = deep_symbolize_keys data <add> data = deep_symbolize_keys(data) <ide> <ide> # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 <del> merger = proc{|key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } <del> translations[locale].merge! data, &merger <add> merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } <add> translations[locale].merge!(data, &merger) <ide> end <ide> <ide> # Return a new hash with all keys and nested keys converted to symbols. <ide> def deep_symbolize_keys(hash) <del> hash.inject({}){|result, (key, value)| <add> hash.inject({}) { |result, (key, value)| <ide> value = deep_symbolize_keys(value) if value.is_a? Hash <ide> result[(key.to_sym rescue key) || key] = value <ide> result <ide> } <ide> end <ide> end <ide> end <del>end <add>end <ide>\ No newline at end of file
1
Text
Text
add examples to the readme
79a78d37e7102f0aadfa49d89b84b095e86824d1
<ide><path>README.md <ide> Throwaway shell in a base ubuntu image <ide> -------------------------------------- <ide> <ide> ```bash <del># Download a base image <del>docker pull base <add>docker pull ubuntu:12.10 <ide> <del># Run an interactive shell in the base image, <add># Run an interactive shell <ide> # allocate a tty, attach stdin and stdout <del>docker run -i -t base /bin/bash <add>docker run -i -t ubuntu:12.10 /bin/bash <ide> ``` <ide> <ide> Detaching from the interactive shell <ide> Starting a long-running worker process <ide> <ide> ```bash <ide> # Start a very useful long-running process <del>JOB=$(docker run -d base /bin/sh -c "while true; do echo Hello world; sleep 1; done") <add>JOB=$(docker run -d ubuntu /bin/sh -c "while true; do echo Hello world; sleep 1; done") <ide> <ide> # Collect the output of the job so far <ide> docker logs $JOB <ide> docker logs $JOB <ide> docker kill $JOB <ide> ``` <ide> <del> <del>Listing all running containers <del>------------------------------ <add>Run an irc bouncer <add>------------------ <ide> <ide> ```bash <del>docker ps <add>BOUNCER_ID=$(docker run -d -p 6667 -u irc shykes/znc $USER $PASSWORD) <add>echo "Configure your irc client to connect to port $(port $BOUNCER_ID 6667) of this machine" <ide> ``` <ide> <add>Run Redis <add>--------- <add> <add>```bash <add>REDIS_ID=$(docker run -d -p 6379 shykes/redis redis-server) <add>echo "Configure your redis client to connect to port $(port $REDIS_ID 6379) of this machine" <add>``` <ide> <ide> Share your own image! <ide> --------------------- <ide> <ide> ```bash <del>docker pull base <del>CONTAINER=$(docker run -d base apt-get install -y curl) <add>CONTAINER=$(docker run -d ubuntu:12.10 apt-get install -y curl) <ide> docker commit -m "Installed curl" $CONTAINER $USER/betterbase <ide> docker push $USER/betterbase <ide> ```
1
Javascript
Javascript
add mustcall to http-abort-queued test
0fbd852578b11006b2c5c127fefcc879ef7b0f80
<ide><path>test/parallel/test-http-abort-queued.js <ide> const http = require('http'); <ide> <ide> let complete; <ide> <del>const server = http.createServer((req, res) => { <add>const server = http.createServer(common.mustCall((req, res) => { <ide> // We should not see the queued /thatotherone request within the server <ide> // as it should be aborted before it is sent. <ide> assert.strictEqual(req.url, '/'); <ide> const server = http.createServer((req, res) => { <ide> complete = complete || function() { <ide> res.end(); <ide> }; <del>}); <add>})); <ide> <del> <del>server.listen(0, () => { <add>server.listen(0, common.mustCall(() => { <ide> const agent = new http.Agent({ maxSockets: 1 }); <ide> assert.strictEqual(Object.keys(agent.sockets).length, 0); <ide> <ide> server.listen(0, () => { <ide> }); <ide> <ide> req1.end(); <del>}); <add>}));
1
Python
Python
add missing docstrings in image preprocessing
00dc75116f80d81e4cb9bc90e2cffa9b40eed153
<ide><path>keras/preprocessing/image.py <ide> def transform_matrix_offset_center(matrix, x, y): <ide> return transform_matrix <ide> <ide> <del>def apply_transform(x, transform_matrix, channel_axis=0, fill_mode='nearest', cval=0.): <add>def apply_transform(x, <add> transform_matrix, <add> channel_axis=0, <add> fill_mode='nearest', <add> cval=0.): <add> """Apply the image transformation specified by a matrix. <add> <add> # Arguments <add> x: 2D numpy array, single image. <add> transform_matrix: Numpy array specifying the geometric transformation. <add> channel_axis: Index of axis for channels in the input tensor. <add> fill_mode: Points outside the boundaries of the input <add> are filled according to the given mode <add> (one of `{'constant', 'nearest', 'reflect', 'wrap'}`). <add> cval: Value used for points outside the boundaries <add> of the input if `mode='constant'`. <add> <add> # Returns <add> The transformed version of the input. <add> """ <ide> x = np.rollaxis(x, channel_axis, 0) <ide> final_affine_matrix = transform_matrix[:2, :2] <ide> final_offset = transform_matrix[:2, 2] <del> channel_images = [ndi.interpolation.affine_transform(x_channel, final_affine_matrix, <del> final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x] <add> channel_images = [ndi.interpolation.affine_transform( <add> x_channel, <add> final_affine_matrix, <add> final_offset, <add> order=0, <add> mode=fill_mode, <add> cval=cval) for x_channel in x] <ide> x = np.stack(channel_images, axis=0) <ide> x = np.rollaxis(x, 0, channel_axis + 1) <ide> return x <ide> def standardize(self, x): <ide> return x <ide> <ide> def random_transform(self, x): <del> """TODO <add> """Randomly augment a single image tensor. <add> <add> # Arguments <add> x: 3D tensor, single image. <add> <add> # Returns <add> A randomly transformed version of the input (same shape). <ide> """ <ide> # x is a single image, so it doesn't have image number at index 0 <ide> img_row_axis = self.row_axis - 1 <ide> def fit(self, x, <ide> <ide> <ide> class Iterator(object): <add> """Abstract base class for image data iterators. <add> <add> # Arguments <add> n: Integer, total number of samples in the dataset to loop over. <add> batch_size: Integer, size of a batch. <add> shuffle: Boolean, whether to shuffle the data between epochs. <add> seed: Random seeding for data shuffling. <add> """ <ide> <ide> def __init__(self, n, batch_size, shuffle, seed): <ide> self.n = n <ide> def reset(self): <ide> self.batch_index = 0 <ide> <ide> def _flow_index(self, n, batch_size=32, shuffle=False, seed=None): <del> # ensure self.batch_index is 0 <add> # Ensure self.batch_index is 0. <ide> self.reset() <ide> while 1: <ide> if seed is not None: <ide> def _flow_index(self, n, batch_size=32, shuffle=False, seed=None): <ide> current_index, current_batch_size) <ide> <ide> def __iter__(self): <del> # needed if we want to do something like: <add> # Needed if we want to do something like: <ide> # for x, y in data_gen.flow(...): <ide> return self <ide> <ide> def __next__(self, *args, **kwargs): <ide> <ide> <ide> class NumpyArrayIterator(Iterator): <add> """Iterator yielding data from a Numpy array. <add> <add> # Arguments <add> x: Numpy array of input data. <add> y: Numpy array of targets data. <add> image_data_generator: Instance of `ImageDataGenerator` <add> to use for random transformations and normalization. <add> batch_size: Integer, size of a batch. <add> shuffle: Boolean, whether to shuffle the data between epochs. <add> seed: Random seed for data shuffling. <add> data_format: String, one of `channels_first`, `channels_last`. <add> save_to_dir: Optional directory where to save the pictures <add> being yielded, in a viewable format. This is useful <add> for visualizing the random transformations being <add> applied, for debugging purposes. <add> save_prefix: String prefix to use for saving sample <add> images (if `save_to_dir` is set). <add> save_format: Format to use for saving sample images <add> (if `save_to_dir` is set). <add> """ <ide> <ide> def __init__(self, x, y, image_data_generator, <ide> batch_size=32, shuffle=False, seed=None, <ide> def __init__(self, x, y, image_data_generator, <ide> super(NumpyArrayIterator, self).__init__(x.shape[0], batch_size, shuffle, seed) <ide> <ide> def next(self): <del> # for python 2.x. <add> # For python 2.x. Yields the next batch. <ide> # Keeps under lock only the mechanism which advances <del> # the indexing of each batch <del> # see http://anandology.com/blog/using-iterators-and-generators/ <add> # the indexing of each batch. <ide> with self.lock: <ide> index_array, current_index, current_batch_size = next(self.index_generator) <ide> # The transformation of images is not under thread lock <ide> def next(self): <ide> <ide> <ide> class DirectoryIterator(Iterator): <add> """Iterator capable of reading images from a directory on disk. <add> <add> # Arguments <add> directory: Path to the directory to read images from. <add> Each subdirectory in this directory will be <add> considered to contain images from one class, <add> or alternatively you could specify class subdirectories <add> via the `classes` argument. <add> image_data_generator: Instance of `ImageDataGenerator` <add> to use for random transformations and normalization. <add> target_size: tuple of integers, dimensions to resize input images to. <add> color_mode: One of `"rgb"`, `"grayscale"`. Color mode to read images. <add> classes: Optional list of strings, names of sudirectories <add> containing images from each class (e.g. `["dogs", "cats"]`). <add> It will be computed automatically if not set. <add> class_mode: Mode for yielding the targets: <add> `"binary"`: binary targets (if there are only two classes), <add> `"categorical"`: categorical targets, <add> `"sparse"`: integer targets, <add> `None`: no targets get yielded (only input images are yielded). <add> batch_size: Integer, size of a batch. <add> shuffle: Boolean, whether to shuffle the data between epochs. <add> seed: Random seed for data shuffling. <add> data_format: String, one of `channels_first`, `channels_last`. <add> save_to_dir: Optional directory where to save the pictures <add> being yielded, in a viewable format. This is useful <add> for visualizing the random transformations being <add> applied, for debugging purposes. <add> save_prefix: String prefix to use for saving sample <add> images (if `save_to_dir` is set). <add> save_format: Format to use for saving sample images <add> (if `save_to_dir` is set). <add> """ <ide> <ide> def __init__(self, directory, image_data_generator, <ide> target_size=(256, 256), color_mode='rgb', <del> data_format=None, <ide> classes=None, class_mode='categorical', <ide> batch_size=32, shuffle=True, seed=None, <add> data_format=None, <ide> save_to_dir=None, save_prefix='', save_format='jpeg', <ide> follow_links=False): <ide> if data_format is None: <ide> def _recursive_list(subpath): <ide> super(DirectoryIterator, self).__init__(self.samples, batch_size, shuffle, seed) <ide> <ide> def next(self): <add> """For python 2.x. Yields the next batch. <add> """ <ide> with self.lock: <ide> index_array, current_index, current_batch_size = next(self.index_generator) <ide> # The transformation of images is not under thread lock
1
Text
Text
document the switch from memcache-client to dalli
3dd5444e56e009276d24a49f451e860daeafd613
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> Rails 4.0 extracted Active Resource to its own gem. If you still need the featur <ide> <ide> * Rails 4.0 has the removed XML parameters parser. You will need to add the `actionpack-xml_parser` gem if you require this feature. <ide> <add>* Rails 4.0 changes the default memcached client from `memcache-client` to `dalli`. To upgrade, simply add `gem 'dalli'` to your `Gemfile`. <add> <ide> * Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`. <ide> <ide> * Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:
1
PHP
PHP
apply styleci recommendations
26e10c7e57ad309c9e8d7a5766a0c0160890d9bc
<ide><path>src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php <ide> protected function typeYear(Fluent $column) <ide> return $this->typeInteger($column); <ide> } <ide> <del> <ide> /** <ide> * Create the column definition for a date-time type. <ide> *
1
Python
Python
fix mypy errors in amazon aws transfer
b164124bfe15e7ef00c235daa2667e0b4ae82466
<ide><path>airflow/providers/amazon/aws/transfers/ftp_to_s3.py <ide> def __init__( <ide> self.encrypt = encrypt <ide> self.gzip = gzip <ide> self.acl_policy = acl_policy <del> self.s3_hook = None <del> self.ftp_hook = None <add> self.s3_hook: Optional[S3Hook] = None <add> self.ftp_hook: Optional[FTPHook] = None <ide> <ide> def __upload_to_s3_from_ftp(self, remote_filename, s3_file_key): <ide> with NamedTemporaryFile() as local_tmp_file: <ide> def execute(self, context: 'Context'): <ide> if self.ftp_filenames == '*': <ide> files = list_dir <ide> else: <del> files = list(filter(lambda file: self.ftp_filenames in file, list_dir)) <add> ftp_filename: str = self.ftp_filenames <add> files = list(filter(lambda f: ftp_filename in f, list_dir)) <ide> <ide> for file in files: <ide> self.log.info(f'Moving file {file}') <ide> <del> if self.s3_filenames: <add> if self.s3_filenames and isinstance(self.s3_filenames, str): <ide> filename = file.replace(self.ftp_filenames, self.s3_filenames) <ide> else: <ide> filename = file
1
PHP
PHP
use the class name as a table alias
4b83af465d1b13e200f4b02c86e39d6c92374cd4
<ide><path>src/ORM/Association.php <ide> public function target(Table $table = null) <ide> return $this->_targetTable = $table; <ide> } <ide> <add> if ($this->_className) { <add> if (strpos($this->_className, '\\') !== false) { <add> $tableAlias = $this->_name; <add> } else { <add> $tableAlias = $this->_className; <add> } <add> } else { <add> $tableAlias = $this->_name; <add> } <add> <ide> $config = []; <del> if (!TableRegistry::exists($this->_name)) { <add> if (!TableRegistry::exists($tableAlias)) { <ide> $config = ['className' => $this->_className]; <ide> } <del> $this->_targetTable = TableRegistry::get($this->_name, $config); <add> $this->_targetTable = TableRegistry::get($tableAlias, $config); <ide> <ide> return $this->_targetTable; <ide> } <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> public function testTargetPlugin() <ide> $table = $this->association->target(); <ide> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $table); <ide> <del> $this->assertFalse(TableRegistry::exists('TestPlugin.Comments')); <add> $this->assertTrue(TableRegistry::exists('TestPlugin.Comments')); <ide> $this->assertFalse(TableRegistry::exists('Comments')); <del> $this->assertTrue(TableRegistry::exists('ThisAssociationName')); <add> $this->assertFalse(TableRegistry::exists('ThisAssociationName')); <ide> <del> $plugin = TableRegistry::get('ThisAssociationName'); <add> $plugin = TableRegistry::get('TestPlugin.Comments'); <ide> $this->assertSame($table, $plugin, 'Should be the same TestPlugin.Comments object'); <ide> } <ide>
2
Java
Java
implement partial rounded borders
4994d6a389b4e41ba25e802edab5d3fdc9e8a4f1
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java <ide> import android.graphics.PathEffect; <ide> import android.graphics.Rect; <ide> import android.graphics.RectF; <add>import android.graphics.Region; <ide> import android.graphics.drawable.Drawable; <ide> import android.os.Build; <ide> import com.facebook.react.common.annotations.VisibleForTesting; <ide> import javax.annotation.Nullable; <ide> <ide> /** <del> * A subclass of {@link Drawable} used for background of {@link ReactViewGroup}. It supports <del> * drawing background color and borders (including rounded borders) by providing a react friendly <del> * API (setter for each of those properties). <add> * A subclass of {@link Drawable} used for background of {@link ReactViewGroup}. It supports drawing <add> * background color and borders (including rounded borders) by providing a react friendly API <add> * (setter for each of those properties). <ide> * <del> * The implementation tries to allocate as few objects as possible depending on which properties are <del> * set. E.g. for views with rounded background/borders we allocate {@code mPathForBorderRadius} and <del> * {@code mTempRectForBorderRadius}. In case when view have a rectangular borders we allocate <del> * {@code mBorderWidthResult} and similar. When only background color is set we won't allocate any <del> * extra/unnecessary objects. <add> * <p>The implementation tries to allocate as few objects as possible depending on which properties <add> * are set. E.g. for views with rounded background/borders we allocate {@code <add> * mInnerClipPathForBorderRadius} and {@code mInnerClipTempRectForBorderRadius}. In case when view <add> * have a rectangular borders we allocate {@code mBorderWidthResult} and similar. When only <add> * background color is set we won't allocate any extra/unnecessary objects. <ide> */ <ide> public class ReactViewBackgroundDrawable extends Drawable { <ide> <ide> private static enum BorderStyle { <ide> <ide> /* Used for rounded border and rounded background */ <ide> private @Nullable PathEffect mPathEffectForBorderStyle; <del> private @Nullable Path mPathForBorderRadius; <add> private @Nullable Path mInnerClipPathForBorderRadius; <add> private @Nullable Path mOuterClipPathForBorderRadius; <ide> private @Nullable Path mPathForBorderRadiusOutline; <ide> private @Nullable Path mPathForBorder; <del> private @Nullable RectF mTempRectForBorderRadius; <add> private @Nullable RectF mInnerClipTempRectForBorderRadius; <add> private @Nullable RectF mOuterClipTempRectForBorderRadius; <ide> private @Nullable RectF mTempRectForBorderRadiusOutline; <ide> private boolean mNeedUpdatePathForBorderRadius = false; <ide> private float mBorderRadius = YogaConstants.UNDEFINED; <ide> public void setBorderWidth(int position, float width) { <ide> } <ide> if (!FloatUtil.floatsEqual(mBorderWidth.getRaw(position), width)) { <ide> mBorderWidth.set(position, width); <del> if (position == Spacing.ALL) { <del> mNeedUpdatePathForBorderRadius = true; <add> switch (position) { <add> case Spacing.ALL: <add> case Spacing.LEFT: <add> case Spacing.BOTTOM: <add> case Spacing.RIGHT: <add> case Spacing.TOP: <add> mNeedUpdatePathForBorderRadius = true; <ide> } <ide> invalidateSelf(); <ide> } <ide> public int getColor() { <ide> <ide> private void drawRoundedBackgroundWithBorders(Canvas canvas) { <ide> updatePath(); <add> canvas.save(); <add> <ide> int useColor = ColorUtil.multiplyColorAlpha(mColor, mAlpha); <ide> if (Color.alpha(useColor) != 0) { // color is not transparent <ide> mPaint.setColor(useColor); <ide> mPaint.setStyle(Paint.Style.FILL); <del> canvas.drawPath(mPathForBorderRadius, mPaint); <add> canvas.drawPath(mInnerClipPathForBorderRadius, mPaint); <ide> } <del> // maybe draw borders? <del> float fullBorderWidth = getFullBorderWidth(); <del> if (fullBorderWidth > 0) { <add> <add> final float borderWidth = getBorderWidthOrDefaultTo(0, Spacing.ALL); <add> final float borderTopWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.TOP); <add> final float borderBottomWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.BOTTOM); <add> final float borderLeftWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.LEFT); <add> final float borderRightWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.RIGHT); <add> <add> if (borderTopWidth > 0 <add> || borderBottomWidth > 0 <add> || borderLeftWidth > 0 <add> || borderRightWidth > 0) { <ide> int borderColor = getFullBorderColor(); <ide> mPaint.setColor(ColorUtil.multiplyColorAlpha(borderColor, mAlpha)); <del> mPaint.setStyle(Paint.Style.STROKE); <del> mPaint.setStrokeWidth(fullBorderWidth); <del> canvas.drawPath(mPathForBorderRadius, mPaint); <add> mPaint.setStyle(Paint.Style.FILL); <add> <add> // Draw border <add> canvas.clipPath(mOuterClipPathForBorderRadius, Region.Op.INTERSECT); <add> canvas.clipPath(mInnerClipPathForBorderRadius, Region.Op.DIFFERENCE); <add> canvas.drawRect(getBounds(), mPaint); <ide> } <add> <add> canvas.restore(); <ide> } <ide> <ide> private void updatePath() { <ide> if (!mNeedUpdatePathForBorderRadius) { <ide> return; <ide> } <add> <ide> mNeedUpdatePathForBorderRadius = false; <del> if (mPathForBorderRadius == null) { <del> mPathForBorderRadius = new Path(); <del> mTempRectForBorderRadius = new RectF(); <add> <add> if (mInnerClipPathForBorderRadius == null) { <add> mInnerClipPathForBorderRadius = new Path(); <add> } <add> <add> if (mOuterClipPathForBorderRadius == null) { <add> mOuterClipPathForBorderRadius = new Path(); <add> } <add> <add> if (mPathForBorderRadiusOutline == null) { <ide> mPathForBorderRadiusOutline = new Path(); <add> } <add> <add> if (mInnerClipTempRectForBorderRadius == null) { <add> mInnerClipTempRectForBorderRadius = new RectF(); <add> } <add> <add> if (mOuterClipTempRectForBorderRadius == null) { <add> mOuterClipTempRectForBorderRadius = new RectF(); <add> } <add> <add> if (mTempRectForBorderRadiusOutline == null) { <ide> mTempRectForBorderRadiusOutline = new RectF(); <ide> } <ide> <del> mPathForBorderRadius.reset(); <add> mInnerClipPathForBorderRadius.reset(); <add> mOuterClipPathForBorderRadius.reset(); <ide> mPathForBorderRadiusOutline.reset(); <ide> <del> mTempRectForBorderRadius.set(getBounds()); <add> mInnerClipTempRectForBorderRadius.set(getBounds()); <add> mOuterClipTempRectForBorderRadius.set(getBounds()); <ide> mTempRectForBorderRadiusOutline.set(getBounds()); <del> float fullBorderWidth = getFullBorderWidth(); <del> if (fullBorderWidth > 0) { <del> mTempRectForBorderRadius.inset(fullBorderWidth * 0.5f, fullBorderWidth * 0.5f); <del> } <add> <add> final float borderWidth = getBorderWidthOrDefaultTo(0, Spacing.ALL); <add> final float borderTopWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.TOP); <add> final float borderBottomWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.BOTTOM); <add> final float borderLeftWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.LEFT); <add> final float borderRightWidth = getBorderWidthOrDefaultTo(borderWidth, Spacing.RIGHT); <add> <add> mInnerClipTempRectForBorderRadius.top += borderTopWidth; <add> mInnerClipTempRectForBorderRadius.bottom -= borderBottomWidth; <add> mInnerClipTempRectForBorderRadius.left += borderLeftWidth; <add> mInnerClipTempRectForBorderRadius.right -= borderRightWidth; <ide> <ide> final float borderRadius = getFullBorderRadius(); <ide> final float topLeftRadius = <ide> private void updatePath() { <ide> final float bottomRightRadius = <ide> getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_RIGHT); <ide> <del> mPathForBorderRadius.addRoundRect( <del> mTempRectForBorderRadius, <add> mInnerClipPathForBorderRadius.addRoundRect( <add> mInnerClipTempRectForBorderRadius, <add> new float[] { <add> Math.max(topLeftRadius - borderLeftWidth, 0), <add> Math.max(topLeftRadius - borderTopWidth, 0), <add> Math.max(topRightRadius - borderRightWidth, 0), <add> Math.max(topRightRadius - borderTopWidth, 0), <add> Math.max(bottomRightRadius - borderRightWidth, 0), <add> Math.max(bottomRightRadius - borderBottomWidth, 0), <add> Math.max(bottomLeftRadius - borderLeftWidth, 0), <add> Math.max(bottomLeftRadius - borderBottomWidth, 0), <add> }, <add> Path.Direction.CW); <add> <add> mOuterClipPathForBorderRadius.addRoundRect( <add> mOuterClipTempRectForBorderRadius, <ide> new float[] { <ide> topLeftRadius, <ide> topLeftRadius, <ide> private void updatePath() { <ide> }, <ide> Path.Direction.CW); <ide> <add> <ide> float extraRadiusForOutline = 0; <ide> <ide> if (mBorderWidth != null) { <ide> private void updatePath() { <ide> Path.Direction.CW); <ide> } <ide> <add> public float getBorderWidthOrDefaultTo(final float defaultValue, final int spacingType) { <add> if (mBorderWidth == null) { <add> return defaultValue; <add> } <add> <add> final float width = mBorderWidth.getRaw(spacingType); <add> <add> if (YogaConstants.isUndefined(width)) { <add> return defaultValue; <add> } <add> <add> return width; <add> } <add> <ide> /** <ide> * Set type of border <ide> */ <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java <ide> import com.facebook.react.uimanager.ReactClippingViewGroupHelper; <ide> import com.facebook.react.uimanager.ReactPointerEventsView; <ide> import com.facebook.react.uimanager.ReactZIndexedViewGroup; <add>import com.facebook.react.uimanager.Spacing; <ide> import com.facebook.react.uimanager.ViewGroupDrawingOrderHelper; <ide> import javax.annotation.Nullable; <ide> <ide> protected void dispatchDraw(Canvas canvas) { <ide> float top = 0f; <ide> float right = getWidth(); <ide> float bottom = getHeight(); <del> final float borderWidth = mReactBackgroundDrawable.getFullBorderWidth(); <ide> <del> if (borderWidth != 0f) { <del> left += borderWidth; <del> top += borderWidth; <del> right -= borderWidth; <del> bottom -= borderWidth; <add> final float borderWidth = mReactBackgroundDrawable.getFullBorderWidth(); <add> final float borderTopWidth = <add> mReactBackgroundDrawable.getBorderWidthOrDefaultTo(borderWidth, Spacing.TOP); <add> final float borderBottomWidth = <add> mReactBackgroundDrawable.getBorderWidthOrDefaultTo(borderWidth, Spacing.BOTTOM); <add> final float borderLeftWidth = <add> mReactBackgroundDrawable.getBorderWidthOrDefaultTo(borderWidth, Spacing.LEFT); <add> final float borderRightWidth = <add> mReactBackgroundDrawable.getBorderWidthOrDefaultTo(borderWidth, Spacing.RIGHT); <add> <add> if (borderTopWidth > 0 <add> || borderLeftWidth > 0 <add> || borderBottomWidth > 0 <add> || borderRightWidth > 0) { <add> left += borderLeftWidth; <add> top += borderTopWidth; <add> right -= borderRightWidth; <add> bottom -= borderBottomWidth; <ide> } <ide> <ide> final float borderRadius = mReactBackgroundDrawable.getFullBorderRadius(); <ide> protected void dispatchDraw(Canvas canvas) { <ide> mPath.addRoundRect( <ide> new RectF(left, top, right, bottom), <ide> new float[] { <del> Math.max(topLeftBorderRadius - borderWidth, 0), <del> Math.max(topLeftBorderRadius - borderWidth, 0), <del> Math.max(topRightBorderRadius - borderWidth, 0), <del> Math.max(topRightBorderRadius - borderWidth, 0), <del> Math.max(bottomRightBorderRadius - borderWidth, 0), <del> Math.max(bottomRightBorderRadius - borderWidth, 0), <del> Math.max(bottomLeftBorderRadius - borderWidth, 0), <del> Math.max(bottomLeftBorderRadius - borderWidth, 0), <add> Math.max(topLeftBorderRadius - borderLeftWidth, 0), <add> Math.max(topLeftBorderRadius - borderTopWidth, 0), <add> Math.max(topRightBorderRadius - borderRightWidth, 0), <add> Math.max(topRightBorderRadius - borderTopWidth, 0), <add> Math.max(bottomRightBorderRadius - borderRightWidth, 0), <add> Math.max(bottomRightBorderRadius - borderBottomWidth, 0), <add> Math.max(bottomLeftBorderRadius - borderLeftWidth, 0), <add> Math.max(bottomLeftBorderRadius - borderBottomWidth, 0), <ide> }, <ide> Path.Direction.CW); <ide> canvas.clipPath(mPath);
2
PHP
PHP
add support for field metadata retrieval
c98e544dc2ea58c9f54b3c17782190e0143a40ff
<ide><path>lib/Cake/Model/Datasource/Database/Connection.php <ide> public function describe($table) { <ide> list($sql, $params) = $this->_driver->describeTableSql($table); <ide> $statement = $this->execute($sql, $params); <ide> $schema = []; <del> // TODO complete. <del> // TODO add tableParameters for platform specific features. <add> <add> $fieldParams = $this->_driver->extraSchemaColumns(); <add> <ide> while ($row = $statement->fetch('assoc')) { <ide> list($type, $length) = $this->_driver->columnType($row['Type']); <ide> $schema[$row['Field']] = [ <ide> public function describe($table) { <ide> if (!empty($row['Key'])) { <ide> $schema[$row['Field']]['key'] = $this->_driver->keyType($row['Key']); <ide> } <add> foreach ($fieldParams as $key => $metadata) { <add> if (!empty($row[$metadata['column']])) { <add> $schema[$row['Field']][$key] = $row[$metadata['column']]; <add> } <add> } <ide> } <ide> return $schema; <ide> } <ide><path>lib/Cake/Model/Datasource/Database/Dialect/MysqlDialectTrait.php <ide> public function columnType($column) { <ide> return 'text'; <ide> } <ide> <add>/** <add> * Get additional column meta data used in schema reflections. <add> * <add> * @return array <add> */ <add> public function extraSchemaColumns() { <add> return [ <add> 'charset' => [ <add> 'column' => false, <add> ], <add> 'collate' => [ <add> 'column' => 'Collation', <add> ], <add> 'comment' => [ <add> 'column' => 'Comment', <add> ] <add> ]; <add> } <add> <ide> } <ide><path>lib/Cake/Model/Datasource/Database/SqlDialectTrait.php <ide> public function rollbackSavePointSQL($name) { <ide> return 'ROLLBACK TO SAVEPOINT LEVEL' . $name; <ide> } <ide> <add>/** <add> * Get extra schema metadata columns <add> * <add> * This method returns information about additional metadata present in the data <add> * generated by describeTableSql <add> * <add> * @return void <add> */ <add> abstract function extraSchemaColumns(); <add> <ide> } <ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/Driver/MysqlTest.php <ide> protected function _createTables($connection) { <ide> body TEXT, <ide> author_id INT(11) NOT NULL, <ide> created DATETIME <del>) <add>) COLLATE=utf8_general_ci <ide> SQL; <ide> $connection->execute($table); <ide> } <ide> public function testDescribeTable() { <ide> 'null' => true, <ide> 'default' => null, <ide> 'length' => 20, <add> 'collate' => 'utf8_general_ci', <ide> ], <ide> 'body' => [ <ide> 'type' => 'text', <ide> 'null' => true, <ide> 'default' => null, <ide> 'length' => null, <add> 'collate' => 'utf8_general_ci', <ide> ], <ide> 'author_id' => [ <ide> 'type' => 'integer',
4
Ruby
Ruby
reuse the column integer converter
d64c7c7033843af601c1e1b4b73d9a524020c335
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid.rb <ide> class Integer < Type <ide> def type_cast(value) <ide> return if value.nil? <ide> <del> value.to_i rescue value ? 1 : 0 <add> ConnectionAdapters::Column.value_to_integer value <ide> end <ide> end <ide>
1
Javascript
Javascript
use animation.name for animationclip
e0bf8b370e7c6e5644cb6be58ddf5310a1b1fc84
<ide><path>examples/js/loaders/GLTFLoader.js <ide> THREE.GLTFLoader = ( function () { <ide> <ide> } <ide> <del> return new THREE.AnimationClip( "animation_" + animationId, undefined, tracks ); <add> var name = animation.name !== undefined ? animation.name : "animation_" + animationId; <add> <add> return new THREE.AnimationClip( name, undefined, tracks ); <ide> <ide> } ); <ide>
1
PHP
PHP
add additional test for chaining
7120eed7f516d50f621be87c85bf4d2c82fee24c
<ide><path>tests/Integration/Queue/JobChainingTest.php <ide> <ide> use Illuminate\Bus\Queueable; <ide> use Orchestra\Testbench\TestCase; <add>use Illuminate\Support\Facades\Queue; <add>use Illuminate\Queue\InteractsWithQueue; <ide> use Illuminate\Foundation\Bus\Dispatchable; <ide> use Illuminate\Contracts\Queue\ShouldQueue; <ide> <ide> public function test_jobs_can_be_chained_on_success() <ide> $this->assertTrue(JobChainingTestFirstJob::$ran); <ide> $this->assertTrue(JobChainingTestSecondJob::$ran); <ide> } <add> <add> <add> public function test_jobs_can_be_chained_via_queue() <add> { <add> Queue::connection('sync')->push((new JobChainingTestFirstJob)->then([ <add> new JobChainingTestSecondJob <add> ])); <add> <add> $this->assertTrue(JobChainingTestFirstJob::$ran); <add> $this->assertTrue(JobChainingTestSecondJob::$ran); <add> } <add> <add> <add> public function test_second_job_is_not_fired_if_first_was_already_deleted() <add> { <add> Queue::connection('sync')->push((new JobChainingTestFailingJob)->then([ <add> new JobChainingTestSecondJob <add> ])); <add> <add> $this->assertFalse(JobChainingTestSecondJob::$ran); <add> } <ide> } <ide> <ide> <ide> public function handle() <ide> static::$ran = true; <ide> } <ide> } <add> <add> <add>class JobChainingTestFailingJob implements ShouldQueue <add>{ <add> use Dispatchable, InteractsWithQueue, Queueable; <add> <add> public function handle() <add> { <add> $this->fail(); <add> } <add>}
1
Text
Text
remove unnecessary instructions
d0157938510e59eb96b9ced18dfb6340a4f96b7f
<ide><path>docs/build-instructions/windows.md <ide> * [node.js - 32bit](http://nodejs.org/download/) v0.10.x <ide> * [Python 2.7.x](http://www.python.org/download/) <ide> * [GitHub for Windows](http://windows.github.com/) <del> * Open the Windows GitHub shell (NOT the Standard PowerShell, the shortcut labeled 'Git Shell' - make sure you have logged in at least once to the GitHub for Windows GUI App) <ide> * Log in to the GitHub for Windows GUI App <del> * `$env:Path = $env:Path + ";C:\path\to\atom\repo\node_modules"` <add> * Open the `Git Shell` app which was installed by GitHub for Windows. <ide> <ide> ## Instructions <ide> <ide> ```bat <del> cd C:\Users\<user>\github <ide> git clone https://github.com/atom/atom/ <ide> cd atom <ide> script\build <ide> ``` <del> <add> <ide> ## Why do I have to use GitHub for Windows? Can't I just use my existing Git? <ide> <ide> You totally can! GitHub for Windows's Git Shell just takes less work to set up. You need to have Posix tools in your `%PATH%` (i.e. `grep`, `sed`, et al.), which isn't the default configuration when you install Git. To fix this, you probably need to fiddle with your system PATH.
1
Ruby
Ruby
use rails command in restart task test
05fa6f3db6e2dfe213d05cc2e1fd82a429660fc6
<ide><path>railties/test/application/rake/restart_test.rb <ide> def teardown <ide> teardown_app <ide> end <ide> <del> test "rake restart touches tmp/restart.txt" do <add> test "rails restart touches tmp/restart.txt" do <ide> Dir.chdir(app_path) do <del> `rake restart` <add> `bin/rails restart` <ide> assert File.exist?("tmp/restart.txt") <ide> <ide> prev_mtime = File.mtime("tmp/restart.txt") <ide> sleep(1) <del> `rake restart` <add> `bin/rails restart` <ide> curr_mtime = File.mtime("tmp/restart.txt") <ide> assert_not_equal prev_mtime, curr_mtime <ide> end <ide> end <ide> <del> test "rake restart should work even if tmp folder does not exist" do <add> test "rails restart should work even if tmp folder does not exist" do <ide> Dir.chdir(app_path) do <ide> FileUtils.remove_dir("tmp") <del> `rake restart` <add> `bin/rails restart` <ide> assert File.exist?("tmp/restart.txt") <ide> end <ide> end <ide> <del> test "rake restart removes server.pid also" do <add> test "rails restart removes server.pid also" do <ide> Dir.chdir(app_path) do <ide> FileUtils.mkdir_p("tmp/pids") <ide> FileUtils.touch("tmp/pids/server.pid") <del> `rake restart` <add> `bin/rails restart` <ide> assert_not File.exist?("tmp/pids/server.pid") <ide> end <ide> end
1
Python
Python
add possibility to create users in ldap mode
4e4c0574cdd3689d22e2e7d03521cb82179e0909
<ide><path>airflow/www/views.py <ide> class CustomUserDBModelView(MultiResourceUserMixin, UserDBModelView): <ide> class CustomUserLDAPModelView(MultiResourceUserMixin, UserLDAPModelView): <ide> """Customize permission names for FAB's builtin UserLDAPModelView.""" <ide> <add> _class_permission_name = permissions.RESOURCE_USER <add> <add> class_permission_name_mapping = { <add> 'userinfoedit': permissions.RESOURCE_MY_PROFILE, <add> 'userinfo': permissions.RESOURCE_MY_PROFILE, <add> } <add> <add> method_permission_name = { <add> 'add': 'create', <add> 'userinfo': 'read', <add> 'download': 'read', <add> 'show': 'read', <add> 'list': 'read', <add> 'edit': 'edit', <add> 'userinfoedit': 'edit', <add> 'delete': 'delete', <add> } <add> <add> base_permissions = [ <add> permissions.ACTION_CAN_CREATE, <add> permissions.ACTION_CAN_READ, <add> permissions.ACTION_CAN_EDIT, <add> permissions.ACTION_CAN_DELETE, <add> ] <add> <ide> <ide> class CustomUserOAuthModelView(MultiResourceUserMixin, UserOAuthModelView): <ide> """Customize permission names for FAB's builtin UserOAuthModelView."""
1
Python
Python
fix bad error message in np.memmap
b60f33dd0747574570764ac8072386dccc85dd44
<ide><path>numpy/core/memmap.py <ide> def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, <ide> <ide> bytes = long(offset + size*_dbytes) <ide> <del> if mode == 'w+' or (mode == 'r+' and flen < bytes): <add> if mode in ('w+', 'r+') and flen < bytes: <ide> fid.seek(bytes - 1, 0) <ide> fid.write(b'\0') <ide> fid.flush() <ide><path>numpy/core/tests/test_memmap.py <ide> def test_no_shape(self): <ide> self.tmpfp.write(b'a'*16) <ide> mm = memmap(self.tmpfp, dtype='float64') <ide> assert_equal(mm.shape, (2,)) <add> <add> def test_empty_array(self): <add> # gh-12653 <add> with pytest.raises(ValueError, match='empty file'): <add> memmap(self.tmpfp, shape=(0,4), mode='w+') <add> <add> self.tmpfp.write(b'\0') <add> <add> # ok now the file is not empty <add> memmap(self.tmpfp, shape=(0,4), mode='w+')
2
Text
Text
update gcp to google in docs
4aca72e17cc67ccf719e3d54166dccd391aec3ce
<ide><path>README.md <ide> pip install apache-airflow==1.10.11 \ <ide> --constraint https://raw.githubusercontent.com/apache/airflow/1.10.11/requirements/requirements-python3.7.txt <ide> ``` <ide> <del>2. Installing with extras (for example postgres,gcp) <add>2. Installing with extras (for example postgres,google) <ide> ```bash <del>pip install apache-airflow[postgres,gcp]==1.10.11 \ <add>pip install apache-airflow[postgres,google]==1.10.11 \ <ide> --constraint https://raw.githubusercontent.com/apache/airflow/1.10.11/requirements/requirements-python3.7.txt <ide> ``` <ide>
1
Text
Text
fix code nits in common/readme
ec6ef6bd9aff2606454fbc2b1d2bc374a7a683b0
<ide><path>test/common/README.md <ide> frame. <ide> // padlen is an 8-bit integer giving the number of padding bytes to include <ide> // final is a boolean indicating whether the End-of-stream flag should be set, <ide> // defaults to false. <del>const data = new http2.DataFrame(id, payload, padlen, final); <add>const frame = new http2.DataFrame(id, payload, padlen, final); <ide> <ide> socket.write(frame.data); <ide> ``` <ide> The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a <ide> // padlen is an 8-bit integer giving the number of padding bytes to include <ide> // final is a boolean indicating whether the End-of-stream flag should be set, <ide> // defaults to false. <del>const data = new http2.HeadersFrame(id, http2.kFakeRequestHeaders, <del> padlen, final); <add>const frame = new http2.HeadersFrame(id, payload, padlen, final); <ide> <ide> socket.write(frame.data); <ide> ```
1
Javascript
Javascript
fix use app.use(router) to add sub router
bfd33d8b408961e8f8d83bdb0aca143ce23d5338
<ide><path>server/boot/challenge.js <ide> function getMDNlinks(links) { <ide> } <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var Challenge = app.models.Challenge; <ide> var User = app.models.User; <ide> <ide> module.exports = function(app) { <ide> router.post('/completed-zipline-or-basejump', completedZiplineOrBasejump); <ide> router.post('/completed-bonfire', completedBonfire); <ide> <add> app.use(router); <add> <ide> function returnNextChallenge(req, res, next) { <ide> if (!req.user) { <ide> return res.redirect('../challenges/learn-how-free-code-camp-works'); <ide><path>server/boot/challengeMap.js <ide> var R = require('ramda'), <ide> <ide> module.exports = function(app) { <ide> var User = app.models.User; <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> <ide> router.get('/map', middleware.userMigration, challengeMap); <ide> router.get('/learn-to-code', function(req, res) { <ide> module.exports = function(app) { <ide> res.redirect(301, '/map'); <ide> }); <ide> <add> app.use(router); <add> <ide> function challengeMap(req, res, next) { <ide> var completedList = []; <ide> <ide><path>server/boot/fieldGuide.js <ide> var R = require('ramda'), <ide> resources = require('../resources/resources'); <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var FieldGuide = app.models.FieldGuide; <ide> <ide> router.get('/field-guide/all-articles', showAllFieldGuides); <ide> router.get('/field-guide/:fieldGuideName', returnIndividualFieldGuide); <ide> router.get('/field-guide/', returnNextFieldGuide); <ide> router.post('/completed-field-guide/', completedFieldGuide); <ide> <add> app.use(router); <add> <ide> function returnIndividualFieldGuide(req, res, next) { <ide> var dashedName = req.params.fieldGuideName; <ide> if (req.user) { <ide><path>server/boot/home.js <ide> var message = <ide> 'Learn to Code JavaScript and get a Coding Job by Helping Nonprofits'; <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> router.get('/', index); <ide> <add> app.use(router); <add> <ide> function index(req, res, next) { <ide> if (req.user && !req.user.profile.picture) { <ide> req.user.profile.picture = <ide><path>server/boot/jobs.js <ide> module.exports = function(app) { <ide> var Job = app.models.Job; <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> <ide> router.get('/jobs', jobsDirectory); <add> app.use(router); <ide> <ide> function jobsDirectory(req, res, next) { <ide> Job.find({}, function(err, jobs) { <ide><path>server/boot/nonprofits.js <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var Nonprofit = app.models.Nonprofit; <ide> <ide> router.get('/nonprofits/directory', nonprofitsDirectory); <ide> router.get('/nonprofits/:nonprofitName', returnIndividualNonprofit); <ide> <add> app.use(router); <add> <ide> function nonprofitsDirectory(req, res, next) { <ide> Nonprofit.find( <ide> { where: { estimatedHours: { $gt: 0 } } }, <ide><path>server/boot/passport.js <ide> var passport = require('passport'), <ide> passportConf = require('../../config/passport'); <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var passportOptions = { <ide> successRedirect: '/', <ide> failureRedirect: '/login' <ide> module.exports = function(app) { <ide> res.redirect(req.session.returnTo || '/'); <ide> } <ide> ); <add> <add> app.use(router); <ide> }; <ide><path>server/boot/redirects.js <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> <ide> router.get('/nonprofit-project-instructions', function(req, res) { <ide> res.redirect( <ide> module.exports = function(app) { <ide> 301, '/field-guide/what-is-the-free-code-camp-privacy-policy?' <ide> ); <ide> }); <add> <add> app.use(router); <ide> }; <ide><path>server/boot/story.js <ide> var nodemailer = require('nodemailer'), <ide> secrets = require('../../config/secrets'); <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var User = app.models.User; <ide> var Story = app.models.Story; <ide> <ide> module.exports = function(app) { <ide> router.get('/news/:storyName', returnIndividualStory); <ide> router.post('/stories/upvote/', upvote); <ide> <add> app.use(router); <add> <ide> function hotRank(timeValue, rank) { <ide> /* <ide> * Hotness ranking algorithm: http://amix.dk/blog/post/19588 <ide><path>server/boot/user.js <ide> var _ = require('lodash'), <ide> resources = require('./../resources/resources'); <ide> <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var User = app.models.User; <ide> <ide> router.get('/login', function(req, res) { <ide> module.exports = function(app) { <ide> // Ensure this is the last route! <ide> router.get('/:username', returnUser); <ide> <add> app.use(router); <add> <ide> /** <ide> * GET /signin <ide> * Siginin page. <ide><path>server/boot/utility.js <ide> var Rx = require('rx'), <ide> <ide> var slack = new Slack(secrets.slackHook); <ide> module.exports = function(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> var User = app.models.User; <ide> var Challenge = app.models.Challenge; <ide> var Story = app.models.Store; <ide> module.exports = function(app) { <ide> <ide> router.get('/api/slack', slackInvite); <ide> <add> app.use(router); <add> <ide> function slackInvite(req, res, next) { <ide> if (req.user) { <ide> if (req.user.email) {
11
Ruby
Ruby
create method ruby_file?
0fcdc9ba0726570e29d6ce93956f6a5da4907ba3
<ide><path>Library/Homebrew/tap.rb <ide> def contents <ide> # an array of all {Formula} files of this {Tap}. <ide> def formula_files <ide> @formula_files ||= if formula_dir.directory? <del> formula_dir.children.select { |file| file.extname == ".rb" } <add> formula_dir.children.select(&method(:ruby_file?)) <ide> else <ide> [] <ide> end <ide> def formula_files <ide> # an array of all {Cask} files of this {Tap}. <ide> def cask_files <ide> @cask_files ||= if cask_dir.directory? <del> cask_dir.children.select { |file| file.extname == ".rb" } <add> cask_dir.children.select(&method(:ruby_file?)) <ide> else <ide> [] <ide> end <ide> end <ide> <add> # returns true if the file has a Ruby extension <add> # @private <add> def ruby_file?(file) <add> file.extname == ".rb" <add> end <add> <ide> # return true if given path would present a {Formula} file in this {Tap}. <ide> # accepts both absolute path and relative path (relative to this {Tap}'s path) <ide> # @private <ide> def formula_file?(file) <ide> file = Pathname.new(file) unless file.is_a? Pathname <ide> file = file.expand_path(path) <del> file.extname == ".rb" && file.parent == formula_dir <add> ruby_file?(file) && file.parent == formula_dir <ide> end <ide> <ide> # return true if given path would present a {Cask} file in this {Tap}. <ide> def formula_file?(file) <ide> def cask_file?(file) <ide> file = Pathname.new(file) unless file.is_a? Pathname <ide> file = file.expand_path(path) <del> file.extname == ".rb" && file.parent == cask_dir <add> ruby_file?(file) && file.parent == cask_dir <ide> end <ide> <ide> # an array of all {Formula} names of this {Tap}.
1
Mixed
Go
fix misleading default for `--replicas`
acc93db32bd0d14801db65d6cb0a0e06d7cec2f7
<ide><path>cli/command/service/opts.go <ide> func (d *DurationOpt) String() string { <ide> if d.value != nil { <ide> return d.value.String() <ide> } <del> return "none" <add> return "" <ide> } <ide> <ide> // Value returns the time.Duration <ide> func (i *Uint64Opt) String() string { <ide> if i.value != nil { <ide> return fmt.Sprintf("%v", *i.value) <ide> } <del> return "none" <add> return "" <ide> } <ide> <ide> // Value returns the uint64 <ide><path>cli/command/service/opts_test.go <ide> func TestUint64OptString(t *testing.T) { <ide> assert.Equal(t, opt.String(), "2345678") <ide> <ide> opt = Uint64Opt{} <del> assert.Equal(t, opt.String(), "none") <add> assert.Equal(t, opt.String(), "") <ide> } <ide> <ide> func TestUint64OptSetAndValue(t *testing.T) { <ide><path>docs/reference/commandline/service_create.md <ide> Options: <ide> --env-file list Read in a file of environment variables (default []) <ide> --group list Set one or more supplementary user groups for the container (default []) <ide> --health-cmd string Command to run to check health <del> --health-interval duration Time between running the check (ns|us|ms|s|m|h) (default none) <add> --health-interval duration Time between running the check (ns|us|ms|s|m|h) <ide> --health-retries int Consecutive failures needed to report unhealthy <del> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default none) <add> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) <ide> --help Print usage <ide> --host list Set one or more custom host-to-IP mappings (host:ip) (default []) <ide> --hostname string Container hostname <ide> Options: <ide> --name string Service name <ide> --network list Network attachments (default []) <ide> --no-healthcheck Disable any container-specified HEALTHCHECK <del> -p, --publish list Publish a port as a node port (default []) <del> --replicas uint Number of tasks (default none) <add> -p, --publish port Publish a port as a node port <add> --replicas uint Number of tasks <ide> --reserve-cpu decimal Reserve CPUs (default 0.000) <ide> --reserve-memory bytes Reserve Memory (default 0 B) <ide> --restart-condition string Restart when condition is met (none, on-failure, or any) <del> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) (default none) <del> --restart-max-attempts uint Maximum number of restarts before giving up (default none) <del> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) (default none) <del> --secret value Specify secrets to expose to the service (default []) <del> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) (default none) <add> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) <add> --restart-max-attempts uint Maximum number of restarts before giving up <add> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) <add> --secret secret Specify secrets to expose to the service <add> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) <ide> -t, --tty Allocate a pseudo-TTY <ide> --update-delay duration Delay between updates (ns|us|ms|s|m|h) (default 0s) <ide> --update-failure-action string Action on update failure (pause|continue) (default "pause") <ide><path>docs/reference/commandline/service_update.md <ide> Options: <ide> --group-add list Add an additional supplementary user group to the container (default []) <ide> --group-rm list Remove a previously added supplementary user group from the container (default []) <ide> --health-cmd string Command to run to check health <del> --health-interval duration Time between running the check (ns|us|ms|s|m|h) (default none) <add> --health-interval duration Time between running the check (ns|us|ms|s|m|h) <ide> --health-retries int Consecutive failures needed to report unhealthy <del> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default none) <add> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) <ide> --help Print usage <ide> --host-add list Add or update a custom host-to-IP mapping (host:ip) (default []) <ide> --host-rm list Remove a custom host-to-IP mapping (host:ip) (default []) <ide> Options: <ide> --mount-add mount Add or update a mount on a service <ide> --mount-rm list Remove a mount by its target path (default []) <ide> --no-healthcheck Disable any container-specified HEALTHCHECK <del> --publish-add list Add or update a published port (default []) <del> --publish-rm list Remove a published port by its target port (default []) <del> --replicas uint Number of tasks (default none) <add> --publish-add port Add or update a published port <add> --publish-rm port Remove a published port by its target port <add> --replicas uint Number of tasks <ide> --reserve-cpu decimal Reserve CPUs (default 0.000) <ide> --reserve-memory bytes Reserve Memory (default 0 B) <ide> --restart-condition string Restart when condition is met (none, on-failure, or any) <del> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) (default none) <del> --restart-max-attempts uint Maximum number of restarts before giving up (default none) <del> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) (default none) <add> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) <add> --restart-max-attempts uint Maximum number of restarts before giving up <add> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) <ide> --rollback Rollback to previous specification <del> --secret-add list Add a secret (default []) <add> --secret-add secret Add or update a secret on a service <ide> --secret-rm list Remove a secret (default []) <del> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) (default none) <add> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) <ide> -t, --tty Allocate a pseudo-TTY <ide> --update-delay duration Delay between updates (ns|us|ms|s|m|h) (default 0s) <ide> --update-failure-action string Action on update failure (pause|continue) (default "pause")
4
Python
Python
add new unit tests for structure assignment
6752d5fb21c7aad538b3ab2c638dd52e38ed6f2a
<ide><path>numpy/core/tests/test_dtype.py <ide> def test_bad_param(self): <ide> 'formats':['i1', 'f4'], <ide> 'offsets':[0, 2]}, align=True) <ide> <add> def test_field_order_equality(self): <add> x = np.dtype({'names': ['A', 'B'], <add> 'formats': ['i4', 'f4'], <add> 'offsets': [0, 4]}) <add> y = np.dtype({'names': ['B', 'A'], <add> 'formats': ['f4', 'i4'], <add> 'offsets': [4, 0]}) <add> assert_equal(x == y, False) <add> <ide> class TestRecord(object): <ide> def test_equivalent_record(self): <ide> """Test whether equivalent record dtypes hash the same.""" <ide><path>numpy/core/tests/test_indexing.py <ide> def test_empty_tuple_index(self): <ide> a = np.array(0) <ide> assert_(isinstance(a[()], np.int_)) <ide> <add> def test_void_scalar_empty_tuple(self): <add> s = np.zeros((), dtype='V4') <add> assert_equal(s[()].dtype, s.dtype) <add> assert_equal(s[()], s) <add> assert_equal(type(s[...]), np.ndarray) <add> <ide> def test_same_kind_index_casting(self): <ide> # Indexes should be cast with same-kind and not safe, even if that <ide> # is somewhat unsafe. So test various different code paths. <ide><path>numpy/core/tests/test_multiarray.py <ide> def test_base_attr(self): <ide> b = a[0] <ide> assert_(b.base is a) <ide> <add> def test_assignment(self): <add> def testassign(arr, v): <add> c = arr.copy() <add> c[0] = v # assign using setitem <add> c[1:] = v # assign using "dtype_transfer" code paths <add> return c <add> <add> dt = np.dtype([('foo', 'i8'), ('bar', 'i8')]) <add> arr = np.ones(2, dt) <add> v1 = np.array([(2,3)], dtype=[('foo', 'i8'), ('bar', 'i8')]) <add> v2 = np.array([(2,3)], dtype=[('bar', 'i8'), ('foo', 'i8')]) <add> v3 = np.array([(2,3)], dtype=[('bar', 'i8'), ('baz', 'i8')]) <add> v4 = np.array([(2,)], dtype=[('bar', 'i8')]) <add> v5 = np.array([(2,3)], dtype=[('foo', 'f8'), ('bar', 'f8')]) <add> w = arr.view({'names': ['bar'], 'formats': ['i8'], 'offsets': [8]}) <add> <add> ans = np.array([(2,3),(2,3)], dtype=dt) <add> assert_equal(testassign(arr, v1), ans) <add> assert_equal(testassign(arr, v2), ans) <add> assert_equal(testassign(arr, v3), ans) <add> assert_raises(ValueError, lambda: testassign(arr, v4)) <add> assert_equal(testassign(arr, v5), ans) <add> w[:] = 4 <add> assert_equal(arr, np.array([(1,4),(1,4)], dtype=dt)) <add> <add> # test field-reordering, assignment by position, and self-assignment <add> a = np.array([(1,2,3)], <add> dtype=[('foo', 'i8'), ('bar', 'i8'), ('baz', 'f4')]) <add> a[['foo', 'bar']] = a[['bar', 'foo']] <add> assert_equal(a[0].item(), (2,1,3)) <add> <add> # test that this works even for 'simple_unaligned' structs <add> # (ie, that PyArray_EquivTypes cares about field order too) <add> a = np.array([(1,2)], dtype=[('a', 'i4'), ('b', 'i4')]) <add> a[['a', 'b']] = a[['b', 'a']] <add> assert_equal(a[0].item(), (2,1)) <add> <add> def test_structuredscalar_indexing(self): <add> # test gh-7262 <add> x = np.empty(shape=1, dtype="(2)3S,(2)3U") <add> assert_equal(x[["f0","f1"]][0], x[0][["f0","f1"]]) <add> assert_equal(x[0], x[0][()]) <ide> <ide> class TestBool(object): <ide> def test_test_interning(self): <ide><path>numpy/ma/tests/test_core.py <ide> def test_check_on_fields(self): <ide> fill_val = np.array((-999, -12345678.9, "???"), <ide> dtype=[("A", int), ("B", float), ("C", "|S3")]) <ide> fval = _check_fill_value(fill_val, ndtype) <del> self.assertTrue(isinstance(fval, ndarray)) <add> assert_(isinstance(fval, ndarray)) <ide> assert_equal(fval.item(), [-999, -12345678.9, b"???"]) <ide> <ide> #.....Using an object-array shouldn't matter either
4
Ruby
Ruby
add headers option to urls in forumlas
38da4dcac02d70f5518115bf8c2a9f3a5d4e4810
<ide><path>Library/Homebrew/download_strategy.rb <ide> def _curl_args <ide> <ide> args += ["--header", meta.fetch(:header)] if meta.key?(:header) <ide> <add> meta.fetch(:headers).each { |h| args += ["--header", h.strip] } if meta.key?(:headers) <add> <ide> args <ide> end <ide>
1
Javascript
Javascript
fix coding style in web/compatibility.js
665b862b7f0f9d3f3cfbece0f3636cc59d5a1b2a
<ide><path>web/compatibility.js <ide> if (typeof PDFJS === 'undefined') { <ide> } <ide> <ide> // some mobile version might not support Float64Array <del> if (typeof Float64Array === 'undefined') <add> if (typeof Float64Array === 'undefined') { <ide> window.Float64Array = Float32Array; <del> <add> } <ide> return; <ide> } <ide> <ide> if (typeof PDFJS === 'undefined') { <ide> } <ide> <ide> function setArrayOffset(array, offset) { <del> if (arguments.length < 2) <add> if (arguments.length < 2) { <ide> offset = 0; <del> for (var i = 0, n = array.length; i < n; ++i, ++offset) <add> } <add> for (var i = 0, n = array.length; i < n; ++i, ++offset) { <ide> this[offset] = array[i] & 0xFF; <add> } <ide> } <ide> <ide> function TypedArray(arg1) { <ide> var result; <ide> if (typeof arg1 === 'number') { <ide> result = []; <del> for (var i = 0; i < arg1; ++i) <add> for (var i = 0; i < arg1; ++i) { <ide> result[i] = 0; <add> } <ide> } else if ('slice' in arg1) { <ide> result = arg1.slice(0); <ide> } else { <ide> if (typeof PDFJS === 'undefined') { <ide> result.byteLength = result.length; <ide> result.set = setArrayOffset; <ide> <del> if (typeof arg1 === 'object' && arg1.buffer) <add> if (typeof arg1 === 'object' && arg1.buffer) { <ide> result.buffer = arg1.buffer; <del> <add> } <ide> return result; <ide> } <ide> <ide> if (typeof PDFJS === 'undefined') { <ide> <ide> // Object.create() ? <ide> (function checkObjectCreateCompatibility() { <del> if (typeof Object.create !== 'undefined') <add> if (typeof Object.create !== 'undefined') { <ide> return; <add> } <ide> <ide> Object.create = function objectCreate(proto) { <ide> function Constructor() {} <ide> if (typeof PDFJS === 'undefined') { <ide> } catch (e) { <ide> definePropertyPossible = false; <ide> } <del> if (definePropertyPossible) return; <add> if (definePropertyPossible) { <add> return; <add> } <ide> } <ide> <ide> Object.defineProperty = function objectDefineProperty(obj, name, def) { <ide> delete obj[name]; <del> if ('get' in def) <add> if ('get' in def) { <ide> obj.__defineGetter__(name, def['get']); <del> if ('set' in def) <add> } <add> if ('set' in def) { <ide> obj.__defineSetter__(name, def['set']); <add> } <ide> if ('value' in def) { <ide> obj.__defineSetter__(name, function objectDefinePropertySetter(value) { <ide> this.__defineGetter__(name, function objectDefinePropertyGetter() { <ide> if (typeof PDFJS === 'undefined') { <ide> <ide> // Object.keys() ? <ide> (function checkObjectKeysCompatibility() { <del> if (typeof Object.keys !== 'undefined') <add> if (typeof Object.keys !== 'undefined') { <ide> return; <add> } <ide> <ide> Object.keys = function objectKeys(obj) { <ide> var result = []; <ide> for (var i in obj) { <del> if (obj.hasOwnProperty(i)) <add> if (obj.hasOwnProperty(i)) { <ide> result.push(i); <add> } <ide> } <ide> return result; <ide> }; <ide> })(); <ide> <ide> // No readAsArrayBuffer ? <ide> (function checkFileReaderReadAsArrayBuffer() { <del> if (typeof FileReader === 'undefined') <add> if (typeof FileReader === 'undefined') { <ide> return; // FileReader is not implemented <add> } <ide> var frPrototype = FileReader.prototype; <ide> // Older versions of Firefox might not have readAsArrayBuffer <del> if ('readAsArrayBuffer' in frPrototype) <add> if ('readAsArrayBuffer' in frPrototype) { <ide> return; // readAsArrayBuffer is implemented <add> } <ide> Object.defineProperty(frPrototype, 'readAsArrayBuffer', { <ide> value: function fileReaderReadAsArrayBuffer(blob) { <ide> var fileReader = new FileReader(); <ide> if (typeof PDFJS === 'undefined') { <ide> var buffer = new ArrayBuffer(data.length); <ide> var uint8Array = new Uint8Array(buffer); <ide> <del> for (var i = 0, ii = data.length; i < ii; i++) <add> for (var i = 0, ii = data.length; i < ii; i++) { <ide> uint8Array[i] = data.charCodeAt(i); <add> } <ide> <ide> Object.defineProperty(originalReader, 'result', { <ide> value: buffer, <ide> if (typeof PDFJS === 'undefined') { <ide> if ('response' in xhrPrototype || <ide> 'mozResponseArrayBuffer' in xhrPrototype || <ide> 'mozResponse' in xhrPrototype || <del> 'responseArrayBuffer' in xhrPrototype) <add> 'responseArrayBuffer' in xhrPrototype) { <ide> return; <add> } <ide> // IE9 ? <ide> if (typeof VBArray !== 'undefined') { <ide> Object.defineProperty(xhrPrototype, 'response', { <ide> if (typeof PDFJS === 'undefined') { <ide> var text = this.responseText; <ide> var i, n = text.length; <ide> var result = new Uint8Array(n); <del> for (i = 0; i < n; ++i) <add> for (i = 0; i < n; ++i) { <ide> result[i] = text.charCodeAt(i) & 0xFF; <add> } <ide> return result; <ide> } <ide> Object.defineProperty(xhrPrototype, 'response', { get: responseGetter }); <ide> })(); <ide> <ide> // window.btoa (base64 encode function) ? <ide> (function checkWindowBtoaCompatibility() { <del> if ('btoa' in window) <add> if ('btoa' in window) { <ide> return; <add> } <ide> <ide> var digits = <ide> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; <ide> if (typeof PDFJS === 'undefined') { <ide> <ide> // window.atob (base64 encode function) ? <ide> (function checkWindowAtobCompatibility() { <del> if ('atob' in window) <add> if ('atob' in window) { <ide> return; <add> } <ide> <ide> // https://github.com/davidchambers/Base64.js <ide> var digits = <ide> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; <ide> window.atob = function (input) { <ide> input = input.replace(/=+$/, ''); <del> if (input.length % 4 == 1) throw new Error('bad atob input'); <add> if (input.length % 4 == 1) { <add> throw new Error('bad atob input'); <add> } <ide> for ( <ide> // initialize result and counters <ide> var bc = 0, bs, buffer, idx = 0, output = ''; <ide> if (typeof PDFJS === 'undefined') { <ide> <ide> // Function.prototype.bind ? <ide> (function checkFunctionPrototypeBindCompatibility() { <del> if (typeof Function.prototype.bind !== 'undefined') <add> if (typeof Function.prototype.bind !== 'undefined') { <ide> return; <add> } <ide> <ide> Function.prototype.bind = function functionPrototypeBind(obj) { <ide> var fn = this, headArgs = Array.prototype.slice.call(arguments, 1); <ide> if (typeof PDFJS === 'undefined') { <ide> // HTMLElement dataset property <ide> (function checkDatasetProperty() { <ide> var div = document.createElement('div'); <del> if ('dataset' in div) <add> if ('dataset' in div) { <ide> return; // dataset property exists <add> } <ide> <ide> Object.defineProperty(HTMLElement.prototype, 'dataset', { <ide> get: function() { <del> if (this._dataset) <add> if (this._dataset) { <ide> return this._dataset; <add> } <ide> <ide> var dataset = {}; <ide> for (var j = 0, jj = this.attributes.length; j < jj; j++) { <ide> var attribute = this.attributes[j]; <del> if (attribute.name.substring(0, 5) != 'data-') <add> if (attribute.name.substring(0, 5) != 'data-') { <ide> continue; <add> } <ide> var key = attribute.name.substring(5).replace(/\-([a-z])/g, <del> function(all, ch) { return ch.toUpperCase(); }); <add> function(all, ch) { <add> return ch.toUpperCase(); <add> }); <ide> dataset[key] = attribute.value; <ide> } <ide> <ide> if (typeof PDFJS === 'undefined') { <ide> // HTMLElement classList property <ide> (function checkClassListProperty() { <ide> var div = document.createElement('div'); <del> if ('classList' in div) <add> if ('classList' in div) { <ide> return; // classList property exists <add> } <ide> <ide> function changeList(element, itemName, add, remove) { <ide> var s = element.className || ''; <ide> var list = s.split(/\s+/g); <del> if (list[0] === '') list.shift(); <add> if (list[0] === '') { <add> list.shift(); <add> } <ide> var index = list.indexOf(itemName); <del> if (index < 0 && add) <add> if (index < 0 && add) { <ide> list.push(itemName); <del> if (index >= 0 && remove) <add> } <add> if (index >= 0 && remove) { <ide> list.splice(index, 1); <add> } <ide> element.className = list.join(' '); <ide> return (index >= 0); <ide> } <ide> if (typeof PDFJS === 'undefined') { <ide> <ide> Object.defineProperty(HTMLElement.prototype, 'classList', { <ide> get: function() { <del> if (this._classList) <add> if (this._classList) { <ide> return this._classList; <add> } <ide> <ide> var classList = Object.create(classListPrototype, { <ide> element: {
1
Mixed
Javascript
add support for line height css values
090196c07c601cdaf5a91ff0ba731cc46945c101
<ide><path>docs/axes/labelling.md <ide> The scale label configuration is nested under the scale configuration in the `sc <ide> | -----| ---- | --------| ----------- <ide> | `display` | `Boolean` | `false` | If true, display the axis title. <ide> | `labelString` | `String` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). <del>| `lineHeight` | `Number` | `` | Height of an individual line of text. If not defined, the font size is used. <add>| `lineHeight` | `Number|String` | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)) <ide> | `fontColor` | Color | `'#666'` | Font color for scale title. <ide> | `fontFamily` | `String` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the scale title, follows CSS font-family options. <ide> | `fontSize` | `Number` | `12` | Font size for scale title. <ide><path>docs/configuration/title.md <ide> The title configuration is passed into the `options.title` namespace. The global <ide> | `fontColor` | Color | `'#666'` | Font color <ide> | `fontStyle` | `String` | `'bold'` | Font style <ide> | `padding` | `Number` | `10` | Number of pixels to add above and below the title text. <del>| `lineHeight` | `Number` | `undefined` | Height of line of text. If not specified, the `fontSize` is used. <add>| `lineHeight` | `Number|String` | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)) <ide> | `text` | `String/String[]` | `''` | Title text to display. If specified as an array, text is rendered on multiple lines. <ide> <ide> ### Position <ide><path>src/core/core.scale.js <ide> defaults._set('scale', { <ide> <ide> // scale label <ide> scaleLabel: { <add> // display property <add> display: false, <add> <ide> // actual label <ide> labelString: '', <ide> <del> // display property <del> display: false, <add> lineHeight: 1.2 <ide> }, <ide> <ide> // label settings <ide> module.exports = function(Chart) { <ide> }; <ide> } <ide> <add> function parseLineHeight(options) { <add> return helpers.options.toLineHeight( <add> helpers.valueOrDefault(options.lineHeight, 1.2), <add> helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize)); <add> } <add> <ide> Chart.Scale = Chart.Element.extend({ <ide> /** <ide> * Get the padding needed for the scale <ide> module.exports = function(Chart) { <ide> var isHorizontal = me.isHorizontal(); <ide> <ide> var tickFont = parseFontOptions(tickOpts); <del> var scaleLabelLineHeight = helpers.valueOrDefault(scaleLabelOpts.lineHeight, parseFontOptions(scaleLabelOpts).size * 1.5); <ide> var tickMarkLength = opts.gridLines.tickMarkLength; <add> var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts); <ide> <ide> // Width <ide> if (isHorizontal) { <ide> module.exports = function(Chart) { <ide> var scaleLabelX; <ide> var scaleLabelY; <ide> var rotation = 0; <del> var halfLineHeight = helpers.valueOrDefault(scaleLabel.lineHeight, scaleLabelFont.size) / 2; <add> var halfLineHeight = parseLineHeight(scaleLabel) / 2; <ide> <ide> if (isHorizontal) { <ide> scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width <ide><path>src/helpers/helpers.options.js <add>'use strict'; <add> <add>/** <add> * @namespace Chart.helpers.options <add> */ <add>module.exports = { <add> /** <add> * Converts the given line height `value` in pixels for a specific font `size`. <add> * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). <add> * @param {Number} size - The font size (in pixels) used to resolve relative `value`. <add> * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid). <add> * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height <add> * @since 2.7.0 <add> */ <add> toLineHeight: function(value, size) { <add> var matches = (''+value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); <add> if (!matches || matches[1] === 'normal') { <add> return size * 1.2; <add> } <add> <add> value = parseFloat(matches[2]); <add> <add> switch (matches[3]) { <add> case 'px': <add> return value; <add> case '%': <add> value /= 100; <add> break; <add> default: <add> break; <add> } <add> <add> return size * value; <add> } <add>}; <ide><path>src/helpers/index.js <ide> module.exports = require('./helpers.core'); <ide> module.exports.easing = require('./helpers.easing'); <ide> module.exports.canvas = require('./helpers.canvas'); <add>module.exports.options = require('./helpers.options'); <ide> module.exports.time = require('./helpers.time'); <ide><path>src/plugins/plugin.title.js <ide> defaults._set('global', { <ide> display: false, <ide> fontStyle: 'bold', <ide> fullWidth: true, <add> lineHeight: 1.2, <ide> padding: 10, <ide> position: 'top', <ide> text: '', <ide> module.exports = function(Chart) { <ide> fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize), <ide> minSize = me.minSize, <ide> lineCount = helpers.isArray(opts.text) ? opts.text.length : 1, <del> lineHeight = valueOrDefault(opts.lineHeight, fontSize), <add> lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize), <ide> textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0; <ide> <ide> if (me.isHorizontal()) { <ide> module.exports = function(Chart) { <ide> fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle), <ide> fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily), <ide> titleFont = helpers.fontString(fontSize, fontStyle, fontFamily), <del> lineHeight = valueOrDefault(opts.lineHeight, fontSize), <add> lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize), <add> offset = lineHeight/2 + opts.padding, <ide> rotation = 0, <ide> titleX, <ide> titleY, <ide> module.exports = function(Chart) { <ide> // Horizontal <ide> if (me.isHorizontal()) { <ide> titleX = left + ((right - left) / 2); // midpoint of the width <del> titleY = top + ((bottom - top) / 2); // midpoint of the height <add> titleY = top + offset; <ide> maxWidth = right - left; <ide> } else { <del> titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2); <add> titleX = opts.position === 'left' ? left + offset : right - offset; <ide> titleY = top + ((bottom - top) / 2); <ide> maxWidth = bottom - top; <ide> rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); <ide><path>test/specs/core.helpers.tests.js <ide> describe('Core helper tests', function() { <ide> }, <ide> position: 'right', <ide> scaleLabel: { <del> labelString: '', <ide> display: false, <add> labelString: '', <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false, <ide> describe('Core helper tests', function() { <ide> }, <ide> position: 'left', <ide> scaleLabel: { <del> labelString: '', <ide> display: false, <add> labelString: '', <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false, <ide><path>test/specs/helpers.options.tests.js <add>'use strict'; <add> <add>describe('Chart.helpers.options', function() { <add> var options = Chart.helpers.options; <add> <add> describe('toLineHeight', function() { <add> it ('should support keyword values', function() { <add> expect(options.toLineHeight('normal', 16)).toBe(16 * 1.2); <add> }); <add> it ('should support unitless values', function() { <add> expect(options.toLineHeight(1.4, 16)).toBe(16 * 1.4); <add> expect(options.toLineHeight('1.4', 16)).toBe(16 * 1.4); <add> }); <add> it ('should support length values', function() { <add> expect(options.toLineHeight('42px', 16)).toBe(42); <add> expect(options.toLineHeight('1.4em', 16)).toBe(16 * 1.4); <add> }); <add> it ('should support percentage values', function() { <add> expect(options.toLineHeight('140%', 16)).toBe(16 * 1.4); <add> }); <add> it ('should fallback to default (1.2) for invalid values', function() { <add> expect(options.toLineHeight(null, 16)).toBe(16 * 1.2); <add> expect(options.toLineHeight(undefined, 16)).toBe(16 * 1.2); <add> expect(options.toLineHeight('foobar', 16)).toBe(16 * 1.2); <add> }); <add> }); <add>}); <ide><path>test/specs/plugin.title.tests.js <ide> describe('Title block tests', function() { <ide> fullWidth: true, <ide> weight: 2000, <ide> fontStyle: 'bold', <add> lineHeight: 1.2, <ide> padding: 10, <ide> text: '' <ide> }); <ide> describe('Title block tests', function() { <ide> <ide> expect(minSize).toEqual({ <ide> width: 400, <del> height: 32 <add> height: 34.4 <ide> }); <ide> }); <ide> <ide> describe('Title block tests', function() { <ide> minSize = title.update(200, 400); <ide> <ide> expect(minSize).toEqual({ <del> width: 32, <add> width: 34.4, <ide> height: 400 <ide> }); <ide> }); <ide> describe('Title block tests', function() { <ide> options.text = ['line1', 'line2']; <ide> options.position = 'left'; <ide> options.display = true; <del> options.lineHeight = 15; <add> options.lineHeight = 1.5; <ide> <ide> var title = new Chart.Title({ <ide> chart: chart, <ide> describe('Title block tests', function() { <ide> var minSize = title.update(200, 400); <ide> <ide> expect(minSize).toEqual({ <del> width: 50, <add> width: 56, <ide> height: 400 <ide> }); <ide> }); <ide> describe('Title block tests', function() { <ide> args: [] <ide> }, { <ide> name: 'translate', <del> args: [300, 66] <add> args: [300, 67.2] <ide> }, { <ide> name: 'rotate', <ide> args: [0] <ide> describe('Title block tests', function() { <ide> args: [] <ide> }, { <ide> name: 'translate', <del> args: [106, 250] <add> args: [117.2, 250] <ide> }, { <ide> name: 'rotate', <ide> args: [-0.5 * Math.PI] <ide> describe('Title block tests', function() { <ide> args: [] <ide> }, { <ide> name: 'translate', <del> args: [126, 250] <add> args: [117.2, 250] <ide> }, { <ide> name: 'rotate', <ide> args: [0.5 * Math.PI] <ide><path>test/specs/scale.category.tests.js <ide> describe('Category scale tests', function() { <ide> }, <ide> position: 'bottom', <ide> scaleLabel: { <add> display: false, <ide> labelString: '', <del> display: false <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false, <ide><path>test/specs/scale.linear.tests.js <ide> describe('Linear Scale', function() { <ide> }, <ide> position: 'left', <ide> scaleLabel: { <del> labelString: '', <ide> display: false, <add> labelString: '', <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false, <ide> describe('Linear Scale', function() { <ide> expect(xScale.paddingBottom).toBeCloseToPixel(0); <ide> expect(xScale.paddingLeft).toBeCloseToPixel(0); <ide> expect(xScale.paddingRight).toBeCloseToPixel(0); <del> expect(xScale.width).toBeCloseToPixel(450); <del> expect(xScale.height).toBeCloseToPixel(46); <add> expect(xScale.width).toBeCloseToPixel(454); <add> expect(xScale.height).toBeCloseToPixel(42); <ide> <ide> expect(yScale.paddingTop).toBeCloseToPixel(0); <ide> expect(yScale.paddingBottom).toBeCloseToPixel(0); <ide> expect(yScale.paddingLeft).toBeCloseToPixel(0); <ide> expect(yScale.paddingRight).toBeCloseToPixel(0); <del> expect(yScale.width).toBeCloseToPixel(48); <del> expect(yScale.height).toBeCloseToPixel(434); <add> expect(yScale.width).toBeCloseToPixel(44); <add> expect(yScale.height).toBeCloseToPixel(438); <ide> }); <ide> <ide> it('should fit correctly when display is turned off', function() { <ide> describe('Linear Scale', function() { <ide> drawBorder: false <ide> }, <ide> scaleLabel: { <del> display: false <add> display: false, <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> display: false, <ide><path>test/specs/scale.logarithmic.tests.js <ide> describe('Logarithmic Scale tests', function() { <ide> }, <ide> position: 'left', <ide> scaleLabel: { <del> labelString: '', <ide> display: false, <add> labelString: '', <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false, <ide><path>test/specs/scale.radialLinear.tests.js <ide> describe('Test the radial linear scale', function() { <ide> }, <ide> position: 'chartArea', <ide> scaleLabel: { <del> labelString: '', <ide> display: false, <add> labelString: '', <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> backdropColor: 'rgba(255,255,255,0.75)', <ide><path>test/specs/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> }, <ide> position: 'bottom', <ide> scaleLabel: { <add> display: false, <ide> labelString: '', <del> display: false <add> lineHeight: 1.2 <ide> }, <ide> ticks: { <ide> beginAtZero: false,
14
Javascript
Javascript
require files directly instead of resolving them
fa03f0b9ccc9ce9fbba64908e4f31374da8fd005
<ide><path>server/render.js <ide> import { renderToString, renderToStaticMarkup } from 'react-dom/server' <ide> import send from 'send' <ide> import generateETag from 'etag' <ide> import fresh from 'fresh' <del>import requireModule from './require' <ide> import getConfig from './config' <ide> import { Router } from '../lib/router' <ide> import { loadGetInitialProps, isResSent } from '../lib/utils' <ide> async function doRender (req, res, pathname, query, { <ide> const pagePath = join(dir, dist, 'dist', 'bundles', 'pages', page) <ide> const documentPath = join(dir, dist, 'dist', 'bundles', 'pages', '_document') <ide> <del> let [Component, Document] = await Promise.all([ <del> requireModule(pagePath), <del> requireModule(documentPath) <del> ]) <add> let Component <add> let Document <add> try { <add> Component = require(pagePath) <add> Document = require(documentPath) <add> } catch (err) { <add> const err = new Error(`Cannot find module`) <add> err.code = 'ENOENT' <add> throw err <add> } <add> <ide> Component = Component.default || Component <ide> Document = Document.default || Document <ide> const asPath = req.url <ide><path>server/require.js <del>import resolve from './resolve' <del> <del>export default async function requireModule (path) { <del> const f = await resolve(path) <del> return require(f) <del>}
2
PHP
PHP
remove console_libs constnat
998cba07592fb66c4494608e35e6231ffbe98977
<ide><path>lib/Cake/Console/ShellDispatcher.php <ide> function __bootstrap() { <ide> include_once CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'templates' . DS . 'skel' . DS . 'Config' . DS . 'core.php'; <ide> App::build(); <ide> } <del> require_once CONSOLE_LIBS . 'ConsoleErrorHandler.php'; <add> require_once CAKE . 'Console' . DS . 'ConsoleErrorHandler.php'; <ide> set_exception_handler(array('ConsoleErrorHandler', 'handleException')); <ide> set_error_handler(array('ConsoleErrorHandler', 'handleError'), Configure::read('Error.level')); <ide> <ide><path>lib/Cake/Test/Case/Console/Command/Task/TemplateTaskTest.php <ide> public function setup() { <ide> $out = $this->getMock('ConsoleOutput', array(), array(), '', false); <ide> $in = $this->getMock('ConsoleInput', array(), array(), '', false); <ide> <del> $this->Task = $this->getMock('TemplateTask', <add> $this->Task = $this->getMock('TemplateTask', <ide> array('in', 'err', 'createFile', '_stop', 'clear'), <ide> array($out, $out, $in) <ide> ); <ide> public function testSet() { <ide> $this->assertEqual($this->Task->templateVars['one'], 'three'); <ide> $this->assertTrue(isset($this->Task->templateVars['four'])); <ide> $this->assertEqual($this->Task->templateVars['four'], 'five'); <del> <add> <ide> $this->Task->templateVars = array(); <ide> $this->Task->set(array(3 => 'three', 4 => 'four')); <ide> $this->Task->set(array(1 => 'one', 2 => 'two')); <ide> public function testFindingInstalledThemesForBake() { <ide> * @return void <ide> */ <ide> public function testGetThemePath() { <del> $defaultTheme = LIBS . dirname(CONSOLE_LIBS) . 'templates' . DS . 'default' .DS; <add> $defaultTheme = LIBS . 'Console' . DS . 'templates' . DS . 'default' .DS; <ide> $this->Task->templatePaths = array('default' => $defaultTheme); <ide> <ide> $this->Task->expects($this->exactly(1))->method('in')->will($this->returnValue('1')); <ide><path>lib/Cake/bootstrap.php <ide> */ <ide> define('IMAGES', WWW_ROOT.'img'.DS); <ide> <del>/** <del> * Path to the console libs direcotry. <del> */ <del> define('CONSOLE_LIBS', CAKE . 'Console' . DS); <del> <ide> /** <ide> * Path to the tests directory. <ide> */
3
Python
Python
improve code quality
004288eac5b4ffbcced7149113150d7cc42df28e
<ide><path>glances/globals.py <ide> import os <ide> import sys <ide> import platform <add>import json <add>from operator import itemgetter <ide> <ide> # OS constants (some libraries/features are OS-dependent) <ide> BSD = sys.platform.find('bsd') != -1 <ide> def safe_makedirs(path): <ide> raise <ide> else: <ide> raise <add> <add> <add>def json_dumps(data): <add> """Return the object data in a JSON format. <add> <add> Manage the issue #815 for Windows OS with UnicodeDecodeError catching. <add> """ <add> try: <add> return json.dumps(data) <add> except UnicodeDecodeError: <add> return json.dumps(data, ensure_ascii=False) <add> <add> <add>def json_dumps_dictlist(data, item): <add> if isinstance(data, dict): <add> try: <add> return json_dumps({item: data[item]}) <add> except: <add> return None <add> elif isinstance(data, list): <add> try: <add> # Source: <add> # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list <add> return json_dumps({item: map(itemgetter(item), data)}) <add> except: <add> return None <add> else: <add> return None <ide><path>glances/plugins/glances_plugin.py <ide> """ <ide> <ide> import re <del>import json <ide> import copy <del>from operator import itemgetter <ide> <add>from glances.globals import json_dumps, json_dumps_dictlist <ide> from glances.compat import iterkeys, itervalues, listkeys, map, mean, nativestr, PY3 <ide> from glances.actions import GlancesActions <ide> from glances.history import GlancesHistory <ide> def is_disabled(self, plugin_name=None): <ide> """Return true if plugin is disabled.""" <ide> return not self.is_enabled(plugin_name=plugin_name) <ide> <del> def _json_dumps(self, d): <del> """Return the object 'd' in a JSON format. <del> <del> Manage the issue #815 for Windows OS <del> """ <del> try: <del> return json.dumps(d) <del> except UnicodeDecodeError: <del> return json.dumps(d, ensure_ascii=False) <del> <ide> def history_enable(self): <ide> return self.args is not None and not self.args.disable_history and self.get_items_history_list() is not None <ide> <ide> def get_stats_history(self, item=None, nb=0): <ide> s = self.get_json_history(nb=nb) <ide> <ide> if item is None: <del> return self._json_dumps(s) <add> return json_dumps(s) <ide> <del> if isinstance(s, dict): <del> try: <del> return self._json_dumps({item: s[item]}) <del> except KeyError as e: <del> logger.error("Cannot get item history {} ({})".format(item, e)) <del> return None <del> elif isinstance(s, list): <del> try: <del> # Source: <del> # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list <del> return self._json_dumps({item: map(itemgetter(item), s)}) <del> except (KeyError, ValueError) as e: <del> logger.error("Cannot get item history {} ({})".format(item, e)) <del> return None <del> else: <del> return None <add> return json_dumps_dictlist(s, item) <ide> <ide> def get_trend(self, item, nb=6): <ide> """Get the trend regarding to the last nb values. <ide> def get_export(self): <ide> <ide> def get_stats(self): <ide> """Return the stats object in JSON format.""" <del> return self._json_dumps(self.stats) <add> return json_dumps(self.stats) <ide> <ide> def get_json(self): <ide> """Return the stats object in JSON format.""" <ide> def get_stats_item(self, item): <ide> <ide> Stats should be a list of dict (processlist, network...) <ide> """ <del> if isinstance(self.stats, dict): <del> try: <del> return self._json_dumps({item: self.stats[item]}) <del> except KeyError as e: <del> logger.error("Cannot get item {} ({})".format(item, e)) <del> return None <del> elif isinstance(self.stats, list): <del> try: <del> # Source: <del> # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list <del> # But https://github.com/nicolargo/glances/issues/1401 <del> return self._json_dumps({item: list(map(itemgetter(item), self.stats))}) <del> except (KeyError, ValueError) as e: <del> logger.error("Cannot get item {} ({})".format(item, e)) <del> return None <del> else: <del> return None <add> return json_dumps_dictlist(self.stats, item) <ide> <ide> def get_stats_value(self, item, value): <ide> """Return the stats object for a specific item=value in JSON format. <ide> def get_stats_value(self, item, value): <ide> if not isinstance(value, int) and value.isdigit(): <ide> value = int(value) <ide> try: <del> return self._json_dumps({value: [i for i in self.stats if i[item] == value]}) <add> return json_dumps({value: [i for i in self.stats if i[item] == value]}) <ide> except (KeyError, ValueError) as e: <ide> logger.error("Cannot get item({})=value({}) ({})".format(item, value, e)) <ide> return None <ide> def get_views(self, item=None, key=None, option=None): <ide> <ide> def get_json_views(self, item=None, key=None, option=None): <ide> """Return the views (in JSON).""" <del> return self._json_dumps(self.get_views(item, key, option)) <add> return json_dumps(self.get_views(item, key, option)) <ide> <ide> def load_limits(self, config): <ide> """Load limits from the configuration file, if it exists.""" <ide> def curse_add_stat(self, key, width=None, header='', display_key=True, separator <ide> <ide> if width is None: <ide> msg_item = header + '{}'.format(key_name) + separator <del> if unit_type == 'float': <del> msg_value = '{:.1f}{}'.format(value, unit_short) + trailer <del> elif 'min_symbol' in self.fields_description[key]: <del> msg_value = ( <del> '{}{}'.format( <del> self.auto_unit(int(value), min_symbol=self.fields_description[key]['min_symbol']), unit_short <del> ) <del> + trailer <del> ) <del> else: <del> msg_value = '{}{}'.format(int(value), unit_short) + trailer <add> msg_template_float = '{:.1f}{}' <add> msg_template = '{}{}' <ide> else: <ide> # Define the size of the message <ide> # item will be on the left <ide> # value will be on the right <ide> msg_item = header + '{:{width}}'.format(key_name, width=width - 7) + separator <del> if unit_type == 'float': <del> msg_value = '{:5.1f}{}'.format(value, unit_short) + trailer <del> elif 'min_symbol' in self.fields_description[key]: <del> msg_value = ( <del> '{:>5}{}'.format( <del> self.auto_unit(int(value), min_symbol=self.fields_description[key]['min_symbol']), unit_short <del> ) <del> + trailer <add> msg_template_float = '{:5.1f}{}' <add> msg_template = '{:>5}{}' <add> <add> if unit_type == 'float': <add> msg_value = msg_template_float.format(value, unit_short) + trailer <add> elif 'min_symbol' in self.fields_description[key]: <add> msg_value = ( <add> msg_template.format( <add> self.auto_unit(int(value), min_symbol=self.fields_description[key]['min_symbol']), unit_short <ide> ) <del> else: <del> msg_value = '{:>5}{}'.format(int(value), unit_short) + trailer <add> + trailer <add> ) <add> else: <add> msg_value = msg_template.format(int(value), unit_short) + trailer <add> <ide> decoration = self.get_views(key=key, option='decoration') <ide> optional = self.get_views(key=key, option='optional') <ide>
2
Python
Python
limit scope to user email only airflow-386
a1c4cd92d536f7bf6617d85df4d197d8adf09d3d
<ide><path>airflow/contrib/auth/backends/github_enterprise_auth.py <ide> def init_app(self, flask_app): <ide> consumer_key=get_config_param('client_id'), <ide> consumer_secret=get_config_param('client_secret'), <ide> # need read:org to get team member list <del> request_token_params={'scope': 'user,read:org'}, <add> request_token_params={'scope': 'user:email,read:org'}, <ide> base_url=self.ghe_host, <ide> request_token_url=None, <ide> access_token_method='POST',
1
Ruby
Ruby
make exists? use bound values
f317cc8bc007978d7b135ddd1acdd7e3d1e582a3
<ide><path>activerecord/lib/active_record/relation/finder_methods.rb <ide> def exists?(conditions = :none) <ide> when Array, Hash <ide> relation = relation.where(conditions) <ide> else <del> relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none <add> if conditions != :none <add> column = columns_hash[primary_key] <add> substitute = connection.substitute_at(column, bind_values.length) <add> relation = where(table[primary_key].eq(substitute)) <add> relation.bind_values += [[column, conditions]] <add> end <ide> end <ide> <ide> connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false <ide><path>activerecord/test/cases/finder_test.rb <ide> def test_exists <ide> assert_equal false, Topic.exists?(45) <ide> assert_equal false, Topic.exists?(Topic.new) <ide> <add> assert_raise(NoMethodError) { Topic.exists?([1,2]) } <add> end <add> <add> def test_exists_fails_when_parameter_has_invalid_type <add> begin <add> assert_equal false, Topic.exists?(("9"*53).to_i) # number that's bigger than int <add> flunk if defined? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter and Topic.connection.is_a? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter # PostgreSQL does raise here <add> rescue ActiveRecord::StatementInvalid <add> # PostgreSQL complains that it can't coerce a numeric that's bigger than int into int <add> rescue Exception <add> flunk <add> end <add> <ide> begin <ide> assert_equal false, Topic.exists?("foo") <add> flunk if defined? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter and Topic.connection.is_a? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter # PostgreSQL does raise here <ide> rescue ActiveRecord::StatementInvalid <ide> # PostgreSQL complains about string comparison with integer field <ide> rescue Exception <ide> flunk <ide> end <del> <del> assert_raise(NoMethodError) { Topic.exists?([1,2]) } <ide> end <ide> <ide> def test_exists_does_not_select_columns_without_alias
2
Python
Python
add test for ticket #298
5a490d046ae11869f1588fc5514c394218c71713
<ide><path>numpy/core/tests/test_regression.py <ide> def check_method_args(self, level=rlevel): <ide> res2 = getattr(N, func)(arr1, arr2) <ide> assert abs(res1-res2).max() < 1e-8, func <ide> <add> def check_mem_lexsort_strings(self, level=rlevel): <add> """Ticket #298""" <add> lst = ['abc','cde','fgh'] <add> N.lexsort((lst,)) <add> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Python
Python
update init_model.py to previous (better) state
a8f4e4990096be4be6922761aae7c73c7f3ce80e
<ide><path>bin/init_model.py <ide> def _read_probs(loc): <ide> return probs, probs['-OOV-'] <ide> <ide> <del>def _read_freqs(loc, max_length=100, min_doc_freq=0, min_freq=200): <add>def _read_freqs(loc, max_length=100, min_doc_freq=5, min_freq=200): <ide> if not loc.exists(): <ide> print("Warning: Frequencies file not found") <ide> return {}, 0.0 <ide> def _read_freqs(loc, max_length=100, min_doc_freq=0, min_freq=200): <ide> else: <ide> file_ = loc.open() <ide> for i, line in enumerate(file_): <del> freq, doc_freq, key = line.split('\t', 2) <add> freq, doc_freq, key = line.rstrip().split('\t', 2) <ide> freq = int(freq) <ide> counts.inc(i+1, freq) <ide> total += freq <ide> def _read_freqs(loc, max_length=100, min_doc_freq=0, min_freq=200): <ide> file_ = loc.open() <ide> probs = {} <ide> for line in file_: <del> freq, doc_freq, key = line.split('\t', 2) <add> freq, doc_freq, key = line.rstrip().split('\t', 2) <ide> doc_freq = int(doc_freq) <ide> freq = int(freq) <ide> if doc_freq >= min_doc_freq and freq >= min_freq and len(key) < max_length: <del># word = literal_eval(key) <del> word = key <add> word = literal_eval(key) <ide> smooth_count = counts.smoother(int(freq)) <del> log_smooth_count = math.log(smooth_count) <del> probs[word] = log_smooth_count - log_total <add> probs[word] = math.log(smooth_count) - log_total <ide> oov_prob = math.log(counts.smoother(0)) - log_total <ide> return probs, oov_prob <ide> <ide> def setup_vocab(get_lex_attr, tag_map, src_dir, dst_dir): <ide> clusters = _read_clusters(src_dir / 'clusters.txt') <ide> probs, oov_prob = _read_probs(src_dir / 'words.sgt.prob') <ide> if not probs: <del> probs, oov_prob = _read_freqs(src_dir / 'freqs.txt') <add> probs, oov_prob = _read_freqs(src_dir / 'freqs.txt.gz') <ide> if not probs: <ide> oov_prob = -20 <ide> else:
1
PHP
PHP
add cookie parsing to convert from psr7 to cakephp
6a72463c72844943638354d86330a2c55e79f982
<ide><path>src/Http/ResponseTransformer.php <ide> public static function toCake(PsrResponse $response) <ide> 'body' => static::getBody($response), <ide> ]; <ide> $cake = new CakeResponse($data); <add> foreach (static::parseCookies($response->getHeader('Set-Cookie')) as $cookie) { <add> $cake->cookie($cookie); <add> } <ide> $cake->header(static::collapseHeaders($response)); <ide> return $cake; <ide> } <ide> protected static function getBody(PsrResponse $response) <ide> return $stream->getContents(); <ide> } <ide> <add> /** <add> * Parse the Set-Cookie headers in a PSR7 response <add> * into the format CakePHP expects. <add> * <add> * @param array $cookieHeader A list of Set-Cookie headers. <add> * @return array Parsed cookie data. <add> */ <add> protected static function parseCookies(array $cookieHeader) <add> { <add> $cookies = []; <add> foreach ($cookieHeader as $cookie) { <add> if (strpos($cookie, '";"') !== false) { <add> $cookie = str_replace('";"', "{__cookie_replace__}", $cookie); <add> $parts = preg_split('/\;[ \t]*/', $cookie); <add> $parts = str_replace("{__cookie_replace__}", '";"', $parts); <add> } else { <add> $parts = preg_split('/\;[ \t]*/', $cookie); <add> } <add> <add> list($name, $value) = explode('=', array_shift($parts), 2); <add> $parsed = compact('name', 'value'); <add> <add> foreach ($parts as $part) { <add> if (strpos($part, '=') !== false) { <add> list($key, $value) = explode('=', $part); <add> } else { <add> $key = $part; <add> $value = true; <add> } <add> <add> $key = strtolower($key); <add> if ($key === 'httponly') { <add> $key = 'httpOnly'; <add> } <add> if ($key === 'expires') { <add> $key = 'expire'; <add> $value = strtotime($value); <add> } <add> if (!isset($parsed[$key])) { <add> $parsed[$key] = $value; <add> } <add> } <add> $cookies[] = $parsed; <add> } <add> return $cookies; <add> } <add> <ide> /** <ide> * Convert a PSR7 Response headers into a flat array <ide> * <ide><path>tests/TestCase/Http/ResponseTransformerTest.php <ide> public function testToCakeBody() <ide> $this->assertSame('A message for you', $result->body()); <ide> } <ide> <add> /** <add> * Test conversion getting cookies. <add> * <add> * @return void <add> */ <add> public function testToCakeCookies() <add> { <add> $cookies = [ <add> 'remember me=1";"1', <add> 'forever=yes; Expires=Wed, 13 Jan 2021 12:30:40 GMT; Path=/some/path; Domain=example.com; HttpOnly; Secure' <add> ]; <add> $psr = new PsrResponse('php://memory', 200, ['Set-Cookie' => $cookies]); <add> $result = ResponseTransformer::toCake($psr); <add> $expected = [ <add> 'name' => 'remember me', <add> 'value' => '1";"1', <add> 'path' => '/', <add> 'domain' => '', <add> 'expire' => 0, <add> 'secure' => false, <add> 'httpOnly' => false, <add> ]; <add> $this->assertEquals($expected, $result->cookie('remember me')); <add> <add> $expected = [ <add> 'name' => 'forever', <add> 'value' => 'yes', <add> 'path' => '/some/path', <add> 'domain' => 'example.com', <add> 'expire' => 1610541040, <add> 'secure' => true, <add> 'httpOnly' => true, <add> ]; <add> $this->assertEquals($expected, $result->cookie('forever')); <add> } <add> <ide> /** <ide> * Test conversion setting the status code. <ide> *
2
Javascript
Javascript
simplify code a little bit
5e46fff39d57fb3695c174d88924dbaad8b45263
<ide><path>lib/SourceMapDevToolPlugin.js <ide> function getTaskForFile(file, chunk, options, compilation) { <ide> file, <ide> asset, <ide> source, <del> sourceMap <add> sourceMap, <add> modules: undefined <ide> }; <ide> } <ide> } <ide> class SourceMapDevToolPlugin { <ide> <ide> compilation.plugin("after-optimize-chunk-assets", function(chunks) { <ide> const moduleToSourceNameMapping = new Map(); <del> let tasks = []; <add> const tasks = []; <ide> <ide> chunks.forEach(function(chunk) { <del> tasks = chunk.files.reduce((queue, file) => { <add> chunk.files.forEach(file => { <ide> if(matchObject(file)) { <ide> const task = getTaskForFile(file, chunk, options, compilation); <ide> <ide> class SourceMapDevToolPlugin { <ide> <ide> task.modules = modules; <ide> <del> queue.push(task); <add> tasks.push(task); <ide> } <ide> } <del> <del> return queue; <del> }, tasks); <add> }); <ide> }); <ide> <ide> const usedNamesSet = new Set(moduleToSourceNameMapping.values());
1
PHP
PHP
appease the stickler
26cbd919740f5cec94561aff6c3c08b830ef55e7
<ide><path>src/Validation/ValidatorAwareTrait.php <ide> */ <ide> namespace Cake\Validation; <ide> <del>use \RuntimeException; <ide> use Cake\Event\EventDispatcherInterface; <add>use RuntimeException; <ide> <ide> /** <ide> * A trait that provides methods for building and
1
Java
Java
allow http delete with request entity
584b831bb9390a49c791d180d023e3a585203215
<ide><path>spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java <ide> import org.apache.http.client.HttpClient; <ide> import org.apache.http.client.config.RequestConfig; <ide> import org.apache.http.client.methods.Configurable; <del>import org.apache.http.client.methods.HttpDelete; <add>import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; <ide> import org.apache.http.client.methods.HttpGet; <ide> import org.apache.http.client.methods.HttpHead; <ide> import org.apache.http.client.methods.HttpOptions; <ide> public void destroy() throws Exception { <ide> this.httpClient.close(); <ide> } <ide> <add> <add> /** <add> * An alternative to {@link org.apache.http.client.methods.HttpDelete} that <add> * extends {@link org.apache.http.client.methods.HttpEntityEnclosingRequestBase} <add> * rather than {@link org.apache.http.client.methods.HttpRequestBase} and <add> * hence allows HTTP delete with a request body. For use with the RestTemplate <add> * exchange methods which allow the combination of HTTP DELETE with entity. <add> * @since 4.1.2 <add> */ <add> private static class HttpDelete extends HttpEntityEnclosingRequestBase { <add> <add> public HttpDelete(URI uri) { <add> super(); <add> setURI(uri); <add> } <add> <add> @Override <add> public String getMethod() { <add> return "DELETE"; <add> } <add> } <ide> } <ide><path>spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java <ide> protected void prepareConnection(HttpURLConnection connection, String httpMethod <ide> else { <ide> connection.setInstanceFollowRedirects(false); <ide> } <del> if ("PUT".equals(httpMethod) || "POST".equals(httpMethod) || "PATCH".equals(httpMethod)) { <add> if ("PUT".equals(httpMethod) || "POST".equals(httpMethod) || <add> "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) { <ide> connection.setDoOutput(true); <ide> } <ide> else { <ide><path>spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.http.client; <ide> <add>import static org.junit.Assert.assertEquals; <add> <add>import java.io.IOException; <add>import java.net.HttpURLConnection; <ide> import java.net.ProtocolException; <add>import java.net.URL; <ide> <ide> import org.junit.Test; <del> <ide> import org.springframework.http.HttpMethod; <ide> <ide> public class BufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { <ide> public void httpMethods() throws Exception { <ide> } <ide> } <ide> <add> @Test <add> public void prepareConnectionWithRequestBody() throws Exception { <add> URL uri = new URL("http://example.com"); <add> testRequestBodyAllowed(uri, "GET", false); <add> testRequestBodyAllowed(uri, "HEAD", false); <add> testRequestBodyAllowed(uri, "OPTIONS", false); <add> testRequestBodyAllowed(uri, "TRACE", false); <add> testRequestBodyAllowed(uri, "PUT", true); <add> testRequestBodyAllowed(uri, "POST", true); <add> testRequestBodyAllowed(uri, "DELETE", true); <add> } <add> <add> private void testRequestBodyAllowed(URL uri, String httpMethod, boolean allowed) throws IOException { <add> HttpURLConnection connection = new TestHttpURLConnection(uri); <add> ((SimpleClientHttpRequestFactory) this.factory).prepareConnection(connection, httpMethod); <add> assertEquals(allowed, connection.getDoOutput()); <add> } <add> <add> <add> private static class TestHttpURLConnection extends HttpURLConnection { <add> <add> public TestHttpURLConnection(URL uri) { <add> super(uri); <add> } <add> <add> @Override <add> public void connect() throws IOException { <add> } <add> <add> @Override <add> public void disconnect() { <add> } <add> <add> @Override <add> public boolean usingProxy() { <add> return false; <add> } <add> } <ide> } <ide><path>spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java <ide> <ide> package org.springframework.http.client; <ide> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertTrue; <add> <ide> import java.net.URI; <ide> <add>import org.apache.http.HttpEntityEnclosingRequest; <ide> import org.apache.http.client.HttpClient; <ide> import org.apache.http.client.config.RequestConfig; <add>import org.apache.http.client.methods.HttpUriRequest; <ide> import org.apache.http.client.protocol.HttpClientContext; <ide> import org.apache.http.impl.client.DefaultHttpClient; <ide> import org.apache.http.impl.client.HttpClientBuilder; <ide> import org.apache.http.params.CoreConnectionPNames; <ide> import org.junit.Test; <del> <ide> import org.springframework.http.HttpMethod; <ide> <del>import static org.junit.Assert.*; <del> <ide> public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { <ide> <ide> @Override <ide> public void assertCustomConfig() throws Exception { <ide> RequestConfig requestConfig = (RequestConfig) config; <ide> assertEquals("Wrong custom connection timeout", 1234, requestConfig.getConnectTimeout()); <ide> assertEquals("Wrong custom socket timeout", 4567, requestConfig.getSocketTimeout()); <add> } <ide> <add> @Test <add> public void createHttpUriRequest() throws Exception { <add> URI uri = new URI("http://example.com"); <add> testRequestBodyAllowed(uri, HttpMethod.GET, false); <add> testRequestBodyAllowed(uri, HttpMethod.HEAD, false); <add> testRequestBodyAllowed(uri, HttpMethod.OPTIONS, false); <add> testRequestBodyAllowed(uri, HttpMethod.TRACE, false); <add> testRequestBodyAllowed(uri, HttpMethod.PUT, true); <add> testRequestBodyAllowed(uri, HttpMethod.POST, true); <add> testRequestBodyAllowed(uri, HttpMethod.PATCH, true); <add> testRequestBodyAllowed(uri, HttpMethod.DELETE, true); <add> <add> } <add> <add> private void testRequestBodyAllowed(URI uri, HttpMethod method, boolean allowed) { <add> HttpUriRequest request = ((HttpComponentsClientHttpRequestFactory) this.factory).createHttpUriRequest(method, uri); <add> assertEquals(allowed, request instanceof HttpEntityEnclosingRequest); <ide> } <add> <ide> }
4
Ruby
Ruby
fix indentation style for private method
06e89c922c770f81c98c68eed9a4bfd96e6770c7
<ide><path>activerecord/test/cases/adapter_test.rb <ide> def test_log_invalid_encoding <ide> <ide> private <ide> <del> def syntax_error_exception_class <del> return Mysql2::Error if defined?(Mysql2) <del> return PG::SyntaxError if defined?(PG) <del> return SQLite3::SQLException if defined?(SQLite3) <del> end <add> def syntax_error_exception_class <add> return Mysql2::Error if defined?(Mysql2) <add> return PG::SyntaxError if defined?(PG) <add> return SQLite3::SQLException if defined?(SQLite3) <add> end <ide> end <ide> <ide> class AdapterForeignKeyTest < ActiveRecord::TestCase
1
PHP
PHP
add click to copy on error text
124a5298abe0e9ef10030e268066209c71683926
<ide><path>templates/layout/dev_error.php <ide> font-size: 30px; <ide> margin: 0; <ide> } <add> .header-title:hover:after { <add> content: attr(data-content); <add> font-size: 18px; <add> vertical-align: middle; <add> cursor: pointer; <add> } <ide> .header-type { <ide> display: block; <ide> font-size: 16px; <ide> </head> <ide> <body> <ide> <header> <del> <h1 class="header-title"> <add> <h1 class="header-title" data-content="&#128203"> <ide> <?= h($this->fetch('title')) ?> <ide> </h1> <ide> <span class="header-type"><?= get_class($error) ?></span> <ide> function each(els, cb) { <ide> }); <ide> event.preventDefault(); <ide> }); <add> <add> bindEvent('.header-title', 'click', function(event) { <add> event.preventDefault(); <add> var text = ''; <add> each(this.childNodes, function(el) { <add> text += el.textContent.trim(); <add> }); <add> <add> // Use execCommand(copy) as it has the widest support. <add> var textArea = document.createElement("textarea"); <add> textArea.value = text; <add> document.body.appendChild(textArea); <add> textArea.focus(); <add> textArea.select(); <add> var el = this; <add> try { <add> document.execCommand('copy'); <add> <add> // Show a success icon and then revert <add> var original = el.getAttribute('data-content'); <add> el.setAttribute('data-content', '\ud83c\udf70'); <add> setTimeout(function () { <add> el.setAttribute('data-content', original); <add> }, 1000); <add> } catch (err) { <add> alert('Unable to update clipboard ' + err); <add> } <add> document.body.removeChild(textArea); <add> this.parentNode.scrollIntoView(true); <add> }); <ide> }); <ide> </script> <ide> </body>
1
PHP
PHP
handle stopexception in shelldispatcher
a723f6b1bae5db403525f731ac2d29353540399c
<ide><path>src/Console/Shell.php <ide> public function hr($newlines = 0, $width = 63) <ide> * @return void <ide> * @link http://book.cakephp.org/3.0/en/console-and-shells.html#styling-output <ide> */ <del> public function abort($message, $exitCode) <add> public function abort($message, $exitCode = self::CODE_ERROR) <ide> { <ide> $this->_io->err('<error>' . $message . '</error>'); <ide> throw new StopException($message, $exitCode); <ide><path>src/Console/ShellDispatcher.php <ide> namespace Cake\Console; <ide> <ide> use Cake\Console\Exception\MissingShellException; <add>use Cake\Console\Exception\StopException; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Exception\Exception; <ide> protected function _bootstrap() <ide> */ <ide> public function dispatch($extra = []) <ide> { <del> $result = $this->_dispatch($extra); <add> try { <add> $result = $this->_dispatch($extra); <add> } catch (StopException $e) { <add> return $e->getCode(); <add> } <ide> if ($result === null || $result === true) { <ide> return 0; <ide> } <ide><path>tests/TestCase/Console/ShellDispatcherTest.php <ide> public function testFindShellAliasedAppShadow() <ide> $this->assertEquals('Sample', $result->name); <ide> } <ide> <add> /** <add> * Verify dispatch handling stop errors <add> * <add> * @return void <add> */ <add> public function testDispatchShellWithAbort() <add> { <add> $io = $this->getMock('Cake\Console\ConsoleIo'); <add> $shell = $this->getMock('Cake\Console\Shell', ['main'], [$io]); <add> $shell->expects($this->once()) <add> ->method('main') <add> ->will($this->returnCallback(function () use ($shell) { <add> $shell->abort('Bad things', 99); <add> })); <add> <add> $dispatcher = $this->getMock('Cake\Console\ShellDispatcher', ['findShell']); <add> $dispatcher->expects($this->any()) <add> ->method('findShell') <add> ->with('aborter') <add> ->will($this->returnValue($shell)); <add> <add> $dispatcher->args = ['aborter']; <add> $result = $dispatcher->dispatch(); <add> $this->assertSame(99, $result, 'Should return the exception error code.'); <add> } <add> <ide> /** <ide> * Verify correct dispatch of Shell subclasses with a main method <ide> *
3
Javascript
Javascript
fix double abortsignal registration
711e210d35b41a7a4b81497affd4ccace1f31d3a
<ide><path>lib/_http_client.js <ide> function ClientRequest(input, options, cb) { <ide> options.headers); <ide> } <ide> <add> let optsWithoutSignal = options; <add> if (optsWithoutSignal.signal) { <add> optsWithoutSignal = ObjectAssign({}, options); <add> delete optsWithoutSignal.signal; <add> } <add> <ide> // initiate connection <ide> if (this.agent) { <del> this.agent.addRequest(this, options); <add> this.agent.addRequest(this, optsWithoutSignal); <ide> } else { <ide> // No agent, default to Connection:close. <ide> this._last = true; <ide> this.shouldKeepAlive = false; <del> if (typeof options.createConnection === 'function') { <add> if (typeof optsWithoutSignal.createConnection === 'function') { <ide> const oncreate = once((err, socket) => { <ide> if (err) { <ide> process.nextTick(() => emitError(this, err)); <ide> function ClientRequest(input, options, cb) { <ide> }); <ide> <ide> try { <del> const newSocket = options.createConnection(options, oncreate); <add> const newSocket = optsWithoutSignal.createConnection(optsWithoutSignal, <add> oncreate); <ide> if (newSocket) { <ide> oncreate(null, newSocket); <ide> } <ide> } catch (err) { <ide> oncreate(err); <ide> } <ide> } else { <del> debug('CLIENT use net.createConnection', options); <del> this.onSocket(net.createConnection(options)); <add> debug('CLIENT use net.createConnection', optsWithoutSignal); <add> this.onSocket(net.createConnection(optsWithoutSignal)); <ide> } <ide> } <ide> } <ide><path>test/parallel/test-http-agent-abort-controller.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add>const Agent = http.Agent; <add>const { getEventListeners, once } = require('events'); <add>const agent = new Agent(); <add>const server = http.createServer(); <add> <add>server.listen(0, common.mustCall(async () => { <add> const port = server.address().port; <add> const host = 'localhost'; <add> const options = { <add> port: port, <add> host: host, <add> _agentKey: agent.getName({ port, host }) <add> }; <add> <add> async function postCreateConnection() { <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const connection = agent.createConnection({ ...options, signal }); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <add> ac.abort(); <add> const [err] = await once(connection, 'error'); <add> assert.strictEqual(err?.name, 'AbortError'); <add> } <add> <add> async function preCreateConnection() { <add> const ac = new AbortController(); <add> const { signal } = ac; <add> ac.abort(); <add> const connection = agent.createConnection({ ...options, signal }); <add> const [err] = await once(connection, 'error'); <add> assert.strictEqual(err?.name, 'AbortError'); <add> } <add> <add> async function agentAsParam() { <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const request = http.get({ <add> port: server.address().port, <add> path: '/hello', <add> agent: agent, <add> signal, <add> }); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <add> ac.abort(); <add> const [err] = await once(request, 'error'); <add> assert.strictEqual(err?.name, 'AbortError'); <add> } <add> <add> async function agentAsParamPreAbort() { <add> const ac = new AbortController(); <add> const { signal } = ac; <add> ac.abort(); <add> const request = http.get({ <add> port: server.address().port, <add> path: '/hello', <add> agent: agent, <add> signal, <add> }); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <add> const [err] = await once(request, 'error'); <add> assert.strictEqual(err?.name, 'AbortError'); <add> } <add> <add> await postCreateConnection(); <add> await preCreateConnection(); <add> await agentAsParam(); <add> await agentAsParamPreAbort(); <add> server.close(); <add>})); <ide><path>test/parallel/test-http-client-abort-destroy.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> const assert = require('assert'); <add>const { getEventListeners } = require('events'); <ide> <ide> { <ide> // abort <ide> const assert = require('assert'); <ide> <ide> <ide> { <del> // Destroy with AbortSignal <add> // Destroy post-abort sync with AbortSignal <ide> <ide> const server = http.createServer(common.mustNotCall()); <ide> const controller = new AbortController(); <del> <add> const { signal } = controller; <ide> server.listen(0, common.mustCall(() => { <del> const options = { port: server.address().port, signal: controller.signal }; <add> const options = { port: server.address().port, signal }; <ide> const req = http.get(options, common.mustNotCall()); <ide> req.on('error', common.mustCall((err) => { <ide> assert.strictEqual(err.code, 'ABORT_ERR'); <ide> assert.strictEqual(err.name, 'AbortError'); <ide> server.close(); <ide> })); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <ide> assert.strictEqual(req.aborted, false); <ide> assert.strictEqual(req.destroyed, false); <ide> controller.abort(); <ide> assert.strictEqual(req.aborted, false); <ide> assert.strictEqual(req.destroyed, true); <ide> })); <ide> } <add> <add>{ <add> // Use post-abort async AbortSignal <add> const server = http.createServer(common.mustNotCall()); <add> const controller = new AbortController(); <add> const { signal } = controller; <add> server.listen(0, common.mustCall(() => { <add> const options = { port: server.address().port, signal }; <add> const req = http.get(options, common.mustNotCall()); <add> req.on('error', common.mustCall((err) => { <add> assert.strictEqual(err.code, 'ABORT_ERR'); <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add> <add> req.on('close', common.mustCall(() => { <add> assert.strictEqual(req.aborted, false); <add> assert.strictEqual(req.destroyed, true); <add> server.close(); <add> })); <add> <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <add> process.nextTick(() => controller.abort()); <add> })); <add>} <add> <add>{ <add> // Use pre-aborted AbortSignal <add> const server = http.createServer(common.mustNotCall()); <add> const controller = new AbortController(); <add> const { signal } = controller; <add> server.listen(0, common.mustCall(() => { <add> controller.abort(); <add> const options = { port: server.address().port, signal }; <add> const req = http.get(options, common.mustNotCall()); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <add> req.on('error', common.mustCall((err) => { <add> assert.strictEqual(err.code, 'ABORT_ERR'); <add> assert.strictEqual(err.name, 'AbortError'); <add> server.close(); <add> })); <add> assert.strictEqual(req.aborted, false); <add> assert.strictEqual(req.destroyed, true); <add> })); <add>} <ide><path>test/parallel/test-http2-client-destroy.js <ide> if (!common.hasCrypto) <ide> const assert = require('assert'); <ide> const h2 = require('http2'); <ide> const { kSocket } = require('internal/http2/util'); <del>const { kEvents } = require('internal/event_target'); <ide> const Countdown = require('../common/countdown'); <del> <add>const { getEventListeners } = require('events'); <ide> { <ide> const server = h2.createServer(); <ide> server.listen(0, common.mustCall(() => { <ide> const Countdown = require('../common/countdown'); <ide> client.on('close', common.mustCall()); <ide> <ide> const { signal } = controller; <del> assert.strictEqual(signal[kEvents].get('abort'), undefined); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <ide> <ide> client.on('error', common.mustCall(() => { <ide> // After underlying stream dies, signal listener detached <del> assert.strictEqual(signal[kEvents].get('abort'), undefined); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <ide> })); <ide> <ide> const req = client.request({}, { signal }); <ide> const Countdown = require('../common/countdown'); <ide> assert.strictEqual(req.aborted, false); <ide> assert.strictEqual(req.destroyed, false); <ide> // Signal listener attached <del> assert.strictEqual(signal[kEvents].get('abort').size, 1); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <ide> <ide> controller.abort(); <ide> <ide> const Countdown = require('../common/countdown'); <ide> const { signal } = controller; <ide> controller.abort(); <ide> <del> assert.strictEqual(signal[kEvents].get('abort'), undefined); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <ide> <ide> client.on('error', common.mustCall(() => { <ide> // After underlying stream dies, signal listener detached <del> assert.strictEqual(signal[kEvents].get('abort'), undefined); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <ide> })); <ide> <ide> const req = client.request({}, { signal }); <ide> // Signal already aborted, so no event listener attached. <del> assert.strictEqual(signal[kEvents].get('abort'), undefined); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <ide> <ide> assert.strictEqual(req.aborted, false); <ide> // Destroyed on same tick as request made <ide><path>test/parallel/test-https-abortcontroller.js <ide> if (!common.hasCrypto) <ide> const fixtures = require('../common/fixtures'); <ide> const https = require('https'); <ide> const assert = require('assert'); <del>const { once } = require('events'); <add>const { once, getEventListeners } = require('events'); <ide> <ide> const options = { <ide> key: fixtures.readKey('agent1-key.pem'), <ide> const options = { <ide> rejectUnauthorized: false, <ide> signal: ac.signal, <ide> }); <add> assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 1); <ide> process.nextTick(() => ac.abort()); <ide> const [ err ] = await once(req, 'error'); <ide> assert.strictEqual(err.name, 'AbortError');
5
Ruby
Ruby
use the trick to get beta releases in the gemfile
c9be5e088c30eedf016ce61ec7236278ac8d1cb1
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def javascript_gemfile_entry <ide> "Use #{options[:javascript]} as the JavaScript library") <ide> <ide> unless options[:skip_turbolinks] <del> gems << GemfileEntry.version("turbolinks", "~> 5.0.0.beta", <add> gems << GemfileEntry.version("turbolinks", "~> 5.x", <ide> "Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks") <ide> end <ide>
1
Ruby
Ruby
check dependencies before download
3fdab5a24d66330c6fd22b384b8cb4e8b2fde02d
<ide><path>Library/Homebrew/cask/installer.rb <ide> def fetch <ide> odebug "Cask::Installer#fetch" <ide> <ide> verify_has_sha if require_sha? && !force? <add> satisfy_dependencies <add> <ide> download <ide> verify <del> <del> satisfy_dependencies <ide> end <ide> <ide> def stage
1
Javascript
Javascript
remove internal uses of beforeobservers
c8f6ecd52885dd4865d9cc3c105da111bd88cd37
<ide><path>packages/ember-runtime/lib/system/array_proxy.js <ide> import { <ide> isArray <ide> } from 'ember-runtime/utils'; <ide> import { computed } from 'ember-metal/computed'; <del>import { <del> _beforeObserver, <del> observer <del>} from 'ember-metal/mixin'; <add>import { observer } from 'ember-metal/mixin'; <ide> import { <ide> beginPropertyChanges, <ide> endPropertyChanges <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> @type Ember.Array <ide> @private <ide> */ <del> content: null, <add> content: computed({ <add> get() { <add> return this._content; <add> }, <add> set(k, v) { <add> if (this._didInitArrayProxy) { <add> var oldContent = this._content; <add> var len = oldContent ? get(oldContent, 'length') : 0; <add> this.arrangedContentArrayWillChange(this, 0, len, undefined); <add> this.arrangedContentWillChange(this); <add> } <add> this._content = v; <add> return v; <add> } <add> }), <add> <add> <ide> <ide> /** <ide> The array that the proxy pretends to be. In the default `ArrayProxy` <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> <ide> @property arrangedContent <ide> @private <del> */ <add> */ <ide> arrangedContent: alias('content'), <ide> <ide> /** <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> get(this, 'content').replace(idx, amt, objects); <ide> }, <ide> <del> /** <del> Invoked when the content property is about to change. Notifies observers that the <del> entire array content will change. <del> <del> @private <del> @method _contentWillChange <del> */ <del> _contentWillChange: _beforeObserver('content', function() { <del> this._teardownContent(); <del> }), <del> <del> _teardownContent() { <del> var content = get(this, 'content'); <del> <add> _teardownContent(content) { <ide> if (content) { <ide> content.removeArrayObserver(this, { <ide> willChange: 'contentArrayWillChange', <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> */ <ide> _contentDidChange: observer('content', function() { <ide> var content = get(this, 'content'); <add> this._teardownContent(this._prevContent); <ide> <ide> Ember.assert('Can\'t set ArrayProxy\'s content to itself', content !== this); <ide> <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> <ide> _setupContent() { <ide> var content = get(this, 'content'); <add> this._prevContent = content; <ide> <ide> if (content) { <ide> Ember.assert(`ArrayProxy expects an Array or Ember.ArrayProxy, but you passed ${typeof content}`, isArray(content) || content.isDestroyed); <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> } <ide> }, <ide> <del> _arrangedContentWillChange: _beforeObserver('arrangedContent', function() { <del> var arrangedContent = get(this, 'arrangedContent'); <del> var len = arrangedContent ? get(arrangedContent, 'length') : 0; <del> <del> this.arrangedContentArrayWillChange(this, 0, len, undefined); <del> this.arrangedContentWillChange(this); <del> <del> this._teardownArrangedContent(arrangedContent); <del> }), <del> <ide> _arrangedContentDidChange: observer('arrangedContent', function() { <add> this._teardownArrangedContent(this._prevArrangedContent); <ide> var arrangedContent = get(this, 'arrangedContent'); <ide> var len = arrangedContent ? get(arrangedContent, 'length') : 0; <ide> <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> <ide> _setupArrangedContent() { <ide> var arrangedContent = get(this, 'arrangedContent'); <add> this._prevArrangedContent = arrangedContent; <ide> <ide> if (arrangedContent) { <ide> Ember.assert(`ArrayProxy expects an Array or Ember.ArrayProxy, but you passed ${typeof arrangedContent}`, <ide> var ArrayProxy = EmberObject.extend(MutableArray, { <ide> }, <ide> <ide> init() { <add> this._didInitArrayProxy = true; <ide> this._super(...arguments); <ide> this._setupContent(); <ide> this._setupArrangedContent(); <ide> }, <ide> <ide> willDestroy() { <ide> this._teardownArrangedContent(); <del> this._teardownContent(); <add> this._teardownContent(this.get('content')); <ide> } <ide> }); <ide> <ide><path>packages/ember-runtime/tests/system/array_proxy/content_change_test.js <ide> QUnit.test('The `arrangedContentWillChange` method is invoked before `content` i <ide> var expectedLength; <ide> <ide> var proxy = ArrayProxy.extend({ <del> content: Ember.A([1, 2, 3]), <del> <ide> arrangedContentWillChange() { <ide> equal(this.get('arrangedContent.length'), expectedLength, 'hook should be invoked before array has changed'); <ide> callCount++; <ide> } <del> }).create(); <add> }).create({ content: Ember.A([1, 2, 3]) }); <ide> <ide> proxy.pushObject(4); <ide> equal(callCount, 0, 'pushing content onto the array doesn\'t trigger it'); <ide> QUnit.test('The `arrangedContentDidChange` method is invoked after `content` is <ide> var expectedLength; <ide> <ide> var proxy = ArrayProxy.extend({ <del> content: Ember.A([1, 2, 3]), <del> <ide> arrangedContentDidChange() { <ide> equal(this.get('arrangedContent.length'), expectedLength, 'hook should be invoked after array has changed'); <ide> callCount++; <ide> } <del> }).create(); <add> }).create({ <add> content: Ember.A([1, 2, 3]) <add> }); <ide> <ide> equal(callCount, 0, 'hook is not called after creating the object'); <ide> <ide><path>packages/ember-views/lib/views/collection_view.js <ide> import EmberArray from 'ember-runtime/mixins/array'; <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <ide> import { computed } from 'ember-metal/computed'; <del>import { <del> observer, <del> _beforeObserver <del>} from 'ember-metal/mixin'; <add>import { observer } from 'ember-metal/mixin'; <ide> import { readViewFactory } from 'ember-views/streams/utils'; <ide> import EmptyViewSupport from 'ember-views/mixins/empty_view_support'; <ide> <ide> var CollectionView = ContainerView.extend(EmptyViewSupport, { <ide> return ret; <ide> }, <ide> <del> /** <del> Invoked when the content property is about to change. Notifies observers that the <del> entire array content will change. <del> <del> @private <del> @method _contentWillChange <del> */ <del> _contentWillChange: _beforeObserver('content', function() { <del> var content = this.get('content'); <del> <del> if (content) { content.removeArrayObserver(this); } <del> var len = content ? get(content, 'length') : 0; <del> this.arrayWillChange(content, 0, len); <del> }), <del> <ide> /** <ide> Check to make sure that the content has changed, and if so, <ide> update the children directly. This is always scheduled <ide> var CollectionView = ContainerView.extend(EmptyViewSupport, { <ide> @method _contentDidChange <ide> */ <ide> _contentDidChange: observer('content', function() { <add> var prevContent = this._prevContent; <add> if (prevContent) { prevContent.removeArrayObserver(this); } <add> var len = prevContent ? get(prevContent, 'length') : 0; <add> this.arrayWillChange(prevContent, 0, len); <add> <ide> var content = get(this, 'content'); <ide> <ide> if (content) { <add> this._prevContent = content; <ide> this._assertArrayLike(content); <ide> content.addArrayObserver(this); <ide> } <ide> <del> var len = content ? get(content, 'length') : 0; <add> len = content ? get(content, 'length') : 0; <ide> this.arrayDidChange(content, 0, null, len); <ide> }), <ide> <ide><path>packages/ember-views/lib/views/container_view.js <ide> import View from 'ember-views/views/view'; <ide> <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <del>import { <del> observer, <del> _beforeObserver <del>} from 'ember-metal/mixin'; <add>import { observer } from 'ember-metal/mixin'; <ide> import { on } from 'ember-metal/events'; <ide> <ide> import containerViewTemplate from 'ember-htmlbars/templates/container-view'; <ide> var ContainerView = View.extend(MutableArray, { <ide> <ide> init() { <ide> this._super(...arguments); <del> <add> this._prevCurrentView = undefined; <ide> var userChildViews = get(this, 'childViews'); <ide> Ember.deprecate('Setting `childViews` on a Container is deprecated.', <ide> Ember.isEmpty(userChildViews), <ide> var ContainerView = View.extend(MutableArray, { <ide> } <ide> }, <ide> <del> _currentViewWillChange: _beforeObserver('currentView', function() { <del> var currentView = get(this, 'currentView'); <del> if (currentView) { <del> currentView.destroy(); <del> } <del> }), <del> <ide> _currentViewDidChange: observer('currentView', function() { <add> var prevView = this._prevCurrentView; <add> if (prevView) { <add> prevView.destroy(); <add> } <ide> var currentView = get(this, 'currentView'); <add> this._prevCurrentView = currentView; <ide> if (currentView) { <ide> Ember.assert('You tried to set a current view that already has a parent. Make sure you don\'t have multiple outlets in the same view.', !currentView.parentView); <ide> this.pushObject(currentView);
4
PHP
PHP
fix cs in smtptransporttest
469a590a06c3103d2f602d69b2389d1687622029
<ide><path>tests/TestCase/Network/Email/SmtpTransportTest.php <ide> public function testExplicitDisconnect() { <ide> * @return void <ide> */ <ide> public function testExplicitDisconnectNotConnected() { <del> $callback = function($arg) { <add> $callback = function($arg) { <ide> $this->assertNotEquals("QUIT\r\n", $arg); <ide> }; <ide> $this->socket->expects($this->any())->method('write')->will($this->returnCallback($callback)); <ide> public function testKeepAlive() { <ide> $email->to('cake@cakephp.org', 'CakePHP'); <ide> $email->expects($this->exactly(2))->method('message')->will($this->returnValue(array('First Line'))); <ide> <del> $callback = function($arg) { <add> $callback = function($arg) { <ide> $this->assertNotEquals("QUIT\r\n", $arg); <ide> }; <ide> $this->socket->expects($this->any())->method('write')->will($this->returnCallback($callback));
1
Javascript
Javascript
update defineplugin to es2015
7d1774666a1071a27058761011957a0fabcd9db6
<ide><path>lib/DefinePlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>var ConstDependency = require("./dependencies/ConstDependency"); <del>var BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); <add>"use strict"; <ide> <del>var NullFactory = require("./NullFactory"); <add>const ConstDependency = require("./dependencies/ConstDependency"); <add>const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); <add>const NullFactory = require("./NullFactory"); <ide> <del>function DefinePlugin(definitions) { <del> this.definitions = definitions; <del>} <del>module.exports = DefinePlugin; <del>DefinePlugin.prototype.apply = function(compiler) { <del> var definitions = this.definitions; <del> compiler.plugin("compilation", function(compilation, params) { <del> compilation.dependencyFactories.set(ConstDependency, new NullFactory()); <del> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); <add>class DefinePlugin { <add> constructor(definitions) { <add> this.definitions = definitions; <add> } <ide> <del> params.normalModuleFactory.plugin("parser", function(parser) { <del> (function walkDefinitions(definitions, prefix) { <del> Object.keys(definitions).forEach(function(key) { <del> var code = definitions[key]; <del> if(code && typeof code === "object" && !(code instanceof RegExp)) { <del> walkDefinitions(code, prefix + key + "."); <del> applyObjectDefine(prefix + key, code); <del> return; <del> } <del> applyDefineKey(prefix, key); <del> applyDefine(prefix + key, code); <del> }); <del> }(definitions, "")); <add> apply(compiler) { <add> let definitions = this.definitions; <add> compiler.plugin("compilation", (compilation, params) => { <add> compilation.dependencyFactories.set(ConstDependency, new NullFactory()); <add> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); <ide> <del> function stringifyObj(obj) { <del> return "{" + Object.keys(obj).map(function(key) { <del> var code = obj[key]; <del> return JSON.stringify(key) + ":" + toCode(code); <del> }).join(",") + "}"; <del> } <add> params.normalModuleFactory.plugin("parser", (parser) => { <add> (function walkDefinitions(definitions, prefix) { <add> Object.keys(definitions).forEach((key) => { <add> let code = definitions[key]; <add> if(code && typeof code === "object" && !(code instanceof RegExp)) { <add> walkDefinitions(code, prefix + key + "."); <add> applyObjectDefine(prefix + key, code); <add> return; <add> } <add> applyDefineKey(prefix, key); <add> applyDefine(prefix + key, code); <add> }); <add> }(definitions, "")); <ide> <del> function toCode(code) { <del> if(code === null) return "null"; <del> else if(code === undefined) return "undefined"; <del> else if(code instanceof RegExp && code.toString) return code.toString(); <del> else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")"; <del> else if(typeof code === "object") return stringifyObj(code); <del> else return code + ""; <del> } <add> function stringifyObj(obj) { <add> return "{" + Object.keys(obj).map((key) => { <add> let code = obj[key]; <add> return JSON.stringify(key) + ":" + toCode(code); <add> }).join(",") + "}"; <add> } <ide> <del> function applyDefineKey(prefix, key) { <del> var splittedKey = key.split("."); <del> splittedKey.slice(1).forEach(function(_, i) { <del> var fullKey = prefix + splittedKey.slice(0, i + 1).join("."); <del> parser.plugin("can-rename " + fullKey, function() { <del> return true; <del> }); <del> }); <del> } <add> function toCode(code) { <add> if(code === null) return "null"; <add> else if(code === undefined) return "undefined"; <add> else if(code instanceof RegExp && code.toString) return code.toString(); <add> else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")"; <add> else if(typeof code === "object") return stringifyObj(code); <add> else return code + ""; <add> } <ide> <del> function applyDefine(key, code) { <del> var isTypeof = /^typeof\s+/.test(key); <del> if(isTypeof) key = key.replace(/^typeof\s+/, ""); <del> var recurse = false; <del> var recurseTypeof = false; <del> code = toCode(code); <del> if(!isTypeof) { <del> parser.plugin("can-rename " + key, function() { <del> return true; <add> function applyDefineKey(prefix, key) { <add> const splittedKey = key.split("."); <add> splittedKey.slice(1).forEach((_, i) => { <add> const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); <add> parser.plugin("can-rename " + fullKey, () => true); <ide> }); <del> parser.plugin("evaluate Identifier " + key, function(expr) { <del> if(recurse) return; <del> recurse = true; <del> var res = this.evaluate(code); <del> recurse = false; <add> } <add> <add> function applyDefine(key, code) { <add> let isTypeof = /^typeof\s+/.test(key); <add> if(isTypeof) key = key.replace(/^typeof\s+/, ""); <add> let recurse = false; <add> let recurseTypeof = false; <add> code = toCode(code); <add> if(!isTypeof) { <add> parser.plugin("can-rename " + key, () => true); <add> parser.plugin("evaluate Identifier " + key, (expr) => { <add> if(recurse) return; <add> let res = parser.evaluate(code); <add> recurse = false; <add> res.setRange(expr.range); <add> return res; <add> }); <add> parser.plugin("expression " + key, (expr) => { <add> let dep = new ConstDependency(code, expr.range); <add> dep.loc = expr.loc; <add> parser.state.current.addDependency(dep); <add> return true; <add> }); <add> } <add> let typeofCode = isTypeof ? code : "typeof (" + code + ")"; <add> parser.plugin("evaluate typeof " + key, (expr) => { <add> if(recurseTypeof) return; <add> let res = parser.evaluate(typeofCode); <add> recurseTypeof = false; <ide> res.setRange(expr.range); <ide> return res; <ide> }); <del> parser.plugin("expression " + key, function(expr) { <del> var dep = new ConstDependency(code, expr.range); <add> parser.plugin("typeof " + key, (expr) => { <add> let res = parser.evaluate(typeofCode); <add> if(!res.isString()) return; <add> let dep = new ConstDependency(JSON.stringify(res.string), expr.range); <ide> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <add> parser.state.current.addDependency(dep); <ide> return true; <ide> }); <ide> } <del> var typeofCode = isTypeof ? code : "typeof (" + code + ")"; <del> parser.plugin("evaluate typeof " + key, function(expr) { <del> if(recurseTypeof) return; <del> recurseTypeof = true; <del> var res = this.evaluate(typeofCode); <del> recurseTypeof = false; <del> res.setRange(expr.range); <del> return res; <del> }); <del> parser.plugin("typeof " + key, function(expr) { <del> var res = this.evaluate(typeofCode); <del> if(!res.isString()) return; <del> var dep = new ConstDependency(JSON.stringify(res.string), expr.range); <del> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <del> return true; <del> }); <del> } <ide> <del> function applyObjectDefine(key, obj) { <del> var code = stringifyObj(obj); <del> parser.plugin("can-rename " + key, function() { <del> return true; <del> }); <del> parser.plugin("evaluate Identifier " + key, function(expr) { <del> return new BasicEvaluatedExpression().setRange(expr.range); <del> }); <del> parser.plugin("evaluate typeof " + key, function(expr) { <del> return new BasicEvaluatedExpression().setString("object").setRange(expr.range); <del> }); <del> parser.plugin("expression " + key, function(expr) { <del> var dep = new ConstDependency(code, expr.range); <del> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <del> return true; <del> }); <del> parser.plugin("typeof " + key, function(expr) { <del> var dep = new ConstDependency("\"object\"", expr.range); <del> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <del> return true; <del> }); <del> } <add> function applyObjectDefine(key, obj) { <add> let code = stringifyObj(obj); <add> parser.plugin("can-rename " + key, () => true); <add> parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setRange(expr.range)); <add> parser.plugin("evaluate typeof " + key, expr => new BasicEvaluatedExpression().setString("object").setRange(expr.range)); <add> parser.plugin("expression " + key, (expr) => { <add> let dep = new ConstDependency(code, expr.range); <add> dep.loc = expr.loc; <add> parser.state.current.addDependency(dep); <add> return true; <add> }); <add> parser.plugin("typeof " + key, (expr) => { <add> let dep = new ConstDependency("\"object\"", expr.range); <add> dep.loc = expr.loc; <add> parser.state.current.addDependency(dep); <add> return true; <add> }); <add> } <add> }); <ide> }); <del> }); <del>}; <add> } <add>} <add>module.exports = DefinePlugin;
1
Ruby
Ruby
use meaningful names with our variables
940404096fecd57fdece94d0a6cfe524f20a2aa8
<ide><path>actionpack/lib/action_view/template/resolver.rb <ide> def query(path, details, formats) <ide> templates = [] <ide> sanitizer = Hash.new { |h,k| h[k] = Dir["#{File.dirname(k)}/*"] } <ide> <del> Dir[query].each do |p| <del> next if File.directory?(p) || !sanitizer[p].include?(p) <add> Dir[query].each do |template| <add> next if File.directory?(template) || !sanitizer[template].include?(template) <ide> <del> handler, format = extract_handler_and_format(p, formats) <del> contents = File.binread p <add> handler, format = extract_handler_and_format(template, formats) <add> contents = File.binread template <ide> <del> templates << Template.new(contents, File.expand_path(p), handler, <del> :virtual_path => path.virtual, :format => format, :updated_at => mtime(p)) <add> templates << Template.new(contents, File.expand_path(template), handler, <add> :virtual_path => path.virtual, :format => format, :updated_at => mtime(template)) <ide> end <ide> <ide> templates
1
Javascript
Javascript
add create identities on flatten users
2f43e0380b5d1b8db6f8a99cb55e7a2d5dd92876
<ide><path>flattenUser.js <ide> /* eslint-disable no-process-exit */ <ide> require('dotenv').load(); <del>var assign = require('lodash/object/assign'), <del> Rx = require('rx'), <add>var Rx = require('rx'), <add> uuid = require('node-uuid'), <add> assign = require('lodash/object/assign'), <ide> mongodb = require('mongodb'), <ide> secrets = require('../config/secrets'); <ide> <ide> var MongoClient = mongodb.MongoClient; <ide> <add>var providers = [ <add> 'facebook', <add> 'twitter', <add> 'google', <add> 'github', <add> 'linkedin' <add>]; <add> <ide> function createConnection(URI) { <ide> return Rx.Observable.create(function(observer) { <ide> MongoClient.connect(URI, function(err, database) { <ide> function insertMany(db, collection, users, options) { <ide> if (err) { <ide> return observer.onError(err); <ide> } <add> observer.onNext(); <ide> observer.onCompleted(); <ide> }); <ide> }); <ide> function insertMany(db, collection, users, options) { <ide> var count = 0; <ide> // will supply our db object <ide> var dbObservable = createConnection(secrets.db).shareReplay(); <del>dbObservable <add> <add>var users = dbObservable <ide> .flatMap(function(db) { <ide> // returns user document, n users per loop where n is the batchsize. <ide> return createQuery(db, 'users', {}); <ide> dbObservable <ide> assign(user, user.portfolio, user.profile); <ide> return user; <ide> }) <del> // batch them into arrays of twenty documents <add> .map(function(user) { <add> if (user.username) { <add> return user; <add> } <add> user.username = 'fcc' + uuid.v4().slice(0, 8); <add> return user; <add> }) <add> .shareReplay(); <add> <add>// batch them into arrays of twenty documents <add>var userSavesCount = users <ide> .bufferWithCount(20) <ide> // get bd object ready for insert <ide> .withLatestFrom(dbObservable, function(users, db) { <ide> dbObservable <ide> return insertMany(dats.db, 'user', dats.users, { w: 1 }); <ide> }) <ide> // count how many times insert completes <del> .count() <add> .count(); <add> <add>// create User Identities <add>var userIdentityCount = users <add> .flatMap(function(user) { <add> var ids = providers <add> .map(function(provider) { <add> return { <add> provider: provider, <add> externalId: user[provider] <add> }; <add> }) <add> .filter(function(ident) { <add> return !!ident.externalId; <add> }); <add> <add> return Rx.Observable.from(ids); <add> }) <add> .bufferWithCount(20) <add> .withLatestFrom(dbObservable, function(identities, db) { <add> return { <add> identities: identities, <add> db: db <add> }; <add> }) <add> .flatMap(function(dats) { <add> // bulk insert into new collection for loopback <add> return insertMany(dats.db, 'userIdentity', dats.identities, { w: 1 }); <add> }) <add> // count how many times insert completes <add> .count(); <add> <add>Rx.Observable.merge( <add> userIdentityCount, <add> userSavesCount <add>) <ide> .subscribe( <ide> function(_count) { <del> count = _count * 20; <add> count += _count * 20; <ide> }, <ide> function(err) { <ide> console.log('an error occured', err);
1
PHP
PHP
unify marshalling with saving
813708af838b95f265b255beab91286d267b1662
<ide><path>Cake/ORM/Marshaller.php <ide> protected function _buildPropertyMap($include) { <ide> $key = $nested; <ide> $nested = []; <ide> } <add> $nested = isset($nested['associated']) ? $nested['associated'] : []; <ide> $assoc = $this->_table->association($key); <ide> if ($assoc) { <ide> $map[$assoc->property()] = [ <ide> protected function _buildPropertyMap($include) { <ide> * @param array $data The data to hydrate. <ide> * @param array $include The associations to include. <ide> * @return Cake\ORM\Entity <add> * @see Cake\ORM\Table::newEntity() <ide> */ <ide> public function one(array $data, $include = []) { <ide> $propertyMap = $this->_buildPropertyMap($include); <ide> protected function _marshalAssociation($assoc, $value, $include) { <ide> * @param array $data The data to hydrate. <ide> * @param array $include The associations to include. <ide> * @return array An array of hydrated records. <add> * @see Cake\ORM\Table::newEntities() <ide> */ <ide> public function many(array $data, $include = []) { <ide> $output = []; <ide><path>Cake/ORM/Table.php <ide> public function marshaller($safe = false) { <ide> * {{{ <ide> * $articles = $this->Articles->newEntity( <ide> * $this->request->data(), <del> * ['Tags', 'Comments' => ['Users']] <add> * ['Tags', 'Comments' => ['associated' => ['Users']]] <ide> * ); <ide> * }}} <ide> * <ide> public function newEntity(array $data, $associations = null) { <ide> * {{{ <ide> * $articles = $this->Articles->newEntities( <ide> * $this->request->data(), <del> * ['Tags', 'Comments' => ['Users']] <add> * ['Tags', 'Comments' => ['associated' => ['Users']]] <ide> * ); <ide> * }}} <ide> * <ide><path>Cake/Test/TestCase/ORM/MarshallerTest.php <ide> public function testOneDeepAssociations() { <ide> ] <ide> ]; <ide> $marshall = new Marshaller($this->comments); <del> $result = $marshall->one($data, ['Articles' => ['Users']]); <add> $result = $marshall->one($data, ['Articles' => ['associated' => ['Users']]]); <ide> <ide> $this->assertEquals( <ide> $data['article']['title'],
3
Javascript
Javascript
replace deprecated eslint configuration
46af4c1d01b90ee6845abf40c813f384286f3ad4
<ide><path>.eslintrc.js <ide> module.exports = { <ide> 'node-core/no-duplicate-requires': 'error', <ide> }, <ide> globals: { <del> Atomics: false, <del> BigInt: false, <del> BigInt64Array: false, <del> BigUint64Array: false, <del> DTRACE_HTTP_CLIENT_REQUEST: false, <del> DTRACE_HTTP_CLIENT_RESPONSE: false, <del> DTRACE_HTTP_SERVER_REQUEST: false, <del> DTRACE_HTTP_SERVER_RESPONSE: false, <del> DTRACE_NET_SERVER_CONNECTION: false, <del> DTRACE_NET_STREAM_END: false, <del> TextEncoder: false, <del> TextDecoder: false, <del> queueMicrotask: false, <add> Atomics: 'readable', <add> BigInt: 'readable', <add> BigInt64Array: 'readable', <add> BigUint64Array: 'readable', <add> DTRACE_HTTP_CLIENT_REQUEST: 'readable', <add> DTRACE_HTTP_CLIENT_RESPONSE: 'readable', <add> DTRACE_HTTP_SERVER_REQUEST: 'readable', <add> DTRACE_HTTP_SERVER_RESPONSE: 'readable', <add> DTRACE_NET_SERVER_CONNECTION: 'readable', <add> DTRACE_NET_STREAM_END: 'readable', <add> TextEncoder: 'readable', <add> TextDecoder: 'readable', <add> queueMicrotask: 'readable', <ide> }, <ide> };
1
Ruby
Ruby
treat more things as errors in `cask audit`
e4356e85d1584ff0de83725875b6e347b8229353
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_untrusted_pkg <ide> <ide> return unless cask.artifacts.any? { |k| k.is_a?(Artifact::Pkg) && k.stanza_options.key?(:allow_untrusted) } <ide> <del> add_warning "allow_untrusted is not permitted in official Homebrew Cask taps" <add> add_error "allow_untrusted is not permitted in official Homebrew Cask taps" <ide> end <ide> <ide> def check_stanza_requires_uninstall <ide> def check_stanza_requires_uninstall <ide> return if cask.artifacts.none? { |k| k.is_a?(Artifact::Pkg) || k.is_a?(Artifact::Installer) } <ide> return if cask.artifacts.any? { |k| k.is_a?(Artifact::Uninstall) } <ide> <del> add_warning "installer and pkg stanzas require an uninstall stanza" <add> add_error "installer and pkg stanzas require an uninstall stanza" <ide> end <ide> <ide> def check_single_pre_postflight <ide> odebug "Auditing preflight and postflight stanzas" <ide> <ide> if cask.artifacts.count { |k| k.is_a?(Artifact::PreflightBlock) && k.directives.key?(:preflight) } > 1 <del> add_warning "only a single preflight stanza is allowed" <add> add_error "only a single preflight stanza is allowed" <ide> end <ide> <ide> count = cask.artifacts.count do |k| <ide> def check_single_pre_postflight <ide> end <ide> return unless count > 1 <ide> <del> add_warning "only a single postflight stanza is allowed" <add> add_error "only a single postflight stanza is allowed" <ide> end <ide> <ide> def check_single_uninstall_zap <ide> odebug "Auditing single uninstall_* and zap stanzas" <ide> <ide> if cask.artifacts.count { |k| k.is_a?(Artifact::Uninstall) } > 1 <del> add_warning "only a single uninstall stanza is allowed" <add> add_error "only a single uninstall stanza is allowed" <ide> end <ide> <ide> count = cask.artifacts.count do |k| <ide> k.is_a?(Artifact::PreflightBlock) && <ide> k.directives.key?(:uninstall_preflight) <ide> end <ide> <del> add_warning "only a single uninstall_preflight stanza is allowed" if count > 1 <add> add_error "only a single uninstall_preflight stanza is allowed" if count > 1 <ide> <ide> count = cask.artifacts.count do |k| <ide> k.is_a?(Artifact::PostflightBlock) && <ide> k.directives.key?(:uninstall_postflight) <ide> end <ide> <del> add_warning "only a single uninstall_postflight stanza is allowed" if count > 1 <add> add_error "only a single uninstall_postflight stanza is allowed" if count > 1 <ide> <ide> return unless cask.artifacts.count { |k| k.is_a?(Artifact::Zap) } > 1 <ide> <del> add_warning "only a single zap stanza is allowed" <add> add_error "only a single zap stanza is allowed" <ide> end <ide> <ide> def check_required_stanzas <ide> def check_latest_with_appcast <ide> return unless cask.version.latest? <ide> return unless cask.appcast <ide> <del> add_warning "Casks with an appcast should not use version :latest" <add> add_error "Casks with an appcast should not use version :latest" <ide> end <ide> <ide> def check_latest_with_auto_updates <ide> return unless cask.version.latest? <ide> return unless cask.auto_updates <ide> <del> add_warning "Casks with `version :latest` should not use `auto_updates`" <add> add_error "Casks with `version :latest` should not use `auto_updates`" <ide> end <ide> <ide> def check_hosting_with_appcast <ide> def check_hosting_with_appcast <ide> when %r{github.com/([^/]+)/([^/]+)/releases/download/(\S+)} <ide> return if cask.version.latest? <ide> <del> add_warning "Download uses GitHub releases, #{add_appcast}" <add> add_error "Download uses GitHub releases, #{add_appcast}" <ide> when %r{sourceforge.net/(\S+)} <ide> return if cask.version.latest? <ide> <del> add_warning "Download is hosted on SourceForge, #{add_appcast}" <add> add_error "Download is hosted on SourceForge, #{add_appcast}" <ide> when %r{dl.devmate.com/(\S+)} <del> add_warning "Download is hosted on DevMate, #{add_appcast}" <add> add_error "Download is hosted on DevMate, #{add_appcast}" <ide> when %r{rink.hockeyapp.net/(\S+)} <del> add_warning "Download is hosted on HockeyApp, #{add_appcast}" <add> add_error "Download is hosted on HockeyApp, #{add_appcast}" <ide> end <ide> end <ide> <ide> def check_desc <ide> <ide> return if cask.desc.present? <ide> <del> add_warning "Cask should have a description. Please add a `desc` stanza." <add> add_error "Cask should have a description. Please add a `desc` stanza." <ide> end <ide> <ide> def check_url <ide> def check_url <ide> def check_download_url_format <ide> odebug "Auditing URL format" <ide> if bad_sourceforge_url? <del> add_warning "SourceForge URL format incorrect. See https://github.com/Homebrew/homebrew-cask/blob/HEAD/doc/cask_language_reference/stanzas/url.md#sourceforgeosdn-urls" <add> add_error "SourceForge URL format incorrect. See https://github.com/Homebrew/homebrew-cask/blob/HEAD/doc/cask_language_reference/stanzas/url.md#sourceforgeosdn-urls" <ide> elsif bad_osdn_url? <del> add_warning "OSDN URL format incorrect. See https://github.com/Homebrew/homebrew-cask/blob/HEAD/doc/cask_language_reference/stanzas/url.md#sourceforgeosdn-urls" <add> add_error "OSDN URL format incorrect. See https://github.com/Homebrew/homebrew-cask/blob/HEAD/doc/cask_language_reference/stanzas/url.md#sourceforgeosdn-urls" <ide> end <ide> end <ide> <ide> def check_token_conflicts <ide> end <ide> <ide> def check_token_valid <del> return unless strict? <del> <del> add_warning "cask token is not lowercase" if cask.token.downcase! <del> <del> add_warning "cask token contains non-ascii characters" unless cask.token.ascii_only? <del> <del> add_warning "cask token + should be replaced by -plus-" if cask.token.include? "+" <del> <del> add_warning "cask token @ should be replaced by -at-" if cask.token.include? "@" <del> <del> add_warning "cask token whitespace should be replaced by hyphens" if cask.token.include? " " <del> <del> add_warning "cask token underscores should be replaced by hyphens" if cask.token.include? "_" <add> add_error "cask token contains non-ascii characters" unless cask.token.ascii_only? <add> add_error "cask token + should be replaced by -plus-" if cask.token.include? "+" <add> add_error "cask token whitespace should be replaced by hyphens" if cask.token.include? " " <add> add_error "cask token @ should be replaced by -at-" if cask.token.include? "@" <add> add_error "cask token underscores should be replaced by hyphens" if cask.token.include? "_" <add> add_error "cask token should not contain double hyphens" if cask.token.include? "--" <ide> <ide> if cask.token.match?(/[^a-z0-9\-]/) <del> add_warning "cask token should only contain alphanumeric characters and hyphens" <add> add_error "cask token should only contain lowercase alphanumeric characters and hyphens" <ide> end <ide> <del> add_warning "cask token should not contain double hyphens" if cask.token.include? "--" <del> <del> return unless cask.token.end_with?("-") || cask.token.start_with?("-") <add> return unless cask.token.start_with?("-") || cask.token.end_with?("-") <ide> <del> add_warning "cask token should not have leading or trailing hyphens" <add> add_error "cask token should not have leading or trailing hyphens" <ide> end <ide> <ide> def check_token_bad_words <ide> return unless strict? <ide> <ide> token = cask.token <ide> <del> add_warning "cask token contains .app" if token.end_with? ".app" <add> add_error "cask token contains .app" if token.end_with? ".app" <ide> <ide> if /-(?<designation>alpha|beta|rc|release-candidate)$/ =~ cask.token && <ide> cask.tap&.official? && <ide> cask.tap != "homebrew/cask-versions" <del> add_warning "cask token contains version designation '#{designation}'" <add> add_error "cask token contains version designation '#{designation}'" <ide> end <ide> <ide> add_warning "cask token mentions launcher" if token.end_with? "launcher" <ide> def check_download <ide> downloaded_path = download.perform <ide> Verify.all(cask, downloaded_path) <ide> rescue => e <del> add_error "download not possible: #{e.message}" <add> add_error "download not possible: #{e}" <ide> end <ide> <ide> def check_appcast_contains_version <ide> def check_appcast_contains_version <ide> end <ide> return if appcast_contents.include? adjusted_version_stanza <ide> <del> add_warning "appcast at URL '#{appcast_stanza}' does not contain"\ <add> add_error "appcast at URL '#{appcast_stanza}' does not contain"\ <ide> " the version number '#{adjusted_version_stanza}':\n#{appcast_contents}" <ide> end <ide>
1
Javascript
Javascript
remove unused import
62b04cfa753076d5ffb1d74b855f8f8db36f5186
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js <ide> import { <ide> requestCurrentTime, <ide> computeExpirationForFiber, <ide> scheduleWork, <del> flushPassiveEffects, <ide> } from './ReactFiberWorkLoop'; <ide> import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberHooks.js <ide> import { <ide> import { <ide> scheduleWork, <ide> computeExpirationForFiber, <del> flushPassiveEffects, <ide> requestCurrentTime, <ide> warnIfNotCurrentlyActingEffectsInDEV, <ide> warnIfNotCurrentlyActingUpdatesInDev,
2
PHP
PHP
fix few errors reported by phpstan
aa23283a223dc6f690e55b3ccddeeae76eb077b9
<ide><path>src/Database/Query.php <ide> class Query implements ExpressionInterface, IteratorAggregate <ide> * The object responsible for generating query placeholders and temporarily store values <ide> * associated to each of those. <ide> * <del> * @var \Cake\Database\ValueBinder|false|null <add> * @var \Cake\Database\ValueBinder|null <ide> */ <ide> protected $_valueBinder; <ide> <ide> public function getValueBinder() <ide> * to the statement object. <ide> * <ide> * @deprecated 3.5.0 Use getValueBinder() for the getter part instead. <del> * @param \Cake\Database\ValueBinder|false|null $binder new instance to be set. If no value is passed the <add> * @param \Cake\Database\ValueBinder|null $binder new instance to be set. If no value is passed the <ide> * default one will be returned <ide> * @return $this|\Cake\Database\ValueBinder <ide> */ <ide><path>src/Log/Engine/ConsoleLog.php <ide> public function log($level, $message, array $context = []) <ide> $message = $this->_format($message, $context); <ide> $output = date('Y-m-d H:i:s') . ' ' . ucfirst($level) . ': ' . $message; <ide> <del> return $this->_output->write(sprintf('<%s>%s</%s>', $level, $output, $level)); <add> return (bool)$this->_output->write(sprintf('<%s>%s</%s>', $level, $output, $level)); <ide> } <ide> } <ide><path>src/ORM/LazyEagerLoader.php <ide> protected function _getQuery($objects, $contain, $source) <ide> return $entity->{$method}($primaryKey); <ide> }); <ide> <add> /** @var \Cake\ORM\Query $query */ <ide> $query = $source <ide> ->find() <ide> ->select((array)$primaryKey)
3
Python
Python
put module import on top of the module
04b602f96f91529a1259909466705f3f9192113c
<ide><path>transformers/pipelines.py <ide> from abc import ABC, abstractmethod <ide> from contextlib import contextmanager <ide> from itertools import groupby <add>from os.path import abspath, exists <ide> from typing import Union, Optional, Tuple, List, Dict <ide> <ide> import numpy as np <ide> def __init__(self, output: str, path: str, column: str): <ide> if self.is_multi_columns: <ide> self.column = [tuple(c.split('=')) if '=' in c else (c, c) for c in self.column] <ide> <del> from os.path import abspath, exists <del> if exists(abspath(self.output)): <del> raise OSError('{} already exists on disk'.format(self.output)) <add> if output is not None: <add> if exists(abspath(self.output)): <add> raise OSError('{} already exists on disk'.format(self.output)) <ide> <del> if not exists(abspath(self.path)): <del> raise OSError('{} doesnt exist on disk'.format(self.path)) <add> if not exists(abspath(self.path)): <add> raise OSError('{} doesnt exist on disk'.format(self.path)) <ide> <ide> @abstractmethod <ide> def __iter__(self):
1
Ruby
Ruby
add failing test
374f788a3c6a8f295de4e5eb134d979eb3dc3513
<ide><path>Library/Homebrew/test/cask/config_spec.rb <ide> expect(config.explicit[:appdir]).to eq(Pathname("/explicit/path/to/apps")) <ide> end <ide> end <add> <add> context "when installing a cask and then adding a global default dir" do <add> let(:config) { described_class.new(default: { appdir: "/default/path/before/adding/fontdir" }) } <add> <add> describe "#appdir" do <add> it "honors metadata of the installed cask" do <add> expect(config.appdir).to eq(Pathname("/default/path/before/adding/fontdir")) <add> end <add> end <add> <add> describe "#fontdir" do <add> it "falls back to global default on incomplete metadata" do <add> expect(config.default).to include(fontdir: Pathname(TEST_TMPDIR).join("cask-fontdir")) <add> end <add> end <add> end <ide> end
1
Python
Python
remove dependency on ftfy
070b6c6495f631fc874f66c3b6ee68e60429bad2
<ide><path>spacy/cli/init_model.py <ide> from ..vectors import Vectors <ide> from ..util import prints, ensure_path, get_lang_class <ide> <add>try: <add> import ftfy <add>except ImportError: <add> ftfy = None <add> <ide> <ide> @plac.annotations( <ide> lang=("model language", "positional", None, str), <ide> def read_freqs(freqs_loc, max_length=100, min_doc_freq=5, min_freq=50): <ide> def read_clusters(clusters_loc): <ide> print("Reading clusters...") <ide> clusters = {} <add> if ftfy is None: <add> print("Warning: No text fixing. Run pip install ftfy if necessary") <ide> with clusters_loc.open() as f: <ide> for line in tqdm(f): <ide> try: <ide> cluster, word, freq = line.split() <del> word = fix_text(word) <add> if ftfy is not None: <add> word = fix_text(word) <ide> except ValueError: <ide> continue <ide> # If the clusterer has only seen the word a few times, its
1
Python
Python
fix training with vectors
b1505380ff9234232d3f4dfe2237a437c20d36e0
<ide><path>spacy/_ml.py <ide> def Tok2Vec(width, embed_size, **kwargs): <ide> "config": { <ide> "vectors_name": pretrained_vectors, <ide> "width": width, <del> "column": cols.index(ID), <add> "column": cols.index("ID") <ide> }, <ide> } <ide> if cnn_maxout_pieces >= 2:
1
Go
Go
add test suite for push/pull code
9e4addde76f4aea4613f09215084812b6a357521
<ide><path>integration-cli/docker_hub_pull_suite_test.go <add>package main <add> <add>import ( <add> "os/exec" <add> "strings" <add> <add> "github.com/go-check/check" <add>) <add> <add>func init() { <add> check.Suite(newDockerHubPullSuite()) <add>} <add> <add>// DockerHubPullSuite provides a isolated daemon that doesn't have all the <add>// images that are baked into our 'global' test environment daemon (e.g., <add>// busybox, httpserver, ...). <add>// <add>// We use it for push/pull tests where we want to start fresh, and measure the <add>// relative impact of each individual operation. As part of this suite, all <add>// images are removed after each test. <add>type DockerHubPullSuite struct { <add> d *Daemon <add> ds *DockerSuite <add>} <add> <add>// newDockerHubPullSuite returns a new instance of a DockerHubPullSuite. <add>func newDockerHubPullSuite() *DockerHubPullSuite { <add> return &DockerHubPullSuite{ <add> ds: &DockerSuite{}, <add> } <add>} <add> <add>// SetUpSuite starts the suite daemon. <add>func (s *DockerHubPullSuite) SetUpSuite(c *check.C) { <add> s.d = NewDaemon(c) <add> if err := s.d.Start(); err != nil { <add> c.Fatalf("starting push/pull test daemon: %v", err) <add> } <add>} <add> <add>// TearDownSuite stops the suite daemon. <add>func (s *DockerHubPullSuite) TearDownSuite(c *check.C) { <add> if err := s.d.Stop(); err != nil { <add> c.Fatalf("stopping push/pull test daemon: %v", err) <add> } <add>} <add> <add>// SetUpTest declares that all tests of this suite require network. <add>func (s *DockerHubPullSuite) SetUpTest(c *check.C) { <add> testRequires(c, Network) <add>} <add> <add>// TearDownTest removes all images from the suite daemon. <add>func (s *DockerHubPullSuite) TearDownTest(c *check.C) { <add> out := s.Cmd(c, "images", "-aq") <add> images := strings.Split(out, "\n") <add> images = append([]string{"-f"}, images...) <add> s.d.Cmd("rmi", images...) <add> s.ds.TearDownTest(c) <add>} <add> <add>// Cmd executes a command against the suite daemon and returns the combined <add>// output. The function fails the test when the command returns an error. <add>func (s *DockerHubPullSuite) Cmd(c *check.C, name string, arg ...string) string { <add> out, err := s.CmdWithError(name, arg...) <add> c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(arg, " "), out, err)) <add> return out <add>} <add> <add>// CmdWithError executes a command against the suite daemon and returns the <add>// combined output as well as any error. <add>func (s *DockerHubPullSuite) CmdWithError(name string, arg ...string) (string, error) { <add> c := s.MakeCmd(name, arg...) <add> b, err := c.CombinedOutput() <add> return string(b), err <add>} <add> <add>// MakeCmd returns a exec.Cmd command to run against the suite daemon. <add>func (s *DockerHubPullSuite) MakeCmd(name string, arg ...string) *exec.Cmd { <add> args := []string{"--host", s.d.sock(), name} <add> args = append(args, arg...) <add> return exec.Command(dockerBinary, args...) <add>}
1
PHP
PHP
accommodate default values for props tag
8d921630680d887293edc8cbedfdace41c9ad45a
<ide><path>src/Illuminate/View/ComponentAttributeBag.php <ide> public function exceptProps($keys) <ide> { <ide> $props = []; <ide> <del> foreach ($keys as $key) { <add> foreach ($keys as $key => $defaultValue) { <add> // If the "key" value is a numeric key, we assume that no default value <add> // has been specified, and use the "default value" as the key. <add> $key = is_numeric($key) ? $defaultValue : $key; <add> <ide> $props[] = $key; <ide> $props[] = Str::kebab($key); <ide> }
1
Javascript
Javascript
fix textinput autocorrect
26aa27da630a8875dfe64f616b6aca59eaa89aaf
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> var TextInput = React.createClass({ <ide> }, <ide> <ide> _focusSubscription: (undefined: ?Function), <add> _lastNativeText: (undefined: ?string), <ide> <ide> componentDidMount: function() { <add> this._lastNativeText = this.props.value; <ide> if (!this.context.focusEmitter) { <ide> if (this.props.autoFocus) { <ide> this.requestAnimationFrame(this.focus); <ide> var TextInput = React.createClass({ <ide> return; <ide> } <ide> <add> this._lastNativeText = text; <add> this.forceUpdate(); <add> }, <add> <add> componentDidUpdate: function () { <ide> // This is necessary in case native updates the text and JS decides <ide> // that the update should be ignored and we should stick with the value <ide> // that we have in JS. <del> if (text !== this.props.value && typeof this.props.value === 'string') { <add> if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { <ide> this.refs.input.setNativeProps({ <ide> text: this.props.value, <ide> });
1
PHP
PHP
add more assertion methods
00ed67e88ca87ef43beb1d6f9ee6117ec8d33c11
<ide><path>src/TestSuite/IntegrationTestCase.php <ide> public function assertRedirect($url, $message = '') { <ide> $this->assertEquals(Router::url($url, ['_full' => true]), $result['Location'], $message); <ide> } <ide> <add>/** <add> * Assert response headers <add> * <add> * @param string $header The header to check <add> * @param string $content The content to check for. <add> * @param string $message The failure message that will be appended to the generated message. <add> * @return void <add> */ <add> public function assertHeader($header, $content, $message = '') { <add> if (!$this->_response) { <add> $this->fail('No response set, cannot assert headers. ' . $message); <add> } <add> $headers = $this->_response->header(); <add> if (!isset($headers[$header])) { <add> $this->fail("The '$header' header is not set. " . $message); <add> } <add> $this->assertEquals($headers[$header], $content, $message); <add> } <add> <add>/** <add> * Assert content type <add> * <add> * @param string $type The content-type to check for. <add> * @param string $message The failure message that will be appended to the generated message. <add> * @return void <add> */ <add> public function assertContentType($type, $message = '') { <add> if (!$this->_response) { <add> $this->fail('No response set, cannot assert content-type. ' . $message); <add> } <add> $alias = $this->_response->getMimeType($type); <add> if ($alias !== false) { <add> $type = $alias; <add> } <add> $result = $this->_response->type(); <add> $this->assertEquals($type, $result, $message); <add> } <add> <ide> /** <ide> * Assert content exists in the response body. <ide> * <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function testAssertRedirect() { <ide> $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']); <ide> } <ide> <add>/** <add> * Test the header assertino <add> * <add> * @return void <add> */ <add> public function testAssertHeader() { <add> $this->_response = new Response(); <add> $this->_response->header('Etag', 'abc123'); <add> <add> $this->assertHeader('Etag', 'abc123'); <add> } <add> <add>/** <add> * Test the content type assertino <add> * <add> * @return void <add> */ <add> public function testAssertContentType() { <add> $this->_response = new Response(); <add> $this->_response->type('json'); <add> <add> $this->assertContentType('json'); <add> $this->assertContentType('application/json'); <add> } <add> <ide> /** <ide> * Test the content assertion. <ide> *
2
Ruby
Ruby
add freetube to github_prerelease_allowlist
6efcde2eefea57692e6bde37ffd99c90151db536
<ide><path>Library/Homebrew/utils/shared_audits.rb <ide> def github_release_data(user, repo, tag) <ide> GITHUB_PRERELEASE_ALLOWLIST = { <ide> "amd-power-gadget" => :all, <ide> "elm-format" => "0.8.3", <add> "freetube" => :all, <ide> "gitless" => "0.8.8", <ide> "infrakit" => "0.5", <ide> "pock" => :all,
1
Javascript
Javascript
add test filter for es6 constructs
588db26d9c658120f33a56c64c4a94e6e1dbf0b4
<ide><path>test/cases/scope-hoisting/renaming-shorthand-5027/test.filter.js <add>var supportsES6 = require("../../../helpers/supportsES6"); <add>var supportDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); <add>var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); <add>var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); <add> <add>module.exports = function(config) { <add> return !config.minimize && <add> supportsES6() && <add> supportDefaultAssignment() && <add> supportsObjectDestructuring() && <add> supportsIteratorDestructuring(); <add>};
1
Ruby
Ruby
rotate the debug.log on each 100mb
64391cd520cd8aee2c8b9ba1b95e4aae4512a6a0
<ide><path>activerecord/test/support/connection.rb <ide> def self.connection_config <ide> <ide> def self.connect <ide> puts "Using #{connection_name}" <del> ActiveRecord::Model.logger = ActiveSupport::Logger.new("debug.log") <add> ActiveRecord::Model.logger = ActiveSupport::Logger.new("debug.log", 0, 100 * 1024 * 1024) <ide> ActiveRecord::Model.configurations = connection_config <ide> ActiveRecord::Model.establish_connection 'arunit' <ide> ARUnit2Model.establish_connection 'arunit2'
1
Javascript
Javascript
ignore case for request headers
7069e4cd3f1228e0508988ecdee2afb3899aedfc
<ide><path>Libraries/Network/XMLHttpRequestBase.js <ide> class XMLHttpRequestBase { <ide> } <ide> <ide> setRequestHeader(header: string, value: any): void { <del> this._headers[header] = value; <add> this._headers[header.toLowerCase()] = value; <ide> } <ide> <ide> open(method: string, url: string, async: ?boolean): void {
1
Javascript
Javascript
fix typos on next-server.js comments.
0d77dda28c8b0eaed38bb203de737ffc1235d42a
<ide><path>packages/next-server/server/next-server.js <ide> export default class Server { <ide> } <ide> }, <ide> { <del> // It's very important keep this route's param optional. <del> // (but it should support as many as params, seperated by '/') <del> // Othewise this will lead to a pretty simple DOS attack. <add> // It's very important to keep this route's param optional. <add> // (but it should support as many params as needed, separated by '/') <add> // Otherwise this will lead to a pretty simple DOS attack. <ide> // See more: https://github.com/zeit/next.js/issues/2617 <ide> match: route('/static/:path*'), <ide> fn: async (req, res, params) => { <ide> export default class Server { <ide> ] <ide> <ide> if (this.nextConfig.useFileSystemPublicRoutes) { <del> // It's very important keep this route's param optional. <del> // (but it should support as many as params, seperated by '/') <del> // Othewise this will lead to a pretty simple DOS attack. <add> // It's very important to keep this route's param optional. <add> // (but it should support as many params as needed, separated by '/') <add> // Otherwise this will lead to a pretty simple DOS attack. <ide> // See more: https://github.com/zeit/next.js/issues/2617 <ide> routes.push({ <ide> match: route('/:path*'),
1
PHP
PHP
apply fixes from styleci
a3f8589bbd01e85e429c7c38d8b2b7bc9cc7dc8d
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> protected function registerScheduleListCommand() <ide> { <ide> $this->app->singleton(ScheduleListCommand::class); <ide> } <del> <add> <ide> /** <ide> * Register the command. <ide> *
1
Ruby
Ruby
adjust route inspection to work with journey
d21e0e2af3d9b21399244c3f3f73378d75cd4697
<ide><path>railties/lib/rails/application/route_inspector.rb <ide> def format all_routes, filter = nil <ide> reqs = reqs.empty? ? constraints.inspect : "#{reqs} #{constraints.inspect}" <ide> end <ide> <del> {:name => route.name.to_s, :verb => route.verb.to_s, :path => route.path, :reqs => reqs} <add> verb = route.verb.source.gsub(/[$^]/, '') <add> {:name => route.name.to_s, :verb => verb, :path => route.path.spec.to_s, :reqs => reqs} <ide> end <ide> <ide> # Skip the route if it's internal info route
1
PHP
PHP
apply fixes from styleci
bbc559073aed1706be8c0ee134c56fdcc347614a
<ide><path>tests/Integration/Foundation/DiscoverEventsTest.php <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventOne; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventTwo; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener; <del>use Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener as ListenerAlias; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\AbstractListener; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\ListenerInterface; <ide>
1
Javascript
Javascript
remove re-exported functions
d0c2b068d778359b885e8d37f212275511f9c425
<ide><path>local-cli/server/util/attachHMRServer.js <ide> <ide> 'use strict'; <ide> <add>const getInverseDependencies = require('../../../packager/src//node-haste/lib/getInverseDependencies'); <ide> const querystring = require('querystring'); <ide> const url = require('url'); <ide> <del>const {getInverseDependencies} = require('../../../packager/src//node-haste/DependencyGraph'); <del> <ide> import type HMRBundle from '../../../packager/src/Bundler/HMRBundle'; <ide> import type Server from '../../../packager/src/Server'; <ide> import type ResolutionResponse <ide><path>packager/src/AssetServer/index.js <ide> const crypto = require('crypto'); <ide> const denodeify = require('denodeify'); <ide> const fs = require('fs'); <del>const getAssetDataFromName = require('../node-haste/DependencyGraph').getAssetDataFromName; <add>const getAssetDataFromName = require('../node-haste/lib/getAssetDataFromName'); <ide> const path = require('path'); <ide> <ide> import type {AssetData} from '../node-haste/lib/getAssetDataFromName'; <ide> class AssetServer { <ide> } <ide> <ide> get(assetPath: string, platform: ?string = null): Promise<Buffer> { <del> const assetData = getAssetDataFromName(assetPath, new Set([platform])); <add> const assetData = getAssetDataFromName( <add> assetPath, <add> new Set(platform != null ? [platform] : []), <add> ); <ide> return this._getAssetRecord(assetPath, platform).then(record => { <ide> for (let i = 0; i < record.scales.length; i++) { <ide> if (record.scales[i] >= assetData.resolution) { <ide> class AssetServer { <ide> scales: Array<number>, <ide> type: string, <ide> |}> { <del> const nameData = getAssetDataFromName(assetPath, new Set([platform])); <add> const nameData = getAssetDataFromName( <add> assetPath, <add> new Set(platform != null ? [platform] : []), <add> ); <ide> const {name, type} = nameData; <ide> <ide> return this._getAssetRecord(assetPath, platform).then(record => { <ide> class AssetServer { <ide> .then(res => { <ide> const dir = res[0]; <ide> const files = res[1]; <del> const assetData = getAssetDataFromName(filename, new Set([platform])); <add> const assetData = getAssetDataFromName( <add> filename, <add> new Set(platform != null ? [platform] : []), <add> ); <ide> <ide> const map = this._buildAssetMap(dir, files, platform); <ide> <ide><path>packager/src/node-haste/DependencyGraph.js <ide> const FilesByDirNameIndex = require('./FilesByDirNameIndex'); <ide> const JestHasteMap = require('jest-haste-map'); <ide> const Module = require('./Module'); <ide> const ModuleCache = require('./ModuleCache'); <del>const Polyfill = require('./Polyfill'); <ide> const ResolutionRequest = require('./DependencyGraph/ResolutionRequest'); <ide> const ResolutionResponse = require('./DependencyGraph/ResolutionResponse'); <ide> <ide> const fs = require('fs'); <del>const getAssetDataFromName = require('./lib/getAssetDataFromName'); <del>const getInverseDependencies = require('./lib/getInverseDependencies'); <ide> const getPlatformExtension = require('./lib/getPlatformExtension'); <ide> const invariant = require('fbjs/lib/invariant'); <ide> const isAbsolutePath = require('absolute-path'); <ide> const path = require('path'); <del>const replacePatterns = require('./lib/replacePatterns'); <ide> const util = require('util'); <ide> <ide> const { <ide> class DependencyGraph extends EventEmitter { <ide> return this._moduleCache.createPolyfill(options); <ide> } <ide> <del> static Module; <del> static Polyfill; <del> static getAssetDataFromName; <del> static replacePatterns; <del> static getInverseDependencies; <del> <ide> } <ide> <del>Object.assign(DependencyGraph, { <del> Module, <del> Polyfill, <del> getAssetDataFromName, <del> replacePatterns, <del> getInverseDependencies, <del>}); <del> <ide> function NotFoundError() { <ide> /* $FlowFixMe: monkey-patching */ <ide> Error.call(this);
3
Go
Go
fix behavior of tty tests
86c00be180f1e6831ca426576a55f5106f156448
<ide><path>integration/commands_test.go <ide> func TestRunDisconnect(t *testing.T) { <ide> }) <ide> } <ide> <del>// Expected behaviour: the process dies when the client disconnects <add>// Expected behaviour: the process stay alive when the client disconnects <add>// but the client detaches. <ide> func TestRunDisconnectTty(t *testing.T) { <ide> <ide> stdin, stdinPipe := io.Pipe() <ide> func TestRunDisconnectTty(t *testing.T) { <ide> <ide> c1 := make(chan struct{}) <ide> go func() { <add> defer close(c1) <ide> // We're simulating a disconnect so the return value doesn't matter. What matters is the <ide> // fact that CmdRun returns. <ide> if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil { <ide> utils.Debugf("Error CmdRun: %s", err) <ide> } <del> <del> close(c1) <ide> }() <ide> <del> setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() { <del> for { <del> // Client disconnect after run -i should keep stdin out in TTY mode <del> l := globalRuntime.List() <del> if len(l) == 1 && l[0].State.IsRunning() { <del> break <del> } <del> time.Sleep(10 * time.Millisecond) <del> } <del> }) <add> container := waitContainerStart(t, 10*time.Second) <ide> <del> // Client disconnect after run -i should keep stdin out in TTY mode <del> container := globalRuntime.List()[0] <add> state := setRaw(t, container) <add> defer unsetRaw(t, container, state) <ide> <add> // Client disconnect after run -i should keep stdin out in TTY mode <ide> setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() { <ide> if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil { <ide> t.Fatal(err) <ide> func TestRunDisconnectTty(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <add> // wait for CmdRun to return <add> setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() { <add> <-c1 <add> }) <add> <ide> // In tty mode, we expect the process to stay alive even after client's stdin closes. <del> // Do not wait for run to finish <ide> <ide> // Give some time to monitor to do his thing <ide> container.WaitTimeout(500 * time.Millisecond) <ide> func TestRunDetach(t *testing.T) { <ide> cli.CmdRun("-i", "-t", unitTestImageID, "cat") <ide> }() <ide> <add> container := waitContainerStart(t, 10*time.Second) <add> <add> state := setRaw(t, container) <add> defer unsetRaw(t, container, state) <add> <ide> setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() { <ide> if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil { <ide> t.Fatal(err) <ide> } <ide> }) <ide> <del> container := globalRuntime.List()[0] <del> <ide> setTimeout(t, "Escape sequence timeout", 5*time.Second, func() { <del> stdinPipe.Write([]byte{16, 17}) <del> if err := stdinPipe.Close(); err != nil { <del> t.Fatal(err) <del> } <add> stdinPipe.Write([]byte{16}) <add> time.Sleep(100 * time.Millisecond) <add> stdinPipe.Write([]byte{17}) <ide> }) <ide> <del> closeWrap(stdin, stdinPipe, stdout, stdoutPipe) <del> <ide> // wait for CmdRun to return <ide> setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() { <ide> <-ch <ide> }) <add> closeWrap(stdin, stdinPipe, stdout, stdoutPipe) <ide> <ide> time.Sleep(500 * time.Millisecond) <ide> if !container.State.IsRunning() { <ide> func TestAttachDetachTruncatedID(t *testing.T) { <ide> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr) <ide> defer cleanup(globalEngine, t) <ide> <add> // Discard the CmdRun output <ide> go stdout.Read(make([]byte, 1024)) <ide> setTimeout(t, "Starting container timed out", 2*time.Second, func() { <ide> if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil { <ide> func TestRunAutoRemove(t *testing.T) { <ide> } <ide> <ide> func TestCmdLogs(t *testing.T) { <add> t.Skip("Test not impemented") <ide> cli := docker.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr) <ide> defer cleanup(globalEngine, t) <ide>
1
Python
Python
use basictokenizer to split over whitespaces
e516a34a158593f82b6f22dc1e568ff8996f0389
<ide><path>transformers/pipelines.py <ide> import numpy as np <ide> <ide> from transformers import AutoConfig, AutoTokenizer, PreTrainedTokenizer, PretrainedConfig, \ <del> SquadExample, squad_convert_examples_to_features, is_tf_available, is_torch_available, logger <add> SquadExample, squad_convert_examples_to_features, is_tf_available, is_torch_available, logger, BasicTokenizer <ide> <ide> if is_tf_available(): <ide> import tensorflow as tf <ide> class NerPipeline(Pipeline): <ide> Named Entity Recognition pipeline using ModelForTokenClassification head. <ide> """ <ide> <add> def __init__(self, model, tokenizer: PreTrainedTokenizer = None, <add> args_parser: ArgumentHandler = None, device: int = -1, <add> binary_output: bool = False): <add> super().__init__(model, tokenizer, args_parser, device, binary_output) <add> <add> self._basic_tokenizer = BasicTokenizer(do_lower_case=False) <add> <ide> def __call__(self, *texts, **kwargs): <ide> inputs, answers = self._args_parser(*texts, **kwargs), [] <ide> for sentence in inputs: <ide> <ide> # Ugly token to word idx mapping (for now) <del> token_to_word, words = [], sentence.split(' ') <add> token_to_word, words = [], self._basic_tokenizer.tokenize(sentence) <ide> for i, w in enumerate(words): <ide> tokens = self.tokenizer.tokenize(w) <ide> token_to_word += [i] * len(tokens)
1
Go
Go
fix merge issue
a48799016a43e6badae72e855f9a90592b6cdd98
<ide><path>api.go <ide> func postImagesGetCache(srv *Server, version float64, w http.ResponseWriter, r * <ide> return nil <ide> } <ide> <del>func postBuild(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := r.ParseMultipartForm(4096); err != nil { <ide> return err <ide> } <ide><path>buildfile.go <ide> func (b *buildFile) CmdFrom(name string) error { <ide> remote = name <ide> } <ide> <del> if err := b.srv.ImagePull(remote, tag, "", b.out); err != nil { <add> if err := b.srv.ImagePull(remote, tag, "", b.out, false); err != nil { <ide> return err <ide> } <ide> <ide><path>commands.go <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> if _, err := w.CreateFormFile("Context", cmd.Arg(0)+"."+compression.Extension()); err != nil { <ide> return err <ide> } <del> multipartBody = io.MultiReader(multipartBody, utils.ProgressReader(ioutil.NopCloser(context), -1, os.Stdout, "Uploading Context %v/%v (%v)")) <add> multipartBody = io.MultiReader(multipartBody, utils.ProgressReader(ioutil.NopCloser(context), -1, os.Stdout, "Uploading Context %v/%v (%v)", false)) <ide> } <ide> <ide> // Send the multipart request with correct content-type <ide><path>server.go <ide> func (srv *Server) ImageInsert(name, url, path string, out io.Writer) (string, e <ide> } <ide> <ide> if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, "Downloading %v/%v (%v)\r", false), path); err != nil { <del> return err <add> return "", err <ide> } <ide> // FIXME: Handle custom repo, tag comment, author <ide> img, err = b.Commit(c, "", "", img.Comment, img.Author, nil)
4
Text
Text
add missing parenthesis on readme.md
eee45e02535b986c1701a8d4442d887931e69720
<ide><path>README.md <ide> Observable.create(emitter -> { <ide> long time = System.currentTimeMillis(); <ide> emitter.onNext(time); <ide> if (time % 2 != 0) { <del> emitter.onError(new IllegalStateException("Odd millisecond!"); <add> emitter.onError(new IllegalStateException("Odd millisecond!")); <ide> break; <ide> } <ide> }
1
Javascript
Javascript
remove leftovers from reacttransitiongroup rewrite
27ea2c7e517e9a70e1a43baf6b8f5be6bf766a72
<ide><path>src/addons/transitions/ReactCSSTransitionGroupChild.js <ide> var ReactCSSTransitionGroupChild = React.createClass({ <ide> queueClass: function(className) { <ide> this.classNameQueue.push(className); <ide> <del> if (this.props.runNextTick) { <del> this.props.runNextTick(this.flushClassNameQueue); <del> return; <del> } <del> <ide> if (!this.timeout) { <ide> this.timeout = setTimeout(this.flushClassNameQueue, TICK); <ide> }
1