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 |
|---|---|---|---|---|---|
Javascript | Javascript | accept numbers for boundaries | f77005cc437376609073c74ec278d5998ab2f351 | <ide><path>curriculum/schema/challengeSchema.js
<ide> const fileJoi = Joi.object().keys({
<ide> head: [Joi.array().items(Joi.string().allow('')), Joi.string().allow('')],
<ide> tail: [Joi.array().items(Joi.string().allow('')), Joi.string().allow('')],
<ide> contents: [Joi.array().items(Joi.string().allow('')), Joi.string().allow('')],
<del> editableRegionBoundaries: [Joi.array().items(Joi.string().allow(''))]
<add> editableRegionBoundaries: [Joi.array().items(Joi.number())]
<ide> });
<ide>
<ide> function getSchemaForLang(lang) { | 1 |
PHP | PHP | add a missing dot in translations | 21c0aed802a69838ba848d93228e725067a2e205 | <ide><path>resources/lang/en/validation.php
<ide> 'string' => 'The :attribute must be at least :min characters.',
<ide> 'array' => 'The :attribute must have at least :min items.',
<ide> ],
<del> 'multiple_of' => 'The :attribute must be a multiple of :value',
<add> 'multiple_of' => 'The :attribute must be a multiple of :value.',
<ide> 'not_in' => 'The selected :attribute is invalid.',
<ide> 'not_regex' => 'The :attribute format is invalid.',
<ide> 'numeric' => 'The :attribute must be a number.', | 1 |
Javascript | Javascript | increase timeout in break-on-uncaught | cc899a4c81ae79b63147dae473ba54d6c58da628 | <ide><path>test/debugger/test-debug-break-on-uncaught.js
<ide> function runScenario(scriptName, throwsOnLine, next) {
<ide> client.connect(port);
<ide> }
<ide>
<add> let interval;
<ide> function runTest(client) {
<ide> client.req(
<ide> {
<ide> function runScenario(scriptName, throwsOnLine, next) {
<ide>
<ide> client.reqContinue(function(error) {
<ide> assert.ifError(error);
<del> setTimeout(assertHasPaused.bind(null, client), 100);
<add> interval = setInterval(assertHasPaused.bind(null, client), 10);
<ide> });
<ide> }
<ide> );
<ide> }
<ide>
<ide> function assertHasPaused(client) {
<del> assert(exceptions.length, 'no exceptions thrown, race condition in test?');
<add> if (!exceptions.length) return;
<add>
<ide> assert.strictEqual(exceptions.length, 1,
<ide> 'debugger did not pause on exception');
<ide> assert.strictEqual(exceptions[0].uncaught, true);
<ide> assert.strictEqual(exceptions[0].script.name, testScript);
<ide> assert.strictEqual(exceptions[0].sourceLine + 1, throwsOnLine);
<ide> asserted = true;
<ide> client.reqContinue(assert.ifError);
<add> clearInterval(interval);
<ide> }
<ide> } | 1 |
Javascript | Javascript | delay process.argv[0] and process.argv0 handling | 728c939e57ec471bf0a114b86074829be622f421 | <ide><path>lib/internal/bootstrap/node.js
<ide> if (!config.noBrowserGlobals) {
<ide>
<ide> setupDOMException();
<ide>
<del>Object.defineProperty(process, 'argv0', {
<del> enumerable: true,
<del> configurable: false,
<del> value: process.argv[0]
<del>});
<del>process.argv[0] = process.execPath;
<del>
<ide> // process.allowedNodeEnvironmentFlags
<ide> Object.defineProperty(process, 'allowedNodeEnvironmentFlags', {
<ide> get() {
<ide><path>lib/internal/bootstrap/pre_execution.js
<ide> const { getOptionValue } = require('internal/options');
<ide> let traceEventsAsyncHook;
<ide>
<ide> function prepareMainThreadExecution() {
<add> // Patch the process object with legacy properties and normalizations
<add> patchProcessObject();
<ide> setupTraceCategoryState();
<ide>
<ide> setupWarningHandler();
<ide> function prepareMainThreadExecution() {
<ide> loadPreloadModules();
<ide> }
<ide>
<add>function patchProcessObject() {
<add> Object.defineProperty(process, 'argv0', {
<add> enumerable: true,
<add> configurable: false,
<add> value: process.argv[0]
<add> });
<add> process.argv[0] = process.execPath;
<add>}
<add>
<ide> function setupWarningHandler() {
<ide> const {
<ide> onWarning
<ide> function loadPreloadModules() {
<ide> }
<ide>
<ide> module.exports = {
<add> patchProcessObject,
<ide> setupCoverageHooks,
<ide> setupWarningHandler,
<ide> setupDebugEnv,
<ide><path>lib/internal/main/worker_thread.js
<ide> // message port.
<ide>
<ide> const {
<add> patchProcessObject,
<ide> setupCoverageHooks,
<ide> setupWarningHandler,
<ide> setupDebugEnv,
<ide> const {
<ide>
<ide> const publicWorker = require('worker_threads');
<ide>
<add>patchProcessObject();
<ide> setupDebugEnv();
<ide>
<ide> const debug = require('util').debuglog('worker'); | 3 |
Javascript | Javascript | allow third party hooks before main module load | 496be457b6a2bc5b01ec13644b9c9783976159b2 | <ide><path>src/node.js
<ide> process.argv[0] = path.join(cwd, process.argv[0]);
<ide> }
<ide>
<add> // To allow people to extend Node in different ways, this hook allows
<add> // one to drop a file lib/_third_party_main.js into the build directory
<add> // which will be executed instead of Node's normal loading.
<add> if (process.binding('natives')['_third_party_main']) {
<add> process.nextTick(function () {
<add> Module._requireNative('_third_party_main');
<add> });
<add> return;
<add> }
<add>
<ide> if (process.argv[1]) {
<ide> if (process.argv[1] == 'debug') {
<ide> // Start the debugger agent | 1 |
Text | Text | add question about pr to feature request template | 12bde090d92019a037ffcabbd78761943fc3914d | <ide><path>.github/ISSUE_TEMPLATE/feature_request.md
<ide> step back and describe what you are trying to achieve.
<ide>
<ide> -->
<ide>
<add>**Are you willing to submit a PR?**
<add>
<add><!--- We accept contributions! -->
<add>
<ide> **Related Issues**
<ide>
<ide> <!-- Is there currently another issue associated with this? --> | 1 |
Ruby | Ruby | fix que integration in active job tests | ee5d18bb920215a5bf49c8da702eca1507079b71 | <ide><path>activejob/test/adapters/que.rb
<ide> require "support/que/inline"
<ide>
<ide> ActiveJob::Base.queue_adapter = :que
<del>Que.mode = :sync
<add>Que.run_synchronously = true | 1 |
Javascript | Javascript | fix webpackerror handling in cache | 5e52f429cc3933cf0ebd6c89ef2d8321206f0357 | <ide><path>lib/Cache.js
<ide> "use strict";
<ide>
<ide> const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = require("tapable");
<del>const { makeWebpackError } = require("./HookWebpackError");
<add>const {
<add> makeWebpackError,
<add> makeWebpackErrorCallback
<add>} = require("./HookWebpackError");
<ide>
<ide> /** @typedef {import("./WebpackError")} WebpackError */
<ide>
<ide> class Cache {
<ide> * @returns {void}
<ide> */
<ide> store(identifier, etag, data, callback) {
<del> this.hooks.store.callAsync(identifier, etag, data, callback);
<add> this.hooks.store.callAsync(
<add> identifier,
<add> etag,
<add> data,
<add> makeWebpackErrorCallback(callback, "Cache.hooks.store")
<add> );
<ide> }
<ide>
<ide> /**
<ide> class Cache {
<ide> * @returns {void}
<ide> */
<ide> endIdle(callback) {
<del> this.hooks.endIdle.callAsync(callback);
<add> this.hooks.endIdle.callAsync(
<add> makeWebpackErrorCallback(callback, "Cache.hooks.endIdle")
<add> );
<ide> }
<ide>
<ide> /**
<ide> * @param {Callback<void>} callback signals when the call finishes
<ide> * @returns {void}
<ide> */
<ide> shutdown(callback) {
<del> this.hooks.shutdown.callAsync(callback);
<add> this.hooks.shutdown.callAsync(
<add> makeWebpackErrorCallback(callback, "Cache.hooks.shutdown")
<add> );
<ide> }
<ide> }
<ide>
<ide><path>lib/HookWebpackError.js
<ide> const WebpackError = require("./WebpackError");
<ide>
<ide> /** @typedef {import("./Module")} Module */
<ide>
<add>/**
<add> * @template T
<add> * @callback Callback
<add> * @param {Error=} err
<add> * @param {T=} stats
<add> * @returns {void}
<add> */
<add>
<ide> class HookWebpackError extends WebpackError {
<ide> /**
<ide> * Creates an instance of HookWebpackError.
<ide> module.exports.makeWebpackError = makeWebpackError;
<ide> * @template T
<ide> * @param {function(WebpackError=, T=): void} callback webpack error callback
<ide> * @param {string} hook name of hook
<del> * @returns {function(Error=, T=): void} generic callback
<add> * @returns {Callback<T>} generic callback
<ide> */
<ide> const makeWebpackErrorCallback = (callback, hook) => {
<ide> return (err, result) => { | 2 |
Ruby | Ruby | remove redundant conditional | 8823b85010a217df555b981a453384e24ce7da47 | <ide><path>actionpack/lib/action_dispatch/testing/assertions/response.rb
<ide> def normalize_argument_to_redirection(fragment)
<ide> when %r{^\w[\w\d+.-]*:.*}
<ide> fragment
<ide> when String
<del> if fragment =~ %r{^\w[\w\d+.-]*:.*}
<del> fragment
<del> else
<del> @request.protocol + @request.host_with_port + fragment
<del> end
<add> @request.protocol + @request.host_with_port + fragment
<ide> when :back
<ide> raise RedirectBackError unless refer = @request.headers["Referer"]
<ide> refer | 1 |
Python | Python | close open files to suppress resourcewarning | f25444cb223b1211082ac0b9882f4972db5c1f1c | <ide><path>examples/legacy/seq2seq/run_distributed_eval.py
<ide> def run_generate():
<ide> save_json(preds, save_path)
<ide> return
<ide> tgt_file = Path(args.data_dir).joinpath(args.type_path + ".target")
<del> labels = [x.rstrip() for x in open(tgt_file).readlines()][: len(preds)]
<add> with open(tgt_file) as f:
<add> labels = [x.rstrip() for x in f.readlines()][: len(preds)]
<ide>
<ide> # Calculate metrics, save metrics, and save _generations.txt
<ide> calc_bleu = "translation" in args.task
<ide><path>examples/research_projects/seq2seq-distillation/run_eval.py
<ide> def run_generate(verbose=True):
<ide> parsed_args = parse_numeric_n_bool_cl_kwargs(rest)
<ide> if parsed_args and verbose:
<ide> print(f"parsed the following generate kwargs: {parsed_args}")
<del> examples = [" " + x.rstrip() if "t5" in args.model_name else x.rstrip() for x in open(args.input_path).readlines()]
<add> with open(args.input_path) as f:
<add> examples = [" " + x.rstrip() if "t5" in args.model_name else x.rstrip() for x in f.readlines()]
<ide> if args.n_obs > 0:
<ide> examples = examples[: args.n_obs]
<ide> Path(args.save_path).parent.mkdir(exist_ok=True)
<ide><path>src/transformers/convert_slow_tokenizer.py
<ide> def __init__(self, *args):
<ide> from .utils import sentencepiece_model_pb2 as model_pb2
<ide>
<ide> m = model_pb2.ModelProto()
<del> m.ParseFromString(open(self.original_tokenizer.vocab_file, "rb").read())
<add> with open(self.original_tokenizer.vocab_file, "rb") as f:
<add> m.ParseFromString(f.read())
<ide> self.proto = m
<ide>
<ide> def vocab(self, proto): | 3 |
Python | Python | add displacy visualisers (see ) | c31792aaec68a67ddaac9ef7ea812345eee0a6bf | <ide><path>spacy/displacy/__init__.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from .render import DependencyRenderer, EntityRenderer
<add>from ..tokens import Doc
<add>from ..util import prints
<add>
<add>
<add>_html = {}
<add>
<add>
<add>def render(docs, style='dep', page=False, minify=False, jupyter=False, options={}):
<add> """Render displaCy visualisation.
<add>
<add> docs (list or Doc): Document(s) to visualise.
<add> style (unicode): Visualisation style, 'dep' or 'ent'.
<add> page (bool): Render markup as full HTML page.
<add> minify (bool): Minify HTML markup.
<add> jupyter (bool): Experimental, use Jupyter's display() to output markup.
<add> options (dict): Visualiser-specific options, e.g. colors.
<add> RETURNS: Rendered HTML markup.
<add> """
<add> if isinstance(docs, Doc):
<add> docs = [docs]
<add> if style is 'dep':
<add> renderer = DependencyRenderer(options=options)
<add> parsed = [parse_deps(doc, options) for doc in docs]
<add> elif style is 'ent':
<add> renderer = EntityRenderer(options=options)
<add> parsed = [parse_ents(doc, options) for doc in docs]
<add> _html['parsed'] = renderer.render(parsed, page=page, minify=minify)
<add> return _html['parsed']
<add>
<add>
<add>def serve(docs, style='dep', page=True, minify=False, options={}, port=5000):
<add> """Serve displaCy visualisation.
<add>
<add> docs (list or Doc): Document(s) to visualise.
<add> style (unicode): Visualisation style, 'dep' or 'ent'.
<add> page (bool): Render markup as full HTML page.
<add> minify (bool): Minify HTML markup.
<add> options (dict): Visualiser-specific options, e.g. colors.
<add> port (int): Port to serve visualisation.
<add> """
<add> from wsgiref import simple_server
<add> render(docs, style=style, page=page, minify=minify, options=options)
<add> httpd = simple_server.make_server('0.0.0.0', port, app)
<add> prints("Using the '%s' visualizer" % style, title="Serving on port %d..." % port)
<add> httpd.serve_forever()
<add>
<add>
<add>def app(environ, start_response):
<add> start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')])
<add> res = _html['parsed'].encode(encoding='utf-8')
<add> return [res]
<add>
<add>
<add>def parse_deps(doc, options={}):
<add> """Generate dependency parse in {'words': [], 'arcs': []} format.
<add>
<add> doc (Doc): Document do parse.
<add> RETURNS (dict): Generated dependency parse keyed by words and arcs.
<add> """
<add> if options.get('collapse_punct', True):
<add> spans = []
<add> for word in doc[:-1]:
<add> if word.is_punct or not word.nbor(1).is_punct:
<add> continue
<add> start = word.i
<add> end = word.i + 1
<add> while end < len(doc) and doc[end].is_punct:
<add> end += 1
<add> span = doc[start : end]
<add> spans.append((span.start_char, span.end_char, word.tag_,
<add> word.lemma_, word.ent_type_))
<add> for span_props in spans:
<add> doc.merge(*span_props)
<add> words = [{'text': w.text, 'tag': w.tag_} for w in doc]
<add> arcs = []
<add> for word in doc:
<add> if word.i < word.head.i:
<add> arcs.append({'start': word.i, 'end': word.head.i,
<add> 'label': word.dep_, 'dir': 'left'})
<add> elif word.i > word.head.i:
<add> arcs.append({'start': word.head.i, 'end': word.i,
<add> 'label': word.dep_, 'dir': 'right'})
<add> return {'words': words, 'arcs': arcs}
<add>
<add>
<add>def parse_ents(doc, options={}):
<add> """Generate named entities in [{start: i, end: i, label: 'label'}] format.
<add>
<add> doc (Doc): Document do parse.
<add> RETURNS (dict): Generated entities keyed by text (original text) and ents.
<add> """
<add> ents = [{'start': ent.start_char, 'end': ent.end_char, 'label': ent.label_}
<add> for ent in doc.ents]
<add> title = doc.user_data.get('title', None)
<add> return {'text': doc.text, 'ents': ents, 'title': title}
<ide><path>spacy/displacy/render.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from .templates import TPL_DEP_SVG, TPL_DEP_WORDS, TPL_DEP_ARCS
<add>from .templates import TPL_ENT, TPL_ENTS, TPL_FIGURE, TPL_TITLE, TPL_PAGE
<add>from ..util import minify_html
<add>
<add>
<add>class DependencyRenderer(object):
<add> """Render dependency parses as SVGs."""
<add> style = 'dep'
<add>
<add> def __init__(self, options={}):
<add> """Initialise dependency renderer.
<add>
<add> options (dict): Visualiser-specific options (compact, word_spacing,
<add> arrow_spacing, arrow_width, arrow_stroke, distance,
<add> offset_x, color, bg, font)
<add> """
<add> self.compact = options.get('compact', False)
<add> distance, arrow_width = (85, 8) if self.compact else (175, 10)
<add> self.word_spacing = options.get('word_spacing', 45)
<add> self.arrow_spacing = options.get('arrow_spacing', 20)
<add> self.arrow_width = options.get('arrow_width', arrow_width)
<add> self.arrow_stroke = options.get('arrow_stroke', 2)
<add> self.distance = options.get('distance', distance)
<add> self.offset_x = options.get('offset_x', 50)
<add> self.color = options.get('color', '#000000')
<add> self.bg = options.get('bg', '#ffffff')
<add> self.font = options.get('font', 'Arial')
<add>
<add> def render(self, parsed, page=False, minify=False):
<add> """Render complete markup.
<add>
<add> parsed (list): Dependency parses to render.
<add> page (bool): Render parses wrapped as full HTML page.
<add> minify (bool): Minify HTML markup.
<add> RETURNS (unicode): Rendered SVG or HTML markup.
<add> """
<add> rendered = [self.render_svg(i, p['words'], p['arcs'])
<add> for i, p in enumerate(parsed)]
<add> if page:
<add> content = ''.join([TPL_FIGURE.format(content=svg) for svg in rendered])
<add> markup = TPL_PAGE.format(content=content)
<add> else:
<add> markup = ''.join(rendered)
<add> if minify:
<add> return minify_html(markup)
<add> return markup
<add>
<add> def render_svg(self, render_id, words, arcs):
<add> """Render SVG.
<add>
<add> render_id (int): Unique ID, typically index of document.
<add> words (list): Individual words and their tags.
<add> arcs (list): Individual arcs and their start, end, direction and label.
<add> RETURNS (unicode): Rendered SVG markup.
<add> """
<add> self.levels = self.get_levels(arcs)
<add> self.highest_level = len(self.levels)
<add> self.offset_y = self.distance/2*self.highest_level+self.arrow_stroke
<add> self.width = self.offset_x+len(words)*self.distance
<add> self.height = self.offset_y+3*self.word_spacing
<add> self.id = render_id
<add> words = [self.render_word(w['text'], w['tag'], i)
<add> for i, w in enumerate(words)]
<add> arcs = [self.render_arrow(a['label'], a['start'], a['end'], a['dir'], i)
<add> for i, a in enumerate(arcs)]
<add> content = ''.join(words) + ''.join(arcs)
<add> return TPL_DEP_SVG.format(id=self.id, width=self.width, height=self.height,
<add> color=self.color, bg=self.bg, font=self.font,
<add> content=content)
<add>
<add> def render_word(self, text, tag, i):
<add> """Render individual word.
<add>
<add> text (unicode): Word text.
<add> tag (unicode): Part-of-speech tag.
<add> i (int): Unique ID, typically word index.
<add> RETURNS (unicode): Rendered SVG markup.
<add> """
<add> y = self.offset_y+self.word_spacing
<add> x = self.offset_x+i*self.distance
<add> return TPL_DEP_WORDS.format(text=text, tag=tag, x=x, y=y)
<add>
<add> def render_arrow(self, label, start, end, direction, i):
<add> """Render indivicual arrow.
<add>
<add> label (unicode): Dependency label.
<add> start (int): Index of start word.
<add> end (int): Index of end word.
<add> direction (unicode): Arrow direction, 'left' or 'right'.
<add> i (int): Unique ID, typically arrow index.
<add> RETURNS (unicode): Rendered SVG markup.
<add> """
<add> level = self.levels.index(end-start)+1
<add> x_start = self.offset_x+start*self.distance+self.arrow_spacing
<add> y = self.offset_y
<add> x_end = (self.offset_x+(end-start)*self.distance+start*self.distance
<add> -self.arrow_spacing*(self.highest_level-level)/4)
<add> y_curve = self.offset_y-level*self.distance/2
<add> if y_curve == 0 and len(self.levels) > 5:
<add> y_curve = -self.distance
<add> arrowhead = self.get_arrowhead(direction, x_start, y, x_end)
<add> arc = self.get_arc(x_start, y, y_curve, x_end)
<add> return TPL_DEP_ARCS.format(id=self.id, i=i, stroke=self.arrow_stroke,
<add> head=arrowhead, label=label, arc=arc)
<add>
<add> def get_arc(self, x_start, y, y_curve, x_end):
<add> """Render individual arc.
<add>
<add> x_start (int): X-coordinate of arrow start point.
<add> y (int): Y-coordinate of arrow start and end point.
<add> y_curve (int): Y-corrdinate of Cubic Bézier y_curve point.
<add> x_end (int): X-coordinate of arrow end point.
<add> RETURNS (unicode): Definition of the arc path ('d' attribute).
<add> """
<add> template = "M{x},{y} C{x},{c} {e},{c} {e},{y}"
<add> if self.compact:
<add> template = "M{x},{y} {x},{c} {e},{c} {e},{y}"
<add> return template.format(x=x_start, y=y, c=y_curve, e=x_end)
<add>
<add> def get_arrowhead(self, direction, x, y, end):
<add> """Render individual arrow head.
<add>
<add> direction (unicode): Arrow direction, 'left' or 'right'.
<add> x (int): X-coordinate of arrow start point.
<add> y (int): Y-coordinate of arrow start and end point.
<add> end (int): X-coordinate of arrow end point.
<add> RETURNS (unicode): Definition of the arrow head path ('d' attribute).
<add> """
<add> if direction is 'left':
<add> pos1, pos2, pos3 = (x, x-self.arrow_width+2, x+self.arrow_width-2)
<add> else:
<add> pos1, pos2, pos3 = (end, end+self.arrow_width-2, end-self.arrow_width+2)
<add> arrowhead = (pos1, y+2, pos2, y-self.arrow_width, pos3, y-self.arrow_width)
<add> return "M{},{} L{},{} {},{}".format(*arrowhead)
<add>
<add> def get_levels(self, arcs):
<add> """Calculate available arc height "levels".
<add> Used to calculate arrow heights dynamically and without wasting space.
<add>
<add> args (list): Individual arcs and their start, end, direction and label.
<add> RETURNS (list): Arc levels sorted from lowest to highest.
<add> """
<add> levels = set(map(lambda arc: arc['end'] - arc['start'], arcs))
<add> return sorted(list(levels))
<add>
<add>
<add>class EntityRenderer(object):
<add> """Render named entities as HTML."""
<add> style = 'ent'
<add>
<add> def __init__(self, options={}):
<add> """Initialise dependency renderer.
<add>
<add> options (dict): Visualiser-specific options (colors, ents)
<add> """
<add> colors = {'org': '#7aecec', 'product': '#bfeeb7', 'gpe': '#feca74',
<add> 'loc': '#ff9561', 'person': '#9886fc', 'norp': '#c887fb',
<add> 'facility': '#9cc9cc', 'event': '#ffeb80', 'language': '#ff8197',
<add> 'work_of_art': '#f0d0ff', 'date': '#bfe1d9', 'time': '#bfe1d9',
<add> 'money': '#e4e7d2', 'quantity': '#e4e7d2', 'ordinal': '#e4e7d2',
<add> 'cardinal': '#e4e7d2', 'percent': '#e4e7d2'}
<add> colors.update(options.get('colors', {}))
<add> self.default_color = '#ddd'
<add> self.colors = colors
<add> self.ents = options.get('ents', None)
<add>
<add> def render(self, parsed, page=False, minify=False):
<add> """Render complete markup.
<add>
<add> parsed (list): Dependency parses to render.
<add> page (bool): Render parses wrapped as full HTML page.
<add> minify (bool): Minify HTML markup.
<add> RETURNS (unicode): Rendered HTML markup.
<add> """
<add> rendered = [self.render_ents(p['text'], p['ents'], p['title']) for p in parsed]
<add> if page:
<add> docs = ''.join([TPL_FIGURE.format(content=doc) for doc in rendered])
<add> markup = TPL_PAGE.format(content=docs)
<add> else:
<add> markup = ''.join(rendered)
<add> if minify:
<add> return minify_html(markup)
<add> return markup
<add>
<add> def render_ents(self, text, spans, title):
<add> """Render entities in text.
<add>
<add> text (unicode): Original text.
<add> spans (list): Individual entity spans and their start, end and label.
<add> """
<add> markup = ''
<add> offset = 0
<add> for span in spans:
<add> label = span['label']
<add> start = span['start']
<add> end = span['end']
<add> entity = text[start:end]
<add> fragments = text[offset:start].split('\n')
<add> for i, fragment in enumerate(fragments):
<add> markup += fragment
<add> if len(fragments) > 1 and i != len(fragments)-1:
<add> markup += '</br>'
<add> if self.ents is None or label.lower() in self.ents:
<add> color = self.colors.get(label.lower(), self.default_color)
<add> markup += TPL_ENT.format(label=label, text=entity, bg=color)
<add> else:
<add> markup += entity
<add> offset = end
<add> markup += text[offset:]
<add> markup = TPL_ENTS.format(content=markup, colors=self.colors)
<add> if title:
<add> markup = TPL_TITLE.format(title=title) + markup
<add> return markup
<ide><path>spacy/displacy/templates.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>
<add>TPL_DEP_SVG = """
<add><svg xmlns="http://www.w3.org/2000/svg" id="{id}" class="displacy" width="{width}" height="{height}" style="color: {color}; background: {bg}; font-family: {font}">{content}</svg>
<add>"""
<add>
<add>
<add>TPL_DEP_WORDS = """
<add><text class="displacy-token" fill="currentColor" text-anchor="middle" y="{y}">
<add> <tspan class="displacy-word" fill="currentColor" x="{x}">{text}</tspan>
<add> <tspan class="displacy-tag" dy="2em" fill="currentColor" x="{x}">{tag}</tspan>
<add></text>
<add>"""
<add>
<add>
<add>TPL_DEP_ARCS = """
<add><g class="displacy-arrow">
<add> <path class="displacy-arc" id="arrow-{id}-{i}" stroke-width="{stroke}px" d="{arc}" fill="none" stroke="currentColor"/>
<add> <text dy="1.25em" style="font-size: 0.8em">
<add> <textPath xlink:href="#arrow-{id}-{i}" class="displacy-label" startOffset="50%" fill="currentColor" text-anchor="middle">{label}</textPath>
<add> </text>
<add> <path class="displacy-arrowhead" d="{head}" fill="currentColor"/>
<add></g>
<add>"""
<add>
<add>
<add>TPL_FIGURE = """
<add><figure style="margin-bottom: 6rem">{content}</figure>
<add>"""
<add>
<add>TPL_TITLE = """
<add><h2 style="margin: 0">{title}</h2>
<add>"""
<add>
<add>
<add>TPL_ENTS = """
<add><div class="entities" style="line-height: 2.5">{content}</div>
<add>"""
<add>
<add>
<add>TPL_ENT = """
<add><mark class="entity" style="background: {bg}; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em; box-decoration-break: clone; -webkit-box-decoration-break: clone">
<add> {text}
<add> <span style="font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; text-transform: uppercase; vertical-align: middle; margin-left: 0.5rem">{label}</span>
<add></mark>
<add>"""
<add>
<add>
<add>TPL_PAGE = """
<add><!DOCTYPE html>
<add><html>
<add> <head>
<add> <title>displaCy</title>
<add> </head>
<add>
<add> <body style="font-size: 16px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; padding: 4rem 2rem;">{content}</body>
<add></html>
<add>"""
<ide><path>spacy/util.py
<ide> def _wrap(text, wrap_max=80, indent=4):
<ide> return textwrap.fill(text, width=wrap_width, initial_indent=indent,
<ide> subsequent_indent=indent, break_long_words=False,
<ide> break_on_hyphens=False)
<add>
<add>
<add>def minify_html(html):
<add> """Perform a template-specific, rudimentary HTML minification for displaCy.
<add> Disclaimer: NOT a general-purpose solution, only removes indentation/newlines.
<add>
<add> html (unicode): Markup to minify.
<add> RETURNS (unicode): "Minified" HTML.
<add> """
<add> return html.strip().replace(' ', '').replace('\n', '') | 4 |
PHP | PHP | handle duplicates method in eloquent collections | 4b9d3e78e6de2d7439eeecb3f1115e8048e64f90 | <ide><path>src/Illuminate/Database/Eloquent/Collection.php
<ide> public function diff($items)
<ide> return $diff;
<ide> }
<ide>
<add> /**
<add> * Get the comparison function to detect duplicates.
<add> *
<add> * @param bool $strict
<add> * @return \Closure
<add> */
<add> protected function duplicateComparator($strict)
<add> {
<add> return function ($a, $b) {
<add> return $a->is($b);
<add> };
<add> }
<add>
<ide> /**
<ide> * Intersect the collection with the given items.
<ide> *
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function duplicates($callback = null, $strict = false)
<ide>
<ide> $uniqueItems = $items->unique(null, $strict);
<ide>
<del> $compare = $strict ? function ($a, $b) {
<del> return $a === $b;
<del> }
<del> : function ($a, $b) {
<del> return $a == $b;
<del> };
<add> $compare = $this->duplicateComparator($strict);
<ide>
<ide> $duplicates = new static;
<ide>
<ide> public function duplicatesStrict($callback = null)
<ide> return $this->duplicates($callback, true);
<ide> }
<ide>
<add> /**
<add> * Get the comparison function to detect duplicates.
<add> *
<add> * @param bool $strict
<add> * @return \Closure
<add> */
<add> protected function duplicateComparator($strict)
<add> {
<add> if ($strict) {
<add> return function ($a, $b) {
<add> return $a === $b;
<add> };
<add> }
<add>
<add> return function ($a, $b) {
<add> return $a == $b;
<add> };
<add> }
<add>
<ide> /**
<ide> * Execute a callback over each item.
<ide> *
<ide><path>tests/Database/DatabaseEloquentCollectionTest.php
<ide> public function testCollectionDiffsWithGivenCollection()
<ide> $this->assertEquals(new Collection([$one]), $c1->diff($c2));
<ide> }
<ide>
<add> public function testCollectionReturnsDuplicateBasedOnlyOnKeys()
<add> {
<add> $one = new TestEloquentCollectionModel();
<add> $two = new TestEloquentCollectionModel();
<add> $three = new TestEloquentCollectionModel();
<add> $four = new TestEloquentCollectionModel();
<add> $one->id = 1;
<add> $one->someAttribute = '1';
<add> $two->id = 1;
<add> $two->someAttribute = '2';
<add> $three->id = 1;
<add> $three->someAttribute = '3';
<add> $four->id = 2;
<add> $four->someAttribute = '4';
<add>
<add> $duplicates = Collection::make([$one, $two, $three, $four])->duplicates()->all();
<add> $this->assertSame([1 => $two, 2 => $three], $duplicates);
<add>
<add> $duplicates = Collection::make([$one, $two, $three, $four])->duplicatesStrict()->all();
<add> $this->assertSame([1 => $two, 2 => $three], $duplicates);
<add> }
<add>
<ide> public function testCollectionIntersectsWithGivenCollection()
<ide> {
<ide> $one = m::mock(Model::class); | 3 |
Javascript | Javascript | use const instead of var | e0a6c8ef76f8132ed8858989548d075d18c7490d | <ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> };
<ide> }
<ide>
<del> var LINE_CAP_STYLES = [ "butt", "round", "square" ];
<del> var LINE_JOIN_STYLES = [ "miter", "round", "bevel" ];
<del> var NORMAL_CLIP = {};
<del> var EO_CLIP = {};
<add> const LINE_CAP_STYLES = [ "butt", "round", "square" ];
<add> const LINE_JOIN_STYLES = [ "miter", "round", "bevel" ];
<add> const NORMAL_CLIP = {};
<add> const EO_CLIP = {};
<ide>
<ide> constructor.prototype = {
<ide> beginDrawing: function(mediaBox) { | 1 |
Python | Python | simplify container logic | 38636c5a3f14b498aea391a4f2c6b09c5e0395bc | <ide><path>airflow/utils.py
<ide> def __exit__(self, type, value, traceback):
<ide> signal.alarm(0)
<ide>
<ide>
<add>def is_container(obj):
<add> """
<add> Test if an object is a container (iterable) but not a string
<add> """
<add> return hasattr(obj, '__iter__') and not isinstance(obj, basestring)
<add>
<add>
<ide> def as_tuple(obj):
<ide> """
<ide> If obj is a container, returns obj as a tuple.
<ide> Otherwise, returns a tuple containing obj.
<ide> """
<del> def _inner_gen():
<del> try:
<del> for i in obj:
<del> yield i
<del> except:
<del> yield obj
<del> if isinstance(obj, basestring):
<del> return (obj,)
<add> if is_container(obj):
<add> return tuple(obj)
<ide> else:
<del> return tuple(_inner_gen())
<add> return tuple([obj])
<ide>
<ide>
<ide> def round_time(dt, delta): | 1 |
Java | Java | expose rootviewtag for reactrootview | 7d27f4941cf9fa0782dd9fd345b8e7ae507477e2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java
<ide> private void attachMeasuredRootViewToInstance(
<ide>
<ide> UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class);
<ide> int rootTag = uiManagerModule.addMeasuredRootView(rootView);
<add> rootView.setRootViewTag(rootTag);
<ide> @Nullable Bundle launchOptions = rootView.getLaunchOptions();
<ide> WritableMap initialProps = launchOptions != null
<ide> ? Arguments.fromBundle(launchOptions)
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> public class ReactRootView extends SizeMonitoringFrameLayout implements RootView
<ide> private @Nullable Bundle mLaunchOptions;
<ide> private @Nullable KeyboardListener mKeyboardListener;
<ide> private @Nullable OnGenericMotionListener mOnGenericMotionListener;
<add> private int mRootViewTag;
<ide> private boolean mWasMeasured = false;
<ide> private boolean mIsAttachedToInstance = false;
<ide> private final JSTouchDispatcher mJSTouchDispatcher = new JSTouchDispatcher(this);
<ide> protected void finalize() throws Throwable {
<ide> "of your hosting Activity or in the onDestroyView() of your hosting Fragment.");
<ide> }
<ide>
<add> public int getRootViewTag() {
<add> return mRootViewTag;
<add> }
<add>
<add> public void setRootViewTag(int rootViewTag) {
<add> mRootViewTag = rootViewTag;
<add> }
<add>
<ide> private class KeyboardListener implements ViewTreeObserver.OnGlobalLayoutListener {
<ide> private final Rect mVisibleViewArea;
<ide> private final int mMinKeyboardHeightDetected;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/XReactInstanceManagerImpl.java
<ide> private void attachMeasuredRootViewToInstance(
<ide>
<ide> UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class);
<ide> int rootTag = uiManagerModule.addMeasuredRootView(rootView);
<add> rootView.setRootViewTag(rootTag);
<ide> @Nullable Bundle launchOptions = rootView.getLaunchOptions();
<ide> WritableMap initialProps = Arguments.makeNativeMap(launchOptions);
<ide> String jsAppModuleName = rootView.getJSModuleName(); | 3 |
Ruby | Ruby | fix typos in test runner's help output | 64eb76ed1688f43955209eedb6373ba86f962659 | <ide><path>railties/lib/rails/test_unit/runner.rb
<ide> def self.parse(args)
<ide>
<ide> opts.separator ""
<ide> opts.on("-e", "--environment [ENV]",
<del> "run tests in the ENV environment") do |env|
<add> "Run tests in the ENV environment") do |env|
<ide> options[:environment] = env.strip
<ide> end
<ide> opts.separator ""
<ide> def self.parse(args)
<ide> opts.separator "Output options:"
<ide>
<ide> opts.on("-b", "--backtrace",
<del> "show the complte backtrace") do
<add> "Show the complete backtrace") do
<ide> options[:backtrace] = true
<ide> end
<ide> | 1 |
Python | Python | add a predict method in tagging task | 9b4be3abfc107e6d38217e5a4793a5ed08fef600 | <ide><path>official/nlp/data/tagging_data_loader.py
<ide> class TaggingDataConfig(cfg.DataConfig):
<ide> """Data config for tagging (tasks/tagging)."""
<ide> is_training: bool = True
<ide> seq_length: int = 128
<add> include_sentence_id: bool = False
<ide>
<ide>
<ide> @data_loader_factory.register_data_loader_cls(TaggingDataConfig)
<ide> class TaggingDataLoader:
<ide> def __init__(self, params: TaggingDataConfig):
<ide> self._params = params
<ide> self._seq_length = params.seq_length
<add> self._include_sentence_id = params.include_sentence_id
<ide>
<ide> def _decode(self, record: tf.Tensor):
<ide> """Decodes a serialized tf.Example."""
<ide> def _decode(self, record: tf.Tensor):
<ide> 'segment_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
<ide> 'label_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
<ide> }
<add> if self._include_sentence_id:
<add> name_to_features['sentence_id'] = tf.io.FixedLenFeature([], tf.int64)
<add>
<ide> example = tf.io.parse_single_example(record, name_to_features)
<ide>
<ide> # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
<ide> def _parse(self, record: Mapping[str, tf.Tensor]):
<ide> 'input_mask': record['input_mask'],
<ide> 'input_type_ids': record['segment_ids']
<ide> }
<add> if self._include_sentence_id:
<add> x['sentence_id'] = record['sentence_id']
<ide> y = record['label_ids']
<ide> return (x, y)
<ide>
<ide><path>official/nlp/tasks/tagging.py
<del># Lint as: python3
<del># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del># ==============================================================================
<del>"""Tagging (e.g., NER/POS) task."""
<del>import logging
<del>from typing import List, Optional
<del>
<del>import dataclasses
<del>
<del>from seqeval import metrics as seqeval_metrics
<del>
<del>import tensorflow as tf
<del>import tensorflow_hub as hub
<del>
<del>from official.core import base_task
<del>from official.modeling.hyperparams import base_config
<del>from official.modeling.hyperparams import config_definitions as cfg
<del>from official.nlp.configs import encoders
<del>from official.nlp.data import data_loader_factory
<del>from official.nlp.modeling import models
<del>from official.nlp.tasks import utils
<del>
<del>
<del>@dataclasses.dataclass
<del>class ModelConfig(base_config.Config):
<del> """A base span labeler configuration."""
<del> encoder: encoders.TransformerEncoderConfig = (
<del> encoders.TransformerEncoderConfig())
<del> head_dropout: float = 0.1
<del> head_initializer_range: float = 0.02
<del>
<del>
<del>@dataclasses.dataclass
<del>class TaggingConfig(cfg.TaskConfig):
<del> """The model config."""
<del> # At most one of `init_checkpoint` and `hub_module_url` can be specified.
<del> init_checkpoint: str = ''
<del> hub_module_url: str = ''
<del> model: ModelConfig = ModelConfig()
<del>
<del> # The real class names, the order of which should match real label id.
<del> # Note that a word may be tokenized into multiple word_pieces tokens, and
<del> # we asssume the real label id (non-negative) is assigned to the first token
<del> # of the word, and a negative label id is assigned to the remaining tokens.
<del> # The negative label id will not contribute to loss and metrics.
<del> class_names: Optional[List[str]] = None
<del> train_data: cfg.DataConfig = cfg.DataConfig()
<del> validation_data: cfg.DataConfig = cfg.DataConfig()
<del>
<del>
<del>def _masked_labels_and_weights(y_true):
<del> """Masks negative values from token level labels.
<del>
<del> Args:
<del> y_true: Token labels, typically shape (batch_size, seq_len), where tokens
<del> with negative labels should be ignored during loss/accuracy calculation.
<del>
<del> Returns:
<del> (masked_y_true, masked_weights) where `masked_y_true` is the input
<del> with each negative label replaced with zero and `masked_weights` is 0.0
<del> where negative labels were replaced and 1.0 for original labels.
<del> """
<del> # Ignore the classes of tokens with negative values.
<del> mask = tf.greater_equal(y_true, 0)
<del> # Replace negative labels, which are out of bounds for some loss functions,
<del> # with zero.
<del> masked_y_true = tf.where(mask, y_true, 0)
<del> return masked_y_true, tf.cast(mask, tf.float32)
<del>
<del>
<del>@base_task.register_task_cls(TaggingConfig)
<del>class TaggingTask(base_task.Task):
<del> """Task object for tagging (e.g., NER or POS)."""
<del>
<del> def __init__(self, params=cfg.TaskConfig, logging_dir=None):
<del> super(TaggingTask, self).__init__(params, logging_dir)
<del> if params.hub_module_url and params.init_checkpoint:
<del> raise ValueError('At most one of `hub_module_url` and '
<del> '`init_checkpoint` can be specified.')
<del> if not params.class_names:
<del> raise ValueError('TaggingConfig.class_names cannot be empty.')
<del>
<del> if params.hub_module_url:
<del> self._hub_module = hub.load(params.hub_module_url)
<del> else:
<del> self._hub_module = None
<del>
<del> def build_model(self):
<del> if self._hub_module:
<del> encoder_network = utils.get_encoder_from_hub(self._hub_module)
<del> else:
<del> encoder_network = encoders.instantiate_encoder_from_cfg(
<del> self.task_config.model.encoder)
<del>
<del> return models.BertTokenClassifier(
<del> network=encoder_network,
<del> num_classes=len(self.task_config.class_names),
<del> initializer=tf.keras.initializers.TruncatedNormal(
<del> stddev=self.task_config.model.head_initializer_range),
<del> dropout_rate=self.task_config.model.head_dropout,
<del> output='logits')
<del>
<del> def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:
<del> model_outputs = tf.cast(model_outputs, tf.float32)
<del> masked_labels, masked_weights = _masked_labels_and_weights(labels)
<del> loss = tf.keras.losses.sparse_categorical_crossentropy(
<del> masked_labels, model_outputs, from_logits=True)
<del> numerator_loss = tf.reduce_sum(loss * masked_weights)
<del> denominator_loss = tf.reduce_sum(masked_weights)
<del> loss = tf.math.divide_no_nan(numerator_loss, denominator_loss)
<del> return loss
<del>
<del> def build_inputs(self, params, input_context=None):
<del> """Returns tf.data.Dataset for sentence_prediction task."""
<del> if params.input_path == 'dummy':
<del>
<del> def dummy_data(_):
<del> dummy_ids = tf.zeros((1, params.seq_length), dtype=tf.int32)
<del> x = dict(
<del> input_word_ids=dummy_ids,
<del> input_mask=dummy_ids,
<del> input_type_ids=dummy_ids)
<del>
<del> # Include some label_id as -1, which will be ignored in loss/metrics.
<del> y = tf.random.uniform(
<del> shape=(1, params.seq_length),
<del> minval=-1,
<del> maxval=len(self.task_config.class_names),
<del> dtype=tf.dtypes.int32)
<del> return (x, y)
<del>
<del> dataset = tf.data.Dataset.range(1)
<del> dataset = dataset.repeat()
<del> dataset = dataset.map(
<del> dummy_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
<del> return dataset
<del>
<del> return data_loader_factory.get_data_loader(params).load(input_context)
<del>
<del> def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
<del> """Validatation step.
<del>
<del> Args:
<del> inputs: a dictionary of input tensors.
<del> model: the keras.Model.
<del> metrics: a nested structure of metrics objects.
<del>
<del> Returns:
<del> A dictionary of logs.
<del> """
<del> features, labels = inputs
<del> outputs = self.inference_step(features, model)
<del> loss = self.build_losses(labels=labels, model_outputs=outputs)
<del>
<del> # Negative label ids are padding labels which should be ignored.
<del> real_label_index = tf.where(tf.greater_equal(labels, 0))
<del> predict_ids = tf.math.argmax(outputs, axis=-1)
<del> predict_ids = tf.gather_nd(predict_ids, real_label_index)
<del> label_ids = tf.gather_nd(labels, real_label_index)
<del> return {
<del> self.loss: loss,
<del> 'predict_ids': predict_ids,
<del> 'label_ids': label_ids,
<del> }
<del>
<del> def aggregate_logs(self, state=None, step_outputs=None):
<del> """Aggregates over logs returned from a validation step."""
<del> if state is None:
<del> state = {'predict_class': [], 'label_class': []}
<del>
<del> def id_to_class_name(batched_ids):
<del> class_names = []
<del> for per_example_ids in batched_ids:
<del> class_names.append([])
<del> for per_token_id in per_example_ids.numpy().tolist():
<del> class_names[-1].append(self.task_config.class_names[per_token_id])
<del>
<del> return class_names
<del>
<del> # Convert id to class names, because `seqeval_metrics` relies on the class
<del> # name to decide IOB tags.
<del> state['predict_class'].extend(id_to_class_name(step_outputs['predict_ids']))
<del> state['label_class'].extend(id_to_class_name(step_outputs['label_ids']))
<del> return state
<del>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<del> """Reduces aggregated logs over validation steps."""
<del> label_class = aggregated_logs['label_class']
<del> predict_class = aggregated_logs['predict_class']
<del> return {
<del> 'f1':
<del> seqeval_metrics.f1_score(label_class, predict_class),
<del> 'precision':
<del> seqeval_metrics.precision_score(label_class, predict_class),
<del> 'recall':
<del> seqeval_metrics.recall_score(label_class, predict_class),
<del> 'accuracy':
<del> seqeval_metrics.accuracy_score(label_class, predict_class),
<del> }
<del>
<del> def initialize(self, model):
<del> """Load a pretrained checkpoint (if exists) and then train from iter 0."""
<del> ckpt_dir_or_file = self.task_config.init_checkpoint
<del> if tf.io.gfile.isdir(ckpt_dir_or_file):
<del> ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)
<del> if not ckpt_dir_or_file:
<del> return
<del>
<del> ckpt = tf.train.Checkpoint(**model.checkpoint_items)
<del> status = ckpt.restore(ckpt_dir_or_file)
<del> status.expect_partial().assert_existing_objects_matched()
<del> logging.info('Finished loading pretrained checkpoint from %s',
<del> ckpt_dir_or_file)
<ide><path>official/nlp/tasks/tagging_test.py
<del># Lint as: python3
<del># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del># ==============================================================================
<del>"""Tests for official.nlp.tasks.tagging."""
<del>import functools
<del>import os
<del>import tensorflow as tf
<del>
<del>from official.nlp.bert import configs
<del>from official.nlp.bert import export_tfhub
<del>from official.nlp.configs import encoders
<del>from official.nlp.data import tagging_data_loader
<del>from official.nlp.tasks import tagging
<del>
<del>
<del>class TaggingTest(tf.test.TestCase):
<del>
<del> def setUp(self):
<del> super(TaggingTest, self).setUp()
<del> self._encoder_config = encoders.TransformerEncoderConfig(
<del> vocab_size=30522, num_layers=1)
<del> self._train_data_config = tagging_data_loader.TaggingDataConfig(
<del> input_path="dummy", seq_length=128, global_batch_size=1)
<del>
<del> def _run_task(self, config):
<del> task = tagging.TaggingTask(config)
<del> model = task.build_model()
<del> metrics = task.build_metrics()
<del>
<del> strategy = tf.distribute.get_strategy()
<del> dataset = strategy.experimental_distribute_datasets_from_function(
<del> functools.partial(task.build_inputs, config.train_data))
<del>
<del> iterator = iter(dataset)
<del> optimizer = tf.keras.optimizers.SGD(lr=0.1)
<del> task.train_step(next(iterator), model, optimizer, metrics=metrics)
<del> task.validation_step(next(iterator), model, metrics=metrics)
<del>
<del> def test_task(self):
<del> # Saves a checkpoint.
<del> encoder = encoders.instantiate_encoder_from_cfg(self._encoder_config)
<del> ckpt = tf.train.Checkpoint(encoder=encoder)
<del> saved_path = ckpt.save(self.get_temp_dir())
<del>
<del> config = tagging.TaggingConfig(
<del> init_checkpoint=saved_path,
<del> model=tagging.ModelConfig(encoder=self._encoder_config),
<del> train_data=self._train_data_config,
<del> class_names=["O", "B-PER", "I-PER"])
<del> task = tagging.TaggingTask(config)
<del> model = task.build_model()
<del> metrics = task.build_metrics()
<del> dataset = task.build_inputs(config.train_data)
<del>
<del> iterator = iter(dataset)
<del> optimizer = tf.keras.optimizers.SGD(lr=0.1)
<del> task.train_step(next(iterator), model, optimizer, metrics=metrics)
<del> task.validation_step(next(iterator), model, metrics=metrics)
<del> task.initialize(model)
<del>
<del> def test_task_with_fit(self):
<del> config = tagging.TaggingConfig(
<del> model=tagging.ModelConfig(encoder=self._encoder_config),
<del> train_data=self._train_data_config,
<del> class_names=["O", "B-PER", "I-PER"])
<del>
<del> task = tagging.TaggingTask(config)
<del> model = task.build_model()
<del> model = task.compile_model(
<del> model,
<del> optimizer=tf.keras.optimizers.SGD(lr=0.1),
<del> train_step=task.train_step,
<del> metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name="accuracy")])
<del> dataset = task.build_inputs(config.train_data)
<del> logs = model.fit(dataset, epochs=1, steps_per_epoch=2)
<del> self.assertIn("loss", logs.history)
<del> self.assertIn("accuracy", logs.history)
<del>
<del> def _export_bert_tfhub(self):
<del> bert_config = configs.BertConfig(
<del> vocab_size=30522,
<del> hidden_size=16,
<del> intermediate_size=32,
<del> max_position_embeddings=128,
<del> num_attention_heads=2,
<del> num_hidden_layers=1)
<del> _, encoder = export_tfhub.create_bert_model(bert_config)
<del> model_checkpoint_dir = os.path.join(self.get_temp_dir(), "checkpoint")
<del> checkpoint = tf.train.Checkpoint(model=encoder)
<del> checkpoint.save(os.path.join(model_checkpoint_dir, "test"))
<del> model_checkpoint_path = tf.train.latest_checkpoint(model_checkpoint_dir)
<del>
<del> vocab_file = os.path.join(self.get_temp_dir(), "uncased_vocab.txt")
<del> with tf.io.gfile.GFile(vocab_file, "w") as f:
<del> f.write("dummy content")
<del>
<del> hub_destination = os.path.join(self.get_temp_dir(), "hub")
<del> export_tfhub.export_bert_tfhub(bert_config, model_checkpoint_path,
<del> hub_destination, vocab_file)
<del> return hub_destination
<del>
<del> def test_task_with_hub(self):
<del> hub_module_url = self._export_bert_tfhub()
<del> config = tagging.TaggingConfig(
<del> hub_module_url=hub_module_url,
<del> class_names=["O", "B-PER", "I-PER"],
<del> train_data=self._train_data_config)
<del> self._run_task(config)
<del>
<del> def test_seqeval_metrics(self):
<del> config = tagging.TaggingConfig(
<del> model=tagging.ModelConfig(encoder=self._encoder_config),
<del> train_data=self._train_data_config,
<del> class_names=["O", "B-PER", "I-PER"])
<del> task = tagging.TaggingTask(config)
<del> model = task.build_model()
<del> dataset = task.build_inputs(config.train_data)
<del>
<del> iterator = iter(dataset)
<del> strategy = tf.distribute.get_strategy()
<del> distributed_outputs = strategy.run(
<del> functools.partial(task.validation_step, model=model),
<del> args=(next(iterator),))
<del> outputs = tf.nest.map_structure(strategy.experimental_local_results,
<del> distributed_outputs)
<del> aggregated = task.aggregate_logs(step_outputs=outputs)
<del> aggregated = task.aggregate_logs(state=aggregated, step_outputs=outputs)
<del> self.assertCountEqual({"f1", "precision", "recall", "accuracy"},
<del> task.reduce_aggregated_logs(aggregated).keys())
<del>
<del>
<del>if __name__ == "__main__":
<del> tf.test.main() | 3 |
Javascript | Javascript | simplify loaddhparam in tls test | eb68a06a3e66cff0092fc26e79f06a25f8f1ac43 | <ide><path>test/parallel/test-tls-client-getephemeralkeyinfo.js
<ide> const fixtures = require('../common/fixtures');
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<ide>
<ide> const key = fixtures.readKey('agent2-key.pem');
<ide> const cert = fixtures.readKey('agent2-cert.pem');
<ide> let ntests = 0;
<ide> let nsuccess = 0;
<ide>
<ide> function loadDHParam(n) {
<del> let path = fixtures.fixturesDir;
<del> if (n !== 'error') path += '/keys';
<del> return fs.readFileSync(`${path}/dh${n}.pem`);
<add> return fixtures.readKey(`dh${n}.pem`);
<ide> }
<ide>
<ide> const cipherlist = {
<ide><path>test/parallel/test-tls-client-mindhsize.js
<ide> let nsuccess = 0;
<ide> let nerror = 0;
<ide>
<ide> function loadDHParam(n) {
<del> const params = [`dh${n}.pem`];
<del> if (n !== 'error')
<del> params.unshift('keys');
<del> return fixtures.readSync(params);
<add> return fixtures.readKey(`dh${n}.pem`);
<ide> }
<ide>
<ide> function test(size, err, next) { | 2 |
Javascript | Javascript | remove redundant info when starting crash reporter | 0e46298648380dc849c09aa92199fc5a6fa9715f | <ide><path>src/crash-reporter-start.js
<ide> module.exports = function(params) {
<ide> const { crashReporter } = require('electron');
<del> const { uploadToServer, appVersion } = params;
<add> const { uploadToServer } = params;
<ide>
<ide> crashReporter.start({
<ide> productName: 'Atom',
<ide> companyName: 'GitHub',
<ide> submitURL: 'https://atom.io/crash_reports',
<del> uploadToServer,
<del> extra: {
<del> appVersion
<del> }
<add> uploadToServer
<ide> });
<ide> };
<ide><path>src/main-process/start.js
<ide> module.exports = function start(resourcePath, devResourcePath, startTime) {
<ide> app.on('open-file', addPathToOpen);
<ide> app.on('open-url', addUrlToOpen);
<ide> app.on('will-finish-launching', () => startCrashReporter({
<del> uploadToServer: config.get('core.telemetryConsent') === 'limited',
<del> appVersion: app.getVersion()
<add> uploadToServer: config.get('core.telemetryConsent') === 'limited'
<ide> }));
<ide>
<ide> if (args.userDataDir != null) {
<ide><path>static/index.js
<ide> : require('../src/crash-reporter-start');
<ide>
<ide> console.log(getWindowLoadSettings())
<del> const { userSettings, appVersion } = getWindowLoadSettings();
<add> const { userSettings } = getWindowLoadSettings();
<ide> const uploadToServer =
<ide> userSettings &&
<ide> userSettings.core &&
<ide> userSettings.core.telemetryConsent === 'limited';
<ide>
<ide> startCrashReporter({
<ide> uploadToServer,
<del> appVersion
<add> process: 'renderer'
<ide> });
<ide>
<ide> const CSON = useSnapshot | 3 |
Mixed | Ruby | define the duration#instance_of? method | eb73d7dafa343507a60f765c43c748d6987ec652 | <ide><path>activesupport/CHANGELOG.md
<add>* Add the `Duration#instance_of?` method that was previously delegated to the
<add> internal `value` attribute.
<add>
<add> *Robin Dupret*
<add>
<ide> * Fix rounding errors with #travel_to by resetting the usec on any passed time to zero, so we only travel
<ide> with per-second precision, not anything deeper than that.
<del>
<add>
<ide> *DHH*
<ide>
<ide> * Fix ActiveSupport::TestCase not to order users' test cases by default.
<ide><path>activesupport/lib/active_support/duration.rb
<ide> def -@ #:nodoc:
<ide> end
<ide>
<ide> def is_a?(klass) #:nodoc:
<del> Duration == klass || value.is_a?(klass)
<add> instance_of?(klass) || value.is_a?(klass)
<ide> end
<ide> alias :kind_of? :is_a?
<ide>
<add> def instance_of?(klass) # :nodoc:
<add> Duration == klass
<add> end
<add>
<ide> # Returns +true+ if +other+ is also a Duration instance with the
<ide> # same +value+, or if <tt>other == value</tt>.
<ide> def ==(other)
<ide><path>activesupport/test/core_ext/duration_test.rb
<ide> def test_eql
<ide> assert !1.eql?(1.second)
<ide> end
<ide>
<add> def test_instance_of
<add> assert !1.minute.instance_of?(Fixnum)
<add> assert !2.days.instance_of?(Fixnum)
<add> end
<add>
<ide> def test_inspect
<ide> assert_equal '0 seconds', 0.seconds.inspect
<ide> assert_equal '1 month', 1.month.inspect | 3 |
Ruby | Ruby | remove nodoc from flashhash #[]= [ci skip] | a39ab3a57d71990af221a462b0076b6f44b18056 | <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> def initialize_copy(other)
<ide> super
<ide> end
<ide>
<del> def []=(k, v) #:nodoc:
<add> def []=(k, v)
<ide> @discard.delete k
<ide> @flashes[k] = v
<ide> end | 1 |
Mixed | Ruby | change datetime to datetime-local helper tag | aa6dde37cd46fc56b6bd3197564a8428399aec33 | <ide><path>actionview/CHANGELOG.md
<add>* A change was made in the helper that renders the `datetime`, being now by default `datetime-local` and
<add> creating an alias of `datetime-local` for `datetime`, `datetime` tag and it passes to be an abstract class for all other tags that inherit from him.
<add>
<add> As a new specification of the HTML 5 the text field type `datetime` will no longer exist and will pass a `datetime-local`.
<add> Ref: https://html.spec.whatwg.org/multipage/forms.html#local-date-and-time-state-(type=datetime-local)
<add>
<add> *Herminio Torres*
<add>
<ide> * Raw template handler (which is also the default template handler in Rails 5) now outputs
<ide> HTML-safe strings.
<ide>
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def time_field(object_name, method, options = {})
<ide> Tags::TimeField.new(object_name, method, self, options).render
<ide> end
<ide>
<del> # Returns a text_field of type "datetime".
<del> #
<del> # datetime_field("user", "born_on")
<del> # # => <input id="user_born_on" name="user[born_on]" type="datetime" />
<del> #
<del> # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z"
<del> # on the object's value, which makes it behave as expected for instances
<del> # of DateTime and ActiveSupport::TimeWithZone.
<del> #
<del> # @user.born_on = Date.new(1984, 1, 12)
<del> # datetime_field("user", "born_on")
<del> # # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" />
<del> #
<del> # You can create values for the "min" and "max" attributes by passing
<del> # instances of Date or Time to the options hash.
<del> #
<del> # datetime_field("user", "born_on", min: Date.today)
<del> # # => <input id="user_born_on" name="user[born_on]" type="datetime" min="2014-05-20T00:00:00.000+0000" />
<del> #
<del> # Alternatively, you can pass a String formatted as an ISO8601 datetime
<del> # with UTC offset as the values for "min" and "max."
<del> #
<del> # datetime_field("user", "born_on", min: "2014-05-20T00:00:00+0000")
<del> # # => <input id="user_born_on" name="user[born_on]" type="datetime" min="2014-05-20T00:00:00.000+0000" />
<del> #
<del> def datetime_field(object_name, method, options = {})
<del> ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
<del> datetime_field is deprecated and will be removed in Rails 5.1.
<del> Use datetime_local_field instead.
<del> MESSAGE
<del> Tags::DatetimeField.new(object_name, method, self, options).render
<del> end
<del>
<ide> # Returns a text_field of type "datetime-local".
<ide> #
<del> # datetime_local_field("user", "born_on")
<add> # datetime_field("user", "born_on")
<ide> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
<ide> #
<ide> # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
<ide> # on the object's value, which makes it behave as expected for instances
<ide> # of DateTime and ActiveSupport::TimeWithZone.
<ide> #
<ide> # @user.born_on = Date.new(1984, 1, 12)
<del> # datetime_local_field("user", "born_on")
<add> # datetime_field("user", "born_on")
<ide> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
<ide> #
<ide> # You can create values for the "min" and "max" attributes by passing
<ide> # instances of Date or Time to the options hash.
<ide> #
<del> # datetime_local_field("user", "born_on", min: Date.today)
<add> # datetime_field("user", "born_on", min: Date.today)
<ide> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
<ide> #
<ide> # Alternatively, you can pass a String formatted as an ISO8601 datetime as
<ide> # the values for "min" and "max."
<ide> #
<del> # datetime_local_field("user", "born_on", min: "2014-05-20T00:00:00")
<add> # datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
<ide> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
<ide> #
<del> def datetime_local_field(object_name, method, options = {})
<add> def datetime_field(object_name, method, options = {})
<ide> Tags::DatetimeLocalField.new(object_name, method, self, options).render
<ide> end
<ide>
<add> alias datetime_local_field datetime_field
<add>
<ide> # Returns a text_field of type "month".
<ide> #
<ide> # month_field("user", "born_on")
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb
<ide> def time_field_tag(name, value = nil, options = {})
<ide> text_field_tag(name, value, options.merge(type: :time))
<ide> end
<ide>
<del> # Creates a text field of type "datetime".
<del> #
<del> # === Options
<del> # * <tt>:min</tt> - The minimum acceptable value.
<del> # * <tt>:max</tt> - The maximum acceptable value.
<del> # * <tt>:step</tt> - The acceptable value granularity.
<del> # * Otherwise accepts the same options as text_field_tag.
<del> def datetime_field_tag(name, value = nil, options = {})
<del> ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
<del> datetime_field_tag is deprecated and will be removed in Rails 5.1.
<del> Use datetime_local_field_tag instead.
<del> MESSAGE
<del> text_field_tag(name, value, options.merge(type: :datetime))
<del> end
<del>
<ide> # Creates a text field of type "datetime-local".
<ide> #
<ide> # === Options
<ide> # * <tt>:min</tt> - The minimum acceptable value.
<ide> # * <tt>:max</tt> - The maximum acceptable value.
<ide> # * <tt>:step</tt> - The acceptable value granularity.
<ide> # * Otherwise accepts the same options as text_field_tag.
<del> def datetime_local_field_tag(name, value = nil, options = {})
<add> def datetime_field_tag(name, value = nil, options = {})
<ide> text_field_tag(name, value, options.merge(type: 'datetime-local'))
<ide> end
<ide>
<add> alias datetime_local_field_tag datetime_field_tag
<add>
<ide> # Creates a text field of type "month".
<ide> #
<ide> # === Options
<ide><path>actionview/lib/action_view/helpers/tags/datetime_field.rb
<ide> def render
<ide> private
<ide>
<ide> def format_date(value)
<del> value.try(:strftime, "%Y-%m-%dT%T.%L%z")
<add> raise NoImplementedError
<ide> end
<ide>
<ide> def datetime_value(value)
<ide><path>actionview/test/template/form_helper_test.rb
<ide> def test_time_field_with_invalid_string_values_for_min_and_max
<ide> end
<ide>
<ide> def test_datetime_field
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T00:00:00.000+0000" />}
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on"))
<del> end
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T00:00:00" />}
<add> assert_dom_equal(expected, datetime_field("post", "written_on"))
<ide> end
<ide>
<ide> def test_datetime_field_with_datetime_value
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<ide> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on"))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on"))
<ide> end
<ide>
<ide> def test_datetime_field_with_extra_attrs
<del> expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00.000+0000" min="2000-06-15T20:45:30.000+0000" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
<add> expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<ide> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<ide> min_value = DateTime.new(2000, 6, 15, 20, 45, 30)
<ide> max_value = DateTime.new(2010, 8, 15, 10, 25, 00)
<ide> step = 60
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step))
<ide> end
<ide>
<ide> def test_datetime_field_with_value_attr
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2013-06-29T13:37:00+00:00" />}
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2013-06-29T13:37:00+00:00" />}
<ide> value = DateTime.new(2013,6,29,13,37)
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on", value: value))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on", value: value))
<ide> end
<ide>
<ide> def test_datetime_field_with_timewithzone_value
<ide> previous_time_zone, Time.zone = Time.zone, 'UTC'
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T15:30:45.000+0000" />}
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T15:30:45" />}
<ide> @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on"))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on"))
<ide> ensure
<ide> Time.zone = previous_time_zone
<ide> end
<ide>
<ide> def test_datetime_field_with_nil_value
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" />}
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" />}
<ide> @post.written_on = nil
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on"))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on"))
<ide> end
<ide>
<ide> def test_datetime_field_with_string_values_for_min_and_max
<del> expected = %{<input id="post_written_on" max="2010-08-15T10:25:00.000+0000" min="2000-06-15T20:45:30.000+0000" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
<add> expected = %{<input id="post_written_on" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<ide> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> min_value = "2000-06-15T20:45:30.000+0000"
<del> max_value = "2010-08-15T10:25:00.000+0000"
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value))
<del> end
<add> min_value = "2000-06-15T20:45:30"
<add> max_value = "2010-08-15T10:25:00"
<add> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value))
<ide> end
<ide>
<ide> def test_datetime_field_with_invalid_string_values_for_min_and_max
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<ide> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<ide> min_value = "foo"
<ide> max_value = "bar"
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value))
<del> end
<add> assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value))
<ide> end
<ide>
<ide> def test_datetime_local_field
<ide> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T00:00:00" />}
<ide> assert_dom_equal(expected, datetime_local_field("post", "written_on"))
<ide> end
<ide>
<del> def test_datetime_local_field_with_datetime_value
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<del> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on"))
<del> end
<del>
<del> def test_datetime_local_field_with_extra_attrs
<del> expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<del> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> min_value = DateTime.new(2000, 6, 15, 20, 45, 30)
<del> max_value = DateTime.new(2010, 8, 15, 10, 25, 00)
<del> step = 60
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value, step: step))
<del> end
<del>
<del> def test_datetime_local_field_with_timewithzone_value
<del> previous_time_zone, Time.zone = Time.zone, 'UTC'
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T15:30:45" />}
<del> @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on"))
<del> ensure
<del> Time.zone = previous_time_zone
<del> end
<del>
<del> def test_datetime_local_field_with_nil_value
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" />}
<del> @post.written_on = nil
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on"))
<del> end
<del>
<del> def test_datetime_local_field_with_string_values_for_min_and_max
<del> expected = %{<input id="post_written_on" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<del> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> min_value = "2000-06-15T20:45:30"
<del> max_value = "2010-08-15T10:25:00"
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value))
<del> end
<del>
<del> def test_datetime_local_field_with_invalid_string_values_for_min_and_max
<del> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
<del> @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
<del> min_value = "foo"
<del> max_value = "bar"
<del> assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value))
<del> end
<del>
<ide> def test_month_field
<ide> expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />}
<ide> assert_dom_equal(expected, month_field("post", "written_on"))
<ide><path>actionview/test/template/form_tag_helper_test.rb
<ide> def test_time_field_tag
<ide> end
<ide>
<ide> def test_datetime_field_tag
<del> expected = %{<input id="appointment" name="appointment" type="datetime" />}
<del> assert_deprecated do
<del> assert_dom_equal(expected, datetime_field_tag("appointment"))
<del> end
<add> expected = %{<input id="appointment" name="appointment" type="datetime-local" />}
<add> assert_dom_equal(expected, datetime_field_tag("appointment"))
<ide> end
<ide>
<ide> def test_datetime_local_field_tag | 6 |
PHP | PHP | allow null in boolean types | 0f6c391104162ca29198e958f7b348cb5d1b2a51 | <ide><path>src/Database/Type/BoolType.php
<ide> class BoolType extends Type
<ide> */
<ide> public function toDatabase($value, Driver $driver)
<ide> {
<del> if ($value === true || $value === false) {
<add> if ($value === true || $value === false || $value === null) {
<ide> return $value;
<ide> }
<ide>
<ide><path>tests/TestCase/Database/TypeTest.php
<ide> public function testBooleanToDatabase()
<ide> $type = Type::build('boolean');
<ide> $driver = $this->getMock('\Cake\Database\Driver');
<ide>
<add> $this->assertNull($type->toDatabase(null, $driver));
<ide> $this->assertTrue($type->toDatabase(true, $driver));
<ide> $this->assertFalse($type->toDatabase(false, $driver));
<ide> $this->assertTrue($type->toDatabase(1, $driver)); | 2 |
Javascript | Javascript | add early exit to strict mode | e52fa4c575e92b27d5d453829c7110bc5193f7a0 | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> function recursivelyTraverseAndDoubleInvokeEffectsInDEV(
<ide> parentFiber: Fiber,
<ide> isInStrictMode: boolean,
<ide> ) {
<add> if ((parentFiber.subtreeFlags & (PlacementDEV | Visibility)) === NoFlags) {
<add> // Parent's descendants have already had effects double invoked.
<add> // Early exit to avoid unnecessary tree traversal.
<add> return;
<add> }
<ide> let child = parentFiber.child;
<ide> while (child !== null) {
<ide> doubleInvokeEffectsInDEV(root, child, isInStrictMode);
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> function recursivelyTraverseAndDoubleInvokeEffectsInDEV(
<ide> parentFiber: Fiber,
<ide> isInStrictMode: boolean,
<ide> ) {
<add> if ((parentFiber.subtreeFlags & (PlacementDEV | Visibility)) === NoFlags) {
<add> // Parent's descendants have already had effects double invoked.
<add> // Early exit to avoid unnecessary tree traversal.
<add> return;
<add> }
<ide> let child = parentFiber.child;
<ide> while (child !== null) {
<ide> doubleInvokeEffectsInDEV(root, child, isInStrictMode); | 2 |
Python | Python | add sep_toekn between question and choice | df52abe3733484bf62069e819680909e349bac72 | <ide><path>examples/single_model_scripts/utils_multiple_choice.py
<ide> def convert_examples_to_features(examples, label_list, max_seq_length,
<ide> if example.question.find("_") != -1:
<ide> tokens_b = tokenizer.tokenize(example.question.replace("_", ending))
<ide> else:
<del> tokens_b = tokenizer.tokenize(example.question + " " + ending)
<add> tokens_b = tokenizer.tokenize(example.question)
<add> tokens_b += [sep_token]
<add> if sep_token_extra:
<add> tokens_b += [sep_token]
<add> tokens_b += tokenizer.tokenize(ending)
<add>
<ide> special_tokens_count = 4 if sep_token_extra else 3
<ide> _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - special_tokens_count)
<ide>
<ide> def _truncate_seq_pair(tokens_a, tokens_b, max_length):
<ide> total_length = len(tokens_a) + len(tokens_b)
<ide> if total_length <= max_length:
<ide> break
<del> if len(tokens_a) > len(tokens_b):
<del> tokens_a.pop()
<del> else:
<del> tokens_b.pop()
<add> # if len(tokens_a) > len(tokens_b):
<add> # tokens_a.pop()
<add> # else:
<add> # tokens_b.pop()
<add> tokens_a.pop()
<ide>
<ide>
<ide> processors = { | 1 |
Javascript | Javascript | favor arrow functions for anonymous callbacks | d03cff7620f0a62433f36abc252532ab0a79a56c | <ide><path>test/parallel/test-https-agent-additional-options.js
<ide> const options = {
<ide> minVersion: 'TLSv1.1',
<ide> };
<ide>
<del>const server = https.Server(options, function(req, res) {
<add>const server = https.Server(options, (req, res) => {
<ide> res.writeHead(200);
<ide> res.end('hello world\n');
<ide> });
<ide> function variations(iter, port, cb) {
<ide> return common.mustCall(cb);
<ide> } else {
<ide> const [key, val] = value;
<del> return common.mustCall(function(res) {
<add> return common.mustCall((res) => {
<ide> res.resume();
<del> https.globalAgent.once('free', common.mustCall(function() {
<add> https.globalAgent.once('free', common.mustCall(() => {
<ide> https.get(
<ide> Object.assign({}, getBaseOptions(port), { [key]: val }),
<ide> variations(iter, port, cb)
<ide> function variations(iter, port, cb) {
<ide> }
<ide> }
<ide>
<del>server.listen(0, common.mustCall(function() {
<del> const port = this.address().port;
<add>server.listen(0, common.mustCall(() => {
<add> const port = server.address().port;
<ide> const globalAgent = https.globalAgent;
<ide> globalAgent.keepAlive = true;
<ide> https.get(getBaseOptions(port), variations(
<ide> updatedValues.entries(),
<ide> port,
<del> common.mustCall(function(res) {
<add> common.mustCall((res) => {
<ide> res.resume();
<del> globalAgent.once('free', common.mustCall(function() {
<add> globalAgent.once('free', common.mustCall(() => {
<ide> // Verify that different keep-alived connections are created
<ide> // for the base call and each variation
<ide> const keys = Object.keys(globalAgent.freeSockets); | 1 |
Ruby | Ruby | ensure tap is full clone | bdd26d04468e6bbd3cf5e9841a1f163d33884e67 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_bot
<ide> p ARGV
<ide>
<ide> tap = resolve_test_tap
<del> # Tap repository if required, this is done before everything else
<del> # because Formula parsing and/or git commit hash lookup depends on it.
<del> safe_system "brew", "tap", tap.name unless tap.installed?
<add> if tap.installed?
<add> # make sure Tap is not a shallow clone.
<add> # bottle revision and bottle upload rely on full clone.
<add> if (tap.path/".git/shallow").exist?
<add> safe_system "git", "-C", tap.path, "fetch", "--unshallow"
<add> end
<add> else
<add> # Tap repository if required, this is done before everything else
<add> # because Formula parsing and/or git commit hash lookup depends on it.
<add> safe_system "brew", "tap", tap.name, "--full"
<add> end
<ide>
<ide> if ARGV.include? "--ci-upload"
<ide> return test_ci_upload(tap) | 1 |
Java | Java | simplify comparison of primitives | e352e9ddaae1726a95c4ecc5d09cbea5d5bf90ff | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveConstructorResolver.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2019 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> public ConstructorExecutor resolve(EvaluationContext context, String typeName, L
<ide> Arrays.sort(ctors, (c1, c2) -> {
<ide> int c1pl = c1.getParameterCount();
<ide> int c2pl = c2.getParameterCount();
<del> return (c1pl < c2pl ? -1 : (c1pl > c2pl ? 1 : 0));
<add> return Integer.compare(c1pl, c2pl);
<ide> });
<ide>
<ide> Constructor<?> closeMatch = null;
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/StandardTypeComparator.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2019 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> else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger)
<ide> return leftBigInteger.compareTo(rightBigInteger);
<ide> }
<ide> else if (leftNumber instanceof Long || rightNumber instanceof Long) {
<del> // Don't call Long.compare here - only available on JDK 1.7+
<del> return compare(leftNumber.longValue(), rightNumber.longValue());
<add> return Long.compare(leftNumber.longValue(), rightNumber.longValue());
<ide> }
<ide> else if (leftNumber instanceof Integer || rightNumber instanceof Integer) {
<del> // Don't call Integer.compare here - only available on JDK 1.7+
<del> return compare(leftNumber.intValue(), rightNumber.intValue());
<add> return Integer.compare(leftNumber.intValue(), rightNumber.intValue());
<ide> }
<ide> else if (leftNumber instanceof Short || rightNumber instanceof Short) {
<del> // Don't call Short.compare here - only available on JDK 1.7+
<del> return compare(leftNumber.shortValue(), rightNumber.shortValue());
<add> return leftNumber.shortValue() - rightNumber.shortValue();
<ide> }
<ide> else if (leftNumber instanceof Byte || rightNumber instanceof Byte) {
<del> // Don't call Short.compare here - only available on JDK 1.7+
<del> return compare(leftNumber.byteValue(), rightNumber.byteValue());
<add> return leftNumber.byteValue() - rightNumber.byteValue();
<ide> }
<ide> else {
<ide> // Unknown Number subtypes -> best guess is double multiplication
<ide> else if (leftNumber instanceof Byte || rightNumber instanceof Byte) {
<ide> throw new SpelEvaluationException(SpelMessage.NOT_COMPARABLE, left.getClass(), right.getClass());
<ide> }
<ide>
<del>
<del> private static int compare(long x, long y) {
<del> return (x < y ? -1 : (x > y ? 1 : 0));
<del> }
<del>
<del> private static int compare(int x, int y) {
<del> return (x < y ? -1 : (x > y ? 1 : 0));
<del> }
<del>
<del> private static int compare(short x, short y) {
<del> return x - y;
<del> }
<del>
<del> private static int compare(byte x, byte y) {
<del> return x - y;
<del> }
<del>
<ide> } | 2 |
Python | Python | move an mport out of a function | 9117a4af30b87f95f87a5ebdb2a0af965d4bebb6 | <ide><path>django/utils/functional.py
<add>import copy
<ide> import operator
<ide> from functools import wraps, update_wrapper
<ide>
<ide> def __deepcopy__(self, memo):
<ide> memo[id(self)] = result
<ide> return result
<ide> else:
<del> import copy
<ide> return copy.deepcopy(self._wrapped, memo)
<ide>
<ide> # Need to pretend to be the wrapped class, for the sake of objects that care | 1 |
Go | Go | remove unused ttyterminal interface | 6ae377ffa0c106749db1bcd6cf158f8b0056dea8 | <ide><path>daemon/execdriver/driver.go
<ide> type Terminal interface {
<ide> Resize(height, width int) error
<ide> }
<ide>
<del>type TtyTerminal interface {
<del> Master() libcontainer.Console
<del>}
<del>
<ide> // ExitStatus provides exit reasons for a container.
<ide> type ExitStatus struct {
<ide> // The exit code with which the container exited.
<ide><path>daemon/execdriver/lxc/driver.go
<ide> func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pi
<ide> return tty, nil
<ide> }
<ide>
<del>func (t *TtyConsole) Master() *os.File {
<del> return t.MasterPty
<del>}
<del>
<ide> func (t *TtyConsole) Resize(h, w int) error {
<ide> return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
<ide> }
<ide><path>daemon/execdriver/native/driver.go
<ide> func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes, rootui
<ide> return tty, nil
<ide> }
<ide>
<del>func (t *TtyConsole) Master() libcontainer.Console {
<del> return t.console
<del>}
<del>
<ide> func (t *TtyConsole) Resize(h, w int) error {
<ide> return term.SetWinsize(t.console.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
<ide> } | 3 |
PHP | PHP | apply fixes from styleci | 5781ad4fc123731eb485c919a1d388faef467da9 | <ide><path>src/Illuminate/Validation/Rules/RequiredIf.php
<ide> public function __construct($condition)
<ide> if (! is_string($condition) && (is_bool($condition) || is_callable($condition))) {
<ide> $this->condition = $condition;
<ide> } else {
<del> throw new InvalidArgumentException("The provided condition must be a callable or boolean.");
<add> throw new InvalidArgumentException('The provided condition must be a callable or boolean.');
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | add jsdoc typings for timers | c4096a35d651399f79948395c233747dcacc83aa | <ide><path>lib/timers.js
<ide> function enroll(item, msecs) {
<ide> }
<ide>
<ide>
<del>/*
<del> * DOM-style timers
<add>/**
<add> * Schedules the execution of a one-time `callback`
<add> * after `after` milliseconds.
<add> * @param {Function} callback
<add> * @param {number} [after]
<add> * @param {any} [arg1]
<add> * @param {any} [arg2]
<add> * @param {any} [arg3]
<add> * @returns {Timeout}
<ide> */
<del>
<ide> function setTimeout(callback, after, arg1, arg2, arg3) {
<ide> validateCallback(callback);
<ide>
<ide> ObjectDefineProperty(setTimeout, customPromisify, {
<ide> }
<ide> });
<ide>
<add>/**
<add> * Cancels a timeout.
<add> * @param {Timeout | string | number} timer
<add> * @returns {void}
<add> */
<ide> function clearTimeout(timer) {
<ide> if (timer && timer._onTimeout) {
<ide> timer._onTimeout = null;
<ide> function clearTimeout(timer) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Schedules repeated execution of `callback`
<add> * every `repeat` milliseconds.
<add> * @param {Function} callback
<add> * @param {number} [repeat]
<add> * @param {any} [arg1]
<add> * @param {any} [arg2]
<add> * @param {any} [arg3]
<add> * @returns {Timeout}
<add> */
<ide> function setInterval(callback, repeat, arg1, arg2, arg3) {
<ide> validateCallback(callback);
<ide>
<ide> function setInterval(callback, repeat, arg1, arg2, arg3) {
<ide> return timeout;
<ide> }
<ide>
<add>/**
<add> * Cancels an interval.
<add> * @param {Timeout | string | number} timer
<add> * @returns {void}
<add> */
<ide> function clearInterval(timer) {
<ide> // clearTimeout and clearInterval can be used to clear timers created from
<ide> // both setTimeout and setInterval, as specified by HTML Living Standard:
<ide> Timeout.prototype.close = function() {
<ide> return this;
<ide> };
<ide>
<add>/**
<add> * Coerces a `Timeout` to a primitive.
<add> * @returns {number}
<add> */
<ide> Timeout.prototype[SymbolToPrimitive] = function() {
<ide> const id = this[async_id_symbol];
<ide> if (!this[kHasPrimitive]) {
<ide> Timeout.prototype[SymbolToPrimitive] = function() {
<ide> return id;
<ide> };
<ide>
<add>/**
<add> * Schedules the immediate execution of `callback`
<add> * after I/O events' callbacks.
<add> * @param {Function} callback
<add> * @param {any} [arg1]
<add> * @param {any} [arg2]
<add> * @param {any} [arg3]
<add> * @returns {Immediate}
<add> */
<ide> function setImmediate(callback, arg1, arg2, arg3) {
<ide> validateCallback(callback);
<ide>
<ide> ObjectDefineProperty(setImmediate, customPromisify, {
<ide> }
<ide> });
<ide>
<del>
<add>/**
<add> * Cancels an immediate.
<add> * @param {Immediate} immediate
<add> * @returns {void}
<add> */
<ide> function clearImmediate(immediate) {
<ide> if (!immediate || immediate._destroyed)
<ide> return; | 1 |
Python | Python | replace import * with explicit import | dc2c4f785a3c552640aba7861f5e1fea849a7cbb | <ide><path>numpy/linalg/lapack_lite/clapack_scrub.py
<ide> import sys, os
<ide> from io import StringIO
<ide> import re
<del>
<del>from Plex import *
<add>from Plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE
<ide> from Plex.Traditional import re as Re
<ide>
<ide> class MyScanner(Scanner): | 1 |
Javascript | Javascript | simplify check in child_process | 549a11c7b275f4c6495e1cae4f34eac5110e888d | <ide><path>lib/child_process.js
<ide> function fork(modulePath /* , args, options */) {
<ide> args = arguments[pos++];
<ide> }
<ide>
<del> if (pos < arguments.length &&
<del> (arguments[pos] === undefined || arguments[pos] === null)) {
<add> if (pos < arguments.length && arguments[pos] == null) {
<ide> pos++;
<ide> }
<ide> | 1 |
PHP | PHP | reset node level when recovering tree | 52853ac5b5a7192970655390772e5fc0973619e8 | <ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> public function recover()
<ide> *
<ide> * @param int $counter The Last left column value that was assigned
<ide> * @param mixed $parentId the parent id of the level to be recovered
<add> * @param int $level Node level
<ide> * @return int The next value to use for the left column
<ide> */
<del> protected function _recoverTree($counter = 0, $parentId = null)
<add> protected function _recoverTree($counter = 0, $parentId = null, $level = -1)
<ide> {
<ide> $config = $this->config();
<ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
<ide> protected function _recoverTree($counter = 0, $parentId = null)
<ide> ->hydrate(false);
<ide>
<ide> $leftCounter = $counter;
<add> $nextLevel = $level + 1;
<ide> foreach ($query as $row) {
<ide> $counter++;
<del> $counter = $this->_recoverTree($counter, $row[$pk[0]]);
<add> $counter = $this->_recoverTree($counter, $row[$pk[0]], $nextLevel);
<ide> }
<ide>
<ide> if ($parentId === null) {
<ide> return $counter;
<ide> }
<ide>
<add> $fields = [$left => $leftCounter, $right => $counter + 1];
<add> if ($config['level']) {
<add> $fields[$config['level']] = $level;
<add> }
<add>
<ide> $this->_table->updateAll(
<del> [$left => $leftCounter, $right => $counter + 1],
<add> $fields,
<ide> [$pk[0] => $parentId]
<ide> );
<ide>
<ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php
<ide> public function testMoveDownMultiplePositions()
<ide> public function testRecover()
<ide> {
<ide> $table = $this->table;
<del> $table->updateAll(['lft' => null, 'rght' => null], []);
<add>
<add> $expectedLevels = $table->find('list', ['valueField' => 'depth'])->toArray();
<add> $table->updateAll(['lft' => null, 'rght' => null, 'depth' => null], []);
<add> $table->behaviors()->Tree->config('level', 'depth');
<ide> $table->recover();
<ide>
<ide> $expected = [
<ide> public function testRecover()
<ide> '__17:18 - 10:radios',
<ide> '21:22 - 11:alien hardware'
<ide> ];
<del> $this->assertMpttValues($expected, $this->table);
<add> $this->assertMpttValues($expected, $table);
<add>
<add> $result = $table->find('list', ['valueField' => 'depth'])->toArray();
<add> $this->assertSame($expectedLevels, $result);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | remove use of arguments in server constructor | cca8de6709ece5b4791d52a8b834da83bfb782d5 | <ide><path>lib/net.js
<ide> function isPipeName(s) {
<ide> return typeof s === 'string' && toNumber(s) === false;
<ide> }
<ide>
<del>exports.createServer = function() {
<del> return new Server(arguments[0], arguments[1]);
<add>exports.createServer = function(options, connectionListener) {
<add> return new Server(options, connectionListener);
<ide> };
<ide>
<ide>
<ide> function afterConnect(status, handle, req, readable, writable) {
<ide> }
<ide>
<ide>
<del>function Server(/* [ options, ] listener */) {
<del> if (!(this instanceof Server)) return new Server(arguments[0], arguments[1]);
<add>function Server(options, connectionListener) {
<add> if (!(this instanceof Server))
<add> return new Server(options, connectionListener);
<add>
<ide> events.EventEmitter.call(this);
<ide>
<ide> var self = this;
<del>
<ide> var options;
<ide>
<del> if (typeof arguments[0] === 'function') {
<add> if (typeof options === 'function') {
<add> connectionListener = options;
<ide> options = {};
<del> self.on('connection', arguments[0]);
<add> self.on('connection', connectionListener);
<ide> } else {
<del> options = arguments[0] || {};
<add> options = options || {};
<ide>
<del> if (typeof arguments[1] === 'function') {
<del> self.on('connection', arguments[1]);
<add> if (typeof connectionListener === 'function') {
<add> self.on('connection', connectionListener);
<ide> }
<ide> }
<ide> | 1 |
Python | Python | fix pip args | b9573e9e2232c3a91e7713f78191a23d4d3e9c77 | <ide><path>spacy/cli/download.py
<ide> def download_model(
<ide> filename: str, user_pip_args: Optional[Sequence[str]] = None
<ide> ) -> None:
<ide> download_url = about.__download_url__ + "/" + filename
<del> pip_args = user_pip_args if user_pip_args is not None else []
<add> pip_args = list(user_pip_args) if user_pip_args is not None else []
<ide> cmd = [sys.executable, "-m", "pip", "install"] + pip_args + [download_url]
<ide> run_command(cmd) | 1 |
Javascript | Javascript | add names to anon functions in node managers | cdc496a0fcc9a7cafc01eca7943b59ab59a42081 | <ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> function ComponentNodeManager(component, isAngleBracket, scope, renderNode, attr
<ide>
<ide> export default ComponentNodeManager;
<ide>
<del>ComponentNodeManager.create = function(renderNode, env, options) {
<add>ComponentNodeManager.create = function ComponentNodeManager_create(renderNode, env, options) {
<ide> let { tagName,
<ide> params,
<ide> attrs,
<ide> function configureCreateOptions(attrs, createOptions) {
<ide> if (attrs.viewName) { createOptions.viewName = getValue(attrs.viewName); }
<ide> }
<ide>
<del>ComponentNodeManager.prototype.render = function(_env, visitor) {
<add>ComponentNodeManager.prototype.render = function ComponentNodeManager_render(_env, visitor) {
<ide> var { component } = this;
<ide>
<del> return instrument(component, function() {
<add> return instrument(component, function ComponentNodeManager_render_instrument() {
<ide> let env = _env.childWithView(component);
<ide>
<ide> env.renderer.componentWillRender(component);
<ide> function nextElementSibling(node) {
<ide> }
<ide> }
<ide>
<del>ComponentNodeManager.prototype.rerender = function(_env, attrs, visitor) {
<add>ComponentNodeManager.prototype.rerender = function ComponentNodeManager_rerender(_env, attrs, visitor) {
<ide> var component = this.component;
<ide>
<del> return instrument(component, function() {
<add> return instrument(component, function ComponentNodeManager_rerender_instrument() {
<ide> let env = _env.childWithView(component);
<ide>
<ide> var snapshot = takeSnapshot(attrs);
<ide> ComponentNodeManager.prototype.rerender = function(_env, attrs, visitor) {
<ide> }, this);
<ide> };
<ide>
<del>ComponentNodeManager.prototype.destroy = function() {
<add>ComponentNodeManager.prototype.destroy = function ComponentNodeManager_destroy() {
<ide> let component = this.component;
<ide>
<ide> // Clear component's render node. Normally this gets cleared
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js
<ide> function ViewNodeManager(component, scope, renderNode, block, expectElement) {
<ide>
<ide> export default ViewNodeManager;
<ide>
<del>ViewNodeManager.create = function(renderNode, env, attrs, found, parentView, path, contentScope, contentTemplate) {
<add>ViewNodeManager.create = function ViewNodeManager_create(renderNode, env, attrs, found, parentView, path, contentScope, contentTemplate) {
<ide> assert('HTMLBars error: Could not find component named "' + path + '" (no component or template with that name was found)', function() {
<ide> if (path) {
<ide> return found.component || found.layout;
<ide> ViewNodeManager.create = function(renderNode, env, attrs, found, parentView, pat
<ide> return new ViewNodeManager(component, contentScope, renderNode, results.block, results.createdElement);
<ide> };
<ide>
<del>ViewNodeManager.prototype.render = function(env, attrs, visitor) {
<add>ViewNodeManager.prototype.render = function ViewNodeManager_render(env, attrs, visitor) {
<ide> var component = this.component;
<ide>
<del> return instrument(component, function() {
<add> return instrument(component, function ViewNodeManager_render_instrument() {
<ide> var newEnv = env;
<ide> if (component) {
<ide> newEnv = env.childWithView(component);
<ide> ViewNodeManager.prototype.render = function(env, attrs, visitor) {
<ide> }, this);
<ide> };
<ide>
<del>ViewNodeManager.prototype.rerender = function(env, attrs, visitor) {
<add>ViewNodeManager.prototype.rerender = function ViewNodeManager_rerender(env, attrs, visitor) {
<ide> var component = this.component;
<ide>
<del> return instrument(component, function() {
<add> return instrument(component, function ViewNodeManager_rerender_instrument() {
<ide> var newEnv = env;
<ide> if (component) {
<ide> newEnv = env.childWithView(component);
<ide> ViewNodeManager.prototype.rerender = function(env, attrs, visitor) {
<ide> }, this);
<ide> };
<ide>
<del>ViewNodeManager.prototype.destroy = function() {
<add>ViewNodeManager.prototype.destroy = function ViewNodeManager_destroy() {
<ide> if (this.component) {
<ide> this.component.destroy();
<ide> this.component = null; | 2 |
Javascript | Javascript | make streamwrap work correctly in "drain" callback | e4dea40ce779ae03a77c194074e5aa06a8a28a78 | <ide><path>lib/internal/wrap_js_stream.js
<ide> class JSStreamWrap extends Socket {
<ide> }
<ide>
<ide> doShutdown(req) {
<del> assert.strictEqual(this[kCurrentShutdownRequest], null);
<del> this[kCurrentShutdownRequest] = req;
<del>
<ide> // TODO(addaleax): It might be nice if we could get into a state where
<ide> // DoShutdown() is not called on streams while a write is still pending.
<ide> //
<ide> class JSStreamWrap extends Socket {
<ide> // so for now that is supported here.
<ide>
<ide> if (this[kCurrentWriteRequest] !== null)
<del> return this.on('drain', () => this.doShutdown(req));
<add> return this.once('drain', () => this.doShutdown(req));
<ide> assert.strictEqual(this[kCurrentWriteRequest], null);
<add> assert.strictEqual(this[kCurrentShutdownRequest], null);
<add> this[kCurrentShutdownRequest] = req;
<ide>
<ide> const handle = this._handle;
<ide>
<ide><path>test/parallel/test-stream-wrap-drain.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { StreamWrap } = require('_stream_wrap');
<add>const { Duplex } = require('stream');
<add>const { internalBinding } = require('internal/test/binding');
<add>const { ShutdownWrap } = internalBinding('stream_wrap');
<add>
<add>// This test makes sure that when an instance of JSStreamWrap is waiting for
<add>// a "drain" event to `doShutdown`, the instance will work correctly when a
<add>// "drain" event emitted.
<add>{
<add> let resolve = null;
<add>
<add> class TestDuplex extends Duplex {
<add> _write(chunk, encoding, callback) {
<add> // We will resolve the write later.
<add> resolve = () => {
<add> callback();
<add> };
<add> }
<add>
<add> _read() {}
<add> }
<add>
<add> const testDuplex = new TestDuplex();
<add> const socket = new StreamWrap(testDuplex);
<add>
<add> socket.write(
<add> // Make the buffer long enough so that the `Writable` will emit "drain".
<add> Buffer.allocUnsafe(socket.writableHighWaterMark * 2),
<add> common.mustCall()
<add> );
<add>
<add> // Make sure that the 'drain' events will be emitted.
<add> testDuplex.on('drain', common.mustCall(() => {
<add> console.log('testDuplex drain');
<add> }));
<add>
<add> assert.strictEqual(typeof resolve, 'function');
<add>
<add> const req = new ShutdownWrap();
<add> req.oncomplete = common.mustCall();
<add> req.handle = socket._handle;
<add> // Should not throw.
<add> socket._handle.shutdown(req);
<add>
<add> resolve();
<add>} | 2 |
Javascript | Javascript | fix suggestion to "npm start -- --reset-cache" | 06dd08316f449d63ccb67a788f4bc845c1e5c060 | <ide><path>packager/src/node-haste/DependencyGraph/ResolutionRequest.js
<ide> class ResolutionRequest {
<ide> `To resolve try the following:\n` +
<ide> ` 1. Clear watchman watches: \`watchman watch-del-all\`.\n` +
<ide> ` 2. Delete the \`node_modules\` folder: \`rm -rf node_modules && npm install\`.\n` +
<del> ' 3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start --reset-cache`.'
<add> ' 3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start -- --reset-cache`.'
<ide> );
<ide> });
<ide> }); | 1 |
Python | Python | remove use of trackablesaver in keras | af70910ffc1d8a3591bfea76728029e100e92a7b | <ide><path>keras/engine/training.py
<ide> from keras.utils import generic_utils
<ide> from keras.utils import io_utils
<ide> from keras.utils import layer_utils
<del>from keras.utils import object_identity
<ide> from keras.utils import tf_utils
<ide> from keras.utils import traceback_utils
<ide> from keras.utils import version_utils
<ide> def __init__(self, *args, **kwargs):
<ide> self._training_state = None
<ide> self._saved_model_inputs_spec = None
<ide> self._saved_model_arg_spec = None
<del> self._trackable_saver = saver_with_op_caching(self)
<add> self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
<ide>
<ide> self._steps_per_execution = None
<ide>
<ide> def save_weights(self,
<ide> with h5py.File(filepath, 'w') as f:
<ide> hdf5_format.save_weights_to_hdf5_group(f, self)
<ide> else:
<del> if tf.executing_eagerly():
<del> session = None
<del> else:
<del> session = backend.get_session()
<del> self._trackable_saver.save(filepath, session=session, options=options)
<add> if not tf.executing_eagerly():
<add> # Call `get_session` to initialize any uninitialized variables.
<add> backend.get_session()
<add> self._checkpoint.write(filepath, options=options)
<add>
<ide> # Record this checkpoint so it's visible from tf.train.latest_checkpoint.
<ide> tf.__internal__.train.update_checkpoint_state(
<ide> save_dir=os.path.dirname(filepath),
<ide> def load_weights(self,
<ide>
<ide> filepath, save_format = _detect_save_format(filepath)
<ide> if save_format == 'tf':
<del> status = self._trackable_saver.restore(filepath, options)
<add> status = self._checkpoint.read(filepath, options)
<ide> if by_name:
<ide> raise NotImplementedError(
<ide> 'Weights may only be loaded based on topology into Models when '
<ide> def _is_per_replica_instance(obj):
<ide> isinstance(obj, tf.__internal__.CompositeTensor))
<ide>
<ide>
<del>def saver_with_op_caching(obj):
<del> if tf.executing_eagerly():
<del> saveables_cache = None
<del> else:
<del> saveables_cache = object_identity.ObjectIdentityWeakKeyDictionary()
<del> return tf.__internal__.tracking.TrackableSaver(
<del> tf.__internal__.tracking.ObjectGraphView(
<del> weakref.ref(obj), saveables_cache=saveables_cache))
<del>
<del>
<ide> def disable_multi_worker(method):
<ide> """Decorator that disallows multi-worker use of `method`."""
<ide>
<ide><path>keras/tests/tracking_util_test.py
<ide> def testLoadFromNameBasedSaver(self):
<ide> self._set_sentinels(root)
<ide> with self.assertRaises(AssertionError):
<ide> self._check_sentinels(root)
<del> object_saver = tf.__internal__.tracking.TrackableSaver(
<del> tf.__internal__.tracking.ObjectGraphView(root))
<add> object_saver = tf.train.Checkpoint(root=root)
<ide> self._set_sentinels(root)
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> if tf.executing_eagerly():
<ide> self._check_sentinels(root)
<ide> if tf.executing_eagerly():
<ide> def testLoadFromNameBasedSaver(self):
<ide> status.run_restore_ops()
<ide> self._check_sentinels(root)
<ide> self._set_sentinels(root)
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> status.initialize_or_restore()
<ide> status.assert_nontrivial_match()
<ide> self._check_sentinels(root)
<ide> # Check that there is no error when keys are missing from the name-based
<ide> # checkpoint.
<ide> root.not_in_name_checkpoint = tf.Variable([1.])
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> with self.assertRaises(AssertionError):
<ide> status.assert_existing_objects_matched()
<ide>
<ide><path>keras/tests/tracking_util_with_v1_optimizers_test.py
<ide> def testLoadFromNameBasedSaver(self):
<ide> self._set_sentinels(root)
<ide> with self.assertRaises(AssertionError):
<ide> self._check_sentinels(root)
<del> object_saver = tf.__internal__.tracking.TrackableSaver(
<del> tf.__internal__.tracking.ObjectGraphView(root))
<add> object_saver = tf.train.Checkpoint(root=root)
<ide> self._set_sentinels(root)
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> if tf.executing_eagerly():
<ide> self._check_sentinels(root)
<ide> if tf.executing_eagerly():
<ide> def testLoadFromNameBasedSaver(self):
<ide> status.run_restore_ops()
<ide> self._check_sentinels(root)
<ide> self._set_sentinels(root)
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> status.initialize_or_restore()
<ide> self._check_sentinels(root)
<ide> # Check that there is no error when keys are missing from the name-based
<ide> # checkpoint.
<ide> root.not_in_name_checkpoint = tf.Variable([1.])
<del> status = object_saver.restore(save_path)
<add> status = object_saver.read(save_path)
<ide> with self.assertRaises(AssertionError):
<ide> status.assert_existing_objects_matched()
<ide> | 3 |
Javascript | Javascript | reduce code size of event modules | 51e66cf9fa3448efdc7c5938405757dbb53c9079 | <ide><path>packages/react-dom/src/events/DOMEventResponderSystem.js
<ide> const eventResponderContext: ReactResponderContext = {
<ide> }
<ide> return false;
<ide> },
<del> isTargetWithinEventComponent(target: Element | Document): boolean {
<del> validateResponderContext();
<del> if (target != null) {
<del> let fiber = getClosestInstanceFromNode(target);
<del> while (fiber !== null) {
<del> if (fiber.stateNode === currentInstance) {
<del> return true;
<del> }
<del> fiber = fiber.return;
<del> }
<del> }
<del> return false;
<del> },
<add> isTargetWithinEventComponent,
<ide> isTargetWithinEventResponderScope(target: Element | Document): boolean {
<ide> validateResponderContext();
<ide> const responder = ((currentInstance: any): ReactEventComponentInstance)
<ide> const eventResponderContext: ReactResponderContext = {
<ide> return focusableElements;
<ide> },
<ide> getActiveDocument,
<add> objectAssign: Object.assign,
<add> getEventPointerType(
<add> event: ReactResponderEvent,
<add> ): '' | 'mouse' | 'keyboard' | 'pen' | 'touch' {
<add> const nativeEvent: any = event.nativeEvent;
<add> const {type, pointerType} = nativeEvent;
<add> if (pointerType != null) {
<add> return pointerType;
<add> }
<add> if (type.indexOf('mouse') === 0) {
<add> return 'mouse';
<add> }
<add> if (type.indexOf('touch') === 0) {
<add> return 'touch';
<add> }
<add> if (type.indexOf('key') === 0) {
<add> return 'keyboard';
<add> }
<add> return '';
<add> },
<add> getEventCurrentTarget(event: ReactResponderEvent): Element {
<add> const target: any = event.target;
<add> let currentTarget = target;
<add> while (
<add> currentTarget.parentNode &&
<add> currentTarget.parentNode.nodeType === Node.ELEMENT_NODE &&
<add> isTargetWithinEventComponent(currentTarget.parentNode)
<add> ) {
<add> currentTarget = currentTarget.parentNode;
<add> }
<add> return currentTarget;
<add> },
<ide> };
<ide>
<add>function isTargetWithinEventComponent(target: Element | Document): boolean {
<add> validateResponderContext();
<add> if (target != null) {
<add> let fiber = getClosestInstanceFromNode(target);
<add> while (fiber !== null) {
<add> if (fiber.stateNode === currentInstance) {
<add> return true;
<add> }
<add> fiber = fiber.return;
<add> }
<add> }
<add> return false;
<add>}
<add>
<ide> function getActiveDocument(): Document {
<ide> const eventComponentInstance = ((currentInstance: any): ReactEventComponentInstance);
<ide> const rootElement = ((eventComponentInstance.rootInstance: any): Element);
<ide><path>packages/react-events/src/Focus.js
<ide> import type {
<ide> } from 'shared/ReactTypes';
<ide>
<ide> import React from 'react';
<del>import {getEventCurrentTarget} from './utils.js';
<ide>
<ide> type FocusProps = {
<ide> disabled: boolean,
<ide> const FocusResponder = {
<ide> if (!state.isFocused) {
<ide> // Limit focus events to the direct child of the event component.
<ide> // Browser focus is not expected to bubble.
<del> state.focusTarget = getEventCurrentTarget(event, context);
<add> state.focusTarget = context.getEventCurrentTarget(event);
<ide> if (state.focusTarget === target) {
<ide> state.isFocused = true;
<ide> state.isLocalFocusVisible = isGlobalFocusVisible;
<ide> const FocusResponder = {
<ide> // Focus should stop being visible if a pointer is used on the element
<ide> // after it was focused using a keyboard.
<ide> if (
<del> state.focusTarget === getEventCurrentTarget(event, context) &&
<add> state.focusTarget === context.getEventCurrentTarget(event) &&
<ide> (type === 'mousedown' ||
<ide> type === 'touchstart' ||
<ide> type === 'pointerdown')
<ide><path>packages/react-events/src/Hover.js
<ide> import type {
<ide> } from 'shared/ReactTypes';
<ide>
<ide> import React from 'react';
<del>import {
<del> getEventPointerType,
<del> getEventCurrentTarget,
<del> isEventPositionWithinTouchHitTarget,
<del>} from './utils';
<add>import {isEventPositionWithinTouchHitTarget} from './utils';
<ide>
<ide> type HoverProps = {
<ide> disabled: boolean,
<ide> const HoverResponder = {
<ide> }
<ide> return;
<ide> }
<del> const pointerType = getEventPointerType(event);
<add> const pointerType = context.getEventPointerType(event);
<ide>
<ide> switch (type) {
<ide> // START
<ide> const HoverResponder = {
<ide> state.isOverTouchHitTarget = true;
<ide> return;
<ide> }
<del> state.hoverTarget = getEventCurrentTarget(event, context);
<add> state.hoverTarget = context.getEventCurrentTarget(event);
<ide> state.ignoreEmulatedMouseEvents = true;
<ide> dispatchHoverStartEvents(event, context, props, state);
<ide> }
<ide><path>packages/react-events/src/Press.js
<ide> import type {
<ide>
<ide> import React from 'react';
<ide>
<del>import {
<del> getEventPointerType,
<del> getEventCurrentTarget,
<del> isEventPositionWithinTouchHitTarget,
<del>} from './utils';
<add>import {isEventPositionWithinTouchHitTarget} from './utils';
<ide>
<ide> type PressProps = {
<ide> disabled: boolean,
<ide> function calculateDelayMS(delay: ?number, min = 0, fallback = 0) {
<ide> }
<ide>
<ide> // TODO: account for touch hit slop
<del>function calculateResponderRegion(target: Element, props: PressProps) {
<del> const pressRetentionOffset = {
<add>function calculateResponderRegion(
<add> context: ReactResponderContext,
<add> target: Element,
<add> props: PressProps,
<add>) {
<add> const pressRetentionOffset = context.objectAssign(
<add> {},
<ide> ...DEFAULT_PRESS_RETENTION_OFFSET,
<ide> ...props.pressRetentionOffset,
<del> };
<add> );
<ide>
<ide> const clientRect = target.getBoundingClientRect();
<ide>
<ide> const PressResponder = {
<ide> return;
<ide> }
<ide> const nativeEvent: any = event.nativeEvent;
<del> const pointerType = getEventPointerType(event);
<add> const pointerType = context.getEventPointerType(event);
<ide>
<ide> switch (type) {
<ide> // START
<ide> const PressResponder = {
<ide>
<ide> state.allowPressReentry = true;
<ide> state.pointerType = pointerType;
<del> state.pressTarget = getEventCurrentTarget(event, context);
<add> state.pressTarget = context.getEventCurrentTarget(event);
<ide> state.responderRegionOnActivation = calculateResponderRegion(
<add> context,
<ide> state.pressTarget,
<ide> props,
<ide> );
<ide> const PressResponder = {
<ide> const {target, type} = event;
<ide>
<ide> const nativeEvent: any = event.nativeEvent;
<del> const pointerType = getEventPointerType(event);
<add> const pointerType = context.getEventPointerType(event);
<ide>
<ide> switch (type) {
<ide> // MOVE
<ide> const PressResponder = {
<ide> state.responderRegionOnDeactivation == null
<ide> ) {
<ide> state.responderRegionOnDeactivation = calculateResponderRegion(
<add> context,
<ide> state.pressTarget,
<ide> props,
<ide> );
<ide> const PressResponder = {
<ide> // already done during move event.
<ide> if (state.responderRegionOnDeactivation == null) {
<ide> state.responderRegionOnDeactivation = calculateResponderRegion(
<add> context,
<ide> state.pressTarget,
<ide> props,
<ide> );
<ide><path>packages/react-events/src/utils.js
<ide> import type {
<ide> ReactResponderContext,
<ide> } from 'shared/ReactTypes';
<ide>
<del>export function getEventCurrentTarget(
<del> event: ReactResponderEvent,
<del> context: ReactResponderContext,
<del>): Element {
<del> const target: any = event.target;
<del> let currentTarget = target;
<del> while (
<del> currentTarget.parentNode &&
<del> currentTarget.parentNode.nodeType === Node.ELEMENT_NODE &&
<del> context.isTargetWithinEventComponent(currentTarget.parentNode)
<del> ) {
<del> currentTarget = currentTarget.parentNode;
<del> }
<del> return currentTarget;
<del>}
<del>
<del>export function getEventPointerType(event: ReactResponderEvent) {
<del> const nativeEvent: any = event.nativeEvent;
<del> const {type, pointerType} = nativeEvent;
<del> if (pointerType != null) {
<del> return pointerType;
<del> }
<del> if (type.indexOf('mouse') === 0) {
<del> return 'mouse';
<del> }
<del> if (type.indexOf('touch') === 0) {
<del> return 'touch';
<del> }
<del> if (type.indexOf('key') === 0) {
<del> return 'keyboard';
<del> }
<del> return '';
<del>}
<del>
<ide> export function isEventPositionWithinTouchHitTarget(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide><path>packages/shared/ReactTypes.js
<ide> export type ReactResponderContext = {
<ide> clearTimeout: (timerId: Symbol) => void,
<ide> getFocusableElementsInScope(): Array<HTMLElement>,
<ide> getActiveDocument(): Document,
<add> objectAssign: Function,
<add> getEventPointerType(
<add> event: ReactResponderEvent,
<add> ): '' | 'mouse' | 'keyboard' | 'pen' | 'touch',
<add> getEventCurrentTarget(event: ReactResponderEvent): Element,
<ide> }; | 6 |
Java | Java | delay check if pattern ends with slash | 0634555424a8742bbe95333c49975437af6eacf8 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java
<ide> protected String getToStringInfix() {
<ide> * <li>If neither instance has patterns, use an empty String (i.e. "").
<ide> * </ul>
<ide> */
<add> @Override
<ide> public PatternsRequestCondition combine(PatternsRequestCondition other) {
<ide> Set<String> result = new LinkedHashSet<String>();
<ide> if (!this.patterns.isEmpty() && !other.patterns.isEmpty()) {
<ide> else if (!other.patterns.isEmpty()) {
<ide> * or a new condition with sorted matching patterns;
<ide> * or {@code null} if no patterns match.
<ide> */
<add> @Override
<ide> public PatternsRequestCondition getMatchingCondition(HttpServletRequest request) {
<ide> if (this.patterns.isEmpty()) {
<ide> return this;
<ide> private String getMatchingPattern(String pattern, String lookupPath) {
<ide> if (this.pathMatcher.match(pattern, lookupPath)) {
<ide> return pattern;
<ide> }
<del> boolean endsWithSlash = pattern.endsWith("/");
<ide> if (this.useTrailingSlashMatch) {
<del> if (!endsWithSlash && this.pathMatcher.match(pattern + "/", lookupPath)) {
<add> if (!pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath)) {
<ide> return pattern +"/";
<ide> }
<ide> }
<ide> private String getMatchingPattern(String pattern, String lookupPath) {
<ide> * contain only patterns that match the request and are sorted with
<ide> * the best matches on top.
<ide> */
<add> @Override
<ide> public int compareTo(PatternsRequestCondition other, HttpServletRequest request) {
<ide> String lookupPath = this.pathHelper.getLookupPathForRequest(request);
<ide> Comparator<String> patternComparator = this.pathMatcher.getPatternComparator(lookupPath); | 1 |
Java | Java | switch equality check in blobmodule.java | 7c5d581d7848206603cf9d80a841afb49759ec1a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java
<ide> public void onMessage(ByteString bytes, WritableMap params) {
<ide> @Override
<ide> public boolean supports(Uri uri, String responseType) {
<ide> String scheme = uri.getScheme();
<del> boolean isRemote = scheme.equals("http") || scheme.equals("https");
<add> boolean isRemote = "http".equals(scheme) || "https".equals(scheme);
<ide>
<ide> return (!isRemote && responseType.equals("blob"));
<ide> } | 1 |
Python | Python | add malformedresponseerror checking for ec2 driver | 3d301d4f80f82568279d792af4710ff7f349aedd | <ide><path>libcloud/drivers/ec2.py
<ide> Amazon EC2 driver
<ide> """
<ide> from libcloud.providers import Provider
<del>from libcloud.types import NodeState, InvalidCredsError
<add>from libcloud.types import NodeState, InvalidCredsError, MalformedResponseError
<ide> from libcloud.base import Node, Response, ConnectionUserAndKey
<ide> from libcloud.base import NodeDriver, NodeSize, NodeImage, NodeLocation
<ide> import base64
<ide> class EC2Response(Response):
<ide> def parse_body(self):
<ide> if not self.body:
<ide> return None
<del> return ET.XML(self.body)
<add> try:
<add> body = ET.XML(self.body)
<add> except:
<add> raise MalformedResponseError("Failed to parse XML", body=self.body, driver=EC2NodeDriver)
<add> return body
<ide>
<ide> def parse_error(self):
<ide> err_list = []
<ide> def parse_error(self):
<ide> if self.status == 403 and self.body[:len(msg)] == msg:
<ide> raise InvalidCredsError(msg)
<ide>
<del> for err in ET.XML(self.body).findall('Errors/Error'):
<add> try:
<add> body = ET.XML(self.body)
<add> except:
<add> raise MalformedResponseError("Failed to parse XML", body=self.body, driver=EC2NodeDriver)
<add>
<add> for err in body.findall('Errors/Error'):
<ide> code, message = err.getchildren()
<ide> err_list.append("%s: %s" % (code.text, message.text))
<ide> if code.text == "InvalidClientTokenId": | 1 |
Ruby | Ruby | push merge code to the callback itself | 929658c98d48eeba7f65ec4afb0f8cbedadaf270 | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def deprecate_per_key_option(options)
<ide> end
<ide> end
<ide>
<del> def initialize_copy(other)
<del> super
<del> @options = {
<del> :if => other.options[:if].dup,
<del> :unless => other.options[:unless].dup
<add> def merge(chain, new_options)
<add> _options = {
<add> :if => @options[:if].dup,
<add> :unless => @options[:unless].dup
<ide> }
<add>
<add> _options[:if].concat Array(new_options.fetch(:unless, []))
<add> _options[:unless].concat Array(new_options.fetch(:if, []))
<add>
<add> self.class.new chain, @filter, @kind, _options
<ide> end
<ide>
<ide> def normalize_options!(options)
<ide> def duplicates?(other)
<ide> end
<ide> end
<ide>
<del> def _update_filter(filter_options, new_options)
<del> filter_options[:if].concat(Array(new_options[:unless])) if new_options.key?(:unless)
<del> filter_options[:unless].concat(Array(new_options[:if])) if new_options.key?(:if)
<del> end
<del>
<del> def recompile!(_options)
<del> deprecate_per_key_option(_options)
<del> _update_filter(self.options, _options)
<del> end
<del>
<ide> # Wraps code with filter
<ide> def apply(next_callback)
<ide> user_conditions = conditions_lambdas
<ide> def skip_callback(name, *filter_list, &block)
<ide> filter = chain.find {|c| c.matches?(type, filter) }
<ide>
<ide> if filter && options.any?
<del> new_filter = filter.dup
<del> new_filter.chain = chain
<add> new_filter = filter.merge(chain, options)
<ide> chain.insert(chain.index(filter), new_filter)
<del> new_filter.recompile!(options)
<ide> end
<ide>
<ide> chain.delete(filter) | 1 |
Javascript | Javascript | remove recursive arg from mesh.clone() | 6cc768f0b459a344f3f4464551576fbdb2e0626e | <ide><path>src/objects/Mesh.js
<ide> THREE.Mesh.prototype.raycast = ( function () {
<ide>
<ide> }() );
<ide>
<del>THREE.Mesh.prototype.clone = function ( recursive ) {
<add>THREE.Mesh.prototype.clone = function () {
<ide>
<ide> var mesh = new THREE.Mesh( this.geometry, this.material );
<ide> return this.cloneProperties( mesh );
<ide>
<ide> };
<ide>
<del>THREE.Mesh.prototype.cloneProperties = function ( mesh, recursive ) {
<add>THREE.Mesh.prototype.cloneProperties = function ( mesh ) {
<ide>
<del> THREE.Object3D.prototype.cloneProperties.call( this, mesh, recursive );
<add> THREE.Object3D.prototype.cloneProperties.call( this, mesh );
<ide>
<ide> return mesh;
<ide> | 1 |
Javascript | Javascript | add test for merge | 09c5e5157d568cac0850e1ed41da1f7f60c66426 | <ide><path>test/core/merge-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("d3.merge");
<add>
<add>suite.addBatch({
<add> "merge": {
<add> "merges an array of arrays": function() {
<add> var a = {}, b = {}, c = {}, d = {}, e = {}, f = {};
<add> assert.deepEqual(d3.merge([[a], [b, c], [d, e, f]]), [a, b, c, d, e, f]);
<add> },
<add> "returns a new array": function() {
<add> var input = [[1, 2, 3], [4, 5], [6]];
<add> assert.isFalse(d3.merge(input) === input);
<add> },
<add> "does not modify the input arrays": function() {
<add> var input = [[1, 2, 3], [4, 5], [6]];
<add> d3.merge(input);
<add> assert.deepEqual(input, [[1, 2, 3], [4, 5], [6]]);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
Mixed | Ruby | log active_job potential matches when asserting | 060a1fb338854da2b99bced7709468f5d53ad368 | <ide><path>activejob/CHANGELOG.md
<add>* Log potential matches in `assert_enqueued_with` and `assert_performed_with`
<add>
<add> *Gareth du Plooy*
<add>
<ide> * Add `at` argument to the `perform_enqueued_jobs` test helper.
<ide>
<ide> *John Crepezzi*, *Eileen Uchitelle*
<ide><path>activejob/lib/active_job/test_helper.rb
<ide> def assert_no_performed_jobs(only: nil, except: nil, queue: nil, &block)
<ide> def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)
<ide> expected = { job: job, args: args, at: at, queue: queue }.compact
<ide> expected_args = prepare_args_for_assertion(expected)
<add> potential_matches = []
<ide>
<ide> if block_given?
<ide> original_enqueued_jobs_count = enqueued_jobs.count
<ide> def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)
<ide>
<ide> matching_job = jobs.find do |enqueued_job|
<ide> deserialized_job = deserialize_args_for_assertion(enqueued_job)
<add> potential_matches << deserialized_job
<ide>
<ide> expected_args.all? do |key, value|
<ide> if value.respond_to?(:call)
<ide> def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)
<ide> end
<ide> end
<ide>
<del> assert matching_job, "No enqueued job found with #{expected}"
<add> message = +"No enqueued job found with #{expected}"
<add> message << "\n\nPotential matches: #{potential_matches.join("\n")}" if potential_matches.present?
<add> assert matching_job, message
<ide> instantiate_job(matching_job)
<ide> end
<ide>
<ide> def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)
<ide> def assert_performed_with(job: nil, args: nil, at: nil, queue: nil, &block)
<ide> expected = { job: job, args: args, at: at, queue: queue }.compact
<ide> expected_args = prepare_args_for_assertion(expected)
<add> potential_matches = []
<ide>
<ide> if block_given?
<ide> original_performed_jobs_count = performed_jobs.count
<ide> def assert_performed_with(job: nil, args: nil, at: nil, queue: nil, &block)
<ide>
<ide> matching_job = jobs.find do |enqueued_job|
<ide> deserialized_job = deserialize_args_for_assertion(enqueued_job)
<add> potential_matches << deserialized_job
<ide>
<ide> expected_args.all? do |key, value|
<ide> if value.respond_to?(:call)
<ide> def assert_performed_with(job: nil, args: nil, at: nil, queue: nil, &block)
<ide> end
<ide> end
<ide>
<del> assert matching_job, "No performed job found with #{expected}"
<add> message = +"No performed job found with #{expected}"
<add> message << "\n\nPotential matches: #{potential_matches.join("\n")}" if potential_matches.present?
<add> assert matching_job, message
<add>
<ide> instantiate_job(matching_job)
<ide> end
<ide>
<ide><path>activejob/test/cases/test_helper_test.rb
<ide> def test_assert_enqueued_with_failure
<ide> end
<ide> end
<ide>
<del> assert_equal 'No enqueued job found with {:job=>NestedJob, :queue=>"low"}', error.message
<add> assert_match(/No enqueued job found with {:job=>NestedJob, :queue=>"low"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_enqueued_with_with_no_block_failure
<ide> def test_assert_enqueued_with_with_no_block_failure
<ide> assert_enqueued_with(job: NestedJob, queue: "low")
<ide> end
<ide>
<del> assert_equal 'No enqueued job found with {:job=>NestedJob, :queue=>"low"}', error.message
<add> assert_match(/No enqueued job found with {:job=>NestedJob, :queue=>"low"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_enqueued_with_args
<ide> def test_assert_enqueued_with_failure_with_global_id_args
<ide> HelloJob.perform_later(ricardo)
<ide> end
<ide> end
<del>
<del> assert_equal "No enqueued job found with {:job=>HelloJob, :args=>[#{wilma.inspect}]}", error.message
<add> assert_match(/No enqueued job found with {:job=>HelloJob, :args=>\[#{wilma.inspect}\]}/, error.message)
<add> assert_match(/Potential matches: {:job=>HelloJob, :args=>\[#<Person.* @id=\"9\"\>\], :queue=>\"default\"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_enqueued_with_failure_with_no_block_with_global_id_args
<ide> def test_assert_enqueued_with_failure_with_no_block_with_global_id_args
<ide> assert_enqueued_with(job: HelloJob, args: [wilma])
<ide> end
<ide>
<del> assert_equal "No enqueued job found with {:job=>HelloJob, :args=>[#{wilma.inspect}]}", error.message
<add> assert_match(/No enqueued job found with {:job=>HelloJob, :args=>\[#{wilma.inspect}\]}/, error.message)
<add> assert_match(/Potential matches: {:job=>HelloJob, :args=>\[#<Person.* @id=\"9\"\>\], :queue=>\"default\"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_enqueued_with_does_not_change_jobs_count
<ide> def test_assert_performed_with_failure_with_global_id_args
<ide> HelloJob.perform_later(ricardo)
<ide> end
<ide> end
<del>
<del> assert_equal "No performed job found with {:job=>HelloJob, :args=>[#{wilma.inspect}]}", error.message
<add> assert_match(/No performed job found with {:job=>HelloJob, :args=>\[#{wilma.inspect}\]}/, error.message)
<add> assert_match(/Potential matches: {:job=>HelloJob, :args=>\[#<Person.* @id=\"9\"\>\], :queue=>\"default\"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_performed_with_without_block_failure_with_global_id_args
<ide> def test_assert_performed_with_without_block_failure_with_global_id_args
<ide> assert_performed_with(job: HelloJob, args: [wilma])
<ide> end
<ide>
<del> assert_equal "No performed job found with {:job=>HelloJob, :args=>[#{wilma.inspect}]}", error.message
<add> assert_match(/No performed job found with {:job=>HelloJob, :args=>\[#{wilma.inspect}\]}/, error.message)
<add> assert_match(/Potential matches: {:job=>HelloJob, :args=>\[#<Person.* @id=\"9\"\>\], :queue=>\"default\"}/, error.message)
<ide> end
<ide>
<ide> def test_assert_performed_with_does_not_change_jobs_count | 3 |
Javascript | Javascript | use strict in driver.js | 17e02e3c39b6af3468e0f857adccdb03d98e39a7 | <ide><path>test/driver.js
<ide> * A Test Driver for PDF.js
<ide> */
<ide>
<add>'use strict';
<add>
<ide> var appPath, browser, canvas, currentTaskIdx, manifest, stdout;
<ide>
<ide> function queryParams() {
<ide> function queryParams() {
<ide> function load() {
<ide> var params = queryParams();
<ide> browser = params.browser;
<del> manifestFile = params.manifestFile;
<add> var manifestFile = params.manifestFile;
<ide> appPath = params.path;
<ide>
<ide> canvas = document.createElement("canvas");
<ide> function snapshotCurrentPage(page, task, failure) {
<ide> log("done"+ (failure ? " (failed!: "+ failure +")" : "") +"\n");
<ide>
<ide> // Set up the next request
<del> backoff = (inFlightRequests > 0) ? inFlightRequests * 10 : 0;
<add> var backoff = (inFlightRequests > 0) ? inFlightRequests * 10 : 0;
<ide> setTimeout(function() {
<ide> ++task.pageNum, nextPage(task);
<ide> },
<ide> function checkScrolling() {
<ide> function log(str) {
<ide> stdout.innerHTML += str;
<ide> checkScrolling();
<del>}
<ide>\ No newline at end of file
<add>} | 1 |
Javascript | Javascript | fix hot test cases | 10517ae3ae5c7335cb146668430aac9a66bdce03 | <ide><path>test/HotTestCases.template.js
<ide> const describeCases = config => {
<ide> _attrs: {},
<ide> setAttribute(name, value) {
<ide> this._attrs[name] = value;
<add> },
<add> parentNode: {
<add> removeChild(node) {
<add> // ok
<add> }
<ide> }
<ide> };
<ide> },
<ide> const describeCases = config => {
<ide> },
<ide> getElementsByTagName(name) {
<ide> if (name === "head") return [this.head];
<add> if (name === "script") return [];
<ide> throw new Error("Not supported");
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove extra wkwebview file not used | ea124a044c8eca6c1eecc8f898c80864d0f6b094 | <ide><path>Libraries/Components/WKWebView/WKWebView.ios.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @format
<del> * @flow
<del> * @providesModule WKWebView
<del> */
<del>
<del>const React = require('react');
<del>
<del>const requireNativeComponent = require('requireNativeComponent');
<del>
<del>const RCTWKWebView = requireNativeComponent('RCTWKWebView');
<del>
<del>type RCTWKWebViewProps = {
<del> allowsInlineMediaPlayback?: boolean,
<del> mediaPlaybackRequiresUserAction?: boolean,
<del> dataDetectorTypes?: boolean,
<del>};
<del>
<del>class WKWebView extends React.Component<RCTWKWebViewProps> {
<del> componentWillReceiveProps(nextProps: RCTWKWebViewProps) {
<del> this.showRedboxOnPropChanges(nextProps, 'allowsInlineMediaPlayback');
<del> this.showRedboxOnPropChanges(nextProps, 'mediaPlaybackRequiresUserAction');
<del> this.showRedboxOnPropChanges(nextProps, 'dataDetectorTypes');
<del> }
<del>
<del> showRedboxOnPropChanges(nextProps: RCTWKWebViewProps, propName: string) {
<del> if (this.props[propName] !== nextProps[propName]) {
<del> console.error(`Changes to property ${propName} do nothing after the initial render.`);
<del> }
<del> }
<del>
<del> render() {
<del> return <RCTWKWebView {...this.props}/>;
<del> }
<del>}
<del>
<del>module.exports = WKWebView; | 1 |
Java | Java | enhance npe messages | 4f86ee02f525a61ef8331fdd2be5c66be3694846 | <ide><path>src/main/java/io/reactivex/internal/observers/ToNotificationObserver.java
<ide> public void onSubscribe(Disposable s) {
<ide> public void onNext(T t) {
<ide> if (t == null) {
<ide> s.dispose();
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> } else {
<ide> try {
<ide> consumer.accept(Notification.<Object>createOnNext(t));
<ide> public void onComplete() {
<ide> RxJavaPlugins.onError(ex);
<ide> }
<ide> }
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableError.java
<ide> public void subscribeActual(Subscriber<? super T> s) {
<ide> error = t;
<ide> }
<ide> if (error == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("Callable returned null throwable. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> EmptySubscription.error(error, s);
<ide> }
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGenerate.java
<ide> public void cancel() {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> actual.onNext(t);
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> terminate = true;
<ide> actual.onError(t);
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java
<ide> public void subscribe(Subscriber<? super T> s) {
<ide>
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> done = true;
<ide> } else {
<ide> queue.offer(t);
<ide> public void clear() {
<ide> queue.clear();
<ide> }
<ide> }
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeErrorCallable.java
<ide> protected void subscribeActual(MaybeObserver<? super T> observer) {
<ide> }
<ide>
<ide> if (ex == null) {
<del> ex = new NullPointerException();
<add> ex = new NullPointerException("Callable returned null throwable. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide>
<ide> observer.onError(ex);
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java
<ide> public void onNext(T t) {
<ide> if (b == null) {
<ide> buffers.clear();
<ide> s.dispose();
<del> actual.onError(new NullPointerException());
<add> actual.onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide>
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableError.java
<ide> public void subscribeActual(Observer<? super T> s) {
<ide> error = t;
<ide> }
<ide> if (error == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("Callable returned null throwable. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> EmptyDisposable.error(error, s);
<ide> }
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java
<ide> public boolean isDisposed() {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> actual.onNext(t);
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> terminate = true;
<ide> actual.onError(t);
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java
<ide> public void subscribe(Observer<? super T> s) {
<ide>
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> done = true;
<ide> } else {
<ide> queue.offer(t);
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java
<ide> public void onSubscribe(Disposable s) {
<ide> public void onNext(T t) {
<ide> if (t == null) {
<ide> s.get().dispose();
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> if (!queue.offer(t)) {
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleError.java
<ide> protected void subscribeActual(SingleObserver<? super T> s) {
<ide> }
<ide>
<ide> if (error == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("Callable returned null throwable. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide>
<ide> EmptyDisposable.error(error, s);
<ide><path>src/main/java/io/reactivex/observers/SafeObserver.java
<ide> public void onNext(T t) {
<ide> }
<ide>
<ide> if (t == null) {
<del> Throwable ex = new NullPointerException();
<add> Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> try {
<ide> s.dispose();
<ide> } catch (Throwable e1) {
<ide> public void onError(Throwable t) {
<ide> }
<ide>
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide>
<ide> try {
<ide><path>src/main/java/io/reactivex/observers/SerializedObserver.java
<ide> public void onNext(T t) {
<ide> }
<ide> if (t == null) {
<ide> s.dispose();
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> synchronized (this) {
<ide><path>src/main/java/io/reactivex/plugins/RxJavaPlugins.java
<ide> public static void onError(Throwable error) {
<ide> } catch (Throwable e) {
<ide> // Exceptions.throwIfFatal(e); TODO decide
<ide> if (error == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> e.printStackTrace(); // NOPMD
<ide> uncaught(e);
<ide> }
<ide> } else {
<ide> if (error == null) {
<del> error = new NullPointerException();
<add> error = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> }
<ide> error.printStackTrace(); // NOPMD
<ide><path>src/main/java/io/reactivex/processors/AsyncProcessor.java
<ide> public void onNext(T t) {
<ide> @SuppressWarnings("unchecked")
<ide> void nullOnNext() {
<ide> value = null;
<del> Throwable ex = new NullPointerException();
<add> Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> error = ex;
<ide> for (AsyncSubscription<T> as : subscribers.getAndSet(TERMINATED)) {
<ide> as.onError(ex);
<ide> void nullOnNext() {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (subscribers.get() == TERMINATED) {
<ide> RxJavaPlugins.onError(t);
<ide><path>src/main/java/io/reactivex/processors/BehaviorProcessor.java
<ide> public void onSubscribe(Subscription s) {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> if (done) {
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide><path>src/main/java/io/reactivex/processors/PublishProcessor.java
<ide> public void onNext(T t) {
<ide> return;
<ide> }
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> for (PublishSubscription<T> s : subscribers.get()) {
<ide> public void onError(Throwable t) {
<ide> return;
<ide> }
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> error = t;
<ide>
<ide><path>src/main/java/io/reactivex/processors/ReplayProcessor.java
<ide> public void onSubscribe(Subscription s) {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> if (done) {
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide> public int size() {
<ide> return s;
<ide> }
<ide> }
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>src/main/java/io/reactivex/subjects/AsyncSubject.java
<ide> public void onNext(T t) {
<ide> @SuppressWarnings("unchecked")
<ide> void nullOnNext() {
<ide> value = null;
<del> Throwable ex = new NullPointerException();
<add> Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> error = ex;
<ide> for (AsyncDisposable<T> as : subscribers.getAndSet(TERMINATED)) {
<ide> as.onError(ex);
<ide> void nullOnNext() {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (subscribers.get() == TERMINATED) {
<ide> RxJavaPlugins.onError(t);
<ide><path>src/main/java/io/reactivex/subjects/BehaviorSubject.java
<ide> public void onSubscribe(Disposable s) {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> if (done) {
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide><path>src/main/java/io/reactivex/subjects/PublishSubject.java
<ide> public void onNext(T t) {
<ide> return;
<ide> }
<ide> if (t == null) {
<del> onError(new NullPointerException("Subject got a null value. Null values are generally not allowed in 2.x operators and sources."));
<add> onError(new NullPointerException("onNext got a null value. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> for (PublishDisposable<T> s : subscribers.get()) {
<ide> public void onError(Throwable t) {
<ide> return;
<ide> }
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> error = t;
<ide>
<ide><path>src/main/java/io/reactivex/subjects/ReplaySubject.java
<ide> public void onSubscribe(Disposable s) {
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (t == null) {
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> if (done) {
<ide> public void onNext(T t) {
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide><path>src/main/java/io/reactivex/subscribers/SafeSubscriber.java
<ide> public void onNext(T t) {
<ide> }
<ide>
<ide> if (t == null) {
<del> Throwable ex = new NullPointerException();
<add> Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> try {
<ide> s.cancel();
<ide> } catch (Throwable e1) {
<ide> public void onError(Throwable t) {
<ide> }
<ide>
<ide> if (t == null) {
<del> t = new NullPointerException();
<add> t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<ide>
<ide> try {
<ide><path>src/main/java/io/reactivex/subscribers/SerializedSubscriber.java
<ide> public void onNext(T t) {
<ide> }
<ide> if (t == null) {
<ide> subscription.cancel();
<del> onError(new NullPointerException());
<add> onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
<ide> return;
<ide> }
<ide> synchronized (this) { | 24 |
Text | Text | remove bad apostrophe | 16c855931b9a52d131904eb883ab2b0ef6abd4eb | <ide><path>docs/guides/options.md
<ide> or
<ide>
<ide> ### autoplay ###
<ide> If autoplay is true, the video will start playing as soon as page is loaded (without any interaction from the user).
<del>NOT SUPPORTED BY APPLE iOS DEVICES. Apple blocks the autoplay functionality in an effort to protect it's customers from unwillingly using a lot of their (often expensive) monthly data plans. A user touch/click is required to start the video in this case.
<add>NOT SUPPORTED BY APPLE iOS DEVICES. Apple blocks the autoplay functionality in an effort to protect its customers from unwillingly using a lot of their (often expensive) monthly data plans. A user touch/click is required to start the video in this case.
<ide> ```html
<ide> <video autoplay ...>
<ide> or | 1 |
Ruby | Ruby | remove unused private method | 04021c4b78abc89045a7d3daf517a5d2dc63e5a7 | <ide><path>railties/lib/rails/rack/logger.rb
<ide> def finish(request)
<ide> instrumenter.finish 'request.action_dispatch', request: request
<ide> end
<ide>
<del> def development?
<del> Rails.env.development?
<del> end
<del>
<ide> def logger
<ide> Rails.logger
<ide> end | 1 |
Text | Text | add note about scope wildcard | bdf960294ada6f5ecbf9494372922f5f9cfb0a94 | <ide><path>CONTRIBUTING.md
<ide> Must be one of the following:
<ide> The scope could be anything specifying place of the commit change. For example `$location`,
<ide> `$browser`, `$compile`, `$rootScope`, `ngHref`, `ngClick`, `ngView`, etc...
<ide>
<add>You can use `*` when the change affects more than a single scope.
<add>
<ide> ### Subject
<ide> The subject contains succinct description of the change:
<ide> | 1 |
Text | Text | fix contribution docs about gulp-cli | f342299845678819c7629e1a569629a8c87ed01a | <ide><path>docs/developers/contributing.md
<ide> Firstly, we need to ensure development dependencies are installed. With node and
<ide>
<ide> ```bash
<ide> > npm install
<del>> npm install -g gulp
<add>> npm install -g gulp-cli
<ide> ```
<ide>
<ide> This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="https://gulpjs.com/" target="_blank">gulp</a>. | 1 |
Javascript | Javascript | fix typo in pet mongoose model | 4ba3607dcbb6ad88a9ee6935504f2dadc91dd0de | <ide><path>examples/with-mongodb-mongoose/models/Pet.js
<ide> const PetSchema = new mongoose.Schema({
<ide> type: Boolean,
<ide> },
<ide> diet: {
<del> /* List of dietary needs, if applicale */
<add> /* List of dietary needs, if applicable */
<ide>
<ide> type: Array,
<ide> }, | 1 |
Text | Text | change the explanation of splice function | 335600d91caca00734759aaeda21901fb5168f9a | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.english.md
<ide> forumTopicId: 301152
<ide>
<ide> ## Description
<ide> <section id='description'>
<del>Remember in the last challenge we mentioned that <code>splice()</code> can take up to three parameters? Well, we can go one step further with <code>splice()</code> — in addition to removing elements, we can use that third parameter, which represents one or more elements, to <em>add</em> them as well. This can be incredibly useful for quickly switching out an element, or a set of elements, for another. For instance, let's say you're storing a color scheme for a set of DOM elements in an array, and want to dynamically change a color based on some action:
<add>Remember in the last challenge we mentioned that <code>splice()</code> can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
<ide>
<ide> ```js
<del>function colorChange(arr, index, newColor) {
<del> arr.splice(index, 1, newColor);
<del> return arr;
<del>}
<del>
<del>let colorScheme = ['#878787', '#a08794', '#bb7e8c', '#c9b6be', '#d1becf'];
<del>
<del>colorScheme = colorChange(colorScheme, 2, '#332327');
<del>// we have removed '#bb7e8c' and added '#332327' in its place
<del>// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']
<add>const numbers = [10, 11, 12, 12, 15];
<add>const startIndex = 3;
<add>const amountToDelete = 1;
<add>
<add>numbers.splice(startIndex, amountToDelete, 13, 14);
<add>// the second entry of 12 is removed, and we add 13 and 14 at the same index
<add>console.log(numbers);
<add>// returns [ 10, 11, 12, 13, 14, 15 ]
<ide> ```
<ide>
<del>This function takes an array of hex values, an index at which to remove an element, and the new color to replace the removed element with. The return value is an array containing a newly modified color scheme! While this example is a bit oversimplified, we can see the value that utilizing <code>splice()</code> to its maximum potential can have.
<add>Here we begin with an array of numbers. We then pass the following to <code>splice()</code>. The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the elements (13, 14) to be inserted at that same index. Note that there can be any number of elements (separated by commas) following <code>amountToDelete</code>, each of which gets inserted.
<ide> </section>
<ide>
<ide> ## Instructions | 1 |
Javascript | Javascript | use `assert` in `fscall` argument checking | 8231cc4d4228da9d62b5362c0aff975cc53d6f05 | <ide><path>lib/internal/fs/promises.js
<ide> const { promisify } = require('internal/util');
<ide> const { EventEmitterMixin } = require('internal/event_target');
<ide> const { watch } = require('internal/fs/watchers');
<ide> const { isIterable } = require('internal/streams/utils');
<add>const assert = require('internal/assert');
<ide>
<ide> const kHandle = Symbol('kHandle');
<ide> const kFd = Symbol('kFd');
<ide> async function handleFdClose(fileOpPromise, closeFunc) {
<ide> }
<ide>
<ide> async function fsCall(fn, handle, ...args) {
<del> if (handle[kRefs] === undefined) {
<del> throw new ERR_INVALID_ARG_TYPE('filehandle', 'FileHandle', handle);
<del> }
<add> assert(handle[kRefs] !== undefined,
<add> 'handle must be an instance of FileHandle');
<ide>
<ide> if (handle.fd === -1) {
<ide> // eslint-disable-next-line no-restricted-syntax
<ide><path>test/parallel/test-fs-promises.js
<ide> async function getHandle(dest) {
<ide> assert.strictEqual(ret.bytesWritten, 2);
<ide> await handle.close();
<ide> }
<add>
<add> // Test prototype methods calling with contexts other than FileHandle
<add> {
<add> const handle = await getHandle(dest);
<add> assert.rejects(() => handle.stat.call({}), {
<add> code: 'ERR_INTERNAL_ASSERTION',
<add> message: /handle must be an instance of FileHandle/
<add> });
<add> await handle.close();
<add> }
<ide> }
<ide>
<ide> doTest().then(common.mustCall()); | 2 |
Javascript | Javascript | use string instead of window.string. close gh-1176 | 31478b90128a60585c087bee57d31148677a99cd | <ide><path>src/ajax.js
<ide> jQuery.extend({
<ide> converters: {
<ide>
<ide> // Convert anything to text
<del> "* text": window.String,
<add> "* text": String,
<ide>
<ide> // Text to html (true = no transformation)
<ide> "text html": true, | 1 |
Mixed | Javascript | add missing err_ prefix on util.callbackify error | 873e2f270fa67c701d59bc99f0f815f1f69b2316 | <ide><path>doc/api/errors.md
<ide> The `ERR_CONSOLE_WRITABLE_STREAM` error code is thrown when `Console` is
<ide> instantiated without `stdout` stream or when `stdout` or `stderr` streams
<ide> are not writable.
<ide>
<add><a id="ERR_FALSY_VALUE_REJECTION"></a>
<add>### ERR_FALSY_VALUE_REJECTION
<add>
<add>The `ERR_FALSY_VALUE_REJECTION` error code is used by the `util.callbackify()`
<add>API when a callbackified `Promise` is rejected with a falsy value (e.g. `null`).
<add>
<ide> <a id="ERR_INDEX_OUT_OF_RANGE"></a>
<ide> ### ERR_INDEX_OUT_OF_RANGE
<ide>
<ide><path>lib/internal/errors.js
<ide> E('ERR_ASSERTION', (msg) => msg);
<ide> E('ERR_CONSOLE_WRITABLE_STREAM',
<ide> (name) => `Console expects a writable stream instance for ${name}`);
<ide> E('ERR_CPU_USAGE', (errMsg) => `Unable to obtain cpu usage ${errMsg}`);
<add>E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value');
<ide> E('ERR_HTTP_HEADERS_SENT',
<ide> 'Cannot render headers after they are sent to the client');
<ide> E('ERR_HTTP_INVALID_CHAR', 'Invalid character in statusMessage.');
<ide> E('ERR_SOCKET_BAD_PORT', 'Port should be > 0 and < 65536');
<ide> E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running');
<ide> E('ERR_V8BREAKITERATOR', 'full ICU data not installed. ' +
<ide> 'See https://github.com/nodejs/node/wiki/Intl');
<del>E('FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value');
<ide> // Add new errors from here...
<ide>
<ide> function invalidArgType(name, expected, actual) {
<ide><path>lib/util.js
<ide> function callbackifyOnRejected(reason, cb) {
<ide> // occurred", we error-wrap so the callback consumer can distinguish between
<ide> // "the promise rejected with null" or "the promise fulfilled with undefined".
<ide> if (!reason) {
<del> const newReason = new errors.Error('FALSY_VALUE_REJECTION');
<add> const newReason = new errors.Error('ERR_FALSY_VALUE_REJECTION');
<ide> newReason.reason = reason;
<ide> reason = newReason;
<ide> Error.captureStackTrace(reason, callbackifyOnRejected);
<ide><path>test/parallel/test-util-callbackify.js
<ide> const values = [
<ide> if (err instanceof Error) {
<ide> if ('reason' in err) {
<ide> assert(!value);
<del> assert.strictEqual(err.code, 'FALSY_VALUE_REJECTION');
<add> assert.strictEqual(err.code, 'ERR_FALSY_VALUE_REJECTION');
<ide> assert.strictEqual(err.reason, value);
<ide> } else {
<ide> assert.strictEqual(String(value).endsWith(err.message), true);
<ide> const values = [
<ide> if (err instanceof Error) {
<ide> if ('reason' in err) {
<ide> assert(!value);
<del> assert.strictEqual(err.code, 'FALSY_VALUE_REJECTION');
<add> assert.strictEqual(err.code, 'ERR_FALSY_VALUE_REJECTION');
<ide> assert.strictEqual(err.reason, value);
<ide> } else {
<ide> assert.strictEqual(String(value).endsWith(err.message), true);
<ide> const values = [
<ide> if (err instanceof Error) {
<ide> if ('reason' in err) {
<ide> assert(!value);
<del> assert.strictEqual(err.code, 'FALSY_VALUE_REJECTION');
<add> assert.strictEqual(err.code, 'ERR_FALSY_VALUE_REJECTION');
<ide> assert.strictEqual(err.reason, value);
<ide> } else {
<ide> assert.strictEqual(String(value).endsWith(err.message), true); | 4 |
PHP | PHP | collapse redundant multi-line conditions | 6b7e767e4b9c19db3e3652a369a9ef7997356f67 | <ide><path>src/Database/Expression/TupleComparison.php
<ide> public function getType(): array
<ide> public function setValue($value): void
<ide> {
<ide> if ($this->isMulti()) {
<del> if (
<del> is_array($value) &&
<del> !is_array(current($value))
<del> ) {
<add> if (is_array($value) && !is_array(current($value))) {
<ide> throw new InvalidArgumentException(
<ide> 'Multi-tuple comparisons require a multi-tuple value, single-tuple given.'
<ide> );
<ide> }
<ide> } else {
<del> if (
<del> is_array($value) &&
<del> is_array(current($value))
<del> ) {
<add> if (is_array($value) && is_array(current($value))) {
<ide> throw new InvalidArgumentException(
<ide> 'Single-tuple comparisons require a single-tuple value, multi-tuple given.'
<ide> ); | 1 |
Text | Text | fix variable scoping bug in server example code | 66d697cb5c32461cf65fe44d797c8648ab2f0fca | <ide><path>doc/api/stream.md
<ide> const server = http.createServer( (req, res) => {
<ide> req.on('end', () => {
<ide> try {
<ide> const data = JSON.parse(body);
<add> // write back something interesting to the user:
<add> res.write(typeof data);
<add> res.end();
<ide> } catch (er) {
<ide> // uh oh! bad json!
<ide> res.statusCode = 400;
<ide> return res.end(`error: ${er.message}`);
<ide> }
<del>
<del> // write back something interesting to the user:
<del> res.write(typeof data);
<del> res.end();
<ide> });
<ide> });
<ide> | 1 |
PHP | PHP | pass listener arguments to middleware method | 3ed70e93460c903b1a860d0d0572f2dcfdbfeb43 | <ide><path>src/Illuminate/Events/Dispatcher.php
<ide> protected function createListenerAndJob($class, $method, $arguments)
<ide> * Propagate listener options to the job.
<ide> *
<ide> * @param mixed $listener
<del> * @param mixed $job
<add> * @param \Illuminate\Events\CallQueuedListener $job
<ide> * @return mixed
<ide> */
<ide> protected function propagateListenerOptions($listener, $job)
<ide> protected function propagateListenerOptions($listener, $job)
<ide> $job->tries = $listener->tries ?? null;
<ide>
<ide> $job->through(array_merge(
<del> method_exists($listener, 'middleware') ? $listener->middleware() : [],
<add> method_exists($listener, 'middleware') ? $listener->middleware(...$job->data) : [],
<ide> $listener->middleware ?? []
<ide> ));
<ide> });
<ide><path>tests/Events/QueuedEventsTest.php
<ide> public function testQueuePropagateMiddleware()
<ide> $d->dispatch('some.event', ['foo', 'bar']);
<ide>
<ide> $fakeQueue->assertPushed(CallQueuedListener::class, function ($job) {
<del> return count($job->middleware) === 1 && $job->middleware[0] instanceof TestMiddleware;
<add> return count($job->middleware) === 1
<add> && $job->middleware[0] instanceof TestMiddleware
<add> && $job->middleware[0]->a === 'foo'
<add> && $job->middleware[0]->b === 'bar';
<ide> });
<ide> }
<ide> }
<ide> public function handle()
<ide>
<ide> class TestDispatcherMiddleware implements ShouldQueue
<ide> {
<del> public function middleware()
<add> public function middleware($a, $b)
<ide> {
<del> return [new TestMiddleware()];
<add> return [new TestMiddleware($a, $b)];
<ide> }
<ide>
<del> public function handle()
<add> public function handle($a, $b)
<ide> {
<ide> //
<ide> }
<ide> }
<ide>
<ide> class TestMiddleware
<ide> {
<add> public $a;
<add> public $b;
<add>
<add> public function __construct($a, $b)
<add> {
<add> $this->a = $a;
<add> $this->b = $b;
<add> }
<add>
<ide> public function handle($job, $next)
<ide> {
<ide> $next($job); | 2 |
Ruby | Ruby | resolve constant lookup issues | 425a02cecea188f502ad8f137271d1b90b9c7558 | <ide><path>actionpack/test/controller/helper_test.rb
<ide>
<ide> ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers'
<ide>
<del>class TestController < ActionController::Base
<del> attr_accessor :delegate_attr
<del> def delegate_method() end
<del> def rescue_action(e) raise end
<del>end
<del>
<ide> module Fun
<ide> class GamesController < ActionController::Base
<ide> def render_hello_world
<ide> def c() end
<ide> end
<ide>
<ide> class HelperTest < Test::Unit::TestCase
<add> class TestController < ActionController::Base
<add> attr_accessor :delegate_attr
<add> def delegate_method() end
<add> def rescue_action(e) raise end
<add> end
<add>
<ide> def setup
<ide> # Increment symbol counter.
<ide> @symbol = (@@counter ||= 'A0').succ!.dup
<ide><path>actionpack/test/controller/render_test.rb
<ide> def test_access_to_action_name_in_view
<ide> # :ported:
<ide> def test_access_to_controller_name_in_view
<ide> get :accessing_controller_name_in_template
<del> assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller.
<add> assert_equal "test", @response.body # name is explicitly set in the controller.
<ide> end
<ide>
<ide> # :ported:
<ide><path>actionpack/test/controller/rescue_test.rb
<ide> def show_errors(exception)
<ide> def with_test_routing
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match 'foo', :to => TestController.action(:foo)
<del> match 'invalid', :to => TestController.action(:invalid)
<del> match 'b00m', :to => TestController.action(:b00m)
<add> match 'foo', :to => ::RescueTest::TestController.action(:foo)
<add> match 'invalid', :to => ::RescueTest::TestController.action(:invalid)
<add> match 'b00m', :to => ::RescueTest::TestController.action(:b00m)
<ide> end
<ide> yield
<ide> end
<ide><path>actionpack/test/controller/verification_test.rb
<ide> def test_no_deprecation_warning_for_named_route
<ide> with_routing do |set|
<ide> set.draw do |map|
<ide> match 'foo', :to => 'test#foo', :as => :foo
<del> match 'verification_test/:action', :to => TestController
<add> match 'verification_test/:action', :to => ::VerificationTest::TestController
<ide> end
<ide> get :guarded_one_for_named_route_test, :two => "not one"
<ide> assert_redirected_to '/foo'
<ide><path>actionpack/test/dispatch/request/json_params_parsing_test.rb
<ide> def assert_parses(expected, actual, headers = {})
<ide> def with_test_routing
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::JsonParamsParsingTest::TestController
<ide> end
<ide> yield
<ide> end
<ide><path>actionpack/test/dispatch/request/query_string_parsing_test.rb
<ide> def teardown
<ide> def assert_parses(expected, actual)
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::QueryStringParsingTest::TestController
<ide> end
<ide>
<ide> get "/parse", actual
<ide> assert_response :ok
<del> assert_equal(expected, TestController.last_query_parameters)
<add> assert_equal(expected, ::QueryStringParsingTest::TestController.last_query_parameters)
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
<ide> def teardown
<ide> def with_test_routing
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::UrlEncodedParamsParsingTest::TestController
<ide> end
<ide> yield
<ide> end
<ide><path>actionpack/test/dispatch/request/xml_params_parsing_test.rb
<ide> def teardown
<ide> def with_test_routing
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::XmlParamsParsingTest::TestController
<ide> end
<ide> yield
<ide> end
<ide> class LegacyXmlParamsParsingTest < XmlParamsParsingTest
<ide> def default_headers
<ide> {'HTTP_X_POST_DATA_FORMAT' => 'xml'}
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>actionpack/test/dispatch/session/cookie_store_test.rb
<ide> def test_session_store_with_expire_after
<ide> def with_test_route_set(options = {})
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::CookieStoreTest::TestController
<ide> end
<ide> options = {:key => SessionKey, :secret => SessionSecret}.merge(options)
<ide> @app = ActionDispatch::Session::CookieStore.new(set, options)
<ide><path>actionpack/test/dispatch/session/mem_cache_store_test.rb
<ide> def test_prevents_session_fixation
<ide> def with_test_route_set
<ide> with_routing do |set|
<ide> set.draw do |map|
<del> match ':action', :to => TestController
<add> match ':action', :to => ::MemCacheStoreTest::TestController
<ide> end
<ide> @app = ActionDispatch::Session::MemCacheStore.new(set, :key => '_session_id')
<ide> yield | 10 |
Text | Text | add deprecation note for easy_install | 9e9944b81af449e470d3f478f9492052612e94b4 | <ide><path>guide/english/python/using-pip/index.md
<ide> Using `easy_install` is also simple. The syntax is:
<ide>
<ide> easy_install <module_name>
<ide>
<del>However, `pip` is more popular than using `easy_install`.
<add>However, `pip` is more popular than using `easy_install`, and `easy_install` is <a href='https://setuptools.readthedocs.io/en/latest/easy_install.html'> deprecated</a>.
<ide>
<ide>
<ide> **Note:** On some systems where both Python 2 & Python 3 is installed, `pip` and `pip3` will do different things. `pip` installs the Python 2 version of the package, and `pip3` will install the Python 3 version of the package. For more information on the difference between Python 2 & 3, see [this](https://guide.freecodecamp.org/python/python-2-vs-python-3) guide. | 1 |
Python | Python | fix a small bug in docscrape | 5a0e7560e7206f9c0f049d8176eab0f8c0b951c6 | <ide><path>doc/sphinxext/docscrape_sphinx.py
<ide> def __init__(self, obj, doc=None, config={}):
<ide> FunctionDoc.__init__(self, obj, doc=doc, config=config)
<ide>
<ide> class SphinxClassDoc(SphinxDocString, ClassDoc):
<del> def __init__(self, obj, doc=None, config={}):
<add> def __init__(self, obj, doc=None, func_doc=None, config={}):
<ide> self.use_plots = config.get('use_plots', False)
<del> ClassDoc.__init__(self, obj, doc=doc, config=config)
<add> ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
<ide>
<ide> class SphinxObjDoc(SphinxDocString):
<ide> def __init__(self, obj, doc=None, config={}): | 1 |
Javascript | Javascript | add tests for process.initgroups | a4cae978fc9a60c31ec443ee72bfc5770a742b92 | <ide><path>test/parallel/test-process-initgroups.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<add>if (common.isWindows || !common.isMainThread) {
<add> assert.strictEqual(process.initgroups, undefined);
<add> return;
<add>}
<add>
<add>[undefined, null, true, {}, [], () => {}].forEach((val) => {
<add> assert.throws(
<add> () => {
<add> process.initgroups(val);
<add> },
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<add> message:
<add> 'The "user" argument must be ' +
<add> 'one of type number or string. ' +
<add> `Received type ${typeof val}`
<add> }
<add> );
<add>});
<add>
<add>[undefined, null, true, {}, [], () => {}].forEach((val) => {
<add> assert.throws(
<add> () => {
<add> process.initgroups('foo', val);
<add> },
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<add> message:
<add> 'The "extraGroup" argument must be ' +
<add> 'one of type number or string. ' +
<add> `Received type ${typeof val}`
<add> }
<add> );
<add>});
<add>
<add>assert.throws(
<add> () => {
<add> process.initgroups(
<add> 'fhqwhgadshgnsdhjsdbkhsdabkfabkveyb',
<add> 'fhqwhgadshgnsdhjsdbkhsdabkfabkveyb'
<add> );
<add> },
<add> {
<add> code: 'ERR_UNKNOWN_CREDENTIAL',
<add> message:
<add> 'Group identifier does not exist: fhqwhgadshgnsdhjsdbkhsdabkfabkveyb'
<add> }
<add>); | 1 |
Ruby | Ruby | use new update_python_resources! signature | 20de58b5ae473939e9a39d4e79c3a6f7601d6bf1 | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide> end
<ide>
<ide> unless args.dry_run?
<del> resources_checked = PyPI.update_python_resources! formula, new_formula_version,
<add> resources_checked = PyPI.update_python_resources! formula, version: new_formula_version,
<ide> silent: args.quiet?, ignore_non_pypi_packages: true
<ide> end
<ide> | 1 |
Python | Python | fix typo in documentation | 1d8b64ef0d094287a0ed7934f77aa93574913760 | <ide><path>celery/app/base.py
<ide> def autodiscover_tasks(self, packages=None,
<ide> baz/__init__.py
<ide> models.py
<ide>
<del> Then calling ``app.autodiscover_tasks(['foo', bar', 'baz'])`` will
<add> Then calling ``app.autodiscover_tasks(['foo', 'bar', 'baz'])`` will
<ide> result in the modules ``foo.tasks`` and ``bar.tasks`` being imported.
<ide>
<ide> Arguments: | 1 |
Ruby | Ruby | fix typo in activerecord test method name | 4a3f5a68c9972290326481ef859e63c53809715d | <ide><path>activerecord/test/cases/base_test.rb
<ide> def test_switching_between_table_name
<ide> end
<ide> end
<ide>
<del> def test_clear_cash_when_setting_table_name
<add> def test_clear_cache_when_setting_table_name
<ide> original_table_name = Joke.table_name
<ide>
<ide> Joke.table_name = "funny_jokes" | 1 |
Text | Text | update index.md input attribute | e13d795cff1772c20b384d93e736c08a42c1bdf9 | <ide><path>guide/english/html/attributes/input-type-attribute/index.md
<ide> title: Input Type Attribute
<ide> The input type attribute specifies the type of the input the user should put in your form.
<ide>
<ide> ### text
<del>One line of a text.
<add>One line of text.
<ide> ```html
<ide> <form>
<ide> <label for="login">Login:</label>
<ide> One line of a text.
<ide> ```
<ide>
<ide> ### password
<del>One line of a text. Text is automatically displayed as a series of dots or asterisks (depends on the browser and OS).
<add>One line of text. Text is automatically displayed as a series of dots or asterisks (depends on the browser and OS).
<ide> ```html
<ide> <form>
<ide> <label for="password">Password:</label>
<ide> The HTML checks if the input matches the e-mail address format (something@someth
<ide> ```
<ide>
<ide> ### number
<del>Allow only numeric input. You can also specify the min and max value allowed. The example below check that the input is number between 1 and 120.
<add>Allow only numeric input. You can also specify the min and max value allowed. The example below checks that the input is number between 1 and 120.
<ide> ```html
<ide> <form>
<ide> <label for="age">Age:</label>
<ide> Let the user choose one or more files from their device storage. Once chosen, th
<ide> ```
<ide>
<ide> ### radio
<del>Only one option can be selected by the user. The group of radio buttons needs to have the same name attribute. You can select automatically one option by using `checked` property (in the example below the value Blue is selected).
<add>Only one option can be selected by the user. The group of radio buttons needs to have the same name attribute. You can select one option automatically by using `checked` property (in the example below the value Blue is selected).
<ide> ```html
<ide> <form>
<ide> <label><input type="radio" name="color" value="red">Red</label>
<ide> The input is displayed as a button, the text which should be displayed in the bu
<ide> ```
<ide>
<ide> ### submit
<del>Displays the submit button. The text which should be displayed in the button is in value attribute. After clicking on the button, the HTML does the validation and if it passes, the form is submitted.
<add>Displays the submit button. The text which should be displayed in the button is in the value attribute. After clicking on the button, HTML validation is performed and if it passes, the form is submitted.
<ide>
<ide> ```html
<ide> <form>
<ide> Displays the submit button. The text which should be displayed in the button is
<ide> ```
<ide>
<ide> ### reset
<del>Displays the reset button. The text which should be displayed in the button is in the value attribute. After clicking on the button, all values from the form are deleted.
<add>Displays the reset button. The text which should be displayed in the button is in the value attribute. After clicking on the button, all entered values from the form are deleted.
<ide> ```html
<ide> <form>
<ide> <input type="reset" value="CANCEL"> | 1 |
Ruby | Ruby | remove xip support | 8113a9fed9fe6dcd41f6a382cb19e61c0abe2887 | <ide><path>Library/Homebrew/cask/lib/hbc/container.rb
<ide> require "hbc/container/ttf"
<ide> require "hbc/container/rar"
<ide> require "hbc/container/xar"
<del>require "hbc/container/xip"
<ide> require "hbc/container/xz"
<ide> require "hbc/container/zip"
<ide>
<ide> def self.autodetect_containers
<ide> Sit,
<ide> Rar,
<ide> Zip,
<del> Xip, # needs to be before xar as this is a cpio inside a gzip inside a xar
<ide> Xar, # need to be before tar as tar can also list xar
<ide> Tar, # or compressed tar (bzip2/gzip/lzma/xz)
<ide> Bzip2, # pure bzip2
<ide><path>Library/Homebrew/cask/lib/hbc/container/xip.rb
<del>require "tmpdir"
<del>
<del>module Hbc
<del> class Container
<del> class Xip < Base
<del> def self.me?(criteria)
<del> criteria.magic_number(/^xar!/n) &&
<del> IO.popen(["/usr/bin/xar", "-t", "-f", criteria.path.to_s], err: "/dev/null") { |io| io.read =~ /\AContent\nMetadata\n\Z/ }
<del> end
<del>
<del> def extract
<del> Dir.mktmpdir do |unpack_dir|
<del> begin
<del> ohai "Verifying signature for #{@path.basename}"
<del> @command.run!("/usr/sbin/pkgutil", args: ["--check-signature", @path])
<del> rescue
<del> raise "Signature check failed."
<del> end
<del>
<del> @command.run!("/usr/bin/xar", args: ["-x", "-f", @path, "Content", "-C", unpack_dir])
<del>
<del> Dir.chdir(@cask.staged_path) do
<del> @command.run!("/usr/bin/cpio", args: ["--quiet", "-i", "-I", Pathname(unpack_dir).join("Content")])
<del> end
<del> end
<del> end
<del> end
<del> end
<del>end | 2 |
Mixed | Javascript | simplify common.port code | 3674bee884bd86a7eb778345a410b2d8ab473a84 | <ide><path>test/common/index.js
<ide> const noop = () => {};
<ide> // Using a `.` prefixed name, which is the convention for "hidden" on POSIX,
<ide> // gets tools to ignore it by default or by simple rules, especially eslint.
<ide> let tmpDirName = '.tmp';
<del>// PORT should match the definition in test/testpy/__init__.py.
<add>
<ide> exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
<add>
<ide> exports.isWindows = process.platform === 'win32';
<ide> exports.isWOW64 = exports.isWindows &&
<ide> (process.env.PROCESSOR_ARCHITEW6432 !== undefined);
<ide> exports.refreshTmpDir = function() {
<ide> };
<ide>
<ide> if (process.env.TEST_THREAD_ID) {
<del> exports.PORT += process.env.TEST_THREAD_ID * 100;
<ide> tmpDirName += `.${process.env.TEST_THREAD_ID}`;
<ide> }
<ide> exports.tmpDir = path.join(testRoot, tmpDirName);
<ide><path>test/testpy/__init__.py
<ide> def GetCommand(self):
<ide> source = open(self.file).read()
<ide> flags_match = FLAGS_PATTERN.search(source)
<ide> if flags_match:
<del> # PORT should match the definition in test/common/index.js.
<del> env = { 'PORT': int(os.getenv('NODE_COMMON_PORT', '12346')) }
<del> env['PORT'] += self.thread_id * 100
<del> flag = flags_match.group(1).strip().format(**env).split()
<add> flag = flags_match.group(1).strip().split()
<ide> # The following block reads config.gypi to extract the v8_enable_inspector
<ide> # value. This is done to check if the inspector is disabled in which case
<ide> # the '--inspect' flag cannot be passed to the node process as it will | 2 |
Text | Text | add comment on deep cloning and re-rendering | 4c9cbd15839d153e4aee9f935c11ec9ca4af10b3 | <ide><path>docs/faq/Performance.md
<ide> If you actually are concerned about reducer performance, you can use a utility s
<ide>
<ide> Immutably updating state generally means making shallow copies, not deep copies. Shallow copies are much faster than deep copies, because fewer objects and fields have to be copied, and it effectively comes down to moving some pointers around.
<ide>
<add>In addition, deep cloning state creates new references for every field. Since the React-Redux `connect` function relies on reference comparisons to determine if data has changed, this means that UI components will be forced to re-render unnecessarily even though the other data hasn't meaningfully changed.
<add>
<ide> However, you *do* need to create a copied and updated object for each level of nesting that is affected. Although that shouldn't be particularly expensive, it's another good reason why you should keep your state normalized and shallow if possible.
<ide>
<ide> > Common Redux misconception: you need to deeply clone the state. Reality: if something inside doesn't change, keep its reference the same!
<ide> Third, only cache a single copy of a record. This is especially important when r
<ide> **Discussions**
<ide> - [Stack Overflow: How to choose the Redux state shape for an app with list/detail views and pagination?](https://stackoverflow.com/questions/33940015/how-to-choose-the-redux-state-shape-for-an-app-with-list-detail-views-and-pagina)
<ide> - [Twitter: ...concerns over having "too much data in the state tree"...](https://twitter.com/acemarke/status/804071531844423683)
<del>- [Advanced Redux entity normalization](https://medium.com/@dcousineau/advanced-redux-entity-normalization-f5f1fe2aefc5)
<ide>\ No newline at end of file
<add>- [Advanced Redux entity normalization](https://medium.com/@dcousineau/advanced-redux-entity-normalization-f5f1fe2aefc5) | 1 |
PHP | PHP | update builder.php | 87a29a2fa2d7a3df8594d0b45ebe3f6093fb8a09 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function where($column, $operator = null, $value = null, $boolean = 'and'
<ide> */
<ide> protected function addArrayOfWheres($column, $boolean, $method = 'where')
<ide> {
<del> return $this->whereNested(function ($query) use ($column, $method) {
<add> return $this->whereNested(function ($query) use ($column, $method, $boolean) {
<ide> foreach ($column as $key => $value) {
<ide> if (is_numeric($key) && is_array($value)) {
<ide> $query->{$method}(...array_values($value));
<ide> } else {
<del> $query->$method($key, '=', $value);
<add> $query->$method($key, '=', $value, $boolean);
<ide> }
<ide> }
<ide> }, $boolean); | 1 |
Mixed | Javascript | add support for layout gravity to toastandroid | 12ec213c0d1610ebc6c0bd233818e387aa1ad4b9 | <ide><path>Examples/UIExplorer/js/ToastAndroidExample.android.js
<ide> var ToastExample = React.createClass({
<ide> <TouchableWithoutFeedback
<ide> onPress={() =>
<ide> ToastAndroid.show('This is a toast with long duration', ToastAndroid.LONG)}>
<del> <Text style={styles.text}>Click me too.</Text>
<add> <Text style={styles.text}>Click me.</Text>
<add> </TouchableWithoutFeedback>
<add> </UIExplorerBlock>
<add> <UIExplorerBlock title="Toast with top gravity">
<add> <TouchableWithoutFeedback
<add> onPress={() =>
<add> ToastAndroid.showWithGravity(
<add> 'This is a toast with top gravity',
<add> ToastAndroid.SHORT,
<add> ToastAndroid.TOP,
<add> )
<add> }>
<add> <Text style={styles.text}>Click me.</Text>
<add> </TouchableWithoutFeedback>
<add> </UIExplorerBlock>
<add> <UIExplorerBlock title="Toast with center gravity">
<add> <TouchableWithoutFeedback
<add> onPress={() =>
<add> ToastAndroid.showWithGravity(
<add> 'This is a toast with center gravity',
<add> ToastAndroid.SHORT,
<add> ToastAndroid.CENTER,
<add> )
<add> }>
<add> <Text style={styles.text}>Click me.</Text>
<add> </TouchableWithoutFeedback>
<add> </UIExplorerBlock>
<add> <UIExplorerBlock title="Toast with bottom gravity">
<add> <TouchableWithoutFeedback
<add> onPress={() =>
<add> ToastAndroid.showWithGravity(
<add> 'This is a toast with bottom gravity',
<add> ToastAndroid.SHORT,
<add> ToastAndroid.BOTTOM,
<add> )
<add> }>
<add> <Text style={styles.text}>Click me.</Text>
<ide> </TouchableWithoutFeedback>
<ide> </UIExplorerBlock>
<ide> </UIExplorerPage>
<ide><path>Libraries/Components/ToastAndroid/ToastAndroid.android.js
<ide> var RCTToastAndroid = require('NativeModules').ToastAndroid;
<ide> *
<ide> * 1. String message: A string with the text to toast
<ide> * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG
<add> *
<add> * There is also a function `showWithGravity` to specify the layout gravity. May be
<add> * ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER
<ide> */
<ide>
<ide> var ToastAndroid = {
<ide>
<add> // Toast duration constants
<ide> SHORT: RCTToastAndroid.SHORT,
<ide> LONG: RCTToastAndroid.LONG,
<ide>
<add> // Toast gravity constants
<add> TOP: RCTToastAndroid.TOP,
<add> BOTTOM: RCTToastAndroid.BOTTOM,
<add> CENTER: RCTToastAndroid.CENTER,
<add>
<ide> show: function (
<ide> message: string,
<ide> duration: number
<ide> ): void {
<ide> RCTToastAndroid.show(message, duration);
<ide> },
<ide>
<add> showWithGravity: function (
<add> message: string,
<add> duration: number,
<add> gravity: number,
<add> ): void {
<add> RCTToastAndroid.showWithGravity(message, duration, gravity);
<add> },
<ide> };
<ide>
<ide> module.exports = ToastAndroid;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/toast/ToastModule.java
<ide>
<ide> package com.facebook.react.modules.toast;
<ide>
<add>import android.view.Gravity;
<ide> import android.widget.Toast;
<ide>
<ide> import com.facebook.react.bridge.NativeModule;
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<del>import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.bridge.ReactContextBaseJavaModule;
<ide> import com.facebook.react.bridge.ReactMethod;
<ide> import com.facebook.react.common.MapBuilder;
<ide> public class ToastModule extends ReactContextBaseJavaModule {
<ide> private static final String DURATION_SHORT_KEY = "SHORT";
<ide> private static final String DURATION_LONG_KEY = "LONG";
<ide>
<add> private static final String GRAVITY_TOP_KEY = "TOP";
<add> private static final String GRAVITY_BOTTOM_KEY = "BOTTOM";
<add> private static final String GRAVITY_CENTER = "CENTER";
<add>
<ide> public ToastModule(ReactApplicationContext reactContext) {
<ide> super(reactContext);
<ide> }
<ide> public Map<String, Object> getConstants() {
<ide> final Map<String, Object> constants = MapBuilder.newHashMap();
<ide> constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
<ide> constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
<add> constants.put(GRAVITY_TOP_KEY, Gravity.TOP | Gravity.CENTER_HORIZONTAL);
<add> constants.put(GRAVITY_BOTTOM_KEY, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
<add> constants.put(GRAVITY_CENTER, Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
<ide> return constants;
<ide> }
<ide>
<ide> @ReactMethod
<ide> public void show(final String message, final int duration) {
<ide> UiThreadUtil.runOnUiThread(new Runnable() {
<ide> @Override
<del> public void run(){
<add> public void run() {
<ide> Toast.makeText(getReactApplicationContext(), message, duration).show();
<ide> }
<ide> });
<ide> }
<add>
<add> @ReactMethod
<add> public void showWithGravity(final String message, final int duration, final int gravity) {
<add> UiThreadUtil.runOnUiThread(new Runnable() {
<add> @Override
<add> public void run() {
<add> Toast toast = Toast.makeText(getReactApplicationContext(), message, duration);
<add> toast.setGravity(gravity, 0, 0);
<add> toast.show();
<add> }
<add> });
<add> }
<ide> } | 3 |
Text | Text | update readme to use bundle exec * | fdf97f42f747c79dfc7a04d609f06c7c3bd5ab2b | <ide><path>docs/README.md
<ide> Use Jekyll to serve the website locally (by default, at `http://localhost:4000`)
<ide>
<ide> ```sh
<ide> $ cd react/docs
<del>$ rake
<del>$ jekyll serve -w
<add>$ bundle exec rake
<add>$ bundle exec jekyll serve -w
<ide> $ open http://localhost:4000/react/
<ide> ```
<ide>
<ide> If you want to modify the CSS or JS, use [Rake](http://rake.rubyforge.org/) to c
<ide>
<ide> ```sh
<ide> $ cd react/docs
<del>$ rake watch # Automatically compiles as needed.
<del># rake Manually compile CSS and JS.
<del># rake css Manually compile CSS, only.
<del># rake js Manually compile JS, only.
<add>$ bundle exec rake watch # Automatically compiles as needed.
<add># bundle exec rake Manually compile CSS and JS.
<add># bundle exec rake js Manually compile JS, only.
<ide> ```
<ide>
<ide> ## Afterthoughts
<ide> The easiest way to do this is to have a separate clone of this repository, check
<ide>
<ide> **Note:** This should only be done for new releases. You should create a tag corresponding to the release tag in the main repository.
<ide>
<add>We also have a rake task that does the same thing (without creating commits). It expects the directory structure mentioned above.
<add>
<add>```sh
<add>$ bundle exec rake release
<add>```
<add>
<ide> ### Removing the Jekyll / Ruby Dependency
<ide>
<ide> In an ideal world, we would not be adding a Ruby dependency on part of our project. We would like to move towards a point where we are using React to render the website. | 1 |
Ruby | Ruby | fix version misdetection from fa582cb9ac65 | 5369199df36a0fbf707e08ef5f3569782fb0cde4 | <ide><path>Library/Homebrew/version.rb
<ide> def self._parse spec
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. http://www.openssl.org/source/openssl-0.9.8s.tar.gz
<del> m = /-([^-]+)/.match(stem)
<add> m = /-v?([^-]+)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. astyle_1.23_macosx.tar.gz | 1 |
Text | Text | add missing period | f7642a476ddacb537e78c564ec19d7bb72964d16 | <ide><path>docs/build-instructions/windows.md
<ide> To also install the newly built application, use `script\build --create-windows-
<ide> * See the next item.
<ide>
<ide> * `error MSB8020: The build tools for Visual Studio 201? (Platform Toolset = 'v1?0') cannot be found.`
<del> * Try setting the `GYP_MSVS_VERSION` environment variable to 2013 or 2015 depending on what version of Visual Studio/Build Tools is installed and then `script\clean` followed by `script\build` (re-open the Command Prompt if you set the variable using the GUI)
<add> * Try setting the `GYP_MSVS_VERSION` environment variable to 2013 or 2015 depending on what version of Visual Studio/Build Tools is installed and then `script\clean` followed by `script\build` (re-open the Command Prompt if you set the variable using the GUI).
<ide>
<ide> * `'node-gyp' is not recognized as an internal or external command, operable program or batch file.`
<ide> * Try running `npm install -g node-gyp`, and run `script\build` again. | 1 |
Python | Python | use protocolerror.errcode value to trace errors | 90e1124ec0863c9abb4dd9acfe86152ce147dde0 | <ide><path>glances/core/glances_client.py
<ide> def login(self):
<ide> except socket.error as err:
<ide> # Fallback to SNMP
<ide> self.client_mode = 'snmp'
<del> logger.error("Connection to Glances server failed: {0}".format(err))
<add> logger.error("Connection to Glances server failed ({0} {1})".format(err.errno, err.strerror))
<ide> fallbackmsg = 'No Glances server found. Trying fallback to SNMP...'
<ide> if not self.return_to_browser:
<ide> print(fallbackmsg)
<ide> else:
<ide> logger.info(fallbackmsg)
<ide> except ProtocolError as err:
<del> # Others errors
<del> if str(err).find(" 401 ") > 0:
<del> msg = "Connection to server failed (bad password)"
<add> # Other errors
<add> msg = "Connection to server failed"
<add> if err.errcode == 401:
<add> msg += " (Bad password)"
<ide> else:
<del> msg = "Connection to server failed ({0})".format(err)
<add> msg += " ({0} {1})".format(err.errcode, err.errmsg)
<ide> self.log_and_exit(msg)
<ide> return False
<ide> | 1 |
Javascript | Javascript | remove deregisternotifier feature for $watch | d2f8f25af2c078c971c7223a8894a01e0595cd20 | <ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> exp: text, //just for compatibility with regular watchers created via $watch
<ide> separators: separators,
<ide> expressions: expressions,
<del> $$watchDelegate: function (scope, listener, objectEquality, deregisterNotifier) {
<add> $$watchDelegate: function (scope, listener, objectEquality) {
<ide> var lastValue;
<ide> return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
<ide> var currValue = compute(values);
<ide> if (isFunction(listener)) {
<ide> listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
<ide> }
<ide> lastValue = currValue;
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide> });
<ide> }
<ide><path>src/ng/parse.js
<ide> function $ParseProvider() {
<ide> }
<ide> };
<ide>
<del> function oneTimeWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
<add> function oneTimeWatch(scope, listener, objectEquality, parsedExpression) {
<ide> var unwatch, lastValue;
<ide> return unwatch = scope.$watch(function oneTimeWatch(scope) {
<ide> return parsedExpression(scope);
<ide> function $ParseProvider() {
<ide> }
<ide> });
<ide> }
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide>
<del> function constantWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
<add> function constantWatch(scope, listener, objectEquality, parsedExpression) {
<ide> var unwatch;
<ide> return unwatch = scope.$watch(function constantWatch(scope) {
<ide> return parsedExpression(scope);
<ide> function $ParseProvider() {
<ide> listener.apply(this, arguments);
<ide> }
<ide> unwatch();
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide>
<ide> function addInterceptor(parsedExpression, interceptorFn) {
<ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * - `scope` refers to the current scope
<ide> * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
<ide> * comparing for reference equality.
<del> * @param {function()=} deregisterNotifier Function to call when the deregistration function
<del> * get called.
<ide> * @returns {function()} Returns a deregistration function for this listener.
<ide> */
<del> $watch: function(watchExp, listener, objectEquality, deregisterNotifier) {
<add> $watch: function(watchExp, listener, objectEquality) {
<ide> var get = compileToFn(watchExp, 'watch');
<ide>
<ide> if (get.$$watchDelegate) {
<del> return get.$$watchDelegate(this, listener, objectEquality, deregisterNotifier, get);
<add> return get.$$watchDelegate(this, listener, objectEquality, get);
<ide> }
<ide> var scope = this,
<ide> array = scope.$$watchers,
<ide> function $RootScopeProvider(){
<ide> return function deregisterWatch() {
<ide> arrayRemove(array, watcher);
<ide> lastDirtyWatch = null;
<del> if (isFunction(deregisterNotifier)) {
<del> deregisterNotifier();
<del> }
<ide> };
<ide> },
<ide>
<ide><path>test/ng/rootScopeSpec.js
<ide> describe('Scope', function() {
<ide> expect(log).toEqual(['watch1', 'watchAction1', 'watch2', 'watchAction2', 'watch3', 'watchAction3',
<ide> 'watch2', 'watch3']);
<ide> }));
<del>
<del> describe('deregisterNotifier', function () {
<del> it('should call the deregisterNotifier when the watch is deregistered', inject(
<del> function($rootScope) {
<del> var notifier = jasmine.createSpy('deregisterNotifier');
<del> var listenerRemove = $rootScope.$watch('noop', noop, false, notifier);
<del>
<del> expect(notifier).not.toHaveBeenCalled();
<del>
<del> listenerRemove();
<del> expect(notifier).toHaveBeenCalledOnce();
<del> }));
<del>
<del>
<del> it('should call the deregisterNotifier when a one-time expression is stable', inject(
<del> function($rootScope) {
<del> var notifier = jasmine.createSpy('deregisterNotifier');
<del> $rootScope.$watch('::foo', noop, false, notifier);
<del>
<del> expect(notifier).not.toHaveBeenCalledOnce();
<del> $rootScope.$digest();
<del> expect(notifier).not.toHaveBeenCalledOnce();
<del>
<del> $rootScope.foo = 'foo';
<del> $rootScope.$digest();
<del> expect(notifier).toHaveBeenCalledOnce();
<del> }));
<del> });
<ide> });
<ide>
<ide> | 4 |
Python | Python | prefer pytest.skip() over skiptest | f531cfd97a99ac8b534fff479e3388888319a606 | <ide><path>numpy/core/tests/_locales.py
<ide> import sys
<ide> import locale
<ide>
<del>from numpy.testing import SkipTest
<add>import pytest
<ide>
<ide> __ALL__ = ['CommaDecimalPointLocale']
<ide>
<ide> class CommaDecimalPointLocale(object):
<ide> tests with locale.LC_NUMERIC set to a locale where commas (',') are used as
<ide> the decimal point instead of periods ('.'). On exit the locale is restored
<ide> to the initial locale. It also serves as context manager with the same
<del> effect. If no such locale is available, it raises SkipTest in both cases.
<add> effect. If no such locale is available, the test is skipped.
<ide>
<ide> .. versionadded:: 1.15.0
<ide>
<ide> class CommaDecimalPointLocale(object):
<ide>
<ide> def setup(self):
<ide> if self.tst_locale is None:
<del> raise SkipTest("No French locale available")
<add> pytest.skip("No French locale available")
<ide> locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
<ide>
<ide> def teardown(self):
<ide> locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
<ide>
<ide> def __enter__(self):
<ide> if self.tst_locale is None:
<del> raise SkipTest("No French locale available")
<add> pytest.skip("No French locale available")
<ide> locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
<ide>
<ide> def __exit__(self, type, value, traceback):
<ide><path>numpy/core/tests/test_multiarray.py
<ide> assert_, assert_raises, assert_warns, assert_equal, assert_almost_equal,
<ide> assert_array_equal, assert_raises_regex, assert_array_almost_equal,
<ide> assert_allclose, IS_PYPY, HAS_REFCOUNT, assert_array_less, runstring,
<del> SkipTest, temppath, suppress_warnings
<add> temppath, suppress_warnings
<ide> )
<ide> from numpy.core.tests._locales import CommaDecimalPointLocale
<ide>
<ide> def test_field_names(self):
<ide>
<ide> # non-ascii unicode field indexing is well behaved
<ide> if not is_py3:
<del> raise SkipTest('non ascii unicode field indexing skipped; '
<del> 'raises segfault on python 2.x')
<add> pytest.skip('non ascii unicode field indexing skipped; '
<add> 'raises segfault on python 2.x')
<ide> else:
<ide> assert_raises(ValueError, a.__setitem__, u'\u03e0', 1)
<ide> assert_raises(ValueError, a.__getitem__, u'\u03e0')
<ide><path>numpy/core/tests/test_print.py
<ide> import pytest
<ide>
<ide> import numpy as np
<del>from numpy.testing import assert_, assert_equal, SkipTest
<add>from numpy.testing import assert_, assert_equal
<ide> from numpy.core.tests._locales import CommaDecimalPointLocale
<ide>
<ide>
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py
<ide> from numpy import (
<ide> array, alltrue, ndarray, zeros, dtype, intp, clongdouble
<ide> )
<del>from numpy.testing import assert_, assert_equal, SkipTest
<add>from numpy.testing import assert_, assert_equal
<ide> from numpy.core.multiarray import typeinfo
<ide> from . import util
<ide>
<ide> def setup_module():
<ide>
<ide> # Check compiler availability first
<ide> if not util.has_c_compiler():
<del> raise SkipTest("No C compiler available")
<add> pytest.skip("No C compiler available")
<ide>
<ide> if wrap is None:
<ide> config_code = """
<ide><path>numpy/f2py/tests/util.py
<ide> import numpy.f2py
<ide>
<ide> from numpy.compat import asbytes, asstr
<del>from numpy.testing import SkipTest, temppath
<add>from numpy.testing import temppath
<ide> from importlib import import_module
<ide>
<ide> try:
<ide> class F2PyTest(object):
<ide>
<ide> def setup(self):
<ide> if sys.platform == 'win32':
<del> raise SkipTest('Fails with MinGW64 Gfortran (Issue #9673)')
<add> pytest.skip('Fails with MinGW64 Gfortran (Issue #9673)')
<ide>
<ide> if self.module is not None:
<ide> return
<ide>
<ide> # Check compiler availability first
<ide> if not has_c_compiler():
<del> raise SkipTest("No C compiler available")
<add> pytest.skip("No C compiler available")
<ide>
<ide> codes = []
<ide> if self.sources:
<ide> def setup(self):
<ide> elif fn.endswith('.f90'):
<ide> needs_f90 = True
<ide> if needs_f77 and not has_f77_compiler():
<del> raise SkipTest("No Fortran 77 compiler available")
<add> pytest.skip("No Fortran 77 compiler available")
<ide> if needs_f90 and not has_f90_compiler():
<del> raise SkipTest("No Fortran 90 compiler available")
<add> pytest.skip("No Fortran 90 compiler available")
<ide>
<ide> # Build the module
<ide> if self.code is not None:
<ide><path>numpy/lib/tests/test__datasource.py
<ide>
<ide> import numpy.lib._datasource as datasource
<ide> from numpy.testing import (
<del> assert_, assert_equal, assert_raises, assert_warns, SkipTest
<add> assert_, assert_equal, assert_raises, assert_warns
<ide> )
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> def test_ValidGzipFile(self):
<ide> import gzip
<ide> except ImportError:
<ide> # We don't have the gzip capabilities to test.
<del> raise SkipTest
<add> pytest.skip()
<ide> # Test datasource's internal file_opener for Gzip files.
<ide> filepath = os.path.join(self.tmpdir, 'foobar.txt.gz')
<ide> fp = gzip.open(filepath, 'w')
<ide> def test_ValidBz2File(self):
<ide> import bz2
<ide> except ImportError:
<ide> # We don't have the bz2 capabilities to test.
<del> raise SkipTest
<add> pytest.skip()
<ide> # Test datasource's internal file_opener for BZip2 files.
<ide> filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2')
<ide> fp = bz2.BZ2File(filepath, 'w')
<ide> def test_Bz2File_text_mode_warning(self):
<ide> import bz2
<ide> except ImportError:
<ide> # We don't have the bz2 capabilities to test.
<del> raise SkipTest
<add> pytest.skip()
<ide> # Test datasource's internal file_opener for BZip2 files.
<ide> filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2')
<ide> fp = bz2.BZ2File(filepath, 'w')
<ide><path>numpy/lib/tests/test_format.py
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> assert_, assert_array_equal, assert_raises, assert_raises_regex,
<del> raises, SkipTest
<add> raises
<ide> )
<ide> from numpy.lib import format
<ide>
<ide> def test_bad_header():
<ide>
<ide> def test_large_file_support():
<ide> if (sys.platform == 'win32' or sys.platform == 'cygwin'):
<del> raise SkipTest("Unknown if Windows has sparse filesystems")
<add> pytest.skip("Unknown if Windows has sparse filesystems")
<ide> # try creating a large sparse file
<ide> tf_name = os.path.join(tempdir, 'sparse_file')
<ide> try:
<ide> def test_large_file_support():
<ide> import subprocess as sp
<ide> sp.check_call(["truncate", "-s", "5368709120", tf_name])
<ide> except Exception:
<del> raise SkipTest("Could not create 5GB large file")
<add> pytest.skip("Could not create 5GB large file")
<ide> # write a small array to the end
<ide> with open(tf_name, "wb") as f:
<ide> f.seek(5368709120)
<ide> def test_large_archive():
<ide> try:
<ide> a = np.empty((2**30, 2), dtype=np.uint8)
<ide> except MemoryError:
<del> raise SkipTest("Could not create large file")
<add> pytest.skip("Could not create large file")
<ide>
<ide> fname = os.path.join(tempdir, "large_archive")
<ide>
<ide><path>numpy/lib/tests/test_io.py
<ide> from numpy.compat import asbytes, bytes, unicode, Path
<ide> from numpy.ma.testutils import assert_equal
<ide> from numpy.testing import (
<del> assert_warns, assert_, SkipTest, assert_raises_regex, assert_raises,
<add> assert_warns, assert_, assert_raises_regex, assert_raises,
<ide> assert_allclose, assert_array_equal, temppath, tempdir, IS_PYPY,
<ide> HAS_REFCOUNT, suppress_warnings, assert_no_gc_cycles,
<ide> )
<ide> def test_utf8_file_nodtype_unicode(self):
<ide> encoding = locale.getpreferredencoding()
<ide> utf8.encode(encoding)
<ide> except (UnicodeError, ImportError):
<del> raise SkipTest('Skipping test_utf8_file_nodtype_unicode, '
<del> 'unable to encode utf8 in preferred encoding')
<add> pytest.skip('Skipping test_utf8_file_nodtype_unicode, '
<add> 'unable to encode utf8 in preferred encoding')
<ide>
<ide> with temppath() as path:
<ide> with io.open(path, "wt") as f:
<ide><path>numpy/linalg/tests/test_linalg.py
<ide> from numpy.linalg.linalg import _multi_dot_matrix_chain_order
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_raises, assert_array_equal,
<del> assert_almost_equal, assert_allclose, SkipTest, suppress_warnings
<add> assert_almost_equal, assert_allclose, suppress_warnings
<ide> )
<ide>
<ide>
<ide> def test_xerbla_override():
<ide> pid = os.fork()
<ide> except (OSError, AttributeError):
<ide> # fork failed, or not running on POSIX
<del> raise SkipTest("Not POSIX or fork failed.")
<add> pytest.skip("Not POSIX or fork failed.")
<ide>
<ide> if pid == 0:
<ide> # child; close i/o file handles
<ide> def test_xerbla_override():
<ide> # parent
<ide> pid, status = os.wait()
<ide> if os.WEXITSTATUS(status) != XERBLA_OK:
<del> raise SkipTest('Numpy xerbla not linked in.')
<add> pytest.skip('Numpy xerbla not linked in.')
<ide>
<ide>
<ide> def test_sdot_bug_8577(): | 9 |
Mixed | Python | add vector training script to bin [ci skip] | 72fb324d954207623030579fcdeda4e3a2e0b8cf | <ide><path>bin/train_word_vectors.py
<add>#!/usr/bin/env python
<add>from __future__ import print_function, unicode_literals, division
<add>
<add>import logging
<add>from pathlib import Path
<add>from collections import defaultdict
<add>from gensim.models import Word2Vec
<add>from preshed.counter import PreshCounter
<add>import plac
<add>import spacy
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>
<add>class Corpus(object):
<add> def __init__(self, directory, min_freq=10):
<add> self.directory = directory
<add> self.counts = PreshCounter()
<add> self.strings = {}
<add> self.min_freq = min_freq
<add>
<add> def count_doc(self, doc):
<add> # Get counts for this document
<add> for word in doc:
<add> self.counts.inc(word.orth, 1)
<add> return len(doc)
<add>
<add> def __iter__(self):
<add> for text_loc in iter_dir(self.directory):
<add> with text_loc.open("r", encoding="utf-8") as file_:
<add> text = file_.read()
<add> yield text
<add>
<add>
<add>def iter_dir(loc):
<add> dir_path = Path(loc)
<add> for fn_path in dir_path.iterdir():
<add> if fn_path.is_dir():
<add> for sub_path in fn_path.iterdir():
<add> yield sub_path
<add> else:
<add> yield fn_path
<add>
<add>
<add>@plac.annotations(
<add> lang=("ISO language code"),
<add> in_dir=("Location of input directory"),
<add> out_loc=("Location of output file"),
<add> n_workers=("Number of workers", "option", "n", int),
<add> size=("Dimension of the word vectors", "option", "d", int),
<add> window=("Context window size", "option", "w", int),
<add> min_count=("Min count", "option", "m", int),
<add> negative=("Number of negative samples", "option", "g", int),
<add> nr_iter=("Number of iterations", "option", "i", int),
<add>)
<add>def main(
<add> lang,
<add> in_dir,
<add> out_loc,
<add> negative=5,
<add> n_workers=4,
<add> window=5,
<add> size=128,
<add> min_count=10,
<add> nr_iter=2,
<add>):
<add> logging.basicConfig(
<add> format="%(asctime)s : %(levelname)s : %(message)s", level=logging.INFO
<add> )
<add> model = Word2Vec(
<add> size=size,
<add> window=window,
<add> min_count=min_count,
<add> workers=n_workers,
<add> sample=1e-5,
<add> negative=negative,
<add> )
<add> nlp = spacy.blank(lang)
<add> corpus = Corpus(in_dir)
<add> total_words = 0
<add> total_sents = 0
<add> for text_no, text_loc in enumerate(iter_dir(corpus.directory)):
<add> with text_loc.open("r", encoding="utf-8") as file_:
<add> text = file_.read()
<add> total_sents += text.count("\n")
<add> doc = nlp(text)
<add> total_words += corpus.count_doc(doc)
<add> logger.info(
<add> "PROGRESS: at batch #%i, processed %i words, keeping %i word types",
<add> text_no,
<add> total_words,
<add> len(corpus.strings),
<add> )
<add> model.corpus_count = total_sents
<add> model.raw_vocab = defaultdict(int)
<add> for orth, freq in corpus.counts:
<add> if freq >= min_count:
<add> model.raw_vocab[nlp.vocab.strings[orth]] = freq
<add> model.scale_vocab()
<add> model.finalize_vocab()
<add> model.iter = nr_iter
<add> model.train(corpus)
<add> model.save(out_loc)
<add>
<add>
<add>if __name__ == "__main__":
<add> plac.call(main)
<ide><path>website/docs/usage/adding-languages.md
<ide> of using deep learning for NLP with limited labeled data. The vectors are also
<ide> useful by themselves – they power the `.similarity` methods in spaCy. For best
<ide> results, you should pre-process the text with spaCy before training the Word2vec
<ide> model. This ensures your tokenization will match. You can use our
<del>[word vectors training script](https://github.com/explosion/spacy-dev-resources/tree/master/training/word_vectors.py),
<add>[word vectors training script](https://github.com/explosion/spacy/tree/master/bin/train_word_vectors.py),
<ide> which pre-processes the text with your language-specific tokenizer and trains
<ide> the model using [Gensim](https://radimrehurek.com/gensim/). The `vectors.bin`
<ide> file should consist of one word and vector per line.
<ide>
<ide> ```python
<del>https://github.com/explosion/spacy-dev-resources/tree/master/training/word_vectors.py
<add>https://github.com/explosion/spacy/tree/master/bin/train_word_vectors.py
<ide> ```
<ide>
<ide> If you don't have a large sample of text available, you can also convert word | 2 |
Javascript | Javascript | move module.id into chunkgraph | bad9d8a271ccd7abe774a48720893e6633b0232b | <ide><path>lib/AmdMainTemplatePlugin.js
<ide> class AmdMainTemplatePlugin {
<ide> );
<ide> const externalsArguments = externals
<ide> .map(
<del> m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__`
<add> m =>
<add> `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
<add> `${chunkGraph.getModuleId(m)}`
<add> )}__`
<ide> )
<ide> .join(", ");
<ide>
<ide><path>lib/ChunkGraph.js
<ide> class ChunkGraphModule {
<ide> this.hash = undefined;
<ide> /** @type {string} */
<ide> this.renderedHash = undefined;
<add> /** @type {string | number} */
<add> this.id = null;
<ide> }
<ide> }
<ide>
<ide> class ChunkGraph {
<ide> array = [];
<ide> chunkModuleIdMap[asyncChunk.id] = array;
<ide> }
<del> array.push(module.id);
<del> chunkModuleHashMap[module.id] = this.getRenderedModuleHash(module);
<add> const moduleId = this.getModuleId(module);
<add> array.push(moduleId);
<add> chunkModuleHashMap[moduleId] = this.getRenderedModuleHash(module);
<ide> }
<ide> }
<ide> if (array !== undefined) {
<ide> class ChunkGraph {
<ide> chunkGroup._blocks.clear();
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {string | number} the id of the module
<add> */
<add> getModuleId(module) {
<add> const cgm = this._getChunkGraphModule(module);
<add> return cgm.id;
<add> }
<add>
<add> /**
<add> * @param {Module} module the module
<add> * @param {string | number} id the id of the module
<add> * @returns {void}
<add> */
<add> setModuleId(module, id) {
<add> const cgm = this._getChunkGraphModule(module);
<add> cgm.id = id;
<add> }
<add>
<ide> /**
<ide> * @param {Module} module the module
<ide> * @returns {string} hash
<ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> }
<ide>
<ide> if (!rebuild) {
<del> cacheModule.disconnect();
<ide> this._modules.set(identifier, cacheModule);
<ide> this.modules.push(cacheModule);
<ide> for (const err of cacheModule.errors) {
<ide> class Compilation {
<ide> this.namedChunkGroups.clear();
<ide> this.additionalChunkAssets.length = 0;
<ide> this.assets = {};
<del> for (const module of this.modules) {
<del> module.unseal();
<del> }
<ide> this.moduleGraph.removeAllModuleAttributes();
<ide> }
<ide>
<ide> class Compilation {
<ide> const modules1 = this.modules;
<ide> for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) {
<ide> const module1 = modules1[indexModule1];
<del> if (module1.id !== null) {
<del> usedIds.add(module1.id);
<add> const moduleId = chunkGraph.getModuleId(module1);
<add> if (moduleId !== null) {
<add> usedIds.add(moduleId);
<ide> }
<ide> }
<ide>
<ide> class Compilation {
<ide> const module2 = modules2[indexModule2];
<ide> // Module that are not in any chunk don't need ids
<ide> if (chunkGraph.getNumberOfModuleChunks(module2) === 0) continue;
<del> if (module2.id === null) {
<add> if (chunkGraph.getModuleId(module2) === null) {
<ide> if (unusedIds.length > 0) {
<del> module2.id = unusedIds.pop();
<add> chunkGraph.setModuleId(module2, unusedIds.pop());
<ide> } else {
<del> module2.id = nextFreeModuleId++;
<add> chunkGraph.setModuleId(module2, nextFreeModuleId++);
<ide> }
<ide> }
<ide> }
<ide> class Compilation {
<ide>
<ide> const modules = this.modules;
<ide> for (let indexModule = 0; indexModule < modules.length; indexModule++) {
<del> const moduleId = modules[indexModule].id;
<add> const moduleId = chunkGraph.getModuleId(modules[indexModule]);
<ide> if (moduleId === null) continue;
<ide> if (usedIds.has(moduleId)) {
<ide> throw new Error(`checkConstraints: duplicate module id ${moduleId}`);
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> return a.userRequest < b.userRequest ? -1 : 1;
<ide> })
<ide> .reduce((map, dep) => {
<del> map[dep.userRequest] = moduleGraph.getModule(dep).id;
<add> const module = moduleGraph.getModule(dep);
<add> map[dep.userRequest] = chunkGraph.getModuleId(module);
<ide> return map;
<ide> }, Object.create(null));
<ide> }
<ide> class ContextModule extends Module {
<ide> .sort((a, b) => comparator(a.module, b.module))
<ide> .reduce((map, { dependency: dep, module }) => {
<ide> const exportsType = module.buildMeta && module.buildMeta.exportsType;
<del> const id = module.id;
<add> const id = chunkGraph.getModuleId(module);
<ide> if (!exportsType) {
<ide> map[id] = this.options.namespaceObject === "strict" ? 1 : 7;
<ide> hasNonHarmony = true;
<ide> module.exports = webpackAsyncContext;`;
<ide> if (chunks.length !== 1) {
<ide> hasMultipleOrNoChunks = true;
<ide> }
<del> const arrayStart = [moduleGraph.getModule(item.dependency).id];
<add> const module = moduleGraph.getModule(item.dependency);
<add> const moduleId = chunkGraph.getModuleId(module);
<add> const arrayStart = [moduleId];
<ide> if (typeof fakeMap === "object") {
<del> arrayStart.push(fakeMap[moduleGraph.getModule(item.dependency).id]);
<add> arrayStart.push(fakeMap[moduleId]);
<ide> }
<ide> map[item.userRequest] = arrayStart.concat(
<ide> chunks.map(chunk => chunk.id)
<ide> webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
<ide> * @returns {string} the source code
<ide> */
<ide> getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
<del> const id = this.id;
<add> const id = chunkGraph.getModuleId(this);
<ide> if (asyncMode === "lazy") {
<ide> if (this.blocks && this.blocks.length > 0) {
<ide> return this.getLazySource(this.blocks, id, chunkGraph);
<ide><path>lib/DependenciesBlock.js
<ide> class DependenciesBlock {
<ide> for (const block of this.blocks) block.updateHash(hash, chunkGraph);
<ide> }
<ide>
<del> disconnect() {
<del> for (const block of this.blocks) block.disconnect();
<del> }
<del>
<del> unseal() {
<del> for (const block of this.blocks) block.unseal();
<del> }
<del>
<ide> /**
<ide> * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance
<ide> * @returns {boolean} returns boolean for filter
<ide><path>lib/Dependency.js
<ide> class Dependency {
<ide> updateHash(hash, chunkGraph) {
<ide> const module = chunkGraph.moduleGraph.getModule(this);
<ide> if (module) {
<del> hash.update(module.id + "");
<add> hash.update(chunkGraph.getModuleId(module) + "");
<ide> }
<ide> }
<ide>
<ide><path>lib/EvalSourceMapDevToolModuleTemplatePlugin.js
<ide> class EvalSourceMapDevToolModuleTemplatePlugin {
<ide> );
<ide> sourceMap.sources = moduleFilenames;
<ide> sourceMap.sourceRoot = options.sourceRoot || "";
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> sourceMap.file = `${moduleId}.js`;
<ide>
<ide> const footer =
<ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> case "umd":
<ide> case "umd2":
<ide> return getSourceForAmdOrUmdExternal(
<del> this.id,
<add> chunkGraph.getModuleId(this),
<ide> this.isOptional(moduleGraph),
<ide> request,
<ide> runtimeTemplate
<ide><path>lib/HashedModuleIdsPlugin.js
<ide> class HashedModuleIdsPlugin {
<ide> compilation.hooks.beforeModuleIds.tap(
<ide> "HashedModuleIdsPlugin",
<ide> modules => {
<add> const chunkGraph = compilation.chunkGraph;
<ide> for (const module of modules) {
<del> if (module.id === null) {
<add> if (chunkGraph.getModuleId(module) === null) {
<ide> const id = module.libIdent({
<ide> context: this.options.context || compiler.options.context
<ide> });
<ide> class HashedModuleIdsPlugin {
<ide> let len = options.hashDigestLength;
<ide> while (usedIds.has(hashId.substr(0, len))) len++;
<ide> const moduleId = hashId.substr(0, len);
<del> module.id = moduleId;
<add> chunkGraph.setModuleId(module, moduleId);
<ide> usedIds.add(moduleId);
<ide> }
<ide> }
<ide><path>lib/HotModuleReplacementPlugin.js
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> chunk,
<ide> compareModulesById(chunkGraph)
<ide> ),
<del> m => m.id
<add> m => chunkGraph.getModuleId(m)
<ide> );
<ide> }
<ide> }
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> for (const module of chunkGraph.getChunkModulesIterable(
<ide> currentChunk
<ide> )) {
<del> allModules.add(module.id);
<add> allModules.add(chunkGraph.getModuleId(module));
<ide> }
<ide> const removedModules = records.chunkModuleIds[chunkId].filter(
<ide> id => !allModules.has(id)
<ide><path>lib/LibManifestPlugin.js
<ide> class LibManifestPlugin {
<ide> return {
<ide> ident,
<ide> data: {
<del> id: module.id,
<add> id: chunkGraph.getModuleId(module),
<ide> buildMeta: module.buildMeta
<ide> }
<ide> };
<ide><path>lib/MainTemplate.js
<ide> module.exports = class MainTemplate {
<ide> chunk
<ide> )) {
<ide> const mayReturn = --i === 0 ? "return " : "";
<add> const moduleId = chunkGraph.getModuleId(entryModule);
<ide> buf.push(
<ide> `${mayReturn}${this.renderRequireFunctionForModule(
<ide> hash,
<ide> chunk,
<del> JSON.stringify(entryModule.id)
<del> )}(${this.requireFn}.s = ${JSON.stringify(entryModule.id)});`
<add> JSON.stringify(moduleId)
<add> )}(${this.requireFn}.s = ${JSON.stringify(moduleId)});`
<ide> );
<ide> }
<ide> }
<ide><path>lib/Module.js
<ide> class Module extends DependenciesBlock {
<ide> /** @type {object} */
<ide> this.buildInfo = undefined;
<ide>
<del> // Info from Compilation (per Compilation)
<del> /** @type {number|string} */
<del> this.id = null;
<del>
<ide> /** @type {boolean} */
<ide> this.useSourceMap = false;
<ide> }
<ide>
<ide> // TODO remove in webpack 6
<ide> // BACKWARD-COMPAT START
<add> get id() {
<add> return ChunkGraph.getChunkGraphForModule(this, "Module.id").getModuleId(
<add> this
<add> );
<add> }
<add>
<add> set id(value) {
<add> ChunkGraph.getChunkGraphForModule(this, "Module.id").setModuleId(
<add> this,
<add> value
<add> );
<add> }
<add>
<ide> /**
<ide> * @returns {string} the hash of the module
<ide> */
<ide> class Module extends DependenciesBlock {
<ide> return (this.buildInfo && this.buildInfo.moduleArgument) || "module";
<ide> }
<ide>
<del> /**
<del> * disconnect the module from the graph
<del> * @returns {void}
<del> */
<del> disconnect() {
<del> this.id = null;
<del>
<del> super.disconnect();
<del> }
<del>
<del> /**
<del> * @returns {void}
<del> */
<del> unseal() {
<del> this.id = null;
<del> super.unseal();
<del> }
<del>
<ide> /**
<ide> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @returns {boolean} true, if the module is optional
<ide> class Module extends DependenciesBlock {
<ide> * @returns {void}
<ide> */
<ide> updateHash(hash, chunkGraph) {
<del> hash.update(`${this.id}`);
<add> hash.update(`${chunkGraph.getModuleId(this)}`);
<ide> const usedExports = chunkGraph.moduleGraph.getUsedExports(this);
<ide> if (typeof usedExports === "boolean") {
<ide> hash.update(JSON.stringify(usedExports));
<ide> class Module extends DependenciesBlock {
<ide> this.blocks.length = 0;
<ide> this.buildMeta = undefined;
<ide> this.buildInfo = undefined;
<del> this.disconnect();
<ide> }
<ide>
<ide> /**
<ide><path>lib/ModuleFilenameHelpers.js
<ide> ModuleFilenameHelpers.createFilename = (
<ide> } else {
<ide> shortIdentifier = module.readableIdentifier(requestShortener);
<ide> identifier = requestShortener.shorten(module.identifier());
<del> moduleId = module.id;
<add> moduleId = chunkGraph.getModuleId(module);
<ide> absoluteResourcePath = module
<ide> .identifier()
<ide> .split("!")
<ide><path>lib/NamedModulesPlugin.js
<ide> class NamedModulesPlugin {
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => {
<ide> compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => {
<add> const chunkGraph = compilation.chunkGraph;
<ide> const namedModules = new Map();
<ide> const context = this.options.context || compiler.options.context;
<ide>
<ide> for (const module of modules) {
<del> let moduleId = module.id;
<add> let moduleId = chunkGraph.getModuleId(module);
<ide> if (moduleId === null) {
<ide> const id = module.libIdent({ context });
<ide> if (id) {
<ide> moduleId = id;
<del> module.id = id;
<add> chunkGraph.setModuleId(module, id);
<ide> }
<ide> }
<ide>
<ide> class NamedModulesPlugin {
<ide> if (namedModule.length > 1) {
<ide> for (const module of namedModule) {
<ide> const requestShortener = new RequestShortener(context);
<del> module.id = `${module.id}?${getHash(
<del> requestShortener.shorten(module.identifier())
<del> )}`;
<add> chunkGraph.setModuleId(
<add> module,
<add> `${chunkGraph.getModuleId(module)}?${getHash(
<add> requestShortener.shorten(module.identifier())
<add> )}`
<add> );
<ide> }
<ide> }
<ide> }
<ide><path>lib/RecordIdsPlugin.js
<ide> class RecordIdsPlugin {
<ide> * @returns {void}
<ide> */
<ide> (modules, records) => {
<add> const chunkGraph = compilation.chunkGraph;
<ide> if (!records.modules) records.modules = {};
<ide> if (!records.modules.byIdentifier) records.modules.byIdentifier = {};
<ide> if (!records.modules.usedIds) records.modules.usedIds = {};
<ide> for (const module of modules) {
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> if (typeof moduleId !== "number") continue;
<ide> const identifier = portableIds
<ide> ? identifierUtils.makePathsRelative(
<ide> class RecordIdsPlugin {
<ide> (modules, records) => {
<ide> if (!records.modules) return;
<ide> if (records.modules.byIdentifier) {
<add> const chunkGraph = compilation.chunkGraph;
<ide> /** @type {Set<number>} */
<ide> const usedIds = new Set();
<ide> for (const module of modules) {
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> if (moduleId !== null) continue;
<ide> const identifier = portableIds
<ide> ? identifierUtils.makePathsRelative(
<ide> class RecordIdsPlugin {
<ide> if (id === undefined) continue;
<ide> if (usedIds.has(id)) continue;
<ide> usedIds.add(id);
<del> module.id = id;
<add> chunkGraph.setModuleId(module, id);
<ide> }
<ide> }
<ide> if (Array.isArray(records.modules.usedIds)) {
<ide><path>lib/RuntimeTemplate.js
<ide> module.exports = class RuntimeTemplate {
<ide> * @returns {string} the code
<ide> */
<ide> weakError({ module, chunkGraph, request, idExpr, type }) {
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> const errorMessage =
<ide> moduleId === null
<ide> ? JSON.stringify("Module is not available (weak dependency)")
<ide> module.exports = class RuntimeTemplate {
<ide> request
<ide> });
<ide> }
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> if (moduleId === null) {
<ide> if (weak) {
<ide> return "null /* weak dependency, without id */";
<ide> module.exports = class RuntimeTemplate {
<ide> request
<ide> });
<ide> }
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> if (moduleId === null) {
<ide> if (weak) {
<ide> // only weak referenced modules don't get an id
<ide> module.exports = class RuntimeTemplate {
<ide> request
<ide> });
<ide> }
<del> if (module.id === null) {
<add> if (chunkGraph.getModuleId(module) === null) {
<ide> if (weak) {
<ide> // only weak referenced modules don't get an id
<ide> // we can always emit an error emitting code here
<ide> module.exports = class RuntimeTemplate {
<ide> request
<ide> });
<ide> }
<del> const moduleId = module.id;
<add> const moduleId = chunkGraph.getModuleId(module);
<ide> if (moduleId === null) {
<ide> if (weak) {
<ide> // only weak referenced modules don't get an id
<ide> module.exports = class RuntimeTemplate {
<ide> });
<ide>
<ide> let getModuleFunction;
<del> let idExpr = JSON.stringify(module.id);
<add> let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
<ide> const comment = this.comment({
<ide> request
<ide> });
<ide> module.exports = class RuntimeTemplate {
<ide> request
<ide> });
<ide> }
<del> if (module.id === null) {
<add> if (chunkGraph.getModuleId(module) === null) {
<ide> if (weak) {
<ide> // only weak referenced modules don't get an id
<ide> // we can always emit an error emitting code here
<ide><path>lib/Stats.js
<ide> class Stats {
<ide> }
<ide> path.reverse();
<ide> const obj = {
<del> id: module.id,
<add> id: chunkGraph.getModuleId(module),
<ide> identifier: module.identifier(),
<ide> name: module.readableIdentifier(requestShortener),
<ide> index: moduleGraph.getPreOrderIndex(module),
<ide> class Stats {
<ide> chunk => chunk.id
<ide> ),
<ide> issuer: issuer && issuer.identifier(),
<del> issuerId: issuer && issuer.id,
<add> issuerId: issuer && chunkGraph.getModuleId(issuer),
<ide> issuerName: issuer && issuer.readableIdentifier(requestShortener),
<ide> issuerPath:
<ide> issuer &&
<ide> path.map(module => ({
<del> id: module.id,
<add> id: chunkGraph.getModuleId(module),
<ide> identifier: module.identifier(),
<ide> name: module.readableIdentifier(requestShortener),
<ide> profile: fnProfile(moduleGraph.getProfile(module))
<ide> class Stats {
<ide> .map(reason => {
<ide> const depAsAny = /** @type {TODO} */ (reason.dependency);
<ide> const obj = {
<del> moduleId: reason.originModule ? reason.originModule.id : null,
<add> moduleId: reason.originModule
<add> ? chunkGraph.getModuleId(reason.originModule)
<add> : null,
<ide> moduleIdentifier: reason.originModule
<ide> ? reason.originModule.identifier()
<ide> : null,
<ide> class Stats {
<ide> obj.origins = Array.from(chunk.groupsIterable, g => g.origins)
<ide> .reduce((a, b) => a.concat(b), [])
<ide> .map(origin => ({
<del> moduleId: origin.module ? origin.module.id : undefined,
<add> moduleId: origin.module
<add> ? chunkGraph.getModuleId(origin.module)
<add> : undefined,
<ide> module: origin.module ? origin.module.identifier() : "",
<ide> moduleIdentifier: origin.module ? origin.module.identifier() : "",
<ide> moduleName: origin.module
<ide><path>lib/Template.js
<ide> class Template {
<ide> /** @type {{id: string|number, source: Source|string}[]} */
<ide> const allModules = modules.map(module => {
<ide> return {
<del> id: module.id,
<add> id: chunkGraph.getModuleId(module),
<ide> source: moduleTemplate.render(module, renderContext)
<ide> };
<ide> });
<ide><path>lib/TemplatedPathPlugin.js
<ide> const replacePathVariables = (path, data) => {
<ide> ? chunk.contentHashWithLength[contentHashType]
<ide> : undefined);
<ide> const module = data.module;
<del> const moduleId = module && module.id;
<add> const moduleId =
<add> module &&
<add> (module instanceof Module ? chunkGraph.getModuleId(module) : module.id);
<ide> const moduleHash =
<ide> module &&
<ide> (module instanceof Module
<ide><path>lib/UmdMainTemplatePlugin.js
<ide> class UmdMainTemplatePlugin {
<ide> return modules
<ide> .map(
<ide> m =>
<del> `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__`
<add> `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
<add> `${chunkGraph.getModuleId(m)}`
<add> )}__`
<ide> )
<ide> .join(", ");
<ide> };
<ide><path>lib/dependencies/ModuleDecoratorDependency.js
<ide> ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate ext
<ide> })}(${originModule.moduleArgument});\n`,
<ide> InitFragment.STAGE_PROVIDES,
<ide> 0,
<del> `module decorator ${originModule.id}`
<add> `module decorator ${chunkGraph.getModuleId(originModule)}`
<ide> )
<ide> ];
<ide> }
<ide><path>lib/optimize/ChunkModuleIdRangePlugin.js
<ide> class ChunkModuleIdRangePlugin {
<ide> let currentId = options.start || 0;
<ide> for (let i = 0; i < chunkModules.length; i++) {
<ide> const m = chunkModules[i];
<del> if (m.id === null) {
<del> m.id = currentId++;
<add> if (chunkGraph.getModuleId(m) === null) {
<add> chunkGraph.setModuleId(m, currentId++);
<ide> }
<ide> if (options.end && currentId > options.end) break;
<ide> }
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> );
<ide> result.add(
<ide> `var ${info.name} = __webpack_require__(${JSON.stringify(
<del> info.module.id
<add> chunkGraph.getModuleId(info.module)
<ide> )});\n`
<ide> );
<ide> if (info.interopNamespaceObjectUsed) {
<ide> class ConcatenatedModule extends Module {
<ide> info.module.updateHash(hash, chunkGraph);
<ide> break;
<ide> case "external":
<del> hash.update(`${info.module.id}`);
<add> hash.update(`${chunkGraph.getModuleId(info.module)}`);
<ide> break;
<ide> }
<ide> }
<ide><path>lib/util/comparators.js
<ide> exports.compareModulesByIdentifier = (a, b) => {
<ide> * @returns {-1|0|1} compare result
<ide> */
<ide> const compareModulesById = (chunkGraph, a, b) => {
<del> return compareIds(a.id, b.id);
<add> return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b));
<ide> };
<ide> /** @type {ParamizedComparator<ChunkGraph, Module>} */
<ide> exports.compareModulesById = createCachedParamizedComparator(
<ide> exports.compareModulesByIndexOrIdentifier = createCachedParamizedComparator(
<ide> * @returns {-1|0|1} compare result
<ide> */
<ide> const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => {
<del> const cmp1 = compareIds(a.id, b.id);
<add> const cmp1 = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b));
<ide> if (cmp1 !== 0) return cmp1;
<ide> const cmp2 = compareIds(a.identifier(), b.identifier());
<ide> return cmp2;
<ide><path>lib/wasm/WasmMainTemplatePlugin.js
<ide> const generateImportObject = (chunkGraph, module, mangle) => {
<ide>
<ide> if (direct) {
<ide> const instanceVar = `m${waitForInstances.size}`;
<del> waitForInstances.set(instanceVar, importedModule.id);
<add> waitForInstances.set(instanceVar, chunkGraph.getModuleId(importedModule));
<ide> properties.push({
<ide> module,
<ide> name,
<ide> const generateImportObject = (chunkGraph, module, mangle) => {
<ide> (param, k) => "p" + k + param.valtype
<ide> );
<ide>
<del> const mod = `installedModules[${JSON.stringify(importedModule.id)}]`;
<add> const mod = `installedModules[${JSON.stringify(
<add> chunkGraph.getModuleId(importedModule)
<add> )}]`;
<ide> const func = `${mod}.exports[${JSON.stringify(usedName)}]`;
<ide>
<ide> properties.push({
<ide> const generateImportObject = (chunkGraph, module, mangle) => {
<ide> ];
<ide> }
<ide>
<add> const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module));
<ide> if (waitForInstances.size === 1) {
<ide> const moduleId = Array.from(waitForInstances.values())[0];
<ide> const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`;
<ide> const variable = Array.from(waitForInstances.keys())[0];
<ide> return Template.asString([
<del> `${JSON.stringify(module.id)}: function() {`,
<add> `${moduleIdStringified}: function() {`,
<ide> Template.indent([
<ide> `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`,
<ide> Template.indent(importObject),
<ide> const generateImportObject = (chunkGraph, module, mangle) => {
<ide> (name, i) => `${name} = array[${i}]`
<ide> ).join(", ");
<ide> return Template.asString([
<del> `${JSON.stringify(module.id)}: function() {`,
<add> `${moduleIdStringified}: function() {`,
<ide> Template.indent([
<ide> `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`,
<ide> Template.indent([`var ${variables};`, ...importObject]),
<ide> const generateImportObject = (chunkGraph, module, mangle) => {
<ide> ]);
<ide> } else {
<ide> return Template.asString([
<del> `${JSON.stringify(module.id)}: function() {`,
<add> `${moduleIdStringified}: function() {`,
<ide> Template.indent(importObject),
<ide> "},"
<ide> ]);
<ide><path>lib/wasm/WebAssemblyModulesPlugin.js
<ide> class WebAssemblyModulesPlugin {
<ide> chunkGraph,
<ide> module
<ide> },
<del> identifier: `webassemblyModule${module.id}`,
<add> identifier: `webassemblyModule${chunkGraph.getModuleId(
<add> module
<add> )}`,
<ide> hash: chunkGraph.getModuleHash(module)
<ide> });
<ide> }
<ide><path>lib/web/JsonpHelpers.js
<ide> exports.getEntryInfo = (chunkGraph, chunk) => {
<ide> return Array.from(
<ide> chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)
<ide> ).map(([module, chunkGroup]) =>
<del> [module.id].concat(
<add> [chunkGraph.getModuleId(module)].concat(
<ide> chunkGroup.chunks.filter(c => c !== chunk).map(c => c.id)
<ide> )
<ide> ); | 28 |
PHP | PHP | add check for all exceptions | 982c730ec935295712bf22a83eec9b940fbbe649 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> public function render($request, Throwable $e)
<ide> return $this->convertValidationExceptionToResponse($e, $request);
<ide> }
<ide>
<del> return $request->expectsJson()
<add> return $this->shouldReturnJson($request, $e)
<ide> ? $this->prepareJsonResponse($request, $e)
<ide> : $this->prepareResponse($request, $e);
<ide> }
<ide> protected function unauthenticated($request, AuthenticationException $exception)
<ide> * Determine if the response should be json.
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<add> * @param \Throwable $e
<ide> * @return bool
<ide> */
<del> protected function shouldReturnJson($request)
<add> protected function shouldReturnJson($request, Throwable $e)
<ide> {
<ide> return $request->expectsJson();
<ide> }
<ide> protected function convertValidationExceptionToResponse(ValidationException $e,
<ide> return $e->response;
<ide> }
<ide>
<del> return $request->expectsJson()
<add> return $this->shouldReturnJson($request, $e)
<ide> ? $this->invalidJson($request, $e)
<ide> : $this->invalid($request, $e);
<ide> } | 1 |
Python | Python | remove adjust_logits_during_generation method | c130e67dce56a092604949a8df6384a17f762189 | <ide><path>src/transformers/configuration_utils.py
<ide> class PretrainedConfig(object):
<ide> logits when used for generation
<ide> - **return_dict_in_generate** (:obj:`bool`, `optional`, defaults to :obj:`False`) -- Whether the model should
<ide> return a :class:`~transformers.file_utils.ModelOutput` instead of a :obj:`torch.LongTensor`
<add> - **forced_bos_token_id** (:obj:`int`, `optional`) -- The id of the token to force as the first generated token
<add> after the :obj:`decoder_start_token_id`. Useful for multilingual models like :doc:`mBART
<add> <../model_doc/mbart>` where the first generated token needs to be the target language token.
<add> - **forced_eos_token_id** (:obj:`int`, `optional`) -- The id of the token to force as the last generated token
<add> when :obj:`max_length` is reached.
<ide>
<ide>
<ide> Parameters for fine-tuning tasks
<ide> def __init__(self, **kwargs):
<ide> self.chunk_size_feed_forward = kwargs.pop("chunk_size_feed_forward", 0)
<ide> self.output_scores = kwargs.pop("output_scores", False)
<ide> self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
<add> self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
<add> self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
<ide>
<ide> # Fine-tuning task arguments
<ide> self.architectures = kwargs.pop("architectures", None)
<ide><path>src/transformers/generation_logits_process.py
<ide> def __call__(
<ide> scores[batch_idx * group_size : (batch_idx + 1) * group_size] -= self._diversity_penalty * token_frequency
<ide>
<ide> return scores
<add>
<add>
<add>class ForcedBOSTokenLogitsProcessor(LogitsProcessor):
<add> r"""
<add> :class:`~transformers.LogitsProcessor` that enforces the specified token as the first generated token.
<add>
<add> Args:
<add> bos_token_id (:obj:`int`):
<add> The id of the token to force as the first generated token.
<add> """
<add>
<add> def __init__(self, bos_token_id: int):
<add> self.bos_token_id = bos_token_id
<add>
<add> def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
<add> cur_len = input_ids.shape[-1]
<add> if cur_len == 1:
<add> num_tokens = scores.shape[1]
<add> scores[:, [i for i in range(num_tokens) if i != self.bos_token_id]] = -float("inf")
<add> scores[:, self.bos_token_id] = 0
<add> return scores
<add>
<add>
<add>class ForcedEOSTokenLogitsProcessor(LogitsProcessor):
<add> r"""
<add> :class:`~transformers.LogitsProcessor` that enforces the specified token as the last generated token when
<add> :obj:`max_length` is reached.
<add>
<add> Args:
<add> max_length (:obj:`int`):
<add> The maximum length of the sequence to be generated.
<add> eos_token_id (:obj:`int`):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached.
<add> """
<add>
<add> def __init__(self, max_length: int, eos_token_id: int):
<add> self.max_length = max_length
<add> self.eos_token_id = eos_token_id
<add>
<add> def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
<add> cur_len = input_ids.shape[-1]
<add> if cur_len == self.max_length - 1:
<add> num_tokens = scores.shape[1]
<add> scores[:, [i for i in range(num_tokens) if i != self.eos_token_id]] = -float("inf")
<add> scores[:, self.eos_token_id] = 0
<add> return scores
<ide><path>src/transformers/generation_tf_utils.py
<ide> def generate(
<ide> attention_mask=None,
<ide> decoder_start_token_id=None,
<ide> use_cache=None,
<add> forced_bos_token_id=None,
<add> forced_eos_token_id=None,
<ide> ):
<ide> r"""
<ide> Generates sequences for models with a language modeling head. The method currently supports greedy decoding,
<ide> def generate(
<ide> use_cache: (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should use the past last key/values attentions (if applicable to the model) to
<ide> speed up decoding.
<add> forced_bos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the first generated token after the :obj:`decoder_start_token_id`.
<add> Useful for multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token
<add> needs to be the target language token.
<add> forced_eos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached.
<ide> model_specific_kwargs:
<ide> Additional model specific kwargs will be forwarded to the :obj:`forward` function of the model.
<ide>
<ide> def generate(
<ide> decoder_start_token_id = (
<ide> decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id
<ide> )
<add> forced_bos_token_id = (
<add> forced_bos_token_id if forced_bos_token_id is not None else self.config.forced_bos_token_id
<add> )
<add> forced_eos_token_id = (
<add> forced_eos_token_id if forced_eos_token_id is not None else self.config.forced_eos_token_id
<add> )
<ide>
<ide> if input_ids is not None:
<ide> batch_size = shape_list(input_ids)[0] # overridden by the input batch_size
<ide> def generate(
<ide> encoder_outputs=encoder_outputs,
<ide> attention_mask=attention_mask,
<ide> use_cache=use_cache,
<add> forced_bos_token_id=forced_bos_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> )
<ide> else:
<ide> output = self._generate_no_beam_search(
<ide> def _generate_beam_search(
<ide> encoder_outputs,
<ide> attention_mask,
<ide> use_cache,
<add> forced_bos_token_id,
<add> forced_eos_token_id,
<ide> ):
<ide> """Generate sequences for each example with beam search."""
<ide>
<ide> def _generate_beam_search(
<ide>
<ide> if self.config.is_encoder_decoder and do_sample is False:
<ide> next_token_logits = self.adjust_logits_during_generation(
<del> next_token_logits, cur_len=cur_len, max_length=max_length
<add> next_token_logits,
<add> cur_len=cur_len,
<add> max_length=max_length,
<add> forced_bos_token_id=forced_bos_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> )
<ide> # calculate log softmax score
<ide> scores = tf.nn.log_softmax(next_token_logits, axis=-1) # (batch_size * num_beams, vocab_size)
<ide> def _generate_beam_search(
<ide> def _reorder_cache(past, beam_idx):
<ide> return tuple(tf.gather(layer_past, beam_idx, axis=1) for layer_past in past)
<ide>
<del> def adjust_logits_during_generation(self, logits, **kwargs):
<add> def adjust_logits_during_generation(
<add> self, logits, cur_len, max_length, forced_bos_token_id, forced_eos_token_id, **kwargs
<add> ):
<ide> """
<ide> Implement in subclasses of :class:`~transformers.PreTrainedModel` for custom behavior to adjust the logits in
<ide> the generate method.
<ide> """
<del> return logits
<add> if cur_len == 1 and forced_bos_token_id is not None:
<add> vocab_range = tf.constant(range(self.config.vocab_size))
<add> return tf.where(vocab_range != forced_bos_token_id, -1e8, logits)
<add> elif cur_len == max_length - 1 and forced_eos_token_id is not None:
<add> vocab_range = tf.constant(range(self.config.vocab_size))
<add> return tf.where(vocab_range != forced_eos_token_id, -1e8, logits)
<add> else:
<add> return logits
<ide>
<ide>
<ide> def _create_next_token_logits_penalties(input_ids, logits, repetition_penalty):
<ide><path>src/transformers/generation_utils.py
<ide> from .generation_beam_search import BeamScorer, BeamSearchScorer
<ide> from .generation_logits_process import (
<ide> EncoderNoRepeatNGramLogitsProcessor,
<add> ForcedBOSTokenLogitsProcessor,
<add> ForcedEOSTokenLogitsProcessor,
<ide> HammingDiversityLogitsProcessor,
<ide> LogitsProcessorList,
<ide> MinLengthLogitsProcessor,
<ide> def _get_logits_processor(
<ide> encoder_input_ids: torch.LongTensor,
<ide> bad_words_ids: List[List[int]],
<ide> min_length: int,
<add> max_length: int,
<ide> eos_token_id: int,
<add> forced_bos_token_id: int,
<add> forced_eos_token_id: int,
<ide> prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
<ide> num_beams: int,
<ide> num_beam_groups: int,
<ide> def _get_logits_processor(
<ide> min_length = min_length if min_length is not None else self.config.min_length
<ide> eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id
<ide> diversity_penalty = diversity_penalty if diversity_penalty is not None else self.config.diversity_penalty
<add> forced_bos_token_id = (
<add> forced_bos_token_id if forced_bos_token_id is not None else self.config.forced_bos_token_id
<add> )
<add> forced_eos_token_id = (
<add> forced_eos_token_id if forced_eos_token_id is not None else self.config.forced_eos_token_id
<add> )
<ide> # instantiate processors list
<ide> processors = LogitsProcessorList()
<ide>
<ide> def _get_logits_processor(
<ide> processors.append(MinLengthLogitsProcessor(min_length, eos_token_id))
<ide> if prefix_allowed_tokens_fn is not None:
<ide> processors.append(PrefixConstrainedLogitsProcessor(prefix_allowed_tokens_fn, num_beams))
<add> if forced_bos_token_id is not None:
<add> processors.append(ForcedBOSTokenLogitsProcessor(forced_bos_token_id))
<add> if forced_eos_token_id is not None:
<add> processors.append(ForcedEOSTokenLogitsProcessor(max_length, forced_eos_token_id))
<ide> return processors
<ide>
<ide> @torch.no_grad()
<ide> def generate(
<ide> output_hidden_states: Optional[bool] = None,
<ide> output_scores: Optional[bool] = None,
<ide> return_dict_in_generate: Optional[bool] = None,
<add> forced_bos_token_id: Optional[int] = None,
<add> forced_eos_token_id: Optional[int] = None,
<ide> **model_kwargs,
<ide> ) -> Union[GreedySearchOutput, SampleOutput, BeamSearchOutput, BeamSampleOutput, torch.LongTensor]:
<ide> r"""
<ide> def generate(
<ide> Whether or not to return the prediction scores. See ``scores`` under returned tensors for more details.
<ide> return_dict_in_generate (:obj:`bool`, `optional`, defaults to `False`):
<ide> Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
<add> forced_bos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the first generated token after the :obj:`decoder_start_token_id`.
<add> Useful for multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token
<add> needs to be the target language token.
<add> forced_eos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached.
<ide>
<ide> model_kwargs:
<ide> Additional model specific kwargs will be forwarded to the :obj:`forward` function of the model. If the
<ide> def generate(
<ide> encoder_input_ids=encoder_input_ids,
<ide> bad_words_ids=bad_words_ids,
<ide> min_length=min_length,
<add> max_length=max_length,
<ide> eos_token_id=eos_token_id,
<add> forced_bos_token_id=forced_bos_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
<ide> num_beams=num_beams,
<ide> num_beam_groups=num_beam_groups,
<ide> def beam_search(
<ide> )
<ide> next_token_logits = outputs.logits[:, -1, :]
<ide>
<del> # adjust tokens for Bart, *e.g.*
<add> # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
<add> # cannot be generated both before and after the `F.log_softmax` operation.
<ide> next_token_logits = self.adjust_logits_during_generation(
<ide> next_token_logits, cur_len=cur_len, max_length=max_length
<ide> )
<ide> def beam_sample(
<ide> )
<ide> next_token_logits = outputs.logits[:, -1, :]
<ide>
<del> # adjust token scores (a no-op by default)
<add> # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
<add> # cannot be generated both before and after the `F.log_softmax` operation.
<ide> next_token_logits = self.adjust_logits_during_generation(
<ide> next_token_logits, cur_len=cur_len, max_length=max_length
<ide> )
<ide> def group_beam_search(
<ide> # select outputs of beams of current group only
<ide> next_token_logits = outputs.logits[batch_group_indices, -1, :]
<ide>
<del> # adjust tokens for Bart, *e.g.*
<add> # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
<add> # cannot be generated both before and after the `F.log_softmax` operation.
<ide> next_token_logits = self.adjust_logits_during_generation(
<ide> next_token_logits, cur_len=cur_len, max_length=max_length
<ide> )
<ide><path>src/transformers/models/bart/configuration_bart.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> """ BART model configuration """
<add>import warnings
<ide>
<ide> from ...configuration_utils import PretrainedConfig
<ide> from ...utils import logging
<ide> class BartConfig(PretrainedConfig):
<ide> just in case (e.g., 512 or 1024 or 2048).
<ide> init_std (:obj:`float`, `optional`, defaults to 0.02):
<ide> The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
<del> force_bos_token_to_be_generated (:obj:`bool`, `optional`, defaults to :obj:`False`):
<del> Whether or not to force BOS token to be generated at step 1 (after ``decoder_start_token_id``), only
<del> :obj:`True` for `bart-large-cnn`.
<ide> encoder_layerdrop: (:obj:`float`, `optional`, defaults to 0.0):
<ide> The LayerDrop probability for the encoder. See the `LayerDrop paper <see
<ide> https://arxiv.org/abs/1909.11556>`__ for more details.
<ide> class BartConfig(PretrainedConfig):
<ide> Whether or not the model should return the last key/values attentions (not used by all models).
<ide> num_labels: (:obj:`int`, `optional`, defaults to 3):
<ide> The number of labels to use in :class:`~transformers.BartForSequenceClassification`.
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 2):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Example::
<ide>
<ide> def __init__(
<ide> classifier_dropout=0.0,
<ide> scale_embedding=False,
<ide> gradient_checkpointing=False,
<del> force_bos_token_to_be_generated=False,
<ide> use_cache=True,
<ide> num_labels=3,
<ide> pad_token_id=1,
<ide> bos_token_id=0,
<ide> eos_token_id=2,
<ide> is_encoder_decoder=True,
<ide> decoder_start_token_id=2,
<add> forced_eos_token_id=2,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> def __init__(
<ide> eos_token_id=eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> decoder_start_token_id=decoder_start_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide> def __init__(
<ide> self.num_hidden_layers = encoder_layers
<ide> self.gradient_checkpointing = gradient_checkpointing
<ide> self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
<del> self.force_bos_token_to_be_generated = force_bos_token_to_be_generated # only relevant for CNN
<add>
<add> # ensure backward compatibilty for BART CNN models
<add> if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
<add> self.forced_bos_token_id = self.bos_token_id
<add> warnings.warn(
<add> f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions."
<add> "The config can simply be saved and uploaded again to be fixed."
<add> )
<ide>
<ide> @property
<ide> def num_attention_heads(self) -> int:
<ide><path>src/transformers/models/bart/modeling_bart.py
<ide> def prepare_inputs_for_generation(
<ide> def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
<ide> return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == 1 and self.config.force_bos_token_to_be_generated:
<del> self._force_token_id_to_be_generated(logits, self.config.bos_token_id)
<del> elif cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/bart/modeling_tf_bart.py
<ide> def _reorder_cache(past, beam_idx):
<ide> + layer_past_key_values[2:],
<ide> )
<ide> return (past[0], reordered_past)
<del>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == 1 and self.config.force_bos_token_to_be_generated:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.bos_token_id, LARGE_NEGATIVE, logits)
<del> elif cur_len == max_length - 1:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> else:
<del> return logits
<ide><path>src/transformers/models/blenderbot/configuration_blenderbot.py
<ide> class BlenderbotConfig(PretrainedConfig):
<ide> Scale embeddings by diving by sqrt(d_model).
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models)
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 2):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Example::
<ide>
<ide> def __init__(
<ide> bos_token_id=1,
<ide> eos_token_id=2,
<ide> encoder_no_repeat_ngram_size=3,
<add> forced_eos_token_id=2,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> def __init__(
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> decoder_start_token_id=decoder_start_token_id,
<ide> encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py
<ide> def prepare_inputs_for_generation(
<ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
<ide> }
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/blenderbot/modeling_tf_blenderbot.py
<ide> def _reorder_cache(past, beam_idx):
<ide> + layer_past_key_values[2:],
<ide> )
<ide> return (past[0], reordered_past)
<del>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> else:
<del> return logits
<ide><path>src/transformers/models/blenderbot_small/configuration_blenderbot_small.py
<ide> class BlenderbotSmallConfig(PretrainedConfig):
<ide> Scale embeddings by diving by sqrt(d_model).
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models)
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 2):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Example::
<ide>
<ide> def __init__(
<ide> pad_token_id=0,
<ide> bos_token_id=1,
<ide> eos_token_id=2,
<add> forced_eos_token_id=2,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> def __init__(
<ide> eos_token_id=eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> decoder_start_token_id=decoder_start_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py
<ide> def prepare_inputs_for_generation(
<ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
<ide> }
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py
<ide> def _reorder_cache(past, beam_idx):
<ide> + layer_past_key_values[2:],
<ide> )
<ide> return (past[0], reordered_past)
<del>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> else:
<del> return logits
<ide><path>src/transformers/models/fsmt/configuration_fsmt.py
<ide> class FSMTConfig(PretrainedConfig):
<ide> search when at least ``num_beams`` sentences are finished per batch or not.
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models).
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 2):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Examples::
<ide>
<ide> def __init__(
<ide> pad_token_id=1,
<ide> bos_token_id=0,
<ide> eos_token_id=2,
<add> forced_eos_token_id=2,
<ide> **common_kwargs
<ide> ):
<ide> if "hidden_size" in common_kwargs:
<ide> def __init__(
<ide> decoder_start_token_id=decoder_start_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> tie_word_embeddings=tie_word_embeddings,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **common_kwargs,
<ide> )
<ide> self.langs = langs
<ide><path>src/transformers/models/fsmt/modeling_fsmt.py
<ide> def prepare_inputs_for_generation(
<ide> def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
<ide> return shift_tokens_right(labels, self.config.pad_token_id)
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_ids_generation(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> def _force_token_ids_generation(self, scores, token_ids) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0"""
<del> if isinstance(token_ids, int):
<del> token_ids = [token_ids]
<del> all_but_token_ids_mask = torch.tensor(
<del> [x for x in range(self.config.tgt_vocab_size) if x not in token_ids],
<del> dtype=torch.long,
<del> device=next(self.parameters()).device,
<del> )
<del> assert len(scores.shape) == 2, "scores should be of rank 2 with shape: [batch_size, vocab_size]"
<del> scores[:, all_but_token_ids_mask] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = []
<ide><path>src/transformers/models/marian/configuration_marian.py
<ide> class MarianConfig(PretrainedConfig):
<ide> Scale embeddings by diving by sqrt(d_model).
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models)
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 0):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Examples::
<ide>
<ide> def __init__(
<ide> gradient_checkpointing=False,
<ide> pad_token_id=58100,
<ide> eos_token_id=0,
<add> forced_eos_token_id=0,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> pad_token_id=pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> decoder_start_token_id=decoder_start_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/marian/modeling_marian.py
<ide> def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
<ide>
<ide> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<ide> logits[:, self.config.pad_token_id] = float("-inf") # never predict pad token.
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<ide> return logits
<ide>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/marian/modeling_tf_marian.py
<ide> def _reorder_cache(past, beam_idx):
<ide> )
<ide> return (past[0], reordered_past)
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<add> def adjust_logits_during_generation(
<add> self, logits, cur_len, max_length, forced_bos_token_id, forced_eos_token_id, **kwargs
<add> ):
<ide> """Never predict pad_token_id. Predict </s> when max_length is reached."""
<ide> vocab_range = tf.constant(range(self.config.vocab_size))
<ide> logits = tf.where(vocab_range == self.config.pad_token_id, LARGE_NEGATIVE, logits)
<del> if cur_len == max_length - 1:
<del> logits = tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> return logits
<add> if cur_len == 1 and forced_bos_token_id is not None:
<add> vocab_range = tf.constant(range(self.config.vocab_size))
<add> return tf.where(vocab_range != forced_bos_token_id, LARGE_NEGATIVE, logits)
<add> elif cur_len == max_length - 1 and forced_eos_token_id is not None:
<add> vocab_range = tf.constant(range(self.config.vocab_size))
<add> return tf.where(vocab_range != forced_eos_token_id, LARGE_NEGATIVE, logits)
<add> else:
<add> return logits
<ide><path>src/transformers/models/mbart/configuration_mbart.py
<ide> class MBartConfig(PretrainedConfig):
<ide> Scale embeddings by diving by sqrt(d_model).
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models)
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 2):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Example::
<ide>
<ide> def __init__(
<ide> pad_token_id=1,
<ide> bos_token_id=0,
<ide> eos_token_id=2,
<add> forced_eos_token_id=2,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> pad_token_id=pad_token_id,
<ide> bos_token_id=bos_token_id,
<ide> eos_token_id=eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/mbart/modeling_mbart.py
<ide> def prepare_inputs_for_generation(
<ide> def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
<ide> return shift_tokens_right(labels, self.config.pad_token_id)
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/mbart/modeling_tf_mbart.py
<ide> def _reorder_cache(past, beam_idx):
<ide> + layer_past_key_values[2:],
<ide> )
<ide> return (past[0], reordered_past)
<del>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> else:
<del> return logits
<ide><path>src/transformers/models/pegasus/configuration_pegasus.py
<ide> class PegasusConfig(PretrainedConfig):
<ide> Scale embeddings by diving by sqrt(d_model).
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models)
<add> forced_eos_token_id (:obj:`int`, `optional`, defaults to 1):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide>
<ide> Example::
<ide>
<ide> def __init__(
<ide> gradient_checkpointing=False,
<ide> pad_token_id=0,
<ide> eos_token_id=1,
<add> forced_eos_token_id=1,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> pad_token_id=pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> decoder_start_token_id=decoder_start_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/pegasus/modeling_pegasus.py
<ide> def prepare_inputs_for_generation(
<ide> def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
<ide> return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1 and self.config.eos_token_id is not None:
<del> self._force_token_id_to_be_generated(logits, self.config.eos_token_id)
<del> return logits
<del>
<del> @staticmethod
<del> def _force_token_id_to_be_generated(scores, token_id) -> None:
<del> """force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
<del> scores[:, [x for x in range(scores.shape[1]) if x != token_id]] = -float("inf")
<del>
<ide> @staticmethod
<ide> def _reorder_cache(past, beam_idx):
<ide> reordered_past = ()
<ide><path>src/transformers/models/pegasus/modeling_tf_pegasus.py
<ide> def _reorder_cache(past, beam_idx):
<ide> + layer_past_key_values[2:],
<ide> )
<ide> return (past[0], reordered_past)
<del>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> if cur_len == max_length - 1:
<del> vocab_range = tf.constant(range(self.config.vocab_size))
<del> return tf.where(vocab_range != self.config.eos_token_id, LARGE_NEGATIVE, logits)
<del> else:
<del> return logits
<ide><path>src/transformers/models/rag/configuration_rag.py
<ide> :obj:`context_attention_mask` are returned. See returned tensors for more detail.
<ide> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<ide> Whether or not the model should return the last key/values attentions (not used by all models).
<add> forced_eos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached. Usually set to
<add> :obj:`eos_token_id`.
<ide> """
<ide>
<ide>
<ide> def __init__(
<ide> do_marginalize=False,
<ide> output_retrieved=False,
<ide> use_cache=True,
<add> forced_eos_token_id=None,
<ide> **kwargs
<ide> ):
<ide> super().__init__(
<ide> bos_token_id=bos_token_id,
<ide> pad_token_id=pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide> decoder_start_token_id=decoder_start_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> is_encoder_decoder=is_encoder_decoder,
<ide> prefix=prefix,
<ide> vocab_size=vocab_size,
<ide> def __init__(
<ide>
<ide> self.use_cache = use_cache
<ide>
<add> if self.forced_eos_token_id is None:
<add> self.forced_eos_token_id = getattr(self.generator, "forced_eos_token_id", None)
<add>
<ide> @classmethod
<ide> def from_question_encoder_generator_configs(
<ide> cls, question_encoder_config: PretrainedConfig, generator_config: PretrainedConfig, **kwargs
<ide><path>src/transformers/models/rag/modeling_rag.py
<ide> def __init__(
<ide> def set_retriever(self, retriever: RagRetriever):
<ide> self.rag.retriever = retriever
<ide>
<del> def adjust_logits_during_generation(self, logits, cur_len, max_length):
<del> return self.rag.generator.adjust_logits_during_generation(logits, cur_len=cur_len, max_length=max_length)
<del>
<ide> def prepare_inputs_for_generation(
<ide> self,
<ide> decoder_input_ids,
<ide> def generate(
<ide> decoder_start_token_id=None,
<ide> n_docs=None,
<ide> prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]] = None,
<add> forced_bos_token_id: Optional[int] = None,
<add> forced_eos_token_id: Optional[int] = None,
<ide> **model_kwargs
<ide> ):
<ide> """
<ide> def generate(
<ide> conditioned on the previously generated tokens :obj:`inputs_ids` and the batch ID :obj:`batch_id`. This
<ide> argument is useful for constrained generation conditioned on the prefix, as described in
<ide> `Autoregressive Entity Retrieval <https://arxiv.org/abs/2010.00904>`__.
<add> forced_bos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the first generated token after the :obj:`decoder_start_token_id`.
<add> Useful for multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token
<add> needs to be the target language token.
<add> forced_eos_token_id (:obj:`int`, `optional`):
<add> The id of the token to force as the last generated token when :obj:`max_length` is reached.
<ide>
<ide> Return:
<ide> :obj:`torch.LongTensor` of shape :obj:`(batch_size * num_return_sequences, sequence_length)`: The generated
<ide> def extend_enc_output(tensor, num_beams=None):
<ide> encoder_input_ids=context_input_ids,
<ide> bad_words_ids=bad_words_ids,
<ide> min_length=min_length,
<add> max_length=max_length,
<ide> eos_token_id=eos_token_id,
<add> forced_bos_token_id=forced_bos_token_id,
<add> forced_eos_token_id=forced_eos_token_id,
<ide> prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
<ide> num_beams=num_beams,
<ide> num_beam_groups=num_beam_groups,
<ide><path>tests/test_generation_logits_process.py
<ide>
<ide> from transformers.generation_logits_process import (
<ide> EncoderNoRepeatNGramLogitsProcessor,
<add> ForcedBOSTokenLogitsProcessor,
<add> ForcedEOSTokenLogitsProcessor,
<ide> HammingDiversityLogitsProcessor,
<ide> LogitsProcessorList,
<ide> MinLengthLogitsProcessor,
<ide> def test_hamming_diversity(self):
<ide> processed_scores[1], torch.tensor([0.2500, -0.7500, 0.2500, 0.2500], device=torch_device), atol=1e-3
<ide> )
<ide> )
<add>
<add> def test_forced_bos_token_logits_processor(self):
<add> vocab_size = 20
<add> batch_size = 4
<add> bos_token_id = 0
<add>
<add> logits_processor = ForcedBOSTokenLogitsProcessor(bos_token_id=bos_token_id)
<add>
<add> # check that all scores are -inf except the bos_token_id score
<add> input_ids = ids_tensor((batch_size, 1), vocab_size=20)
<add> scores = self._get_uniform_logits(batch_size, vocab_size)
<add> scores = logits_processor(input_ids, scores)
<add> self.assertTrue(torch.isneginf(scores[:, bos_token_id + 1 :]).all())
<add> self.assertListEqual(scores[:, bos_token_id].tolist(), 4 * [0]) # score for bos_token_id shold be zero
<add>
<add> # check that bos_token_id is not forced if current length is greater than 1
<add> input_ids = ids_tensor((batch_size, 4), vocab_size=20)
<add> scores = self._get_uniform_logits(batch_size, vocab_size)
<add> scores = logits_processor(input_ids, scores)
<add> self.assertFalse(torch.isinf(scores).any())
<add>
<add> def test_forced_eos_token_logits_processor(self):
<add> vocab_size = 20
<add> batch_size = 4
<add> eos_token_id = 0
<add> max_length = 5
<add>
<add> logits_processor = ForcedEOSTokenLogitsProcessor(max_length=max_length, eos_token_id=eos_token_id)
<add>
<add> # check that all scores are -inf except the eos_token_id when max_length is reached
<add> input_ids = ids_tensor((batch_size, 4), vocab_size=20)
<add> scores = self._get_uniform_logits(batch_size, vocab_size)
<add> scores = logits_processor(input_ids, scores)
<add> self.assertTrue(torch.isneginf(scores[:, eos_token_id + 1 :]).all())
<add> self.assertListEqual(scores[:, eos_token_id].tolist(), 4 * [0]) # score for eos_token_id should be zero
<add>
<add> # check that eos_token_id is not forced if max_length is not reached
<add> input_ids = ids_tensor((batch_size, 3), vocab_size=20)
<add> scores = self._get_uniform_logits(batch_size, vocab_size)
<add> scores = logits_processor(input_ids, scores)
<add> self.assertFalse(torch.isinf(scores).any())
<ide><path>tests/test_generation_utils.py
<ide> from transformers import BartForConditionalGeneration, BartTokenizer, top_k_top_p_filtering
<ide> from transformers.generation_beam_search import BeamSearchScorer
<ide> from transformers.generation_logits_process import (
<add> ForcedBOSTokenLogitsProcessor,
<add> ForcedEOSTokenLogitsProcessor,
<ide> HammingDiversityLogitsProcessor,
<ide> LogitsProcessorList,
<ide> MinLengthLogitsProcessor,
<ide> def _get_input_ids_and_config(self):
<ide> return config, input_ids, attention_mask, max_length
<ide>
<ide> @staticmethod
<del> def _get_logits_processor_and_kwargs(input_length, eos_token_id, diversity_penalty=None):
<add> def _get_logits_processor_and_kwargs(
<add> input_length,
<add> eos_token_id,
<add> forced_bos_token_id=None,
<add> forced_eos_token_id=None,
<add> max_length=None,
<add> diversity_penalty=None,
<add> ):
<ide> process_kwargs = {
<ide> "min_length": input_length + 1,
<ide> "bad_words_ids": [[1, 0]],
<ide> def _get_logits_processor_and_kwargs(input_length, eos_token_id, diversity_penal
<ide> if eos_token_id is not None
<ide> else []
<ide> )
<add> + (
<add> [
<add> ForcedBOSTokenLogitsProcessor(forced_bos_token_id),
<add> ]
<add> if forced_bos_token_id is not None
<add> else []
<add> )
<add> + (
<add> [ForcedEOSTokenLogitsProcessor(max_length, forced_eos_token_id)]
<add> if forced_eos_token_id is not None
<add> else []
<add> )
<ide> + [
<ide> NoBadWordsLogitsProcessor(process_kwargs["bad_words_ids"], eos_token_id),
<ide> NoRepeatNGramLogitsProcessor(process_kwargs["no_repeat_ngram_size"]),
<ide> def _greedy_generate(
<ide> output_hidden_states=False,
<ide> return_dict_in_generate=False,
<ide> ):
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<ide> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], model.config.eos_token_id
<add> input_ids.shape[-1],
<add> eos_token_id=model.config.eos_token_id,
<add> forced_bos_token_id=model.config.forced_bos_token_id,
<add> forced_eos_token_id=model.config.forced_eos_token_id,
<add> max_length=max_length,
<ide> )
<ide>
<ide> kwargs = {}
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<ide>
<ide> output_generate = model.generate(
<ide> input_ids,
<ide> def test_sample_generate(self):
<ide> for model_class in self.all_generative_model_classes:
<ide> config, input_ids, attention_mask, max_length = self._get_input_ids_and_config()
<ide> model = model_class(config).to(torch_device).eval()
<del> process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], model.config.eos_token_id
<del> )
<del> logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs(num_beams=1)
<ide>
<ide> if model.config.is_encoder_decoder:
<ide> max_length = 4
<ide>
<add> process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<add> input_ids.shape[-1],
<add> model.config.eos_token_id,
<add> forced_bos_token_id=model.config.forced_bos_token_id,
<add> forced_eos_token_id=model.config.forced_eos_token_id,
<add> max_length=max_length,
<add> )
<add> logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs(num_beams=1)
<add>
<ide> # check `generate()` and `sample()` are equal
<ide> output_sample, output_generate = self._sample_generate(
<ide> model=model,
<ide> def test_sample_generate_dict_output(self):
<ide> config, input_ids, attention_mask, max_length = self._get_input_ids_and_config()
<ide> config.use_cache = False
<ide> model = model_class(config).to(torch_device).eval()
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<add>
<ide> process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], model.config.eos_token_id
<add> input_ids.shape[-1],
<add> model.config.eos_token_id,
<add> forced_bos_token_id=model.config.forced_bos_token_id,
<add> forced_eos_token_id=model.config.forced_eos_token_id,
<add> max_length=max_length,
<ide> )
<ide> logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs(num_beams=1)
<ide>
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<del>
<ide> output_sample, output_generate = self._sample_generate(
<ide> model=model,
<ide> input_ids=input_ids,
<ide> def test_beam_search_generate(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> model = model_class(config).to(torch_device).eval()
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<ide>
<ide> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], config.eos_token_id
<add> input_ids.shape[-1],
<add> config.eos_token_id,
<add> config.forced_bos_token_id,
<add> config.forced_eos_token_id,
<add> max_length,
<ide> )
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<ide> beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs(input_ids.shape[0], max_length)
<ide>
<ide> # check `generate()` and `beam_search()` are equal
<ide> def test_beam_search_generate_dict_output(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> model = model_class(config).to(torch_device).eval()
<del> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], config.eos_token_id
<del> )
<ide> if model.config.is_encoder_decoder:
<ide> max_length = 4
<add>
<add> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<add> input_ids.shape[-1],
<add> config.eos_token_id,
<add> config.forced_bos_token_id,
<add> config.forced_eos_token_id,
<add> max_length,
<add> )
<ide> beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs(input_ids.shape[0], max_length)
<ide> output_generate, output_beam_search = self._beam_search_generate(
<ide> model=model,
<ide> def test_beam_search_generate_dict_outputs_use_cache(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> if not hasattr(config, "use_cache"):
<ide> # only relevant if model has "use_cache"
<ide> return
<ide>
<ide> model = model_class(config).to(torch_device).eval()
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<ide>
<ide> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], config.eos_token_id
<add> input_ids.shape[-1],
<add> config.eos_token_id,
<add> config.forced_bos_token_id,
<add> config.forced_eos_token_id,
<add> max_length,
<ide> )
<ide>
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<ide> beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs(input_ids.shape[0], max_length)
<ide>
<ide> config.use_cache = True
<ide> def test_beam_sample_generate(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs(num_beams=1)
<ide>
<ide> def test_beam_sample_generate_dict_output(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> model = model_class(config).to(torch_device).eval()
<ide> logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs(num_beams=1)
<ide> def test_group_beam_search_generate(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<add>
<add> model = model_class(config).to(torch_device).eval()
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<ide>
<ide> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], config.eos_token_id, diversity_penalty=2.0
<add> input_ids.shape[-1],
<add> config.eos_token_id,
<add> config.forced_bos_token_id,
<add> config.forced_eos_token_id,
<add> max_length,
<add> diversity_penalty=2.0,
<ide> )
<ide>
<del> model = model_class(config).to(torch_device).eval()
<del>
<ide> # check `generate()` and `group_beam_search()` are equal
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<ide> beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs(input_ids.shape[0], max_length)
<ide> output_generate, output_group_beam_search = self._group_beam_search_generate(
<ide> model=model,
<ide> def test_group_beam_search_generate_dict_output(self):
<ide> # shorter than `max_length` can be generated which could lead to flaky circle ci
<ide> # failures if the top `num_return_sequences` beams are all shorter than the longest beam
<ide> config.eos_token_id = None
<add> config.forced_eos_token_id = None
<ide>
<ide> model = model_class(config).to(torch_device).eval()
<add> if model.config.is_encoder_decoder:
<add> max_length = 4
<ide>
<ide> logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
<del> input_ids.shape[-1], config.eos_token_id, diversity_penalty=2.0
<add> input_ids.shape[-1],
<add> config.eos_token_id,
<add> config.forced_bos_token_id,
<add> config.forced_eos_token_id,
<add> max_length,
<add> diversity_penalty=2.0,
<ide> )
<ide>
<ide> num_return_sequences = 1
<del> if model.config.is_encoder_decoder:
<del> max_length = 4
<ide> beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs(
<ide> input_ids.shape[0], max_length, num_return_sequences=num_return_sequences
<ide> )
<ide><path>tests/test_pipelines_summarization.py
<ide> def test_input_too_long(self):
<ide> decoder_attention_heads=1,
<ide> max_length=4,
<ide> min_length=1,
<add> forced_eos_token_id=None,
<ide> )
<ide> model = BartForConditionalGeneration(config)
<ide> # Bias output towards L | 29 |
Javascript | Javascript | add missing arguments in code comment | 5e20dcc7248a5cfd31414415ceaf9db61533dea2 | <ide><path>packages/ember-metal/lib/events.js
<ide> function actionsDiff(obj, eventName, otherActions) {
<ide> @param {String} eventName
<ide> @param {Object|Function} targetOrMethod A target object or a function
<ide> @param {Function|String} method A function or the name of a function to be called on `target`
<add> @param {Boolean} once A flag whether a function should only be called once
<ide> */
<ide> function addListener(obj, eventName, target, method, once) {
<ide> Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName);
<ide> function watchedEvents(obj) {
<ide> @param obj
<ide> @param {String} eventName
<ide> @param {Array} params
<add> @param {Array} actions
<ide> @return true
<ide> */
<ide> function sendEvent(obj, eventName, params, actions) { | 1 |
Javascript | Javascript | fix symbol lookup for older node.js versions | d51c4277d334497a42a130869b50ced6d2868bcd | <ide><path>test/helpers/createLazyTestEnv.js
<ide> const STATE_SYM = Object.getOwnPropertySymbols(global).find(
<del> s => s.description === "JEST_STATE_SYMBOL"
<add> Symbol("x").description
<add> ? s => s.description === "JEST_STATE_SYMBOL"
<add> : s => s.toString() === "Symbol(JEST_STATE_SYMBOL)"
<ide> );
<add>if (!STATE_SYM) {
<add> throw new Error(
<add> `Unable to find JEST_STATE_SYMBOL in ${Object.getOwnPropertySymbols(global)
<add> .map(s => s.toString())
<add> .join(", ")}`
<add> );
<add>}
<ide>
<ide> module.exports = (globalTimeout = 2000, nameSuffix = "") => {
<ide> const state = global[STATE_SYM]; | 1 |
Ruby | Ruby | remove unused method | 2ad34f46a1c4b8c59f37c2846ed0fcf3b4401e3a | <ide><path>actionpack/test/controller/send_file_test.rb
<ide> def file
<ide> def data
<ide> send_data(file_data, options)
<ide> end
<del>
<del> def multibyte_text_data
<del> send_data("Кирилица\n祝您好運.", options)
<del> end
<ide> end
<ide>
<ide> class SendFileTest < ActionController::TestCase | 1 |
Ruby | Ruby | use pip2 instead of pip | f8d5b20512700c9458c51523bda2da24f4212b0c | <ide><path>Library/Homebrew/missing_formula.rb
<ide> def blacklisted_reason(name)
<ide> #{Formatter.url("https://pip.readthedocs.io/en/stable/installing/")}
<ide> EOS
<ide> when "pil" then <<-EOS.undent
<del> Instead of PIL, consider `pip install pillow`.
<add> Instead of PIL, consider `pip2 install pillow`.
<ide> EOS
<ide> when "macruby" then <<-EOS.undent
<ide> MacRuby is not packaged and is on an indefinite development hiatus.
<ide> def blacklisted_reason(name)
<ide> ruin SSH's security.
<ide> EOS
<ide> when "gsutil" then <<-EOS.undent
<del> Install gsutil with `pip install gsutil`
<add> Install gsutil with `pip2 install gsutil`
<ide> EOS
<ide> when "gfortran" then <<-EOS.undent
<ide> GNU Fortran is now provided as part of GCC, and can be installed with: | 1 |
Javascript | Javascript | implement xhrloader in stlloader.js | 5c07056cdd54d7c52d5eb304c502ab1fb748c52f | <ide><path>examples/js/loaders/STLLoader.js
<ide> * Supports both binary and ASCII encoded files, with automatic detection of type.
<ide> *
<ide> * Limitations:
<del> * Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
<del> * There is perhaps some question as to how valid it is to always assume little-endian-ness.
<del> * ASCII decoding assumes file is UTF-8. Seems to work for the examples...
<add> * Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
<add> * There is perhaps some question as to how valid it is to always assume little-endian-ness.
<add> * ASCII decoding assumes file is UTF-8. Seems to work for the examples...
<ide> *
<ide> * Usage:
<del> * var loader = new THREE.STLLoader();
<del> * loader.addEventListener( 'load', function ( event ) {
<del> *
<del> * var geometry = event.content;
<del> * scene.add( new THREE.Mesh( geometry ) );
<del> *
<del> * } );
<del> * loader.load( './models/stl/slotted_disk.stl' );
<add> * var loader = new THREE.STLLoader();
<add> * loader.load( './models/stl/slotted_disk.stl', function(geometry){
<add> * scene.add( new THREE.Mesh( geometry ) );
<add> * });
<ide> *
<ide> * For binary STLs geometry might contain colors for vertices. To use it:
<del> * ... // use the same code to load STL as above
<del> * var geometry = event.content;
<del> * if (geometry.hasColors) {
<del> * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
<del> * } else { .... }
<del> * var mesh = new THREE.Mesh( geometry, material );
<add> * ... // use the same code to load STL as above
<add> * if (geometry.hasColors) {
<add> * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
<add> * } else { .... }
<add> * var mesh = new THREE.Mesh( geometry, material );
<ide> */
<ide>
<ide>
<del>THREE.STLLoader = function (manager) {
<del> this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
<add>THREE.STLLoader = function (manager, crossOrigin) {
<add> this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
<add> this.crossOrigin = crossOrigin;
<ide> };
<ide>
<ide> THREE.STLLoader.prototype = {
<ide> THREE.STLLoader.prototype = {
<ide>
<ide> };
<ide>
<del>THREE.STLLoader.prototype.load = function ( url, callback ) {
<del>
<del> var scope = this;
<del>
<del> var xhr = new XMLHttpRequest();
<del>
<del> function onloaded( event ) {
<del>
<del> if ( event.target.status === 200 || event.target.status === 0 ) {
<del>
<del> var geometry = scope.parse( event.target.response || event.target.responseText );
<del>
<del> scope.dispatchEvent( { type: 'load', content: geometry } );
<del>
<del> if ( callback ) callback( geometry );
<del>
<del> } else {
<del>
<del> scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']', response: event.target.statusText } );
<del>
<del> }
<del>
<del> }
<del>
<del> xhr.addEventListener( 'load', function(event){
<del> onloaded(event);
<del> scope.manager.itemEnd( url );
<del> }, false );
<del>
<del> xhr.addEventListener( 'progress', function ( event ) {
<del>
<del> scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
<del>
<del> }, false );
<add>THREE.STLLoader.prototype.load = function ( url, onLoad, onProgress, onError ) {
<ide>
<del> xhr.addEventListener( 'error', function () {
<add> var scope = this;
<ide>
<del> scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
<add> var loader = new THREE.XHRLoader( scope.manager );
<add> loader.setCrossOrigin( this.crossOrigin );
<add> loader.setResponseType('arraybuffer');
<add> loader.load( url, function ( text ) {
<ide>
<del> }, false );
<add> var geometry = scope.parse( text );
<ide>
<del> if ( xhr.overrideMimeType ) xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );
<del> xhr.open( 'GET', url, true );
<del> xhr.responseType = 'arraybuffer';
<del> xhr.send( null );
<add> if ( onLoad )
<add> onLoad( geometry );
<ide>
<del> scope.manager.itemStart( url );
<add> }, onProgress, onError);
<ide>
<ide> };
<ide> | 1 |
Javascript | Javascript | add spec for redbox | c44d4f9ef6adbc68ed9baefb6f1df5ea0c8276e9 | <ide><path>Libraries/BugReporting/BugReporting.js
<ide> const RCTDeviceEventEmitter = require('../EventEmitter/RCTDeviceEventEmitter');
<ide> const infoLog = require('../Utilities/infoLog');
<ide>
<ide> import type EmitterSubscription from '../vendor/emitter/EmitterSubscription';
<add>import NativeRedBox from '../NativeModules/specs/NativeRedBox';
<ide>
<ide> type ExtraData = {[key: string]: string};
<ide> type SourceCallback = () => string;
<ide> class BugReporting {
<ide> BugReportingNativeModule.setExtraData &&
<ide> BugReportingNativeModule.setExtraData(extraData, fileData);
<ide>
<del> const RedBoxNativeModule = require('../BatchedBridge/NativeModules').RedBox;
<del> RedBoxNativeModule &&
<del> RedBoxNativeModule.setExtraData &&
<del> RedBoxNativeModule.setExtraData(extraData, 'From BugReporting.js');
<add> if (NativeRedBox != null && NativeRedBox.setExtraData != null) {
<add> NativeRedBox.setExtraData(extraData, 'From BugReporting.js');
<add> }
<ide>
<ide> return {extras: extraData, files: fileData};
<ide> }
<ide><path>Libraries/NativeModules/specs/NativeRedBox.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +setExtraData: (extraData: Object, identifier: string) => void;
<add> +dismiss: () => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('RedBox');
<ide><path>Libraries/Utilities/HMRClient.js
<ide> const invariant = require('invariant');
<ide>
<ide> const MetroHMRClient = require('metro/src/lib/bundle-modules/HMRClient');
<ide>
<add>import NativeRedBox from '../NativeModules/specs/NativeRedBox';
<add>
<ide> /**
<ide> * HMR Client that receives from the server HMR updates and propagates them
<ide> * runtime to reflects those changes.
<ide> Error: ${e.message}`;
<ide> });
<ide>
<ide> hmrClient.on('update', () => {
<del> if (Platform.OS === 'ios') {
<del> const RCTRedBox = require('../BatchedBridge/NativeModules').RedBox;
<del> RCTRedBox && RCTRedBox.dismiss && RCTRedBox.dismiss();
<add> if (
<add> Platform.OS === 'ios' &&
<add> NativeRedBox != null &&
<add> NativeRedBox.dismiss != null
<add> ) {
<add> NativeRedBox.dismiss();
<ide> } else {
<ide> const RCTExceptionsManager = require('../BatchedBridge/NativeModules')
<ide> .ExceptionsManager; | 3 |
Ruby | Ruby | freeze columns before using them as hash keys | 3aef5ce9b35a4659379201eb6bb1dba355a83ba4 | <ide><path>activerecord/lib/active_record/result.rb
<ide> class Result
<ide> attr_reader :columns, :rows, :column_types
<ide>
<ide> def initialize(columns, rows, column_types = {})
<del> @columns = columns
<add> @columns = columns.map{|c| c.freeze}
<ide> @rows = rows
<ide> @hash_rows = nil
<ide> @column_types = column_types | 1 |
PHP | PHP | use the instance config trait on dispatch filters | f4d1eb1542c690b691005d0355d22c373152d744 | <ide><path>src/Routing/DispatcherFilter.php
<ide>
<ide> namespace Cake\Routing;
<ide>
<add>use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Event\Event;
<ide> use Cake\Event\EventListener;
<del>use Cake\Utility\Hash;
<ide>
<ide> /**
<ide> * This abstract class represents a filter to be applied to a dispatcher cycle. It acts as as
<ide> */
<ide> abstract class DispatcherFilter implements EventListener {
<ide>
<add> use InstanceConfigTrait;
<add>
<ide> /**
<ide> * Default priority for all methods in this filter
<ide> *
<ide> abstract class DispatcherFilter implements EventListener {
<ide> public $priority = 10;
<ide>
<ide> /**
<del> * Settings for this filter
<add> * Default config
<add> *
<add> * These are merged with user-provided config when the class is used.
<ide> *
<ide> * @var array
<ide> */
<del> public $settings = array();
<add> protected $_defaultConfig = [];
<ide>
<ide> /**
<ide> * Constructor.
<ide> *
<del> * @param array $settings Configuration settings for the filter.
<add> * @param array $config Settings for the filter.
<ide> */
<del> public function __construct($settings = array()) {
<del> $this->settings = Hash::merge($this->settings, $settings);
<add> public function __construct($config = []) {
<add> $this->config($config);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | add _ for unused last arg | a4eed027411c7db1091d2fdc26135b67c9b985bd | <ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> def test
<ide> ]
<ide>
<ide> def generate_test_dummy(force = false)
<del> opts = (options.dup || {}).keep_if { |k, | PASSTHROUGH_OPTIONS.map(&:to_s).include?(k) }
<add> opts = (options.dup || {}).keep_if { |k, _| PASSTHROUGH_OPTIONS.map(&:to_s).include?(k) }
<ide> opts[:force] = force
<ide> opts[:skip_bundle] = true
<ide> opts[:skip_listen] = true | 1 |
Javascript | Javascript | update documentation to avoid global view access | 13c807b7e085cd91e5d40263b0ab0f299ee6a078 | <ide><path>packages/ember-handlebars-compiler/lib/main.js
<ide> var EmberHandlebars = Ember.Handlebars = objectCreate(Handlebars);
<ide> Which is functionally equivalent to:
<ide>
<ide> ```handlebars
<del> {{view App.CalendarView}}
<add> {{view 'calendar'}}
<ide> ```
<ide>
<ide> Options in the helper will be passed to the view in exactly the same
<ide><path>packages/ember-handlebars/lib/controls/select.js
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select content=names}}
<add> {{view "select" content=names}}
<ide> ```
<ide>
<ide> Would result in the following HTML:
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select
<del> content=names
<del> value=selectedName
<del> }}
<add> {{view "select" content=names value=selectedName}}
<ide> ```
<ide>
<ide> Would result in the following HTML with the `<option>` for 'Tom' selected:
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select
<add> {{view "select"
<ide> content=programmers
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"}}
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select
<add> {{view "select"
<ide> content=programmers
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"
<ide> var SelectOptgroup = CollectionView.extend({
<ide>
<ide> App.ApplicationController = Ember.ObjectController.extend({
<ide> selectedPerson: tom,
<del> programmers: [
<del> yehuda,
<del> tom
<del> ]
<add> programmers: [ yehuda, tom ]
<ide> });
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select
<add> {{view "select"
<ide> content=programmers
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```javascript
<ide> App.ApplicationController = Ember.ObjectController.extend({
<ide> selectedProgrammer: null,
<del> programmers: [
<del> "Yehuda",
<del> "Tom"
<del> ]
<add> programmers: ["Yehuda", "Tom"]
<ide> });
<ide> ```
<ide>
<ide> ``` handlebars
<del> {{view Ember.Select
<add> {{view "select"
<ide> content=programmers
<ide> value=selectedProgrammer
<ide> }}
<ide> var SelectOptgroup = CollectionView.extend({
<ide> ```javascript
<ide> App.ApplicationController = Ember.ObjectController.extend({
<ide> selectedProgrammer: null,
<del> programmers: [
<del> "Yehuda",
<del> "Tom"
<del> ]
<add> programmers: [ "Yehuda", "Tom" ]
<ide> });
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select
<add> {{view "select"
<ide> content=programmers
<ide> value=selectedProgrammer
<ide> prompt="Please select a name"
<ide> var Select = View.extend({
<ide> Otherwise, this should be a list of objects. For instance:
<ide>
<ide> ```javascript
<del> Ember.Select.create({
<add> var App = Ember.Application.create();
<add> var App.MySelect = Ember.Select.extend({
<ide> content: Ember.A([
<ide> { id: 1, firstName: 'Yehuda' },
<ide> { id: 2, firstName: 'Tom' }
<ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> var alias = computed.alias;
<ide> Given an empty `<body>` the following template:
<ide>
<ide> ```handlebars
<del> {{#collection contentBinding="App.items"}}
<add> {{! application.hbs }}
<add> {{#collection content=model}}
<ide> Hi {{view.content.name}}
<ide> {{/collection}}
<ide> ```
<ide>
<ide> And the following application code
<ide>
<ide> ```javascript
<del> App = Ember.Application.create()
<del> App.items = [
<del> Ember.Object.create({name: 'Dave'}),
<del> Ember.Object.create({name: 'Mary'}),
<del> Ember.Object.create({name: 'Sara'})
<del> ]
<add> App = Ember.Application.create();
<add> App.ApplicationRoute = Ember.Route.extend({
<add> model: function(){
<add> return [{name: 'Yehuda'},{name: 'Tom'},{name: 'Peter'}];
<add> }
<add> });
<ide> ```
<ide>
<del> Will result in the HTML structure below
<add> The following HTML will result:
<ide>
<ide> ```html
<ide> <div class="ember-view">
<del> <div class="ember-view">Hi Dave</div>
<del> <div class="ember-view">Hi Mary</div>
<del> <div class="ember-view">Hi Sara</div>
<add> <div class="ember-view">Hi Yehuda</div>
<add> <div class="ember-view">Hi Tom</div>
<add> <div class="ember-view">Hi Peter</div>
<ide> </div>
<ide> ```
<ide>
<del> ### Blockless use in a collection
<add> ### Non-block version of collection
<ide>
<del> If you provide an `itemViewClass` option that has its own `template` you can
<add> If you provide an `itemViewClass` option that has its own `template` you may
<ide> omit the block.
<ide>
<ide> The following template:
<ide>
<ide> ```handlebars
<del> {{collection contentBinding="App.items" itemViewClass="App.AnItemView"}}
<add> {{! application.hbs }}
<add> {{collection content=model itemViewClass="an-item"}}
<ide> ```
<ide>
<ide> And application code
<ide>
<ide> ```javascript
<ide> App = Ember.Application.create();
<del> App.items = [
<del> Ember.Object.create({name: 'Dave'}),
<del> Ember.Object.create({name: 'Mary'}),
<del> Ember.Object.create({name: 'Sara'})
<del> ];
<add> App.ApplicationRoute = Ember.Route.extend({
<add> model: function(){
<add> return [{name: 'Yehuda'},{name: 'Tom'},{name: 'Peter'}];
<add> }
<add> });
<ide>
<ide> App.AnItemView = Ember.View.extend({
<ide> template: Ember.Handlebars.compile("Greetings {{view.content.name}}")
<ide> var alias = computed.alias;
<ide>
<ide> ```html
<ide> <div class="ember-view">
<del> <div class="ember-view">Greetings Dave</div>
<del> <div class="ember-view">Greetings Mary</div>
<del> <div class="ember-view">Greetings Sara</div>
<add> <div class="ember-view">Greetings Yehuda</div>
<add> <div class="ember-view">Greetings Tom</div>
<add> <div class="ember-view">Greetings Peter</div>
<ide> </div>
<ide> ```
<ide>
<ide> var alias = computed.alias;
<ide> the helper by passing it as the first argument:
<ide>
<ide> ```handlebars
<del> {{#collection App.MyCustomCollectionClass contentBinding="App.items"}}
<add> {{#collection "my-custom-collection" content=model}}
<ide> Hi {{view.content.name}}
<ide> {{/collection}}
<ide> ```
<ide>
<add> This example would look for the class `App.MyCustomCollection`.
<add>
<ide> ### Forwarded `item.*`-named Options
<ide>
<ide> As with the `{{view}}`, helper options passed to the `{{collection}}` will be
<ide> var alias = computed.alias;
<ide> item (note the camelcasing):
<ide>
<ide> ```handlebars
<del> {{#collection contentBinding="App.items"
<add> {{#collection content=model
<ide> itemTagName="p"
<ide> itemClassNames="greeting"}}
<ide> Howdy {{view.content.name}}
<ide> var alias = computed.alias;
<ide>
<ide> ```html
<ide> <div class="ember-view">
<del> <p class="ember-view greeting">Howdy Dave</p>
<del> <p class="ember-view greeting">Howdy Mary</p>
<del> <p class="ember-view greeting">Howdy Sara</p>
<add> <p class="ember-view greeting">Howdy Yehuda</p>
<add> <p class="ember-view greeting">Howdy Tom</p>
<add> <p class="ember-view greeting">Howdy Peter</p>
<ide> </div>
<ide> ```
<ide>
<ide><path>packages/ember-handlebars/lib/helpers/each.js
<ide> GroupedEach.prototype = {
<ide> };
<ide>
<ide> /**
<del> The `{{#each}}` helper loops over elements in a collection, rendering its
<del> block once for each item. It is an extension of the base Handlebars `{{#each}}`
<del> helper:
<add> The `{{#each}}` helper loops over elements in a collection. It is an extension
<add> of the base Handlebars `{{#each}}` helper.
<add>
<add> The default behavior of `{{#each}}` is to yield its inner block once for every
<add> item in an array. Each yield will provide the item as the context of the block.
<ide>
<ide> ```javascript
<del> Developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}];
<add> var developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}];
<ide> ```
<ide>
<ide> ```handlebars
<del> {{#each Developers}}
<add> {{#each developers}}
<ide> {{name}}
<add> {{! `this` is each developer }}
<ide> {{/each}}
<ide> ```
<ide>
<del> `{{each}}` supports an alternative syntax with element naming:
<add> `{{#each}}` supports an alternative syntax with element naming. This preserves
<add> context of the yielded block:
<ide>
<ide> ```handlebars
<del> {{#each person in Developers}}
<add> {{#each person in developers}}
<ide> {{person.name}}
<add> {{! `this` is whatever it was outside the #each }}
<ide> {{/each}}
<ide> ```
<ide>
<del> When looping over objects that do not have properties, `{{this}}` can be used
<del> to render the object:
<add> The same rules apply to arrays of primitives, but the items may need to be
<add> references with `{{this}}`.
<ide>
<ide> ```javascript
<del> DeveloperNames = ['Yehuda', 'Tom', 'Paul']
<add> var developerNames = ['Yehuda', 'Tom', 'Paul']
<ide> ```
<ide>
<ide> ```handlebars
<del> {{#each DeveloperNames}}
<add> {{#each developerNames}}
<ide> {{this}}
<ide> {{/each}}
<ide> ```
<add>
<ide> ### {{else}} condition
<add>
<ide> `{{#each}}` can have a matching `{{else}}`. The contents of this block will render
<ide> if the collection is empty.
<ide>
<ide> ```
<del> {{#each person in Developers}}
<add> {{#each person in developers}}
<ide> {{person.name}}
<ide> {{else}}
<ide> <p>Sorry, nobody is available for this task.</p>
<ide> {{/each}}
<ide> ```
<del> ### Specifying a View class for items
<del> If you provide an `itemViewClass` option that references a view class
<del> with its own `template` you can omit the block.
<add>
<add> ### Specifying an alternative view for each item
<add>
<add> `itemViewClass` can control which view will be used during the render of each
<add> item's template.
<ide>
<ide> The following template:
<ide>
<ide> ```handlebars
<del> {{#view App.MyView }}
<del> {{each view.items itemViewClass="App.AnItemView"}}
<del> {{/view}}
<add> <ul>
<add> {{#each developers itemViewClass="person"}}
<add> {{name}}
<add> {{/each}}
<add> </ul>
<ide> ```
<ide>
<del> And application code
<add> Will use the following view for each item
<ide>
<ide> ```javascript
<del> App = Ember.Application.create({
<del> MyView: Ember.View.extend({
<del> items: [
<del> Ember.Object.create({name: 'Dave'}),
<del> Ember.Object.create({name: 'Mary'}),
<del> Ember.Object.create({name: 'Sara'})
<del> ]
<del> })
<add> App.PersonView = Ember.View.extend({
<add> tagName: 'li'
<ide> });
<add> ```
<add>
<add> Resulting in HTML output that looks like the following:
<ide>
<del> App.AnItemView = Ember.View.extend({
<del> template: Ember.Handlebars.compile("Greetings {{name}}")
<add> ```html
<add> <ul>
<add> <li class="ember-view">Yehuda</li>
<add> <li class="ember-view">Tom</li>
<add> <li class="ember-view">Paul</li>
<add> </ul>
<add> ```
<add>
<add> `itemViewClass` also enables a non-block form of `{{each}}`. The view
<add> must {{#crossLink "Ember.View/toc_templates"}}provide its own template{{/crossLink}},
<add> and then the block should be dropped. An example that outputs the same HTML
<add> as the previous one:
<add>
<add> ```javascript
<add> App.PersonView = Ember.View.extend({
<add> tagName: 'li',
<add> template: '{{name}}'
<ide> });
<ide> ```
<ide>
<del> Will result in the HTML structure below
<add> ```handlebars
<add> <ul>
<add> {{each developers itemViewClass="person"}}
<add> </ul>
<add> ```
<ide>
<del> ```html
<del> <div class="ember-view">
<del> <div class="ember-view">Greetings Dave</div>
<del> <div class="ember-view">Greetings Mary</div>
<del> <div class="ember-view">Greetings Sara</div>
<del> </div>
<add> ### Specifying an alternative view for no items (else)
<add>
<add> The `emptyViewClass` option provides the same flexibility to the `{{else}}`
<add> case of the each helper.
<add>
<add> ```javascript
<add> App.NoPeopleView = Ember.View.extend({
<add> tagName: 'li',
<add> template: 'No person is available, sorry'
<add> });
<ide> ```
<ide>
<del> If an `itemViewClass` is defined on the helper, and therefore the helper is not
<del> being used as a block, an `emptyViewClass` can also be provided optionally.
<del> The `emptyViewClass` will match the behavior of the `{{else}}` condition
<del> described above. That is, the `emptyViewClass` will render if the collection
<del> is empty.
<add> ```handlebars
<add> <ul>
<add> {{#each developers emptyViewClass="no-people"}}
<add> <li>{{name}}</li>
<add> {{/each}}
<add> </ul>
<add> ```
<ide>
<del> ### Representing each item with a Controller.
<del> By default the controller lookup within an `{{#each}}` block will be
<del> the controller of the template where the `{{#each}}` was used. If each
<del> item needs to be presented by a custom controller you can provide a
<del> `itemController` option which references a controller by lookup name.
<del> Each item in the loop will be wrapped in an instance of this controller
<del> and the item itself will be set to the `model` property of that controller.
<add> ### Wrapping each item in a controller
<ide>
<del> This is useful in cases where properties of model objects need transformation
<del> or synthesis for display:
<add> Controllers in Ember manage state and decorate data. In many cases,
<add> providing a controller for each item in a list can be useful.
<add> Specifically, an {{#crossLink "Ember.ObjectController"}}Ember.ObjectController{{/crossLink}}
<add> should probably be used. Item controllers are passed the item they
<add> will present as a `model` property, and an object controller will
<add> proxy property lookups to `model` for us.
<add>
<add> This allows state and decoration to be added to the controller
<add> while any other property lookups are delegated to the model. An example:
<ide>
<ide> ```javascript
<del> App.DeveloperController = Ember.ObjectController.extend({
<add> App.RecruitController = Ember.ObjectController.extend({
<ide> isAvailableForHire: function() {
<del> return !this.get('model.isEmployed') && this.get('model.isSeekingWork');
<add> return !this.get('isEmployed') && this.get('isSeekingWork');
<ide> }.property('isEmployed', 'isSeekingWork')
<ide> })
<ide> ```
<ide>
<ide> ```handlebars
<del> {{#each person in developers itemController="developer"}}
<add> {{#each person in developers itemController="recruit"}}
<ide> {{person.name}} {{#if person.isAvailableForHire}}Hire me!{{/if}}
<ide> {{/each}}
<ide> ```
<ide>
<del> Each itemController will receive a reference to the current controller as
<del> a `parentController` property.
<del>
<ide> ### (Experimental) Grouped Each
<ide>
<del> When used in conjunction with the experimental [group helper](https://github.com/emberjs/group-helper),
<del> you can inform Handlebars to re-render an entire group of items instead of
<del> re-rendering them one at a time (in the event that they are changed en masse
<del> or an item is added/removed).
<add> If a list's membership often changes, but properties of items in that
<add> group rarely change, a significant improvement in template rendering
<add> time can be achieved by using the experimental [group helper](https://github.com/emberjs/group-helper).
<ide>
<ide> ```handlebars
<ide> {{#group}}
<ide> GroupedEach.prototype = {
<ide> {{/group}}
<ide> ```
<ide>
<del> This can be faster than the normal way that Handlebars re-renders items
<del> in some cases.
<add> When the membership of `people` changes, or when any property changes, the entire
<add> `{{#group}}` block will be re-rendered.
<ide>
<del> If for some reason you have a group with more than one `#each`, you can make
<del> one of the collections be updated in normal (non-grouped) fashion by setting
<del> the option `groupedRows=true` (counter-intuitive, I know).
<del>
<del> For example,
<add> An `{{#each}}` inside the `{{#group}}` helper can opt-out of the special group
<add> behavior by passing the `groupedRows` option. For example:
<ide>
<ide> ```handlebars
<del> {{dealershipName}}
<del>
<ide> {{#group}}
<ide> {{#each dealers}}
<add> {{! uses group's special behavior }}
<ide> {{firstName}} {{lastName}}
<ide> {{/each}}
<ide>
<ide> {{#each car in cars groupedRows=true}}
<add> {{! does not use group's special behavior }}
<ide> {{car.make}} {{car.model}} {{car.color}}
<ide> {{/each}}
<ide> {{/group}}
<ide> ```
<del> Any change to `dealershipName` or the `dealers` collection will cause the
<del> entire group to be re-rendered. However, changes to the `cars` collection
<del> will be re-rendered individually (as normal).
<ide>
<del> Note that `group` behavior is also disabled by specifying an `itemViewClass`.
<add> Any change to the `dealers` collection will cause the entire group to be re-rendered.
<add> Changes to the `cars` collection will be re-rendered individually, as they are with
<add> normal `{{#each}}` usage.
<add>
<add> `{{#group}}` is implemented with an `itemViewClass`, so specifying an `itemViewClass`
<add> on an `{{#each}}` will also disable the special re-rendering behavior.
<ide>
<ide> @method each
<ide> @for Ember.Handlebars.helpers
<ide> @param [name] {String} name for item (used with `in`)
<ide> @param [path] {String} path
<ide> @param [options] {Object} Handlebars key/value pairs of options
<ide> @param [options.itemViewClass] {String} a path to a view class used for each item
<add> @param [options.emptyViewClass] {String} a path to a view class used for each item
<ide> @param [options.itemController] {String} name of a controller to be created for each item
<ide> @param [options.groupedRows] {boolean} enable normal item-by-item rendering when inside a `#group` helper
<ide> */
<ide><path>packages/ember-handlebars/lib/helpers/view.js
<ide> export var ViewHelper = EmberObject.create({
<ide> specify a path to a custom view class.
<ide>
<ide> ```handlebars
<del> {{#view "MyApp.CustomView"}}
<add> {{#view "custom"}}{{! will look up App.CustomView }}
<ide> hello.
<ide> {{/view}}
<ide> ```
<ide> export var ViewHelper = EmberObject.create({
<ide> innerViewClass: Ember.View.extend({
<ide> classNames: ['a-custom-view-class-as-property']
<ide> }),
<del> template: Ember.Handlebars.compile('{{#view "view.innerViewClass"}} hi {{/view}}')
<add> template: Ember.Handlebars.compile('{{#view view.innerViewClass}} hi {{/view}}')
<ide> });
<ide>
<ide> MyApp.OuterView.create().appendTo('body');
<ide> export var ViewHelper = EmberObject.create({
<ide> supplying a block. Attempts to use both a `templateName` option and supply a
<ide> block will throw an error.
<ide>
<add> ```javascript
<add> var App = Ember.Application.create();
<add> App.WithTemplateDefinedView = Ember.View.extend({
<add> templateName: 'defined-template'
<add> });
<add> ```
<add>
<add> ```handlebars
<add> {{! application.hbs }}
<add> {{view 'with-template-defined'}}
<add> ```
<add>
<ide> ```handlebars
<del> {{view "MyApp.ViewWithATemplateDefined"}}
<add> {{! defined-template.hbs }}
<add> Some content for the defined template view.
<ide> ```
<ide>
<ide> ### `viewName` property
<ide><path>packages/ember-views/lib/views/collection_view.js
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide> The view for each item in the collection will have its `content` property set
<ide> to the item.
<ide>
<del> ## Specifying itemViewClass
<add> ## Specifying `itemViewClass`
<ide>
<ide> By default the view class for each item in the managed collection will be an
<ide> instance of `Ember.View`. You can supply a different class by setting the
<ide> `CollectionView`'s `itemViewClass` property.
<ide>
<del> Given an empty `<body>` and the following code:
<add> Given the following application code:
<ide>
<ide> ```javascript
<del> someItemsView = Ember.CollectionView.create({
<add> var App = Ember.Application.create();
<add> App.ItemListView = Ember.CollectionView.extend({
<ide> classNames: ['a-collection'],
<ide> content: ['A','B','C'],
<ide> itemViewClass: Ember.View.extend({
<ide> template: Ember.Handlebars.compile("the letter: {{view.content}}")
<ide> })
<ide> });
<add> ```
<ide>
<del> someItemsView.appendTo('body');
<add> And a simple application template:
<add>
<add> ```handlebars
<add> {{view 'item-list'}}
<ide> ```
<ide>
<del> Will result in the following HTML structure
<add> The following HTML will result:
<ide>
<ide> ```html
<ide> <div class="ember-view a-collection">
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide> "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result
<ide> in the item views receiving an appropriately matched `tagName` property.
<ide>
<del> Given an empty `<body>` and the following code:
<add> Given the following application code:
<ide>
<ide> ```javascript
<del> anUnorderedListView = Ember.CollectionView.create({
<add> var App = Ember.Application.create();
<add> App.UnorderedListView = Ember.CollectionView.create({
<ide> tagName: 'ul',
<ide> content: ['A','B','C'],
<ide> itemViewClass: Ember.View.extend({
<ide> template: Ember.Handlebars.compile("the letter: {{view.content}}")
<ide> })
<ide> });
<add> ```
<ide>
<del> anUnorderedListView.appendTo('body');
<add> And a simple application template:
<add>
<add> ```handlebars
<add> {{view 'unordered-list-view'}}
<ide> ```
<ide>
<del> Will result in the following HTML structure
<add> The following HTML will result:
<ide>
<ide> ```html
<ide> <ul class="ember-view a-collection">
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide> ```
<ide>
<ide> Additional `tagName` pairs can be provided by adding to
<del> `Ember.CollectionView.CONTAINER_MAP `
<add> `Ember.CollectionView.CONTAINER_MAP`. For example:
<ide>
<ide> ```javascript
<ide> Ember.CollectionView.CONTAINER_MAP['article'] = 'section'
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide> `createChildView` method can be overidden:
<ide>
<ide> ```javascript
<del> CustomCollectionView = Ember.CollectionView.extend({
<add> App.CustomCollectionView = Ember.CollectionView.extend({
<ide> createChildView: function(viewClass, attrs) {
<ide> if (attrs.content.kind == 'album') {
<ide> viewClass = App.AlbumView;
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide> will be the `CollectionView`s only child.
<ide>
<ide> ```javascript
<del> aListWithNothing = Ember.CollectionView.create({
<add> var App = Ember.Application.create();
<add> App.ListWithNothing = Ember.CollectionView.create({
<ide> classNames: ['nothing']
<ide> content: null,
<ide> emptyView: Ember.View.extend({
<ide> template: Ember.Handlebars.compile("The collection is empty")
<ide> })
<ide> });
<add> ```
<add>
<add> And a simple application template:
<ide>
<del> aListWithNothing.appendTo('body');
<add> ```handlebars
<add> {{view 'list-with-nothing'}}
<ide> ```
<ide>
<del> Will result in the following HTML structure
<add> The following HTML will result:
<ide>
<ide> ```html
<ide> <div class="ember-view nothing">
<ide><path>packages/ember-views/lib/views/view.js
<ide> var EMPTY_ARRAY = [];
<ide> on the descendent.
<ide>
<ide> ```javascript
<del> OuterView = Ember.View.extend({
<del> template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"),
<add> var App = Ember.Application.create();
<add> App.OuterView = Ember.View.extend({
<add> template: Ember.Handlebars.compile("outer {{#view 'inner'}}inner{{/view}} outer"),
<ide> eventManager: Ember.Object.create({
<ide> mouseEnter: function(event, view) {
<ide> // view might be instance of either
<ide> var EMPTY_ARRAY = [];
<ide> })
<ide> });
<ide>
<del> InnerView = Ember.View.extend({
<add> App.InnerView = Ember.View.extend({
<ide> click: function(event) {
<ide> // will be called if rendered inside
<ide> // an OuterView because OuterView's | 7 |
Go | Go | remove use of docker/docker/pkg/homedir | 9fd12a5e3104befcd9a6fead9f28b0346339c75d | <ide><path>libnetwork/client/mflag/flag.go
<ide> import (
<ide> "strings"
<ide> "text/tabwriter"
<ide> "time"
<del>
<del> "github.com/docker/docker/pkg/homedir"
<ide> )
<ide>
<ide> // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
<ide> func isZeroValue(value string) bool {
<ide> // otherwise, the default values of all defined flags in the set.
<ide> func (fs *FlagSet) PrintDefaults() {
<ide> writer := tabwriter.NewWriter(fs.Out(), 20, 1, 3, ' ', 0)
<del> home := homedir.Get()
<add> home, _ := os.UserHomeDir()
<ide>
<ide> // Don't substitute when HOME is /
<ide> if runtime.GOOS != "windows" && home == "/" {
<ide> func (fs *FlagSet) PrintDefaults() {
<ide> val := flag.DefValue
<ide>
<ide> if home != "" && strings.HasPrefix(val, home) {
<del> val = homedir.GetShortcutString() + val[len(home):]
<add> val = getShortcutString() + val[len(home):]
<ide> }
<ide>
<ide> if isZeroValue(val) {
<ide> func (fs *FlagSet) PrintDefaults() {
<ide> writer.Flush()
<ide> }
<ide>
<add>func getShortcutString() string {
<add> if runtime.GOOS == "windows" {
<add> return "%USERPROFILE%"
<add> }
<add> return "~"
<add>}
<add>
<ide> // PrintDefaults prints to standard error the default values of all defined command-line flags.
<ide> func PrintDefaults() {
<ide> CommandLine.PrintDefaults() | 1 |
Javascript | Javascript | fix lint issues | 9fe5a6b5a86adb163b02a200bf7562aca87c53e0 | <ide><path>packages/@ember/-internals/glimmer/tests/integration/input-test.js
<ide> moduleFor(
<ide> }
<ide>
<ide> ['@test GH18211 input checked attribute, without a value, works with the action helper']() {
<del> this.render(`<input type="checkbox" checked {{action "someAction"}}>`, { actions: { someAction() {} } });
<add> this.render(`<input type="checkbox" checked {{action "someAction"}}>`, {
<add> actions: { someAction() {} },
<add> });
<ide> this.assertPropertyHasValue('checked', true);
<ide> }
<ide>
<ide> ['@test GH18211 input checked attribute, with a value, works with the action helper']() {
<del> this.render(`<input type="checkbox" checked={{true}} {{action "someAction"}}>`, { actions: { someAction() {} } });
<add> this.render(`<input type="checkbox" checked={{true}} {{action "someAction"}}>`, {
<add> actions: { someAction() {} },
<add> });
<ide> this.assertPropertyHasValue('checked', true);
<ide> }
<del>
<add>
<ide> ['@test GH18211 input checked attribute, without a value, works with attributes with values']() {
<del> this.render(`<input type="checkbox" checked click={{action "someAction"}}>`, { actions: { someAction() {} } });
<add> this.render(`<input type="checkbox" checked click={{action "someAction"}}>`, {
<add> actions: { someAction() {} },
<add> });
<ide> this.assertPropertyHasValue('checked', true);
<ide> }
<ide>
<ide> ['@test GH18211 input checked attribute, without a value, works with event attributes']() {
<del> this.render(`<input type="checkbox" checked onclick={{action "someAction"}}>`, { actions: { someAction() {} } });
<add> this.render(`<input type="checkbox" checked onclick={{action "someAction"}}>`, {
<add> actions: { someAction() {} },
<add> });
<ide> this.assertPropertyHasValue('checked', true);
<ide> }
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.