content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | add docs for abstract class generators | aeab40b4e3eb6c4e17d9895f38b82c6a99e41136 | <ide><path>guides/source/active_record_multiple_databases.md
<ide> Lastly, for new primary databases you need to set the `migrations_paths` to the
<ide> where you will store migrations for that database. We'll look more at `migrations_paths`
<ide> later on in this guide.
<ide>
<del>Now that we have a new database, let's set up the model. In order to use the new database we
<del>need to create a new abstract class and connect to the animals databases.
<add>Now that we have a new database, let's set up the connection model. In order to use the
<add>new database we need to create a new abstract class and connect to the animals databases.
<ide>
<ide> ```ruby
<del>class AnimalsBase < ApplicationRecord
<add>class AnimalsRecord < ApplicationRecord
<ide> self.abstract_class = true
<ide>
<ide> connects_to database: { writing: :animals, reading: :animals_replica }
<ide> Note that there is no command for creating the users and you'll need to do that
<ide> to support the readonly users for your replicas. If you want to create just the animals
<ide> database you can run `bin/rails db:create:animals`.
<ide>
<del>## Migrations
<add>## Generators & Migrations
<ide>
<ide> Migrations for multiple databases should live in their own folders prefixed with the
<ide> name of the database key in the configuration.
<ide> so that the file is generated in the correct directory. The command can be run l
<ide> $ bin/rails generate migration CreateDogs name:string --database animals
<ide> ```
<ide>
<add>If you are using Rails generators, the scaffold and model generators will create the abstract
<add>class for you. Simply pass the database key to the command line
<add>
<add>```bash
<add>$ bin/rails generate scaffold Dog name:title --database animals
<add>```
<add>
<add>A class with the database name and `Record` will be created. In this example
<add>the database is `Animals` so we end up with `AnimalsRecord`:
<add>
<add>```ruby
<add>class AnimalsRecord < ApplicationRecord
<add> self.abstract_class = true
<add>
<add> connects_to database: { writing: :animals }
<add>end
<add>```
<add>
<add>The generated model will automatically inherit from `AnimalsRecord`.
<add>
<add>```ruby
<add>class Dog < AnimalsRecord
<add>end
<add>```
<add>
<add>Note: Since Rails doesn't know which database is the replica for your writer you will need to
<add>add this to the abstract class after you're done.
<add>
<add>Rails will only generate the new class once. It will not be overwritten by new scaffolds
<add>or deleted if the scaffold is deleted.
<add>
<add>If you already have an abstract class and its name differs from `AnimalsRecord` you can pass
<add>the `--parent` option to indicate you want a different abstract class:
<add>
<add>```bash
<add>$ bin/rails generate scaffold Dog name:title --database animals --parent Animals::Record
<add>```
<add>
<add>This will skip generating `AnimalsRecord` since you've indicated to Rails that you want to
<add>use a different parent class.
<add>
<ide> ## Activating automatic connection switching
<ide>
<ide> Finally, in order to use the read-only replica in your application you'll need to activate | 1 |
Javascript | Javascript | ignore object properties which start with $ | aa3c54c73f7470999535294899a1c33cd193f455 | <ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> modelValue = ctrl.$modelValue,
<ide> values = valuesFn(scope) || [],
<ide> keys = keyName ? sortedKeys(values) : values,
<add> key,
<ide> groupLength, length,
<ide> groupIndex, index,
<ide> locals = {},
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> // We now build up the list of options we need (we merge later)
<ide> for (index = 0; length = keys.length, index < length; index++) {
<del> locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
<del> optionGroupName = groupByFn(scope, locals) || '';
<add>
<add> key = index;
<add> if (keyName) {
<add> key = keys[index];
<add> if ( key.charAt(0) === '$' ) continue;
<add> locals[keyName] = key;
<add> }
<add>
<add> locals[valueName] = values[key];
<add>
<add> optionGroupName = groupByFn(scope, locals) || '';
<ide> if (!(optionGroup = optionGroups[optionGroupName])) {
<ide> optionGroup = optionGroups[optionGroupName] = [];
<ide> optionGroupNames.push(optionGroupName);
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide> expect(jqLite(element.find('option')[0]).text()).toEqual('blank');
<ide> });
<ide>
<add> it('should ignore $ and $$ properties', function() {
<add> createSelect({
<add> 'ng-options': 'key as value for (key, value) in object',
<add> 'ng-model': 'selected'
<add> });
<add>
<add> scope.$apply(function() {
<add> scope.object = {'regularProperty': 'visible', '$$private': 'invisible', '$property': 'invisible'};
<add> scope.selected = 'regularProperty';
<add> });
<add>
<add> var options = element.find('option');
<add> expect(options.length).toEqual(1);
<add> expect(sortedHtml(options[0])).toEqual('<option value="regularProperty">visible</option>');
<add> });
<ide>
<ide> describe('binding', function() {
<ide> | 2 |
Javascript | Javascript | remove unused constructor parameter | 6638549a7517387fe5ac8ec877c064808c709334 | <ide><path>src/controllers/controller.bubble.js
<ide> export default class BubbleController extends DatasetController {
<ide> }
<ide>
<ide> /**
<add> * @param {number} index
<add> * @param {string} [mode]
<ide> * @protected
<ide> */
<ide> resolveDataElementOptions(index, mode) {
<ide><path>src/core/core.element.js
<ide> export default class Element {
<ide>
<ide> static extend = inherits;
<ide>
<del> constructor(cfg) {
<add> constructor() {
<ide> this.x = undefined;
<ide> this.y = undefined;
<ide> this.active = false;
<ide> this.options = undefined;
<ide> this.$animations = undefined;
<del>
<del> if (cfg) {
<del> Object.assign(this, cfg);
<del> }
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | add description to i18n-routing | bb96fefa8019a593e62ba5e3a615879000c5f740 | <ide><path>docs/advanced-features/i18n-routing.md
<add>---
<add>description: Next.js has built-in support for internationalized routing and language detection. Learn more here.
<add>---
<add>
<ide> # Internationalized Routing
<ide>
<ide> <details> | 1 |
Javascript | Javascript | fix variable charges for force layout | 0a7af55aa9f156a8a62b478bb27eee71e09961f8 | <ide><path>d3.layout.js
<ide> d3.layout.force = function() {
<ide> nodes = [],
<ide> links = [],
<ide> distances,
<del> strengths;
<add> strengths,
<add> charges;
<ide>
<del> function repulse(node, kc) {
<add> function repulse(node) {
<ide> return function(quad, x1, y1, x2, y2) {
<ide> if (quad.point !== node) {
<ide> var dx = quad.cx - node.x,
<ide> d3.layout.force = function() {
<ide>
<ide> /* Barnes-Hut criterion. */
<ide> if ((x2 - x1) * dn < theta) {
<del> var k = kc * quad.count * dn * dn;
<add> var k = quad.charge * dn * dn;
<ide> node.px -= dx * k;
<ide> node.py -= dy * k;
<ide> return true;
<ide> }
<ide>
<ide> if (quad.point && isFinite(dn)) {
<del> var k = kc * dn * dn;
<add> var k = quad.pointCharge * dn * dn;
<ide> node.px -= dx * k;
<ide> node.py -= dy * k;
<ide> }
<ide> d3.layout.force = function() {
<ide> }
<ide>
<ide> // compute quadtree center of mass and apply charge forces
<del> if (k = alpha * charge) {
<del> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes));
<add> if (charge) {
<add> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
<ide> i = -1; while (++i < n) {
<ide> if (!(o = nodes[i]).fixed) {
<del> q.visit(repulse(o, k));
<add> q.visit(repulse(o));
<ide> }
<ide> }
<ide> }
<ide> d3.layout.force = function() {
<ide>
<ide> force.charge = function(x) {
<ide> if (!arguments.length) return charge;
<del> charge = x;
<add> charge = typeof x === "function" ? x : +x;
<ide> return force;
<ide> };
<ide>
<ide> d3.layout.force = function() {
<ide> if (isNaN(o.py)) o.py = o.y;
<ide> }
<ide>
<add> charges = [];
<add> if (typeof charge === "function") {
<add> for (i = 0; i < n; ++i) {
<add> charges[i] = +charge.call(this, nodes[i], i);
<add> }
<add> } else {
<add> for (i = 0; i < n; ++i) {
<add> charges[i] = charge;
<add> }
<add> }
<add>
<ide> // initialize node position based on first neighbor
<ide> function position(dimension, size) {
<ide> var neighbors = neighbor(i),
<ide> function d3_layout_forceDrag() {
<ide> d3_layout_forceDragForce.resume(); // restart annealing
<ide> }
<ide>
<del>function d3_layout_forceAccumulate(quad) {
<add>function d3_layout_forceAccumulate(quad, alpha, charges) {
<ide> var cx = 0,
<ide> cy = 0;
<del> quad.count = 0;
<add> quad.charge = 0;
<ide> if (!quad.leaf) {
<ide> var nodes = quad.nodes,
<ide> n = nodes.length,
<ide> function d3_layout_forceAccumulate(quad) {
<ide> while (++i < n) {
<ide> c = nodes[i];
<ide> if (c == null) continue;
<del> d3_layout_forceAccumulate(c);
<del> quad.count += c.count;
<del> cx += c.count * c.cx;
<del> cy += c.count * c.cy;
<add> d3_layout_forceAccumulate(c, alpha, charges);
<add> quad.charge += c.charge;
<add> cx += c.charge * c.cx;
<add> cy += c.charge * c.cy;
<ide> }
<ide> }
<ide> if (quad.point) {
<ide> function d3_layout_forceAccumulate(quad) {
<ide> quad.point.x += Math.random() - .5;
<ide> quad.point.y += Math.random() - .5;
<ide> }
<del> quad.count++;
<del> cx += quad.point.x;
<del> cy += quad.point.y;
<add> var k = alpha * charges[quad.point.index];
<add> quad.charge += quad.pointCharge = k;
<add> cx += k * quad.point.x;
<add> cy += k * quad.point.y;
<ide> }
<del> quad.cx = cx / quad.count;
<del> quad.cy = cy / quad.count;
<add> quad.cx = cx / quad.charge;
<add> quad.cy = cy / quad.charge;
<ide> }
<ide>
<ide> function d3_layout_forceLinkDistance(link) {
<ide><path>d3.layout.min.js
<del>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children,c;return b&&(c=b.length)?R(b[c-1]):a}function Q(a){var b=a.children;return b&&b.length?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b&&b.length?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a){var b=0,c=0;a.count=0;if(!a.leaf){var d=a.nodes,e=d.length,f=-1,g;while(++f<e){g=d[f];if(g==null)continue;k(g),a.count+=g.count,b+=g.count*g.cx,c+=g.count*g.cy}}a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function B(b){g(f=b),e=a}function A(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(l=n*r){k(e=d3.geom.quadtree(v)),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(z(g,l))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function z(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<t){var k=b*c.count*j*j;a.px-=h*k,a.py-=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.px-=h*k,a.py-=i*k}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);return a.resume()},a.resume=function(){n=.1,d3.timer(A);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",B).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){var c=a.children;c&&c.length?(a.x=P(c),a.y=O(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})()
<ide>\ No newline at end of file
<add>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children,c;return b&&(c=b.length)?R(b[c-1]):a}function Q(a){var b=a.children;return b&&b.length?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b&&b.length?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function C(b){g(f=b),e=a}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;a.px-=g*j,a.py-=h*j;return!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=typeof b=="function"?b:+b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){n=.1,d3.timer(B);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){var c=a.children;c&&c.length?(a.x=P(c),a.y=O(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})()
<ide>\ No newline at end of file
<ide><path>src/layout/force.js
<ide> d3.layout.force = function() {
<ide>
<ide> /* Barnes-Hut criterion. */
<ide> if ((x2 - x1) * dn < theta) {
<del> var k = alpha * quad.count * dn * dn;
<add> var k = quad.charge * dn * dn;
<ide> node.px -= dx * k;
<ide> node.py -= dy * k;
<ide> return true;
<ide> }
<ide>
<ide> if (quad.point && isFinite(dn)) {
<del> var k = kc * dn * dn;
<add> var k = quad.pointCharge * dn * dn;
<ide> node.px -= dx * k;
<ide> node.py -= dy * k;
<ide> }
<ide> d3.layout.force = function() {
<ide> }
<ide>
<ide> // compute quadtree center of mass and apply charge forces
<del> if (charge && alpha) {
<del> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), charges);
<add> if (charge) {
<add> d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
<ide> i = -1; while (++i < n) {
<ide> if (!(o = nodes[i]).fixed) {
<ide> q.visit(repulse(o));
<ide> d3.layout.force = function() {
<ide> };
<ide>
<ide> force.charge = function(x) {
<del> charge = typeof x === function ? x : +x;
<add> if (!arguments.length) return charge;
<add> charge = typeof x === "function" ? x : +x;
<ide> return force;
<ide> };
<ide>
<ide> d3.layout.force = function() {
<ide> ++o.target.weight;
<ide> }
<ide>
<del> charges = [];
<ide> for (i = 0; i < n; ++i) {
<ide> o = nodes[i];
<ide> if (isNaN(o.x)) o.x = position("x", w);
<ide> if (isNaN(o.y)) o.y = position("y", h);
<ide> if (isNaN(o.px)) o.px = o.x;
<ide> if (isNaN(o.py)) o.py = o.y;
<ide> }
<add>
<add> charges = [];
<ide> if (typeof charge === "function") {
<ide> for (i = 0; i < n; ++i) {
<ide> charges[i] = +charge.call(this, nodes[i], i);
<ide> function d3_layout_forceDrag() {
<ide> d3_layout_forceDragForce.resume(); // restart annealing
<ide> }
<ide>
<del>function d3_layout_forceAccumulate(quad, charges) {
<add>function d3_layout_forceAccumulate(quad, alpha, charges) {
<ide> var cx = 0,
<ide> cy = 0;
<del> quad.count = 0;
<add> quad.charge = 0;
<ide> if (!quad.leaf) {
<ide> var nodes = quad.nodes,
<ide> n = nodes.length,
<ide> function d3_layout_forceAccumulate(quad, charges) {
<ide> while (++i < n) {
<ide> c = nodes[i];
<ide> if (c == null) continue;
<del> d3_layout_forceAccumulate(c, charges);
<del> quad.count += c.count;
<del> cx += c.count * c.cx;
<del> cy += c.count * c.cy;
<add> d3_layout_forceAccumulate(c, alpha, charges);
<add> quad.charge += c.charge;
<add> cx += c.charge * c.cx;
<add> cy += c.charge * c.cy;
<ide> }
<ide> }
<ide> if (quad.point) {
<ide> function d3_layout_forceAccumulate(quad, charges) {
<ide> quad.point.x += Math.random() - .5;
<ide> quad.point.y += Math.random() - .5;
<ide> }
<del> var k = charges[quad.point.index];
<del> quad.count += k;
<del> cx += k*quad.point.x;
<del> cy += k*quad.point.y;
<add> var k = alpha * charges[quad.point.index];
<add> quad.charge += quad.pointCharge = k;
<add> cx += k * quad.point.x;
<add> cy += k * quad.point.y;
<ide> }
<del> quad.cx = cx / quad.count;
<del> quad.cy = cy / quad.count;
<add> quad.cx = cx / quad.charge;
<add> quad.cy = cy / quad.charge;
<ide> }
<ide>
<ide> function d3_layout_forceLinkDistance(link) { | 3 |
PHP | PHP | ignore tablespaces in dump | e5bfb69708085fef4e48250e3c264df2865198e9 | <ide><path>src/Illuminate/Database/Schema/MySqlSchemaState.php
<ide> public function load($path)
<ide> */
<ide> protected function baseDumpCommand()
<ide> {
<del> $command = 'mysqldump '.$this->connectionString().' --skip-add-locks --skip-comments --skip-set-charset --tz-utc';
<add> $command = 'mysqldump '.$this->connectionString().' --no-tablespaces --skip-add-locks --skip-comments --skip-set-charset --tz-utc';
<ide>
<ide> if (! $this->connection->isMaria()) {
<ide> $command .= ' --column-statistics=0 --set-gtid-purged=OFF'; | 1 |
Javascript | Javascript | try ios 11.2 | 0b1adbb2e7bd47845aab92fd77d02c8e37cba091 | <ide><path>karma-shared.conf.js
<ide> module.exports = function(config, specificOptions) {
<ide> 'SL_iOS_11': {
<ide> base: 'SauceLabs',
<ide> browserName: 'iphone',
<del> version: '11.3'
<add> platform: 'OS X 10.12',
<add> version: '11.2'
<ide> },
<ide>
<ide> 'BS_Chrome': { | 1 |
Javascript | Javascript | fix global leak | 5a21138e37e016c044eeb7d53ffa0ac77a5e71a1 | <ide><path>src/node.js
<ide> // check if the file exists and is not a directory
<ide> var tryFile = function(requestPath) {
<ide> try {
<del> stats = fs.statSync(requestPath);
<add> var stats = fs.statSync(requestPath);
<ide> if (stats && !stats.isDirectory()) {
<ide> return requestPath;
<ide> } | 1 |
Text | Text | fix typos in models/slim/readme.md (#904) | f88eef947cc99aee82d60c50fce4d46ac1166572 | <ide><path>slim/README.md
<ide> See
<ide>
<ide> #### The ResNet and VGG Models have 1000 classes but the ImageNet dataset has 1001
<ide>
<del>The ImageNet dataset provied has an empty background class which was can be used
<add>The ImageNet dataset provided has an empty background class which can be used
<ide> to fine-tune the model to other tasks. If you try training or fine-tuning the
<ide> VGG or ResNet models using the ImageNet dataset, you might encounter the
<ide> following error: | 1 |
Python | Python | add ability to connect a neptune.ai run | 6f3c99acca30efa34e9222dbbec87218c6c07724 | <ide><path>src/transformers/integrations.py
<ide> def setup(self, args, state, model):
<ide> api_token=os.getenv("NEPTUNE_API_TOKEN"),
<ide> mode=os.getenv("NEPTUNE_CONNECTION_MODE", "async"),
<ide> name=os.getenv("NEPTUNE_RUN_NAME", None),
<add> run=os.getenv("NEPTUNE_RUN_ID", None),
<ide> )
<ide> combined_dict = args.to_dict()
<ide> if hasattr(model, "config") and model.config is not None: | 1 |
Java | Java | avoid unnecessary call to get message type | 4e4145ac27d15a8078c1f1b468b5fd61ec332d21 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java
<ide> /*
<del> * Copyright 2002-2018 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 void stopInternal() {
<ide> @Override
<ide> protected void handleMessageInternal(Message<?> message) {
<ide> MessageHeaders headers = message.getHeaders();
<del> SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
<ide> String destination = SimpMessageHeaderAccessor.getDestination(headers);
<ide> String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
<ide>
<ide> protected void handleMessageInternal(Message<?> message) {
<ide> return;
<ide> }
<ide>
<add> SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
<ide> if (SimpMessageType.MESSAGE.equals(messageType)) {
<ide> logMessage(message);
<ide> sendMessageToSubscribers(destination, message); | 1 |
Text | Text | add article on automated accessibility tools | 558cdc000a547d77bfa5023bea4613d8eae42821 | <ide><path>guide/english/accessibility/automated-testing/index.md
<ide> title: Automated Accessibility Testing Tools
<ide> ---
<ide> ## Automated Accessibility Testing
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/accessibility/automated-testing/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>Automated Accessibility Testing Tools provide you with a way to test your application or website for common accessibility issues. They also help you meet accessibility guidelines. These tools are also called Web Accessibility Evaluation tools. With these tools you can test your entire codebase as a whole. This is much easier and less time-consuming than using manual tools which require you to check every page individually.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>### What Are They Testing For?
<add>They are testing to see if your content follows established guidelines such as Section 508 Compliance, Web Content Accessibility Guidelines (WCAG), and the Americans with Disabilities Act (ADA).
<add>
<add>### How Do They Work?
<add>This depends on the tool you are using, and the language or framework that your codebase is written in. Many integrate with a testing suite.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<ide> #### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>[W3C List of Web Accessibility Tools](https://www.w3.org/WAI/ER/tools/)
<add>[W3C Guide to Selecting Accessibility Tools](https://www.w3.org/WAI/test-evaluate/tools/selecting/)
<add>[Comparing 3 Top Automated Accessibility Tools](https://medium.com/myplanet-musings/comparing-3-top-automated-accessibility-testing-tools-wave-tenon-io-and-google-lighthouse-d3897d7bb311) | 1 |
Ruby | Ruby | fix i18n of attributes with multi-digit indexes | cd619e97818110201d38e572c95ab7393bc70f4a | <ide><path>activemodel/lib/active_model/error.rb
<ide> def self.full_message(attribute, message, base_class) # :nodoc:
<ide> attribute = attribute.to_s
<ide>
<ide> if i18n_customize_full_message && base_class.respond_to?(:i18n_scope)
<del> attribute = attribute.remove(/\[\d\]/)
<add> attribute = attribute.remove(/\[\d+\]/)
<ide> parts = attribute.split(".")
<ide> attribute_name = parts.pop
<ide> namespace = parts.join("/") unless parts.empty?
<ide> def self.generate_message(attribute, type, base, options) # :nodoc:
<ide>
<ide> if base.class.respond_to?(:i18n_scope)
<ide> i18n_scope = base.class.i18n_scope.to_s
<del> attribute = attribute.to_s.remove(/\[\d\]/)
<add> attribute = attribute.to_s.remove(/\[\d+\]/)
<ide>
<ide> defaults = base.class.lookup_ancestors.flat_map do |klass|
<ide> [ :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
<ide><path>activemodel/test/cases/error_test.rb
<ide> def test_initialize
<ide> I18n.backend.store_translations(:en, activemodel: { errors: { models: { 'error_test/manager': {
<ide> attributes: { reports: { name: { presence: "must be present" } } } } } } })
<ide>
<del> error = ActiveModel::Error.new(Manager.new, :'reports[0].name', :presence)
<add> error = ActiveModel::Error.new(Manager.new, :'reports[123].name', :presence)
<ide>
<ide> assert_equal "must be present", error.message
<ide> end
<ide><path>activemodel/test/cases/validations/i18n_validation_test.rb
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_attribut
<ide> errors: { models: { 'person/contacts/addresses': { attributes: { street: { format: "%{message}" } } } } } })
<ide>
<ide> person = person_class.new
<del> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].street', "cannot be blank")
<del> assert_equal "Contacts/addresses country cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].country', "cannot be blank")
<add> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].street', "cannot be blank")
<add> assert_equal "Contacts/addresses country cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].country', "cannot be blank")
<ide> end
<ide>
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_model_format
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_model_fo
<ide> errors: { models: { 'person/contacts/addresses': { format: "%{message}" } } } })
<ide>
<ide> person = person_class.new
<del> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].street', "cannot be blank")
<del> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].country', "cannot be blank")
<add> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].street', "cannot be blank")
<add> assert_equal "cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].country', "cannot be blank")
<ide> end
<ide>
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_i18n_attribute_name
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_i18n_att
<ide> })
<ide>
<ide> person = person_class.new
<del> assert_equal "Contacts/addresses street cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].street', "cannot be blank")
<del> assert_equal "Country cannot be blank", person.errors.full_message(:'contacts[0]/addresses[0].country', "cannot be blank")
<add> assert_equal "Contacts/addresses street cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].street', "cannot be blank")
<add> assert_equal "Country cannot be blank", person.errors.full_message(:'contacts[0]/addresses[123].country', "cannot be blank")
<ide> end
<ide>
<ide> def test_errors_full_messages_with_indexed_deeply_nested_attributes_without_i18n_config | 3 |
PHP | PHP | remove comment bloat from view class | 42cff59a7d28e1066d94ee297ea779d7fcb9a2a0 | <ide><path>system/view.php
<ide> public function get()
<ide> {
<ide> static::$last = $this->view;
<ide>
<del> // -----------------------------------------------------
<ide> // Get the evaluated content of all of the sub-views.
<del> // -----------------------------------------------------
<ide> foreach ($this->data as &$data)
<ide> {
<ide> if ($data instanceof View or $data instanceof Response)
<ide> public function get()
<ide> }
<ide> }
<ide>
<del> // -----------------------------------------------------
<ide> // Extract the view data into the local scope.
<del> // -----------------------------------------------------
<ide> extract($this->data, EXTR_SKIP);
<ide>
<del> // -----------------------------------------------------
<del> // Start the output buffer so nothing escapes to the
<del> // browser. The response will be sent later.
<del> // -----------------------------------------------------
<ide> ob_start();
<ide>
<ide> $path = $this->find();
<ide>
<del> // -----------------------------------------------------
<del> // We include the view into the local scope within a
<del> // try / catch block to catch any exceptions that may
<del> // occur while the view is rendering.
<add> // We include the view into the local scope within a try / catch to catch any
<add> // exceptions that may occur while the view is rendering.
<ide> //
<del> // Otherwise, a white screen of death will be shown
<del> // if an exception occurs while rendering the view.
<del> // -----------------------------------------------------
<add> // Otherwise, a white screen of death will be shown if an exception occurs
<add> // while rendering the view.
<ide> try
<ide> {
<ide> include $path; | 1 |
Text | Text | add a webpacker guide [ci skip] | 59009c29309be68de1e53a3c0cfec63cd895eb48 | <ide><path>guides/source/webpacker.md
<add>Webpacker
<add>=========
<add>
<add>This guide will show you how to install and use Webpacker to package JavaScript, CSS, and other assets for the client-side of your Rails application.
<add>
<add>After reading this guide, you will know:
<add>
<add>* What Webpacker does and why it is different from Sprockets.
<add>* How to install Webpacker and integrate it with your framework of choice.
<add>* How to use Webpacker for JavaScript assets.
<add>* How to use Webpacker for CSS assets.
<add>* How to use Webpacker for static assets.
<add>* How to deploy a site that uses Webpacker.
<add>* How to use Webpacker in alternate Rails contexts, such as engines or Docker containers.
<add>
<add>--------------------------------------------------------------
<add>
<add>What Is Webpacker?
<add>------------------
<add>
<add>Webpacker is a Rails wrapper around the [webpack](https://webpack.js.org) build system that provides a standard webpack configuration and reasonable defaults.
<add>
<add>### What is webpack?
<add>
<add>The goal of webpack, or any front-end build system, is to allow you to write your front-end code in a way that is convenient for developers and then package that code in a way that is convenient for browsers. With webpack, you can manage JavaScript, CSS, and static assets like files or fonts. Webpack will allow you to write your code, reference other code in your application, transform you code, and combine your code into easily downloadable packs.
<add>
<add>See the [webpack documentation](https://webpack.js.org) for information.
<add>### How is Webpacker Different from Sprockets?
<add>
<add>Rails also ships with Sprockets, an asset-packaging tool whose features overlap with Webpacker. Both tools will compile your JavaScript into into browser-friendly files, and minify and fingerprint them in production. Both tools allow you to incrementally change files in development.
<add>
<add>Sprockets, which was designed to be used with Rails, is somewhat simpler to integrate. In particular, code can be added to Sprockets via a Ruby gem. However, webpack is better at integrating with more current JavaScript tools and NPM packages, and allows for a wider range of integration. It is the current practice of Basecamp to use webpack for JavaScript and Sprockets for CSS, although you can do CSS in webpack.
<add>
<add>You should choose webpacker over Sprockets on a new project, if you want to use NPM packages, and if you want access to the most current JavaScript features and tools. You should choose Sprockets over Webpacker for legacy applications where migration might be costly, if you want to integrate using Gems, or if you have a very small amount of code to package.
<add>
<add>If you are familiar with Sprockets, the following guide might give you some idea of how to translate. Please note that each tool has a slightly different structure, and the concepts don't directly map onto each other
<add>
<add>|Task | Sprockets | Webpacker |
<add>|------------------|-------------------|-------------------|
<add>|Attach JavaScript |javascript_link_tag|javascript_pack_tag|
<add>|Attach CSS |stylesheet_link_tag|stylesheet_pack_tag|
<add>|Link to an image |image_url |image_pack_tag |
<add>|Link to an asset |asset_url |asset_pack_tag |
<add>|Require a script |//= require |import or require |
<add>
<add>Installing Webpacker
<add>--------------------
<add>
<add>To use Webpacker, you must install the Yarn package manager, version 1.x or up, and you must have Node.js installed, version 10.13.0 and up.
<add>
<add>NOTE: Webpacker depends on NPM and Yarn. NPM, the Node package manager registry, is the primary repository for publishing and downloading open source JavaScript projects, both for Node.js and browser runtimes. It is analogous to rubygems.org for Ruby gems. Yarn is a command line utility that enables installation and management of JavaScript dependencies, much like Bundler does for Ruby.
<add>
<add>Webpacker is installed by default in Rails 6.0 and up. In an older version, you can install it when a new project is created by adding `--webpack` to a `rails new` command. In an existing project, webpacker can be added by installing `bundle exec rails webpacker:install`. This installation command creates local files:
<add>
<add>|File |Location |Explanation |
<add>|------------------------|------------------------|------------------------------------------------------------|
<add>|Javascript Folder | `app/javascript` |A place for your front-end source |
<add>|Webpacker Configuration | `config/webpacker.yml` |Configure the Webpacker gem |
<add>|Babel Configuration | `babel.config.js` |Configuration for the https://babeljs.io JavaScript Compiler|
<add>|PostCSS Configuration | `postcss.config.js` |Configuration for the https://postcss.org CSS Post-Processor|
<add>|Browserlist | `.browserslistrc` |https://github.com/browserslist/browserslist |
<add>
<add>
<add>The installation also calls the `yarn` package manager, creates a `package.json` file with a basic set of packages listed, and uses Yarn to install these dependencies.
<add>
<add>### Integrating Frameworks with Webpacker
<add>
<add>Webpacker also contains support for many popular JavaScript frameworks and tools. Typically, these are installed either when the application is created with something like `rails new myapp --webpack=<framework_name>` or with a separate command line task, like `rails webpacker:install:<framework_name>`.
<add>
<add>These integrations typically install the set of NPM packages needed to get started with the framework or tool, a "hello world" page to show that it works, and any other webpack loaders or transformations needed to compile the tool. The supported frameworks and tools are:
<add>
<add>INFO. It's possible to install frameworks not included in this list. These are basic integrations of popular choices.
<add>
<add>|Framework |Install command |Description |
<add>|------------------|------------------------------------|--------------------------------------------------|
<add>|Angular |`rails webpacker:install:angular` |Sets up Angular and Typescript |
<add>|CoffeeScript |`rails webpacker:install:coffee` |Sets up CoffeeScript |
<add>|Elm |`rails webpacker:install:elm` |Sets up Elm |
<add>|ERB |`rails webpacker:install:erb` |Sets up ERB support on your Javascript files |
<add>|React |`rails webpacker:install:react` |Sets up ReactJS |
<add>|Stimulus |`rails webpacker:install:stimulus` |Sets up StimulusJS |
<add>|Svelte |`rails webpacker:install:svelte` |Sets up Svelte JS |
<add>|TypeScript |`rails webpacker:install:typescript`|Sets up Typescript for your project using Babel's TypeScript support|
<add>|Vue |`rails webpacker:install:vue` |Sets up VueJS |
<add>
<add>For More information about the existing integrations, see https://github.com/rails/webpacker/blob/master/docs/integrations.md.
<add>
<add>Usage
<add>-----
<add>### Using Webpacker for JavaScript
<add>
<add>With Webpacker installed, by default any JavaScript file in the `app/javascripts/packs` directory will get compiled to its own pack file.
<add>
<add>So if you have a file called `app/javascript/packs/application.js`, Webpacker will create a pack called `application`, and you can add it to your Rails application with the code `<%= javascript_pack_tag "application" %>`. With that in place, in development, Rails will re-compile the `application.js` file every time it changes and you load a page that uses that pack. Typically, the file in the actual `packs` directory will be a manifest that mostly loads other files, but it can also have arbitrary JavaScript code.
<add>
<add>The default pack created for you by Webpacker will link to Rails default JavaScript packages if they have been included in the project:
<add>
<add>```
<add>require("@rails/ujs").start()
<add>require("turbolinks").start()
<add>require("@rails/activestorage").start()
<add>require("channels")
<add>```
<add>
<add>You'll need to include a pack that requires these packages to use them in your Rails application.
<add>
<add>It is important to note that only webpack entry files should be placed in the `app/javascript/packs` directory; webpack will create a separate dependency graph for each entry point so a large number of packs will increase compilation overhead. The rest of your asset source code should live outside this directory though Webpacker does not place any restrictions or make any suggestions on how to structure your source code. Here is an example:
<add>```sh
<add>app/javascript:
<add> ├── packs:
<add> │ # only webpack entry files here
<add> │ └── application.js
<add> │ └── application.css
<add> └── src:
<add> │ └── my_component.js
<add> └── stylesheets:
<add> │ └── my_styles.css
<add> └── images:
<add> └── logo.svg
<add>```
<add>
<add>Typically the pack file itself is largely a manifest that uses `import` or `require` to load the necessary files and may also do some initialization.
<add>
<add>If you want to change these directories, you can adjust the `source_path` (default `app/javascript`) and `source_entry_path` (default `packs`) in the `configuration/webpacker.yml` file.
<add>
<add>Within source files, `import` statements are resolved relative to the file doing the import, so `import Bar from "./foo"` finds a `foo.js` file in the same directory as the current file, while `import Bar from "../src/foo"` finds a file in a sibling directory named `src`.
<add>
<add>### Using Webpacker for CSS
<add>
<add>Out of the box, Webpacker supports CSS and SCSS using the PostCSS processor.
<add>
<add>To include CSS code in your packs, first include your CSS files in your top level pack file as though it was a JavaScript file. So if your CSS top-level manifest is in `app/javascript/styles/styles.scss`, you can import it with `import styles/styles`. This tells webpack to include your CSS file in the download. To actually load it in the page, you need to include a `<stylesheet_pack_tag "application">`, where the `application` is the same pack name that you were using. (Note, the docs still say you need to use `stylesheet_pack_tag`, but experimenting suggests that the CSS will load without it.)
<add>
<add>If you are using a CSS framework, you can add it to Webpacker by following the instructions to load the framework as an NPM module using `yarn`, typically `yarn add <framework>`. The framework should have instructions on importing it into a CSS or SCSS file.
<add>
<add>
<add>### Using Webpacker for Static Assets
<add>
<add>The default Webpacker [configuration](https://github.com/rails/webpacker/blob/master/lib/install/config/webpacker.yml#L21) should work out of the box for static assets.
<add>The configuration includes a number of image and font file format extentions, allowing Webpack to include them in the generated `manifest.json` file.
<add>
<add>With webpack, static assets can be imported directly in JavaScript files. The imported value represents the url to the asset. For example:
<add>
<add>```javascript
<add>import myImageUrl from '../images/my-image.jpg'
<add>
<add>// ...
<add>let myImage = new Image();
<add>myImage.src = myImageUrl;
<add>myImage.alt = "I'm a Webpacker-bundled image";
<add>document.body.appendChild(myImage);
<add>```
<add>
<add>To reference Webpacker static assets from a Rails view, the assets need to be explicitly required from Webpacker-bundled JavaScript files. Unlike Sprockets, Webpacker does not import your static assets by default. The default `app/javascript/packs/application.js` file has a template for importing files from a given directory, which you can uncomment for every directory you want to have static files in. The directories are relative to `app/javascript`. The template uses the directory `images`, but you can use anything in `app/javascript`:
<add>
<add>```
<add>const images = require.context("../images", true)
<add>const imagePath = name => images(name, true)
<add>```
<add>
<add>Static assets will be output into a directory under `public/packs/media`. For example, an image located and imported at `app/javascript/images/my-image.jpg` will be output at `public/packs/media/images/my-image-abcd1234.jpg`. To render an image tag for this image in a Rails view, use `image_pack_tag 'media/images/my-image.jpg`.
<add>
<add>The Webpacker ActionView helpers for static assets correspond to asset pipeline helpers according to the following table:
<add>
<add>|ActionView helper | Webpacker helper |
<add>|------------------|------------------|
<add>|favicon_link_tag |favicon_pack_tag |
<add>|image_tag |image_pack_tag |
<add>
<add>Also the generic helper `asset_pack_path` takes the local location of a file and returns its webpacker location for use in Rails views.
<add>
<add>You can also access the image by directly referencing the file from a CSS file in `app/javascript`.
<add>
<add>### Webpacker in Rails Engines
<add>
<add>As of Webpacker version 5, Webpacker is not "engine-aware," which means Webpacker does not have feature-parity with Sprockets when it comes to use within Rails engines. The [Webpacker engine guides](https://github.com/rails/webpacker/blob/master/docs/engines.md) provide some detailed workarounds to add Webpacker-support and developing locally against an engine with Webpacker.
<add>
<add>Gem authors of Rails engines who wish to support consumers using Webpacker are encouraged to distribute frontend assets as an NPM package in addition to the gem itself and provide instructions (or an installer) to demonstrate how host apps should integrate. A good example of this approach is [Alchemy CMS](https://github.com/AlchemyCMS/alchemy_cms).
<add>
<add>### Hot module replacement
<add>
<add>Webpacker out-of-the-box supports HMR with webpack-dev-server and you can toggle it by setting dev_server/hmr option inside webpacker.yml.
<add>
<add>Checkout this guide for more information:
<add>
<add>https://webpack.js.org/configuration/dev-server/#devserver-hot
<add>To support HMR with React you would need to add react-hot-loader. Checkout this guide for more information:
<add>
<add>https://gaearon.github.io/react-hot-loader/getstarted/
<add>
<add>Don't forget to disable HMR if you are not running webpack-dev-server otherwise you will get not found error for stylesheets.
<add>
<add>Webpacker in Different Environments
<add>-----------------------------------
<add>
<add>Webpacker has three environments by default `development`, `test`, and `production`. You can add additional environment configurations in the `webpacker.yml` file and set different defaults for each environment, Webpacker will also load the file `config/webpack/<environment>.js` for additional environment setup.
<add>
<add>## Running Webpacker in Development
<add>
<add>Webpacker ships with two binstub files to run in development: `./bin/webpack` and `./bin/webpack-dev-server`. Both are thin wrappers around the standard `webpack.js` and `webpack-dev-server.js` executables and ensure that the right configuration files and environmental variables are loaded based on your environment.
<add>
<add>By default, Webpacker compiles automatically on demand in development when a Rails page loads. You can change this by changing to `compile: false` in the `config/webpacker.yml` file. This means that you don't have to run any separate processes. Compilation errors are logged to the standard Rails log. You can, however, run `bin/webpack` to force compilation of your packs.
<add>
<add>If you want to use live code reloading, or you have enough JavaScript that on-demand compilation is too slow, you'll need to run `./bin/webpack-dev-server` or `ruby ./bin/webpack-dev-server`. This process will watch for changes in the `app/javascript/packs/*.js` files and automatically recompile and reload the browser to match.
<add>
<add>Windows users will need to run these commands in a terminal separate from `bundle exec rails s`.
<add>
<add>Once you start this development server, Webpacker will automatically start proxying all webpack asset requests to this server. When you stop the server, it'll revert back to on-demand compilation.
<add>
<add>The Webpacker [Documentation](https://github.com/rails/webpacker) gives information on environment variables you can use to control `webpack-dev-server`. See additional notes in the [rails/webpacker docs on the webpack-dev-server usage](https://github.com/rails/webpacker/blob/master/docs/webpack-dev-server.md).
<add>
<add>### Deploying Webpacker
<add>
<add>Webpacker adds a `Webpacker:compile` task to the `assets:precompile` rake task, so any existing deploy pipeline that was using `assets:precompile` should work. The compile task will compile the packs and place them in `public/packs`.
<add>
<add>Additional Documentation
<add>------------------------
<add>
<add>For more information on advanced topics, such as using Webpacker with popular frameworks, consult the [Webpacker Documentation](https://github.com/rails/webpacker). | 1 |
Javascript | Javascript | change ios fontfamily example | 54bbe1b6ea45ed0d80b887e52dce15a9d9c431f3 | <ide><path>RNTester/js/examples/TextInput/TextInputExample.ios.js
<ide> exports.examples = [
<ide> return (
<ide> <View>
<ide> <TextInput
<del> style={[styles.default, {fontFamily: 'sans-serif'}]}
<del> placeholder="Custom fonts like Sans-Serif are supported"
<add> style={[styles.default, {fontFamily: 'Cochin'}]}
<add> placeholder="Custom fonts like Cochin are supported"
<ide> />
<ide> <TextInput
<del> style={[
<del> styles.default,
<del> {fontFamily: 'sans-serif', fontWeight: 'bold'},
<del> ]}
<del> placeholder="Sans-Serif bold"
<add> style={[styles.default, {fontFamily: 'Cochin', fontWeight: 'bold'}]}
<add> placeholder="Cochin bold"
<ide> />
<ide> <TextInput
<del> style={[
<del> styles.default,
<del> {fontFamily: 'sans-serif', fontWeight: '500'},
<del> ]}
<del> placeholder="Sans-Serif 500"
<add> style={[styles.default, {fontFamily: 'Cochin', fontWeight: '500'}]}
<add> placeholder="Cochin 500"
<ide> />
<ide> <TextInput
<ide> style={[
<ide> styles.default,
<del> {fontFamily: 'sans-serif', fontStyle: 'italic'},
<add> {fontFamily: 'Cochin', fontStyle: 'italic'},
<ide> ]}
<del> placeholder="Sans-Serif italic"
<add> placeholder="Cochin italic"
<ide> />
<ide> <TextInput
<del> style={[styles.default, {fontFamily: 'serif'}]}
<del> placeholder="Serif"
<add> style={[styles.default, {fontFamily: 'Courier'}]}
<add> placeholder="Courier"
<ide> />
<ide> </View>
<ide> ); | 1 |
Javascript | Javascript | use common.mustcall(), and log the events | b52a8f3507a6df179d0cf2144c88173607926241 | <ide><path>test/parallel/test-tls-set-encoding.js
<ide> const messageUtf8 = 'x√ab c';
<ide> const messageAscii = 'xb\b\u001aab c';
<ide>
<ide> const server = tls.Server(options, common.mustCall(function(socket) {
<add> console.log('server: on secureConnection', socket.getProtocol());
<ide> socket.end(messageUtf8);
<ide> }));
<ide>
<ide> server.listen(0, function() {
<ide> client.setEncoding('ascii');
<ide>
<ide> client.on('data', function(d) {
<add> console.log('client: on data', d);
<ide> assert.ok(typeof d === 'string');
<ide> buffer += d;
<ide> });
<ide>
<add> client.on('secureConnect', common.mustCall(() => {
<add> console.log('client: on secureConnect');
<add> }));
<add>
<add> client.on('close', common.mustCall(function() {
<add> console.log('client: on close');
<ide>
<del> client.on('close', function() {
<ide> // readyState is deprecated but we want to make
<ide> // sure this isn't triggering an assert in lib/net.js
<ide> // See https://github.com/nodejs/node-v0.x-archive/issues/1069.
<ide> server.listen(0, function() {
<ide> assert.strictEqual(messageAscii, buffer);
<ide>
<ide> server.close();
<del> });
<add> }));
<ide> }); | 1 |
Go | Go | fix empty-lines (revive) | cd381aea5688e2913ba33ce3607e48d5eb49c1d3 | <ide><path>libnetwork/agent.go
<ide> func (c *controller) handleNodeTableEvent(ev events.Event) {
<ide> return
<ide> }
<ide> c.processNodeDiscovery([]net.IP{nodeAddr.Addr}, isAdd)
<del>
<ide> }
<ide>
<ide> func (c *controller) handleEpTableEvent(ev events.Event) {
<ide><path>libnetwork/bitseq/sequence.go
<ide> func (h *Handle) Destroy() error {
<ide>
<ide> // ToByteArray converts this handle's data into a byte array
<ide> func (h *Handle) ToByteArray() ([]byte, error) {
<del>
<ide> h.Lock()
<ide> defer h.Unlock()
<ide> ba := make([]byte, 16)
<ide><path>libnetwork/controller.go
<ide> func (c *controller) NewNetwork(networkType, name string, id string, options ...
<ide>
<ide> if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope {
<ide> return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
<del>
<ide> }
<ide> if network.ingress && cap.DataScope != datastore.GlobalScope {
<ide> return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
<ide><path>libnetwork/datastore/datastore_test.go
<ide> func TestAtomicKVObjectFlatKey(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<ide> }
<ide>
<ide> // dummy data used to test the datastore
<ide><path>libnetwork/datastore/mock_store.go
<ide> func (s *MockStore) Get(key string) (*store.KVPair, error) {
<ide> return nil, nil
<ide> }
<ide> return &store.KVPair{Value: mData.Data, LastIndex: mData.Index}, nil
<del>
<ide> }
<ide>
<ide> // Put a value at "key"
<ide><path>libnetwork/default_gateway.go
<ide> var procGwNetwork = make(chan (bool), 1)
<ide> */
<ide>
<ide> func (sb *sandbox) setupDefaultGW() error {
<del>
<ide> // check if the container already has a GW endpoint
<ide> if ep := sb.getEndpointInGWNetwork(); ep != nil {
<ide> return nil
<ide><path>libnetwork/drivers/bridge/bridge.go
<ide> func (d *driver) createNetwork(config *networkConfiguration) (err error) {
<ide> }
<ide>
<ide> func (d *driver) DeleteNetwork(nid string) error {
<del>
<ide> d.configNetwork.Lock()
<ide> defer d.configNetwork.Unlock()
<ide>
<ide><path>libnetwork/drivers/bridge/link.go
<ide> func newLink(parentIP, childIP string, ports []types.TransportPort, bridge strin
<ide> ports: ports,
<ide> bridge: bridge,
<ide> }
<del>
<ide> }
<ide>
<ide> func (l *link) Enable() error {
<ide><path>libnetwork/drivers/bridge/port_mapping.go
<ide> func (n *bridgeNetwork) allocatePortsInternal(bindings []types.PortBinding, cont
<ide> // validatePortBindingIPv4 validates the port binding, populates the missing Host IP field and returns true
<ide> // if this is a valid IPv4 binding, else returns false
<ide> func (n *bridgeNetwork) validatePortBindingIPv4(bnd *types.PortBinding, containerIPv4, defHostIP net.IP) bool {
<del> //Return early if there is a valid Host IP, but its not a IPv4 address
<add> // Return early if there is a valid Host IP, but its not a IPv4 address
<ide> if len(bnd.HostIP) > 0 && bnd.HostIP.To4() == nil {
<ide> return false
<ide> }
<ide> func (n *bridgeNetwork) validatePortBindingIPv4(bnd *types.PortBinding, containe
<ide> }
<ide> bnd.IP = containerIPv4
<ide> return true
<del>
<ide> }
<ide>
<ide> // validatePortBindingIPv6 validates the port binding, populates the missing Host IP field and returns true
<ide><path>libnetwork/drivers/bridge/setup_ip_tables.go
<ide> func removeIPChains(version iptables.IPVersion) {
<ide> {Name: IsolationChain2, Table: iptables.Filter, IPTable: ipt},
<ide> {Name: oldIsolationChain, Table: iptables.Filter, IPTable: ipt},
<ide> } {
<del>
<ide> if err := chainInfo.Remove(); err != nil {
<ide> logrus.Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
<ide> }
<ide><path>libnetwork/drivers/bridge/setup_ipv6_test.go
<ide> func TestSetupIPv6(t *testing.T) {
<ide> if !found {
<ide> t.Fatalf("Bridge device does not have requested IPv6 address %v", bridgeIPv6)
<ide> }
<del>
<ide> }
<ide>
<ide> func TestSetupGatewayIPv6(t *testing.T) {
<ide><path>libnetwork/drivers/macvlan/macvlan_store.go
<ide> func (d *driver) initStore(option map[string]interface{}) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<ide> }
<ide>
<ide> return nil
<ide><path>libnetwork/drivers/overlay/encryption.go
<ide> import (
<ide> "fmt"
<ide> "hash/fnv"
<ide> "net"
<add> "strconv"
<ide> "sync"
<ide> "syscall"
<ide>
<del> "strconv"
<del>
<ide> "github.com/docker/docker/libnetwork/drivers/overlay/overlayutils"
<ide> "github.com/docker/docker/libnetwork/iptables"
<ide> "github.com/docker/docker/libnetwork/ns"
<ide> func (e *encrMap) String() string {
<ide> b.WriteString(",")
<ide> }
<ide> b.WriteString("]")
<del>
<ide> }
<ide> return b.String()
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_network.go
<ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) erro
<ide> }
<ide>
<ide> func (n *network) setupSubnetSandbox(s *subnet, brName, vxlanName string) error {
<del>
<ide> if hostMode {
<ide> // Try to delete stale bridge interface if it exists
<ide> if err := deleteInterface(brName); err != nil {
<ide> func (n *network) releaseVxlanID() ([]uint32, error) {
<ide> }
<ide>
<ide> func (n *network) obtainVxlanID(s *subnet) error {
<del> //return if the subnet already has a vxlan id assigned
<add> // return if the subnet already has a vxlan id assigned
<ide> if n.vxlanID(s) != 0 {
<ide> return nil
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_serf.go
<ide> func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.I
<ide> }
<ide> }
<ide>
<del>func (d *driver) startSerfLoop(eventCh chan serf.Event, notifyCh chan ovNotify,
<del> exitCh chan chan struct{}) {
<del>
<add>func (d *driver) startSerfLoop(eventCh chan serf.Event, notifyCh chan ovNotify, exitCh chan chan struct{}) {
<ide> for {
<ide> select {
<ide> case notify, ok := <-notifyCh:
<ide><path>libnetwork/drivers/overlay/ov_utils.go
<ide> func deleteInterfaceBySubnet(brPrefix string, s *subnet) error {
<ide> }
<ide> }
<ide> return nil
<del>
<ide> }
<ide>
<ide> func deleteInterface(name string) error {
<ide><path>libnetwork/drivers/overlay/overlay.go
<ide> func Fini(drv driverapi.Driver) {
<ide> }
<ide>
<ide> func (d *driver) configure() error {
<del>
<ide> // Apply OS specific kernel configs if needed
<ide> d.initOS.Do(applyOStweaks)
<ide>
<ide><path>libnetwork/drivers/overlay/peerdb.go
<ide> func (d *driver) peerDbSearch(nid string, peerIP net.IP) (*peerKey, *peerEntry,
<ide> return pKeyMatched, pEntryMatched, nil
<ide> }
<ide>
<del>func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<del> peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) {
<del>
<add>func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) {
<ide> d.peerDb.Lock()
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask
<ide> return b, i
<ide> }
<ide>
<del>func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<del> peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) {
<del>
<add>func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) {
<ide> d.peerDb.Lock()
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<ide> }
<ide> }
<ide>
<del>func (d *driver) peerAddOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<del> peerMac net.HardwareAddr, vtep net.IP, l2Miss, l3Miss, updateDB, localPeer bool) error {
<del>
<add>func (d *driver) peerAddOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, peerMac net.HardwareAddr, vtep net.IP, l2Miss, l3Miss, updateDB, localPeer bool) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> }
<ide> func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMas
<ide> }
<ide> }
<ide>
<del>func (d *driver) peerDeleteOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<del> peerMac net.HardwareAddr, vtep net.IP, localPeer bool) error {
<del>
<add>func (d *driver) peerDeleteOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, peerMac net.HardwareAddr, vtep net.IP, localPeer bool) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> }
<ide><path>libnetwork/endpoint.go
<ide> func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
<ide> tplist = append(tplist, tp)
<ide> }
<ide> ep.generic[netlabel.ExposedPorts] = tplist
<del>
<ide> }
<ide> }
<ide>
<ide> func (ep *endpoint) sbJoin(sb *sandbox, options ...EndpointOption) (err error) {
<ide> ep.Name(), ep.ID(), err)
<ide> }
<ide> }
<del>
<ide> }
<ide>
<ide> if !sb.needDefaultGW() {
<ide><path>libnetwork/errors_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestErrorInterfaces(t *testing.T) {
<del>
<ide> badRequestErrorList := []error{ErrInvalidID(""), ErrInvalidName(""), ErrInvalidJoin{}, ErrInvalidNetworkDriver(""), InvalidContainerIDError(""), ErrNoSuchNetwork(""), ErrNoSuchEndpoint("")}
<ide> for _, err := range badRequestErrorList {
<ide> switch u := err.(type) {
<ide> func TestErrorInterfaces(t *testing.T) {
<ide> t.Fatalf("Failed to detect err %v is of type ForbiddenError. Got type: %T", err, u)
<ide> }
<ide> }
<del>
<ide> }
<ide><path>libnetwork/etchosts/etchosts_test.go
<ide> func TestUpdateIgnoresPrefixedHostname(t *testing.T) {
<ide> if expected := "5.5.5.5\tprefix\n3.3.3.3\tprefixAndMore\n4.4.4.4\tunaffectedHost\n"; !bytes.Contains(content, []byte(expected)) {
<ide> t.Fatalf("Expected to find '%s' got '%s'", expected, content)
<ide> }
<del>
<ide> }
<ide>
<ide> // This regression test covers the host prefix issue for the
<ide><path>libnetwork/ipam/allocator_test.go
<ide> func TestOverlappingRequests(t *testing.T) {
<ide> }
<ide>
<ide> func TestUnusualSubnets(t *testing.T) {
<del>
<ide> subnet := "192.168.0.2/31"
<ide>
<ide> outsideTheRangeAddresses := []struct {
<ide> func TestUnusualSubnets(t *testing.T) {
<ide> }
<ide>
<ide> for _, store := range []bool{false, true} {
<del>
<ide> allocator, err := getAllocator(store)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestUnusualSubnets(t *testing.T) {
<ide> if err != ipamapi.ErrNoAvailableIPs {
<ide> t.Fatal("Did not get expected error when pool is exhausted.")
<ide> }
<del>
<ide> }
<ide> }
<ide>
<ide> func benchmarkRequest(b *testing.B, a *Allocator, subnet string) {
<ide> }
<ide>
<ide> func BenchmarkRequest(b *testing.B) {
<del>
<ide> subnets := []string{
<ide> "10.0.0.0/24",
<ide> "10.0.0.0/16",
<ide><path>libnetwork/ipams/null/null_test.go
<ide> func TestOtherRequests(t *testing.T) {
<ide> if err == nil {
<ide> t.Fatal("Unexpected success")
<ide> }
<del>
<ide> }
<ide><path>libnetwork/iptables/firewalld.go
<ide> func getDockerZoneSettings() []interface{} {
<ide> description: "zone for docker bridge network interfaces",
<ide> target: "ACCEPT",
<ide> }
<del> slice := []interface{}{
<add> return []interface{}{
<ide> settings.version,
<ide> settings.name,
<ide> settings.description,
<ide> func getDockerZoneSettings() []interface{} {
<ide> settings.sourcePorts,
<ide> settings.icmpBlockInversion,
<ide> }
<del> return slice
<del>
<ide> }
<ide>
<ide> // setupDockerZone creates a zone called docker in firewalld which includes docker interfaces to allow
<ide><path>libnetwork/iptables/firewalld_test.go
<ide> func TestPassthrough(t *testing.T) {
<ide> t.Fatal("rule1 does not exist")
<ide> }
<ide> }
<del>
<ide> }
<ide><path>libnetwork/iptables/iptables.go
<ide> func (iptable IPTable) ProgramChain(c *ChainInfo, bridgeName string, hairpinMode
<ide> } else if len(output) != 0 {
<ide> return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
<ide> }
<del>
<ide> }
<ide> establish := []string{
<ide> "-o", bridgeName,
<ide> func (iptable IPTable) RemoveExistingChain(name string, table Table) error {
<ide>
<ide> // Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
<ide> func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
<del>
<ide> iptable := GetIptable(c.IPTable.Version)
<ide> daddr := ip.String()
<ide> if ip.IsUnspecified() {
<ide><path>libnetwork/libnetwork_internal_test.go
<ide> func TestAuxAddresses(t *testing.T) {
<ide> }
<ide>
<ide> for _, i := range input {
<del>
<ide> n.ipamV4Config = []*IpamConf{{PreferredPool: i.masterPool, SubPool: i.subPool, AuxAddresses: i.auxAddresses}}
<ide>
<ide> err = n.ipamAllocate()
<ide><path>libnetwork/libnetwork_test.go
<ide> func TestNetworkConfig(t *testing.T) {
<ide> if err := configNetwork.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<ide> }
<ide>
<ide> func TestUnknownNetwork(t *testing.T) {
<ide> func TestEndpointMultipleJoins(t *testing.T) {
<ide> if _, ok := err.(types.ForbiddenError); !ok {
<ide> t.Fatalf("Failed with unexpected error type: %T. Desc: %s", err, err.Error())
<ide> }
<del>
<ide> }
<ide>
<ide> func TestLeaveAll(t *testing.T) {
<ide><path>libnetwork/network.go
<ide> func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoi
<ide> defer n.ctrlr.networkLocker.Unlock(n.id) //nolint:errcheck
<ide>
<ide> return n.createEndpoint(name, options...)
<del>
<ide> }
<ide>
<ide> func (n *network) createEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
<ide> func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectT
<ide> }
<ide>
<ide> func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) {
<del>
<ide> ipamV4Config := make([]*IpamConf, len(ipV4Data))
<ide>
<ide> for i, data := range ipV4Data {
<ide> func (n *network) deleteLoadBalancerSandbox() error {
<ide> if err != nil {
<ide> logrus.Warnf("Failed to find load balancer endpoint %s on network %s: %v", endpointName, name, err)
<ide> } else {
<del>
<ide> info := endpoint.Info()
<ide> if info != nil {
<ide> sb := info.Sandbox()
<ide><path>libnetwork/networkdb/cluster.go
<ide> func (nDB *NetworkDB) retryJoin(ctx context.Context, members []string) {
<ide> return
<ide> }
<ide> }
<del>
<ide> }
<ide>
<ide> func (nDB *NetworkDB) clusterJoin(members []string) error {
<ide><path>libnetwork/osl/namespace_linux.go
<ide> func GenerateKey(containerID string) string {
<ide> index = tmpindex
<ide> tmpkey = id
<ide> }
<del>
<ide> }
<ide> }
<ide> containerID = tmpkey
<ide><path>libnetwork/osl/route_linux.go
<ide> func (n *networkNamespace) AddStaticRoute(r *types.StaticRoute) error {
<ide> }
<ide>
<ide> func (n *networkNamespace) RemoveStaticRoute(r *types.StaticRoute) error {
<del>
<ide> err := n.removeRoute(n.nsPath(), r.Destination, r.NextHop)
<ide> if err == nil {
<ide> n.Lock()
<ide><path>libnetwork/osl/sandbox_linux_test.go
<ide> func TestSetInterfaceIP(t *testing.T) {
<ide> }
<ide>
<ide> func TestLiveRestore(t *testing.T) {
<del>
<ide> defer testutils.SetupTestOSContext(t)()
<ide>
<ide> key, err := newKey(t)
<ide><path>libnetwork/resolver.go
<ide> func (r *resolver) handleSRVQuery(query *dns.Msg) (*dns.Msg, error) {
<ide> resp.Extra = append(resp.Extra, rr1)
<ide> }
<ide> return resp, nil
<del>
<ide> }
<ide>
<ide> func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) {
<ide><path>libnetwork/resolver_test.go
<ide> func TestDNSIPQuery(t *testing.T) {
<ide> t.Log("Response: ", resp.String())
<ide> checkDNSResponseCode(t, resp, dns.RcodeServerFailure)
<ide> w.ClearResponse()
<del>
<ide> }
<ide>
<ide> func newDNSHandlerServFailOnce(requests *int) func(w dns.ResponseWriter, r *dns.Msg) {
<ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
<ide> }
<ide>
<ide> for i := 0; i < len(reqName); i++ {
<del>
<ide> // First check for local container alias
<ide> ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
<ide> if ip != nil {
<ide><path>libnetwork/sandbox_dns_unix.go
<ide> func (sb *sandbox) setupDNS() error {
<ide>
<ide> // When the user specify a conainter in the host namespace and do no have any dns option specified
<ide> // we just copy the host resolv.conf from the host itself
<del> if sb.config.useDefaultSandBox &&
<del> len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
<del>
<add> if sb.config.useDefaultSandBox && len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
<ide> // We are working under the assumption that the origin file option had been properly expressed by the upper layer
<ide> // if not here we are going to error out
<ide> if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
<ide> func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
<ide> if currHash != "" && currHash != currRC.Hash {
<ide> // Seems the user has changed the container resolv.conf since the last time
<ide> // we checked so return without doing anything.
<del> //logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
<add> // logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
<ide> return nil
<ide> }
<ide>
<ide><path>libnetwork/service_common.go
<ide> func (c *controller) cleanupServiceBindings(cleanupNID string) {
<ide> for _, f := range cleanupFuncs {
<ide> f()
<ide> }
<del>
<ide> }
<ide>
<ide> func makeServiceCleanupFunc(c *controller, s *service, nID, eID string, vip net.IP, ip net.IP) func() {
<ide> func (c *controller) addServiceBinding(svcName, svcID, nID, eID, containerName s
<ide> }
<ide>
<ide> func (c *controller) rmServiceBinding(svcName, svcID, nID, eID, containerName string, vip net.IP, ingressPorts []*PortConfig, serviceAliases []string, taskAliases []string, ip net.IP, method string, deleteSvcRecords bool, fullRemove bool) error {
<del>
<ide> var rmService bool
<ide>
<ide> skey := serviceKey{
<ide><path>libnetwork/store.go
<ide> func (c *controller) networkWatchLoop(nw *netWatch, ep *endpoint, ecCh <-chan da
<ide>
<ide> for _, lEp := range delEpMap {
<ide> ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), false)
<del>
<ide> }
<ide> for _, lEp := range addEp {
<ide> ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), true)
<ide><path>libnetwork/store_linux_test.go
<ide> func TestBoltdbBackend(t *testing.T) {
<ide> defer os.Remove("/tmp/boltdb.db")
<ide> config := &store.Config{Bucket: "testBackend"}
<ide> testLocalBackend(t, "boltdb", "/tmp/boltdb.db", config)
<del>
<ide> }
<ide>
<ide> func TestNoPersist(t *testing.T) { | 40 |
PHP | PHP | capitalize uuid acronym | 81c2e9db84857e273bc6fc63acdae9c32dcb54a8 | <ide><path>lib/Cake/Test/Case/Model/Datasource/Database/SqliteTest.php
<ide> public function testVirtualFieldWithFunction() {
<ide> }
<ide>
<ide> /**
<del> * Test that records can be inserted with uuid primary keys, and
<add> * Test that records can be inserted with UUID primary keys, and
<ide> * that the primary key is not blank
<ide> *
<ide> * @return void
<ide> public function testUuidPrimaryKeyInsertion() {
<ide> $Model = ClassRegistry::init('Uuid');
<ide>
<ide> $data = array(
<del> 'title' => 'A uuid should work',
<add> 'title' => 'A UUID should work',
<ide> 'count' => 10
<ide> );
<ide> $Model->create($data);
<ide> $this->assertTrue((bool)$Model->save());
<ide> $result = $Model->read();
<ide>
<ide> $this->assertEquals($data['title'], $result['Uuid']['title']);
<del> $this->assertTrue(Validation::uuid($result['Uuid']['id']), 'Not a uuid');
<add> $this->assertTrue(Validation::uuid($result['Uuid']['id']), 'Not a UUID');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Utility/Validation.php
<ide> public static function userDefined($check, $object, $method, $args = null) {
<ide> }
<ide>
<ide> /**
<del> * Checks that a value is a valid uuid - http://tools.ietf.org/html/rfc4122
<add> * Checks that a value is a valid UUID - http://tools.ietf.org/html/rfc4122
<ide> *
<ide> * @param string $check Value to check
<ide> * @return boolean Success | 2 |
Go | Go | fix typo in integration-cli | 2dfb57b6706daee8e0855319bc2b121bf970267a | <ide><path>integration-cli/docker_cli_rm_test.go
<ide> func (s *DockerSuite) TestRmContainerRunning(c *check.C) {
<ide> func (s *DockerSuite) TestRmContainerForceRemoveRunning(c *check.C) {
<ide> createRunningContainer(c, "foo")
<ide>
<del> // Stop then remove with -s
<add> // Stop then remove with -f
<ide> dockerCmd(c, "rm", "-f", "foo")
<ide> }
<ide> | 1 |
Mixed | Python | apply suggestions from code review | e766e8c56d2fe6ddf9800659cd408d8f4b7141a6 | <ide><path>spacy/language.py
<ide> def replace_listeners(
<ide> )
<ide> raise ValueError(err)
<ide> pipe = self.get_pipe(pipe_name)
<del> # Update the config accordingly by coping the tok2vec model to all
<add> # Update the config accordingly by copying the tok2vec model to all
<ide> # sections defined in the listener paths
<ide> for listener_path in listeners:
<ide> # Check if the path actually exists in the config
<ide><path>website/docs/api/language.md
<ide> when loading a config with
<ide> | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<ide> | `tok2vec_name` | Name of the token-to-vector component, typically `"tok2vec"` or `"transformer"`.~~str~~ |
<ide> | `pipe_name` | Name of pipeline component to replace listeners for. ~~str~~ |
<del>| `listeners` | The paths to the listeners, relative to the component config, e.g. `["model.tok2vec"]`. Typically, implementations will only connect to one tok2vec component, `model.tok2vec`, but in theory, custom models can use multiple listeners. The value here can either be an empty list to not replace any listeners, or a _complete_ list of the paths to all listener layers used by the model.~~Iterable[str]~~ |
<add>| `listeners` | The paths to the listeners, relative to the component config, e.g. `["model.tok2vec"]`. Typically, implementations will only connect to one tok2vec component, `model.tok2vec`, but in theory, custom models can use multiple listeners. The value here can either be an empty list to not replace any listeners, or a _complete_ list of the paths to all listener layers used by the model that should be replaced.~~Iterable[str]~~ |
<ide>
<ide> ## Language.meta {#meta tag="property"}
<ide> | 2 |
Javascript | Javascript | add canmangle flag to getexports | ab280135b1f04549ace96a0f2cbd1e91ba07204b | <ide><path>lib/Dependency.js
<ide> const DependencyReference = require("./dependencies/DependencyReference");
<ide> /**
<ide> * @typedef {Object} ExportSpec
<ide> * @property {string} name the name of the export
<del> * @property {Module=} from when reexported: from which module
<del> * @property {string[] | null=} export when reexported: from which export
<add> * @property {boolean=} canMangle can the export be renamed (defaults to true)
<add> * @property {Module=} from when reexported: from which module
<add> * @property {string[] | null=} export when reexported: from which export
<ide> */
<ide>
<ide> /**
<ide><path>lib/FlagDependencyExportsPlugin.js
<ide> class FlagDependencyExportsPlugin {
<ide> exportInfo.provided = true;
<ide> changed = true;
<ide> }
<add> if (exportNameOrSpec.canMangle === false) {
<add> if (exportInfo.canMangleProvide !== false) {
<add> exportInfo.canMangleProvide = false;
<add> changed = true;
<add> }
<add> }
<ide> if (exportNameOrSpec.from) {
<ide> const fromExportsInfo = moduleGraph.getExportsInfo(
<ide> exportNameOrSpec.from
<ide><path>lib/dependencies/StaticExportsDependency.js
<ide> "use strict";
<ide>
<ide> const makeSerializable = require("../util/makeSerializable");
<del>const DependencyReference = require("./DependencyReference");
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<add>/** @typedef {import("../Dependency").ExportSpec} ExportSpec */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide> class StaticExportsDependency extends NullDependency {
<ide> return "static exports";
<ide> }
<ide>
<del> /**
<del> * Returns the referenced module and export
<del> * @param {ModuleGraph} moduleGraph module graph
<del> * @returns {DependencyReference} reference
<del> */
<del> getReference(moduleGraph) {
<del> if (this.canMangle) return null;
<del> // reference itself
<del> // this sets usedExports to true, which prevents mangling
<del> // TODO introduce a flag whether exports can be mangled or not
<del> return new DependencyReference(
<del> () => moduleGraph.getParentModule(this),
<del> DependencyReference.NS_OBJECT_IMPORTED,
<del> false
<del> );
<del> }
<del>
<ide> /**
<ide> * Returns the exported names
<ide> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {ExportsSpec | undefined} export names
<ide> */
<ide> getExports(moduleGraph) {
<del> return {
<del> exports: this.exports,
<del> dependencies: undefined
<del> };
<add> if (!this.canMangle && this.exports !== true) {
<add> return {
<add> exports: this.exports.map(name => ({
<add> name,
<add> canMangle: false
<add> })),
<add> dependencies: undefined
<add> };
<add> } else {
<add> return {
<add> exports: this.exports,
<add> dependencies: undefined
<add> };
<add> }
<ide> }
<ide>
<ide> /**
<ide> class StaticExportsDependency extends NullDependency {
<ide> */
<ide> updateHash(hash, chunkGraph) {
<ide> hash.update(JSON.stringify(this.exports));
<add> if (this.canMangle) hash.update("canMangle");
<ide> super.updateHash(hash, chunkGraph);
<ide> }
<ide> | 3 |
Javascript | Javascript | adjust mobile view for email-signup page | 42e8b2247e6551e4ee2929f01c2c669cfd8300d7 | <ide><path>client/src/pages/email-sign-up.js
<ide> class AcceptPrivacyTerms extends Component {
<ide> <title>{t('misc.email-signup')} | freeCodeCamp.org</title>
<ide> </Helmet>
<ide> <Grid className='default-page-wrapper email-sign-up'>
<add> <Spacer />
<ide> <SectionHeader>{t('misc.email-signup')}</SectionHeader>
<ide> <Row>
<del> <IntroDescription />
<ide> <Col md={8} mdOffset={2} sm={10} smOffset={1} xs={12}>
<add> <IntroDescription />
<ide> <strong>{t('misc.quincy')}</strong>
<ide> <Spacer />
<ide> <p>{t('misc.email-blast')}</p> | 1 |
Ruby | Ruby | add missing period [ci skip] | d473561071082489fa3f6ce11b42c9beea9b0ddc | <ide><path>activerecord/lib/active_record/errors.rb
<ide> class StatementTimeout < StatementInvalid
<ide> class QueryCanceled < StatementInvalid
<ide> end
<ide>
<del> # AdapterTimeout will be raised when database clients times out while waiting from the server
<add> # AdapterTimeout will be raised when database clients times out while waiting from the server.
<ide> class AdapterTimeout < StatementInvalid
<ide> end
<ide> | 1 |
Python | Python | remove printing of config | 8353ca5a516ba7e1bfb4d8d0207f2854de8d73f4 | <ide><path>examples/training/train_textcat.py
<ide> def main(config_path, output_dir=None, n_iter=20, n_texts=2000, init_tok2vec=Non
<ide>
<ide> print(f"Loading nlp model from {config_path}")
<ide> nlp_config = Config().from_disk(config_path)
<del> print(f"config: {nlp_config}")
<ide> nlp, _ = util.load_model_from_config(nlp_config, auto_fill=True)
<ide>
<ide> # ensure the nlp object was defined with a textcat component | 1 |
Javascript | Javascript | add a comment about supporting hint replacement | e1f7edfae8c6de2dcfa1a4481496189e04fd1115 | <ide><path>fonts.js
<ide> var Type1Parser = function() {
<ide>
<ide> // This is the same things about hint replacement, if it is not used
<ide> // entry 3 can be replaced by {3}
<add> // TODO support hint replacment
<ide> if (index == 3) {
<ide> charstring.push(3);
<ide> i++;
<ide> CFF.prototype = {
<ide> return type2Charstrings;
<ide> },
<ide>
<del> getType2Subrs: function cff_getType2Charstrings(type1Subrs) {
<add> getType2Subrs: function cff_getType2Subrs(type1Subrs) {
<ide> var bias = 0;
<ide> var count = type1Subrs.length;
<ide> if (count < 1240) | 1 |
Ruby | Ruby | fix doc format for `duplicable?` [ci skip] | af2e39f3d5a0f0300fac21666b016d4cf21938b6 | <ide><path>activesupport/lib/active_support/core_ext/object/duplicable.rb
<ide> def duplicable?
<ide> class BigDecimal
<ide> # BigDecimals are duplicable:
<ide> #
<del> # BigDecimal.new("1.2").duplicable? # => true
<del> # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
<add> # BigDecimal.new("1.2").duplicable? # => true
<add> # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
<ide> def duplicable?
<ide> true
<ide> end
<ide> class Complex
<ide>
<ide> # Complexes are not duplicable:
<ide> #
<del> # Complex(1).duplicable? # => false
<del> # Complex(1).dup # => TypeError: can't copy Complex
<add> # Complex(1).duplicable? # => false
<add> # Complex(1).dup # => TypeError: can't copy Complex
<ide> def duplicable?
<ide> false
<ide> end
<ide> class Rational
<ide>
<ide> # Rationals are not duplicable:
<ide> #
<del> # Rational(1).duplicable? # => false
<del> # Rational(1).dup # => TypeError: can't copy Rational
<add> # Rational(1).duplicable? # => false
<add> # Rational(1).dup # => TypeError: can't copy Rational
<ide> def duplicable?
<ide> false
<ide> end | 1 |
PHP | PHP | add followingredirects() method | 030d5212d89be18b5b91133f1c01fce68e433b63 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> trait MakesHttpRequests
<ide> */
<ide> protected $serverVariables = [];
<ide>
<add> /**
<add> * Whether redirects should be followed.
<add> *
<add> * @var bool
<add> */
<add> protected $followRedirects = false;
<add>
<ide> /**
<ide> * Define additional headers to be sent with the request.
<ide> *
<ide> public function handle($request, $next)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Automatically follow any redirects returned from the response.
<add> *
<add> * @return $this
<add> */
<add> public function followingRedirects()
<add> {
<add> $this->followRedirects = true;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Visit the given URI with a GET request.
<ide> *
<ide> public function call($method, $uri, $parameters = [], $cookies = [], $files = []
<ide> $request = Request::createFromBase($symfonyRequest)
<ide> );
<ide>
<add> if ($this->followRedirects) {
<add> $response = $this->followRedirects($response);
<add> }
<add>
<ide> $kernel->terminate($request, $response);
<ide>
<ide> return $this->createTestResponse($response);
<ide> protected function extractFilesFromDataArray(&$data)
<ide> return $files;
<ide> }
<ide>
<add> /**
<add> * Follow a redirect chain until a non-redirect is received.
<add> *
<add> * @param \Illuminate\Http\Response $response
<add> * @return \Illuminate\Http\Response
<add> */
<add> protected function followRedirects($response)
<add> {
<add> while ($response->isRedirect()) {
<add> $response = $this->get($response->headers->get('Location'));
<add> }
<add>
<add> return $response;
<add> }
<add>
<ide> /**
<ide> * Create the test response instance from the given response.
<ide> * | 1 |
Mixed | Ruby | fix output messages - docs [ci skip] | 2ef4d5ed5cbbb2a9266c99535e5f51918ae3e3b6 | <ide><path>activemodel/lib/active_model/errors.rb
<ide> def initialize(base)
<ide> @messages = {}
<ide> end
<ide>
<del> def initialize_dup(other) #:nodoc:
<add> def initialize_dup(other) # :nodoc:
<ide> @messages = other.messages.dup
<ide> super
<ide> end
<ide>
<ide> # Clear the error messages.
<ide> #
<del> # person.errors.full_messages # => ["name can not be nil"]
<add> # person.errors.full_messages # => ["name can not be nil"]
<ide> # person.errors.clear
<ide> # person.errors.full_messages # => []
<ide> def clear
<ide> def clear
<ide> # Returns +true+ if the error messages include an error for the given key
<ide> # +attribute+, +false+ otherwise.
<ide> #
<del> # person.errors.messages # => { name: ["can not be nil"] }
<add> # person.errors.messages # => {:name=>["can not be nil"]}
<ide> # person.errors.include?(:name) # => true
<del> # person.errors.include?(:age) # => false
<add> # person.errors.include?(:age) # => false
<ide> def include?(attribute)
<ide> (v = messages[attribute]) && v.any?
<ide> end
<ide> def include?(attribute)
<ide>
<ide> # Get messages for +key+.
<ide> #
<del> # person.errors.messages # => { name: ["can not be nil"] }
<add> # person.errors.messages # => {:name=>["can not be nil"]}
<ide> # person.errors.get(:name) # => ["can not be nil"]
<ide> # person.errors.get(:age) # => nil
<ide> def get(key)
<ide> def size
<ide>
<ide> # Returns all message values.
<ide> #
<del> # person.errors.messages # => { name: ["can not be nil", "must be specified"] }
<add> # person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
<ide> # person.errors.values # => [["can not be nil", "must be specified"]]
<ide> def values
<ide> messages.values
<ide> end
<ide>
<ide> # Returns all message keys.
<ide> #
<del> # person.errors.messages # => { name: ["can not be nil", "must be specified"] }
<add> # person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
<ide> # person.errors.keys # => [:name]
<ide> def keys
<ide> messages.keys
<ide> def to_xml(options={})
<ide> # object. You can pass the <tt>:full_messages</tt> option. This determines
<ide> # if the json object should contain full messages or not (false by default).
<ide> #
<del> # person.as_json # => { name: ["can not be nil"] }
<del> # person.as_json(full_messages: true) # => { name: ["name can not be nil"] }
<add> # person.as_json # => {:name=>["can not be nil"]}
<add> # person.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
<ide> def as_json(options=nil)
<ide> to_hash(options && options[:full_messages])
<ide> end
<ide>
<ide> # Returns a Hash of attributes with their error messages. If +full_messages+
<ide> # is +true+, it will contain full messages (see +full_message+).
<ide> #
<del> # person.to_hash # => { name: ["can not be nil"] }
<del> # person.to_hash(true) # => { name: ["name can not be nil"] }
<add> # person.to_hash # => {:name=>["can not be nil"]}
<add> # person.to_hash(true) # => {:name=>["name can not be nil"]}
<ide> def to_hash(full_messages = false)
<ide> if full_messages
<ide> messages = {}
<ide> def to_hash(full_messages = false)
<ide> # # => ["is invalid", "must be implemented"]
<ide> #
<ide> # person.errors.messages
<del> # # => { name: ["must be implemented", "is invalid"] }
<add> # # => {:name=>["must be implemented", "is invalid"]}
<ide> #
<ide> # If +message+ is a symbol, it will be translated using the appropriate
<ide> # scope (see +generate_message+).
<ide> def to_hash(full_messages = false)
<ide> # <tt>:strict</tt> option can also be set to any other exception.
<ide> #
<ide> # person.errors.add(:name, nil, strict: true)
<del> # # => ActiveModel::StrictValidationFailed: name is invalid
<add> # # => ActiveModel::StrictValidationFailed: name is invalid
<ide> # person.errors.add(:name, nil, strict: NameIsInvalid)
<del> # # => NameIsInvalid: name is invalid
<add> # # => NameIsInvalid: name is invalid
<ide> #
<ide> # person.errors.messages # => {}
<ide> def add(attribute, message = nil, options = {})
<ide> def add(attribute, message = nil, options = {})
<ide> #
<ide> # person.errors.add_on_empty(:name)
<ide> # person.errors.messages
<del> # # => { name: ["can't be empty"] }
<add> # # => {:name=>["can't be empty"]}
<ide> def add_on_empty(attributes, options = {})
<ide> [attributes].flatten.each do |attribute|
<ide> value = @base.send(:read_attribute_for_validation, attribute)
<ide> def add_on_empty(attributes, options = {})
<ide> #
<ide> # person.errors.add_on_blank(:name)
<ide> # person.errors.messages
<del> # # => { name: ["can't be blank"] }
<add> # # => {:name=>["can't be blank"]}
<ide> def add_on_blank(attributes, options = {})
<ide> [attributes].flatten.each do |attribute|
<ide> value = @base.send(:read_attribute_for_validation, attribute)
<ide><path>activesupport/lib/active_support/core_ext/array/extract_options.rb
<ide> class Array
<ide> # end
<ide> #
<ide> # options(1, 2) # => {}
<del> # options(1, 2, a: :b) # => {a: :b}
<add> # options(1, 2, a: :b) # => {:a=>:b}
<ide> def extract_options!
<ide> if last.is_a?(Hash) && last.extractable_options?
<ide> pop
<ide><path>activesupport/lib/active_support/core_ext/array/wrap.rb
<ide> class Array
<ide> # The last point is particularly worth comparing for some enumerables:
<ide> #
<ide> # Array(foo: :bar) # => [[:foo, :bar]]
<del> # Array.wrap(foo: :bar) # => [{foo: :bar}]
<add> # Array.wrap(foo: :bar) # => [{:foo=>:bar}]
<ide> #
<ide> # There's also a related idiom that uses the splat operator:
<ide> #
<ide><path>activesupport/lib/active_support/core_ext/hash/deep_merge.rb
<ide> class Hash
<ide> # h1.deep_merge(h2) #=> {x: {y: [7, 8, 9]}, z: "xyz"}
<ide> # h2.deep_merge(h1) #=> {x: {y: [4, 5, 6]}, z: [7, 8, 9]}
<ide> # h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
<del> # #=> {x: {y: [4, 5, 6, 7, 8, 9]}, z: [7, 8, 9, "xyz"]}
<add> # #=> {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
<ide> def deep_merge(other_hash, &block)
<ide> dup.deep_merge!(other_hash, &block)
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/hash/slice.rb
<ide> def slice(*keys)
<ide> # Returns a hash containing the removed key/value pairs.
<ide> #
<ide> # { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
<del> # # => {c: 3, d: 4}
<add> # # => {:c=>3, :d=>4}
<ide> def slice!(*keys)
<ide> keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
<ide> omit = slice(*self.keys - keys)
<ide> def slice!(*keys)
<ide>
<ide> # Removes and returns the key/value pairs matching the given keys.
<ide> #
<del> # { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => { a: 1, b: 2 }
<del> # { a: 1, b: 2 }.extract!(:a, :x) # => { a: 1 }
<add> # { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
<add> # { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
<ide> def extract!(*keys)
<ide> keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
<ide> end
<ide><path>guides/source/active_record_validations_callbacks.md
<ide> end
<ide> person = Person.new
<ide> person.valid? # => false
<ide> person.errors
<del> # => {name: ["can't be blank", "is too short (minimum is 3 characters)"]}
<add> # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
<ide>
<ide> person = Person.new(name: "John Doe")
<ide> person.valid? # => true
<ide> Callbacks can also be registered to only fire on certain lifecycle events:
<ide> ```ruby
<ide> class User < ActiveRecord::Base
<ide> before_validation :normalize_name, on: :create
<del>
<add>
<ide> # :on takes an array as well
<ide> after_validation :set_location, on: [ :create, :update ]
<ide>
<ide><path>guides/source/active_support_core_extensions.md
<ide> This method is similar in purpose to `Kernel#Array`, but there are some differen
<ide> The last point is particularly worth comparing for some enumerables:
<ide>
<ide> ```ruby
<del>Array.wrap(foo: :bar) # => [{foo: :bar}]
<add>Array.wrap(foo: :bar) # => [{:foo=>:bar}]
<ide> Array(foo: :bar) # => [[:foo, :bar]]
<ide> ```
<ide>
<ide> Ruby has a built-in method `Hash#merge` that merges two hashes:
<ide>
<ide> ```ruby
<ide> {a: 1, b: 1}.merge(a: 0, c: 2)
<del># => {a: 0, b: 1, c: 2}
<add># => {:a=>0, :b=>1, :c=>2}
<ide> ```
<ide>
<ide> Active Support defines a few more ways of merging hashes that may be convenient.
<ide> Active Support defines `Hash#deep_merge`. In a deep merge, if a key is found in
<ide>
<ide> ```ruby
<ide> {a: {b: 1}}.deep_merge(a: {c: 2})
<del># => {a: {b: 1, c: 2}}
<add># => {:a=>{:b=>1, :c=>2}}
<ide> ```
<ide>
<ide> The method `deep_merge!` performs a deep merge in place.
<ide> The method `diff` returns a hash that represents a diff of the receiver and the
<ide> # => {}, first rule
<ide>
<ide> {a: 1}.diff(a: 2)
<del># => {a: 1}, second rule
<add># => {:a=>1}, second rule
<ide>
<ide> {a: 1}.diff(b: 2)
<del># => {a: 1, b: 2}, third rule
<add># => {:a=>1, :b=>2}, third rule
<ide>
<ide> {a: 1, b: 2, c: 3}.diff(b: 1, c: 3, d: 4)
<del># => {a: 1, b: 2, d: 4}, all rules
<add># => {:a=>1, :b=>2, :d=>4}, all rules
<ide>
<ide> {}.diff({}) # => {}
<del>{a: 1}.diff({}) # => {a: 1}
<del>{}.diff(a: 1) # => {a: 1}
<add>{a: 1}.diff({}) # => {:a=>1}
<add>{}.diff(a: 1) # => {:a=>1}
<ide> ```
<ide>
<ide> An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice:
<ide> NOTE: Defined in `active_support/core_ext/hash/diff.rb`.
<ide> The method `except` returns a hash with the keys in the argument list removed, if present:
<ide>
<ide> ```ruby
<del>{a: 1, b: 2}.except(:a) # => {b: 2}
<add>{a: 1, b: 2}.except(:a) # => {:b=>2}
<ide> ```
<ide>
<ide> If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
<ide> The method `symbolize_keys` returns a hash that has a symbolized version of the
<ide>
<ide> ```ruby
<ide> {nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
<del># => {1 => 1, nil => nil, a: "a"}
<add># => {1=>1, nil=>nil, :a=>"a"}
<ide> ```
<ide>
<ide> WARNING. Note in the previous example only one key was symbolized.
<ide> The result in case of collision is undefined:
<ide>
<ide> ```ruby
<ide> {"a" => 1, a: 2}.symbolize_keys
<del># => {a: 2}, in my test, can't rely on this result though
<add># => {:a=>2}, in my test, can't rely on this result though
<ide> ```
<ide>
<ide> This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
<ide> Ruby has built-in support for taking slices out of strings and arrays. Active Su
<ide>
<ide> ```ruby
<ide> {a: 1, b: 2, c: 3}.slice(:a, :c)
<del># => {c: 3, a: 1}
<add># => {:c=>3, :a=>1}
<ide>
<ide> {a: 1, b: 2, c: 3}.slice(:b, :X)
<del># => {b: 2} # non-existing keys are ignored
<add># => {:b=>2} # non-existing keys are ignored
<ide> ```
<ide>
<ide> If the receiver responds to `convert_key` keys are normalized:
<ide>
<ide> ```ruby
<ide> {a: 1, b: 2}.with_indifferent_access.slice("a")
<del># => {a: 1}
<add># => {:a=>1}
<ide> ```
<ide>
<ide> NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
<ide> There's also `slice!` which in addition to perform a slice in place returns what
<ide>
<ide> ```ruby
<ide> hash = {a: 1, b: 2}
<del>rest = hash.slice!(:a) # => {b: 2}
<del>hash # => {a: 1}
<add>rest = hash.slice!(:a) # => {:b=>2}
<add>hash # => {:a=>1}
<ide> ```
<ide>
<ide> NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
<ide> The method `extract!` removes and returns the key/value pairs matching the given
<ide>
<ide> ```ruby
<ide> hash = {a: 1, b: 2}
<del>rest = hash.extract!(:a) # => {a: 1}
<del>hash # => {b: 2}
<add>rest = hash.extract!(:a) # => {:a=>1}
<add>hash # => {:b=>2}
<ide> ```
<ide>
<ide> The method `extract!` returns the same subclass of Hash, that the receiver is.
<ide><path>guides/source/active_support_instrumentation.md
<ide> ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*a
<ide>
<ide> event.name # => "process_action.action_controller"
<ide> event.duration # => 10 (in milliseconds)
<del> event.payload # => { extra: :information }
<add> event.payload # => {:extra=>information}
<ide>
<ide> Rails.logger.info "#{event} Received!"
<ide> end
<ide> Now you can listen to this event with:
<ide>
<ide> ```ruby
<ide> ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
<del> puts data.inspect # { this: :data }
<add> puts data.inspect # {:this=>:data}
<ide> end
<ide> ```
<ide>
<ide><path>guides/source/i18n.md
<ide> Also, a key can translate to a (potentially nested) hash of grouped translations
<ide>
<ide> ```ruby
<ide> I18n.t 'activerecord.errors.messages'
<del># => { inclusion: "is not included in the list", exclusion: ... }
<add># => {:inclusion=>"is not included in the list", :exclusion=> ... }
<ide> ```
<ide>
<ide> #### "Lazy" Lookup | 9 |
Ruby | Ruby | set the default charset in response initialize | dd8c76d9b90da5c1b551e26c7d27d9519a19b711 | <ide><path>actionpack/lib/action_dispatch/http/response.rb
<ide> class Response
<ide>
<ide> # The charset of the response. HTML wants to know the encoding of the
<ide> # content you're giving them, so we need to send that along.
<del> attr_accessor :charset
<add> attr_reader :charset
<ide>
<ide> CONTENT_TYPE = "Content-Type".freeze
<ide> SET_COOKIE = "Set-Cookie".freeze
<ide> def initialize(status = 200, header = {}, body = [], default_headers: self.class
<ide> @sending = false
<ide> @sent = false
<ide> @content_type = nil
<del> @charset = nil
<add> @charset = self.class.default_charset
<ide>
<ide> if content_type = self[CONTENT_TYPE]
<ide> type, charset = content_type.split(/;\s*charset=/)
<ide> def content_type=(content_type)
<ide> @content_type = content_type.to_s
<ide> end
<ide>
<add> # Sets the HTTP character set.
<add> def charset=(charset)
<add> if nil == charset
<add> @charset = self.class.default_charset
<add> else
<add> @charset = charset
<add> end
<add> end
<add>
<ide> # The response code of the request.
<ide> def response_code
<ide> @status
<ide> def assign_default_content_type_and_charset!(headers)
<ide> return if headers[CONTENT_TYPE].present?
<ide>
<ide> @content_type ||= Mime::HTML
<del> @charset ||= self.class.default_charset unless @charset == false
<ide>
<ide> type = @content_type.to_s.dup
<del> type << "; charset=#{@charset}" if append_charset?
<add> type << "; charset=#{charset}" if append_charset?
<ide>
<ide> headers[CONTENT_TYPE] = type
<ide> end | 1 |
Ruby | Ruby | remove duplicated `delivery_method` definition | e4cf71bf7a8be80ad4624ae3d21f5646e21cfe21 | <ide><path>actionmailer/test/parameterized_test.rb
<ide> class ParameterizedTest < ActiveSupport::TestCase
<ide>
<ide> @previous_deliver_later_queue_name = ActionMailer::Base.deliver_later_queue_name
<ide> ActionMailer::Base.deliver_later_queue_name = :test_queue
<del> ActionMailer::Base.delivery_method = :test
<ide>
<ide> @mail = ParamsMailer.with(inviter: "david@basecamp.com", invitee: "jason@basecamp.com").invitation
<ide> end | 1 |
Text | Text | update changelog with time column type casting fix | acf583a5e00be0fb684f73ad51cdad0237c981b2 | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Fix time column type casting for invalid time string values to correctly return nil.
<add>
<add> *Adam Meehan*
<add>
<ide> * Allow to pass Symbol or Proc into :limit option of #accepts_nested_attributes_for
<ide>
<ide> *Mikhail Dieterle* | 1 |
Java | Java | find @responsestatus recursively on getcause() | 26cfe5795fcaf59288a3c0e3ccdbb60751a9dd4b | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2015 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> protected ModelAndView doResolveException(HttpServletRequest request, HttpServle
<ide> logger.warn("Handling of @ResponseStatus resulted in Exception", resolveEx);
<ide> }
<ide> }
<add> else if (ex.getCause() != null && ex.getCause() instanceof Exception) {
<add> ex = (Exception) ex.getCause();
<add> return doResolveException(request, response, handler, ex);
<add> }
<ide> return null;
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.web.servlet.mvc.annotation;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> import java.util.Locale;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<add>import org.springframework.beans.TypeMismatchException;
<ide> import org.springframework.context.i18n.LocaleContextHolder;
<ide> import org.springframework.context.support.StaticMessageSource;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.mock.web.test.MockHttpServletRequest;
<ide> import org.springframework.mock.web.test.MockHttpServletResponse;
<add>import org.springframework.tests.sample.beans.ITestBean;
<ide> import org.springframework.web.bind.annotation.ResponseStatus;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide>
<del>import static org.junit.Assert.*;
<del>
<ide> /** @author Arjen Poutsma */
<ide> public class ResponseStatusExceptionResolverTests {
<ide>
<ide> public void notAnnotated() {
<ide> assertNull("ModelAndView returned", mav);
<ide> }
<ide>
<add> // SPR-12903
<add>
<add> @Test
<add> public void nestedException() throws Exception {
<add> Exception cause = new StatusCodeAndReasonMessageException();
<add> TypeMismatchException ex = new TypeMismatchException("value", ITestBean.class, cause);
<add> ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
<add> assertNotNull("No ModelAndView returned", mav);
<add> assertTrue("No Empty ModelAndView returned", mav.isEmpty());
<add> assertEquals("Invalid status code", 410, response.getStatus());
<add> }
<add>
<ide> @ResponseStatus(HttpStatus.BAD_REQUEST)
<ide> @SuppressWarnings("serial")
<ide> private static class StatusCodeException extends Exception {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
<ide> import org.springframework.web.bind.annotation.ExceptionHandler;
<ide> import org.springframework.web.bind.annotation.InitBinder;
<ide> import org.springframework.web.bind.annotation.ModelAttribute;
<add>import org.springframework.web.bind.annotation.PathVariable;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> import org.springframework.web.bind.annotation.RequestHeader;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> public void initialize(GenericWebApplicationContext context) {
<ide> assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString());
<ide> }
<ide>
<add> // SPR-12903
<add>
<add> @Test
<add> public void pathVariableWithCustomConverter() throws Exception {
<add> initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
<add> @Override
<add> public void initialize(GenericWebApplicationContext context) {
<add> RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class);
<add> csDef.getPropertyValues().add("converters", new AnnotatedExceptionRaisingConverter());
<add> RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class);
<add> wbiDef.getPropertyValues().add("conversionService", csDef);
<add> RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
<add> adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef);
<add> context.registerBeanDefinition("handlerAdapter", adapterDef);
<add> }
<add> }, PathVariableWithCustomConverterController.class);
<add>
<add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath/1");
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> getServlet().service(request, response);
<add> assertEquals(404, response.getStatus());
<add> }
<add>
<ide> @Test
<ide> public void methodNotAllowed() throws Exception {
<ide> initServletWithControllers(MethodNotAllowedController.class);
<ide> public ITestBean convert(String source) {
<ide> }
<ide> }
<ide>
<add> @Controller
<add> public static class PathVariableWithCustomConverterController {
<add>
<add> @RequestMapping("/myPath/{id}")
<add> public void myHandle(@PathVariable("id") ITestBean bean) throws Exception {
<add> }
<add> }
<add>
<add> public static class AnnotatedExceptionRaisingConverter implements Converter<String, ITestBean> {
<add>
<add> @Override
<add> public ITestBean convert(String source) {
<add> throw new NotFoundException();
<add> }
<add>
<add> @ResponseStatus(HttpStatus.NOT_FOUND)
<add> private static class NotFoundException extends RuntimeException {
<add> }
<add> }
<add>
<ide> @Controller
<ide> public static class MethodNotAllowedController {
<ide> | 3 |
Javascript | Javascript | improve parameter docs for boolean attributes | ae70ec7946a75fc1760158f954b27fb59342d568 | <ide><path>src/ng/directive/booleanAttrs.js
<ide> </doc:example>
<ide> *
<ide> * @element INPUT
<del> * @param {expression} ngDisabled Angular expression that will be evaluated.
<add> * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
<add> * then special attribute "disabled" will be set on the element
<ide> */
<ide>
<ide>
<ide> </doc:example>
<ide> *
<ide> * @element INPUT
<del> * @param {expression} ngChecked Angular expression that will be evaluated.
<add> * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
<add> * then special attribute "checked" will be set on the element
<ide> */
<ide>
<ide>
<ide> </doc:example>
<ide> *
<ide> * @element INPUT
<del> * @param {string} expression Angular expression that will be evaluated.
<add> * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
<add> * then special attribute "readonly" will be set on the element
<ide> */
<ide>
<ide>
<ide> </doc:example>
<ide> *
<ide> * @element OPTION
<del> * @param {string} expression Angular expression that will be evaluated.
<add> * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
<add> * then special attribute "selected" will be set on the element
<ide> */
<ide>
<ide> /**
<ide> </doc:example>
<ide> *
<ide> * @element DETAILS
<del> * @param {string} expression Angular expression that will be evaluated.
<add> * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
<add> * then special attribute "open" will be set on the element
<ide> */
<ide>
<ide> var ngAttributeAliasDirectives = {}; | 1 |
Javascript | Javascript | reset cache before every test | fd83d3724ad30a93254f08cb82f981eaddb5dbff | <ide><path>test/helpers/testabilityPatch.js
<del>/* global jQuery: true, uid: true */
<add>/* global jQuery: true, uid: true, jqCache: true */
<ide> 'use strict';
<ide>
<ide> /**
<ide> if (window._jQuery) _jQuery.event.special.change = undefined;
<ide> if (window.bindJQuery) bindJQuery();
<ide>
<ide> beforeEach(function() {
<add>
<ide> // all this stuff is not needed for module tests, where jqlite and publishExternalAPI and jqLite are not global vars
<ide> if (window.publishExternalAPI) {
<ide> publishExternalAPI(angular);
<ide> beforeEach(function() {
<ide>
<ide> // reset to jQuery or default to us.
<ide> bindJQuery();
<del> jqLiteCacheSizeInit();
<add>
<add> // Clear the cache to prevent memory leak failures from previous tests
<add> // breaking subsequent tests unnecessarily
<add> jqCache = jqLite.cache = {};
<ide> }
<ide>
<ide> angular.element(document.body).empty().removeData();
<ide> afterEach(function() {
<ide> }
<ide> }
<ide>
<del>
<ide> // copied from Angular.js
<ide> // we need this method here so that we can run module tests with wrapped angular.js
<ide> function forEachSorted(obj, iterator, context) {
<ide> function dealoc(obj) {
<ide>
<ide>
<ide> function jqLiteCacheSize() {
<del> var size = 0;
<del> forEach(jqLite.cache, function() { size++; });
<del> return size - jqLiteCacheSize.initSize;
<del>}
<del>jqLiteCacheSize.initSize = 0;
<del>
<del>function jqLiteCacheSizeInit() {
<del> jqLiteCacheSize.initSize = jqLiteCacheSize.initSize + jqLiteCacheSize();
<add> return Object.keys(jqLite.cache).length;
<ide> }
<ide>
<ide> | 1 |
Text | Text | add marsonya to collaborators | c685e4ae009371e82687f5a9c00c588471a247b7 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Denys Otrishko** <<shishugi@gmail.com>> (he/him)
<ide> * [Lxxyx](https://github.com/Lxxyx) -
<ide> **Zijian Liu** <<lxxyxzj@gmail.com>> (he/him)
<add>* [marsonya](https://github.com/marsonya) -
<add> **Akhil Marsonya** <<akhil.marsonya27@gmail.com>> (he/him)
<ide> * [mcollina](https://github.com/mcollina) -
<ide> **Matteo Collina** <<matteo.collina@gmail.com>> (he/him)
<ide> * [Mesteery](https://github.com/Mesteery) - | 1 |
Text | Text | update radial linear scale docs | 876ddc89313cef693771a70b571d844b062e7fc4 | <ide><path>docs/02-Scales.md
<ide> Name | Type | Default | Description
<ide> backdropColor | Color | 'rgba(255, 255, 255, 0.75)' | Color of label backdrops
<ide> backdropPaddingX | Number | 2 | Horizontal padding of label backdrop
<ide> backdropPaddingY | Number | 2 | Vertical padding of label backdrop
<add>beginAtZero | Boolean | - | if true, scale will inclulde 0 if it is not already included.
<add>min | Number | - | User defined minimum number for the scale, overrides minimum value from data.
<add>max | Number | - | User defined maximum number for the scale, overrides maximum value from data.
<ide> maxTicksLimit | Number | 11 | Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines.
<ide> showLabelBackdrop | Boolean | true | If true, draw a background behind the tick labels
<add>stepSize | Number | - | User defined fixed step size for the scale. If set, the scale ticks will be enumerated by multiple of stepSize, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.
<add>stepSize | Number | - | if defined, it can be used along with the min and the max to give a custom number of steps. See the example below.
<add>suggestedMax | Number | - | User defined maximum number for the scale, overrides maximum value *except for if* it is lower than the maximum value.
<add>suggestedMin | Number | - | User defined minimum number for the scale, overrides minimum value *except for if* it is higher than the minimum value.
<ide>
<ide> ### Update Default Scale config
<ide> | 1 |
Javascript | Javascript | remove discrete lanes and priorities | dcdf8de7e1489fda5cee70acbd1310ee1bb0d312 | <ide><path>packages/react-devtools-scheduling-profiler/src/import-worker/__tests__/preprocessData-test.internal.js
<ide> describe(preprocessData, () => {
<ide> {
<ide> componentStack: '',
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.005,
<ide> type: 'schedule-render',
<ide> },
<ide> describe(preprocessData, () => {
<ide> componentStack: '',
<ide> isCascading: false,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.013,
<ide> type: 'schedule-state-update',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.004999999999999999,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.006,
<ide> type: 'render-idle',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.001,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.006,
<ide> type: 'render',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.002999999999999999,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.008,
<ide> type: 'commit',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 1,
<ide> duration: 0.0010000000000000009,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.009,
<ide> type: 'layout-effects',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.002,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.012,
<ide> type: 'passive-effects',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.005000000000000001,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.015,
<ide> type: 'render-idle',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.0010000000000000009,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.015,
<ide> type: 'render',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.002999999999999999,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.017,
<ide> type: 'commit',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 1,
<ide> duration: 0.0010000000000000009,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.018,
<ide> type: 'layout-effects',
<ide> },
<ide> describe(preprocessData, () => {
<ide> depth: 0,
<ide> duration: 0.0009999999999999974,
<ide> laneLabels: ['Default'],
<del> lanes: [7],
<add> lanes: [5],
<ide> timestamp: 0.021,
<ide> type: 'passive-effects',
<ide> },
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> import {
<ide> } from './ReactDOMUpdateBatching';
<ide>
<ide> import {
<del> InputDiscreteLanePriority as InputDiscreteLanePriority_old,
<ide> InputContinuousLanePriority as InputContinuousLanePriority_old,
<ide> DefaultLanePriority as DefaultLanePriority_old,
<ide> getCurrentUpdateLanePriority as getCurrentUpdateLanePriority_old,
<ide> setCurrentUpdateLanePriority as setCurrentUpdateLanePriority_old,
<ide> } from 'react-reconciler/src/ReactFiberLane.old';
<ide> import {
<del> InputDiscreteLanePriority as InputDiscreteLanePriority_new,
<ide> InputContinuousLanePriority as InputContinuousLanePriority_new,
<ide> DefaultLanePriority as DefaultLanePriority_new,
<ide> getCurrentUpdateLanePriority as getCurrentUpdateLanePriority_new,
<ide> import {
<ide> } from 'react-reconciler/src/SchedulerWithReactIntegration.new';
<ide> import type {LanePriority} from 'react-reconciler/src/ReactFiberLane.new';
<ide>
<del>const InputDiscreteLanePriority = enableNewReconciler
<del> ? InputDiscreteLanePriority_new
<del> : InputDiscreteLanePriority_old;
<ide> const InputContinuousLanePriority = enableNewReconciler
<ide> ? InputContinuousLanePriority_new
<ide> : InputContinuousLanePriority_old;
<ide> export function createEventListenerWrapperWithPriority(
<ide> const eventPriority = getEventPriority(domEventName);
<ide> let listenerWrapper;
<ide> switch (eventPriority) {
<del> case InputDiscreteLanePriority:
<add> case SyncLanePriority:
<ide> listenerWrapper = dispatchDiscreteEvent;
<ide> break;
<ide> case InputContinuousLanePriority:
<ide> export function getEventPriority(domEventName: DOMEventName): * {
<ide> case 'popstate':
<ide> case 'select':
<ide> case 'selectstart':
<del> return InputDiscreteLanePriority;
<add> return SyncLanePriority;
<ide> case 'drag':
<ide> case 'dragenter':
<ide> case 'dragexit':
<ide><path>packages/react-reconciler/src/ReactFiberLane.new.js
<ide> import {
<ide> NoPriority as NoSchedulerPriority,
<ide> } from './SchedulerWithReactIntegration.new';
<ide>
<del>export const SyncLanePriority: LanePriority = 15;
<del>export const SyncBatchedLanePriority: LanePriority = 14;
<del>
<del>const InputDiscreteHydrationLanePriority: LanePriority = 13;
<del>export const InputDiscreteLanePriority: LanePriority = 12;
<add>export const SyncLanePriority: LanePriority = 13;
<add>export const SyncBatchedLanePriority: LanePriority = 12;
<ide>
<ide> const InputContinuousHydrationLanePriority: LanePriority = 11;
<ide> export const InputContinuousLanePriority: LanePriority = 10;
<ide> export const NoLane: Lane = /* */ 0b0000000000000000000
<ide> export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001;
<ide> export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010;
<ide>
<del>export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100;
<del>export const InputDiscreteLane: Lanes = /* */ 0b0000000000000000000000000001000;
<del>
<del>const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000010000;
<del>export const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000000100000;
<del>
<del>export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000001000000;
<del>export const DefaultLane: Lanes = /* */ 0b0000000000000000000000010000000;
<del>
<del>const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000100000000;
<del>const TransitionLanes: Lanes = /* */ 0b0000000011111111111111000000000;
<del>const TransitionLane1: Lane = /* */ 0b0000000000000000000001000000000;
<del>const TransitionLane2: Lane = /* */ 0b0000000000000000000010000000000;
<del>const TransitionLane3: Lane = /* */ 0b0000000000000000000100000000000;
<del>const TransitionLane4: Lane = /* */ 0b0000000000000000001000000000000;
<del>const TransitionLane5: Lane = /* */ 0b0000000000000000010000000000000;
<del>const TransitionLane6: Lane = /* */ 0b0000000000000000100000000000000;
<del>const TransitionLane7: Lane = /* */ 0b0000000000000001000000000000000;
<del>const TransitionLane8: Lane = /* */ 0b0000000000000010000000000000000;
<del>const TransitionLane9: Lane = /* */ 0b0000000000000100000000000000000;
<del>const TransitionLane10: Lane = /* */ 0b0000000000001000000000000000000;
<del>const TransitionLane11: Lane = /* */ 0b0000000000010000000000000000000;
<del>const TransitionLane12: Lane = /* */ 0b0000000000100000000000000000000;
<del>const TransitionLane13: Lane = /* */ 0b0000000001000000000000000000000;
<del>const TransitionLane14: Lane = /* */ 0b0000000010000000000000000000000;
<add>const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000100;
<add>export const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000000001000;
<add>
<add>export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000010000;
<add>export const DefaultLane: Lanes = /* */ 0b0000000000000000000000000100000;
<add>
<add>const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000001000000;
<add>const TransitionLanes: Lanes = /* */ 0b0000000011111111111111110000000;
<add>const TransitionLane1: Lane = /* */ 0b0000000000000000000000010000000;
<add>const TransitionLane2: Lane = /* */ 0b0000000000000000000000100000000;
<add>const TransitionLane3: Lane = /* */ 0b0000000000000000000001000000000;
<add>const TransitionLane4: Lane = /* */ 0b0000000000000000000010000000000;
<add>const TransitionLane5: Lane = /* */ 0b0000000000000000000100000000000;
<add>const TransitionLane6: Lane = /* */ 0b0000000000000000001000000000000;
<add>const TransitionLane7: Lane = /* */ 0b0000000000000000010000000000000;
<add>const TransitionLane8: Lane = /* */ 0b0000000000000000100000000000000;
<add>const TransitionLane9: Lane = /* */ 0b0000000000000001000000000000000;
<add>const TransitionLane10: Lane = /* */ 0b0000000000000010000000000000000;
<add>const TransitionLane11: Lane = /* */ 0b0000000000000100000000000000000;
<add>const TransitionLane12: Lane = /* */ 0b0000000000001000000000000000000;
<add>const TransitionLane13: Lane = /* */ 0b0000000000010000000000000000000;
<add>const TransitionLane14: Lane = /* */ 0b0000000000100000000000000000000;
<add>const TransitionLane15: Lane = /* */ 0b0000000001000000000000000000000;
<add>const TransitionLane16: Lane = /* */ 0b0000000010000000000000000000000;
<ide>
<ide> const RetryLanes: Lanes = /* */ 0b0000111100000000000000000000000;
<ide> const RetryLane1: Lane = /* */ 0b0000000100000000000000000000000;
<ide> export function getLabelsForLanes(lanes: Lanes): Array<string> | void {
<ide> if (lanes & SyncBatchedLane) {
<ide> labels.push('SyncBatched');
<ide> }
<del> if (lanes & InputDiscreteHydrationLane) {
<del> labels.push('InputDiscreteHydration');
<del> }
<del> if (lanes & InputDiscreteLane) {
<del> labels.push('InputDiscrete');
<del> }
<ide> if (lanes & InputContinuousHydrationLane) {
<ide> labels.push('InputContinuousHydration');
<ide> }
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> case SyncBatchedLane:
<ide> return_highestLanePriority = SyncBatchedLanePriority;
<ide> return SyncBatchedLane;
<del> case InputDiscreteHydrationLane:
<del> return_highestLanePriority = InputDiscreteHydrationLanePriority;
<del> return InputDiscreteHydrationLane;
<del> case InputDiscreteLane:
<del> return_highestLanePriority = InputDiscreteLanePriority;
<del> return InputDiscreteLane;
<ide> case InputContinuousHydrationLane:
<ide> return_highestLanePriority = InputContinuousHydrationLanePriority;
<ide> return InputContinuousHydrationLane;
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> case TransitionLane12:
<ide> case TransitionLane13:
<ide> case TransitionLane14:
<add> case TransitionLane15:
<add> case TransitionLane16:
<ide> return_highestLanePriority = TransitionPriority;
<ide> return lanes & TransitionLanes;
<ide> case RetryLane1:
<ide> export function lanePriorityToSchedulerPriority(
<ide> case SyncLanePriority:
<ide> case SyncBatchedLanePriority:
<ide> return ImmediateSchedulerPriority;
<del> case InputDiscreteHydrationLanePriority:
<del> case InputDiscreteLanePriority:
<ide> case InputContinuousHydrationLanePriority:
<ide> case InputContinuousLanePriority:
<ide> return UserBlockingSchedulerPriority;
<ide> export function findUpdateLane(lanePriority: LanePriority): Lane {
<ide> return SyncLane;
<ide> case SyncBatchedLanePriority:
<ide> return SyncBatchedLane;
<del> case InputDiscreteLanePriority:
<del> return SyncLane;
<ide> case InputContinuousLanePriority:
<ide> return InputContinuousLane;
<ide> case DefaultLanePriority:
<ide> export function getBumpedLaneForHydration(
<ide> case SyncBatchedLanePriority:
<ide> lane = NoLane;
<ide> break;
<del> case InputDiscreteHydrationLanePriority:
<del> case InputDiscreteLanePriority:
<del> lane = InputDiscreteHydrationLane;
<del> break;
<del> case InputContinuousHydrationLanePriority:
<ide> case InputContinuousLanePriority:
<ide> lane = InputContinuousHydrationLane;
<ide> break;
<ide><path>packages/react-reconciler/src/ReactFiberLane.old.js
<ide> import {
<ide> NoPriority as NoSchedulerPriority,
<ide> } from './SchedulerWithReactIntegration.old';
<ide>
<del>export const SyncLanePriority: LanePriority = 15;
<del>export const SyncBatchedLanePriority: LanePriority = 14;
<del>
<del>const InputDiscreteHydrationLanePriority: LanePriority = 13;
<del>export const InputDiscreteLanePriority: LanePriority = 12;
<add>export const SyncLanePriority: LanePriority = 13;
<add>export const SyncBatchedLanePriority: LanePriority = 12;
<ide>
<ide> const InputContinuousHydrationLanePriority: LanePriority = 11;
<ide> export const InputContinuousLanePriority: LanePriority = 10;
<ide> export const NoLane: Lane = /* */ 0b0000000000000000000
<ide> export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001;
<ide> export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010;
<ide>
<del>export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100;
<del>export const InputDiscreteLane: Lanes = /* */ 0b0000000000000000000000000001000;
<del>
<del>const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000010000;
<del>export const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000000100000;
<del>
<del>export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000001000000;
<del>export const DefaultLane: Lanes = /* */ 0b0000000000000000000000010000000;
<del>
<del>const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000100000000;
<del>const TransitionLanes: Lanes = /* */ 0b0000000011111111111111000000000;
<del>const TransitionLane1: Lane = /* */ 0b0000000000000000000001000000000;
<del>const TransitionLane2: Lane = /* */ 0b0000000000000000000010000000000;
<del>const TransitionLane3: Lane = /* */ 0b0000000000000000000100000000000;
<del>const TransitionLane4: Lane = /* */ 0b0000000000000000001000000000000;
<del>const TransitionLane5: Lane = /* */ 0b0000000000000000010000000000000;
<del>const TransitionLane6: Lane = /* */ 0b0000000000000000100000000000000;
<del>const TransitionLane7: Lane = /* */ 0b0000000000000001000000000000000;
<del>const TransitionLane8: Lane = /* */ 0b0000000000000010000000000000000;
<del>const TransitionLane9: Lane = /* */ 0b0000000000000100000000000000000;
<del>const TransitionLane10: Lane = /* */ 0b0000000000001000000000000000000;
<del>const TransitionLane11: Lane = /* */ 0b0000000000010000000000000000000;
<del>const TransitionLane12: Lane = /* */ 0b0000000000100000000000000000000;
<del>const TransitionLane13: Lane = /* */ 0b0000000001000000000000000000000;
<del>const TransitionLane14: Lane = /* */ 0b0000000010000000000000000000000;
<add>const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000100;
<add>export const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000000001000;
<add>
<add>export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000010000;
<add>export const DefaultLane: Lanes = /* */ 0b0000000000000000000000000100000;
<add>
<add>const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000001000000;
<add>const TransitionLanes: Lanes = /* */ 0b0000000011111111111111110000000;
<add>const TransitionLane1: Lane = /* */ 0b0000000000000000000000010000000;
<add>const TransitionLane2: Lane = /* */ 0b0000000000000000000000100000000;
<add>const TransitionLane3: Lane = /* */ 0b0000000000000000000001000000000;
<add>const TransitionLane4: Lane = /* */ 0b0000000000000000000010000000000;
<add>const TransitionLane5: Lane = /* */ 0b0000000000000000000100000000000;
<add>const TransitionLane6: Lane = /* */ 0b0000000000000000001000000000000;
<add>const TransitionLane7: Lane = /* */ 0b0000000000000000010000000000000;
<add>const TransitionLane8: Lane = /* */ 0b0000000000000000100000000000000;
<add>const TransitionLane9: Lane = /* */ 0b0000000000000001000000000000000;
<add>const TransitionLane10: Lane = /* */ 0b0000000000000010000000000000000;
<add>const TransitionLane11: Lane = /* */ 0b0000000000000100000000000000000;
<add>const TransitionLane12: Lane = /* */ 0b0000000000001000000000000000000;
<add>const TransitionLane13: Lane = /* */ 0b0000000000010000000000000000000;
<add>const TransitionLane14: Lane = /* */ 0b0000000000100000000000000000000;
<add>const TransitionLane15: Lane = /* */ 0b0000000001000000000000000000000;
<add>const TransitionLane16: Lane = /* */ 0b0000000010000000000000000000000;
<ide>
<ide> const RetryLanes: Lanes = /* */ 0b0000111100000000000000000000000;
<ide> const RetryLane1: Lane = /* */ 0b0000000100000000000000000000000;
<ide> export function getLabelsForLanes(lanes: Lanes): Array<string> | void {
<ide> if (lanes & SyncBatchedLane) {
<ide> labels.push('SyncBatched');
<ide> }
<del> if (lanes & InputDiscreteHydrationLane) {
<del> labels.push('InputDiscreteHydration');
<del> }
<del> if (lanes & InputDiscreteLane) {
<del> labels.push('InputDiscrete');
<del> }
<ide> if (lanes & InputContinuousHydrationLane) {
<ide> labels.push('InputContinuousHydration');
<ide> }
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> case SyncBatchedLane:
<ide> return_highestLanePriority = SyncBatchedLanePriority;
<ide> return SyncBatchedLane;
<del> case InputDiscreteHydrationLane:
<del> return_highestLanePriority = InputDiscreteHydrationLanePriority;
<del> return InputDiscreteHydrationLane;
<del> case InputDiscreteLane:
<del> return_highestLanePriority = InputDiscreteLanePriority;
<del> return InputDiscreteLane;
<ide> case InputContinuousHydrationLane:
<ide> return_highestLanePriority = InputContinuousHydrationLanePriority;
<ide> return InputContinuousHydrationLane;
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> case TransitionLane12:
<ide> case TransitionLane13:
<ide> case TransitionLane14:
<add> case TransitionLane15:
<add> case TransitionLane16:
<ide> return_highestLanePriority = TransitionPriority;
<ide> return lanes & TransitionLanes;
<ide> case RetryLane1:
<ide> export function lanePriorityToSchedulerPriority(
<ide> case SyncLanePriority:
<ide> case SyncBatchedLanePriority:
<ide> return ImmediateSchedulerPriority;
<del> case InputDiscreteHydrationLanePriority:
<del> case InputDiscreteLanePriority:
<ide> case InputContinuousHydrationLanePriority:
<ide> case InputContinuousLanePriority:
<ide> return UserBlockingSchedulerPriority;
<ide> export function findUpdateLane(lanePriority: LanePriority): Lane {
<ide> return SyncLane;
<ide> case SyncBatchedLanePriority:
<ide> return SyncBatchedLane;
<del> case InputDiscreteLanePriority:
<del> return SyncLane;
<ide> case InputContinuousLanePriority:
<ide> return InputContinuousLane;
<ide> case DefaultLanePriority:
<ide> export function getBumpedLaneForHydration(
<ide> case SyncBatchedLanePriority:
<ide> lane = NoLane;
<ide> break;
<del> case InputDiscreteHydrationLanePriority:
<del> case InputDiscreteLanePriority:
<del> lane = InputDiscreteHydrationLane;
<del> break;
<del> case InputContinuousHydrationLanePriority:
<ide> case InputContinuousLanePriority:
<ide> lane = InputContinuousHydrationLane;
<ide> break;
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js
<ide> import {markRenderScheduled} from './SchedulingProfiler';
<ide> // entry point, but we can't do this because of a circular dependency.
<ide> // They are used by third-party renderers so they need to stay up to date.
<ide> export {
<del> InputDiscreteLanePriority as DiscreteEventPriority,
<add> SyncLanePriority as DiscreteEventPriority,
<ide> InputContinuousLanePriority as ContinuousEventPriority,
<ide> DefaultLanePriority as DefaultEventPriority,
<ide> IdleLanePriority as IdleEventPriority,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> import {markRenderScheduled} from './SchedulingProfiler';
<ide> // entry point, but we can't do this because of a circular dependency.
<ide> // They are used by third-party renderers so they need to stay up to date.
<ide> export {
<del> InputDiscreteLanePriority as DiscreteEventPriority,
<add> SyncLanePriority as DiscreteEventPriority,
<ide> InputContinuousLanePriority as ContinuousEventPriority,
<ide> DefaultLanePriority as DefaultEventPriority,
<ide> IdleLanePriority as IdleEventPriority,
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> NoLanePriority,
<ide> SyncLanePriority,
<ide> SyncBatchedLanePriority,
<del> InputDiscreteLanePriority,
<ide> DefaultLanePriority,
<ide> NoLanes,
<ide> NoLane,
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> // TODO: Temporary until we confirm this warning is not fired.
<ide> if (
<ide> existingCallbackNode == null &&
<del> existingCallbackPriority !== InputDiscreteLanePriority &&
<ide> existingCallbackPriority !== SyncLanePriority
<ide> ) {
<ide> console.error(
<ide> function performSyncWorkOnRoot(root) {
<ide> exitStatus = renderRootSync(root, lanes);
<ide> } else {
<ide> lanes = getNextLanes(root, NoLanes);
<del> // Because we don't cancel synchronous tasks, sometimes more than one
<del> // synchronous task ends up being scheduled. This is an artifact of the fact
<del> // that we have two different lanes that schedule sync tasks: discrete and
<del> // sync. If we had only one, then (I believe) this extra check wouldn't be
<del> // necessary, because there's nothing higher priority than sync that would
<del> // cause us to cancel it.
<del> // TODO: Merge InputDiscreteLanePriority with SyncLanePriority, then delete
<del> // this bailout.
<del> if (supportsMicrotasks) {
<del> const nextLanesPriority = returnNextLanesPriority();
<del> if (nextLanesPriority < InputDiscreteLanePriority) {
<del> return null;
<del> }
<del> }
<ide> exitStatus = renderRootSync(root, lanes);
<ide> }
<ide>
<ide> export function discreteUpdates<A, B, C, D, R>(
<ide> ): R {
<ide> const previousLanePriority = getCurrentUpdateLanePriority();
<ide> try {
<del> setCurrentUpdateLanePriority(InputDiscreteLanePriority);
<add> setCurrentUpdateLanePriority(SyncLanePriority);
<ide> return fn(a, b, c, d);
<ide> } finally {
<ide> setCurrentUpdateLanePriority(previousLanePriority);
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> NoLanePriority,
<ide> SyncLanePriority,
<ide> SyncBatchedLanePriority,
<del> InputDiscreteLanePriority,
<ide> DefaultLanePriority,
<ide> NoLanes,
<ide> NoLane,
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> // TODO: Temporary until we confirm this warning is not fired.
<ide> if (
<ide> existingCallbackNode == null &&
<del> existingCallbackPriority !== InputDiscreteLanePriority &&
<ide> existingCallbackPriority !== SyncLanePriority
<ide> ) {
<ide> console.error(
<ide> function performSyncWorkOnRoot(root) {
<ide> exitStatus = renderRootSync(root, lanes);
<ide> } else {
<ide> lanes = getNextLanes(root, NoLanes);
<del> // Because we don't cancel synchronous tasks, sometimes more than one
<del> // synchronous task ends up being scheduled. This is an artifact of the fact
<del> // that we have two different lanes that schedule sync tasks: discrete and
<del> // sync. If we had only one, then (I believe) this extra check wouldn't be
<del> // necessary, because there's nothing higher priority than sync that would
<del> // cause us to cancel it.
<del> // TODO: Merge InputDiscreteLanePriority with SyncLanePriority, then delete
<del> // this bailout.
<del> if (supportsMicrotasks) {
<del> const nextLanesPriority = returnNextLanesPriority();
<del> if (nextLanesPriority < InputDiscreteLanePriority) {
<del> return null;
<del> }
<del> }
<ide> exitStatus = renderRootSync(root, lanes);
<ide> }
<ide>
<ide> export function discreteUpdates<A, B, C, D, R>(
<ide> ): R {
<ide> const previousLanePriority = getCurrentUpdateLanePriority();
<ide> try {
<del> setCurrentUpdateLanePriority(InputDiscreteLanePriority);
<add> setCurrentUpdateLanePriority(SyncLanePriority);
<ide> return fn(a, b, c, d);
<ide> } finally {
<ide> setCurrentUpdateLanePriority(previousLanePriority);
<ide><path>packages/react-reconciler/src/__tests__/DebugTracing-test.internal.js
<ide> describe('DebugTracing', () => {
<ide>
<ide> let logs;
<ide>
<del> const DEFAULT_LANE_STRING = '0b0000000000000000000000010000000';
<add> const DEFAULT_LANE_STRING = '0b0000000000000000000000000100000';
<ide> const RETRY_LANE_STRING = '0b0000000100000000000000000000000';
<ide>
<ide> beforeEach(() => { | 9 |
Javascript | Javascript | convert the `xref` to a "normal" class | bc828cd41f9ce25e8ce1a483f53b4ddb3fa5ccec | <ide><path>src/core/xref.js
<ide> import {
<ide> } from "./core_utils.js";
<ide> import { CipherTransformFactory } from "./crypto.js";
<ide>
<del>var XRef = (function XRefClosure() {
<del> // eslint-disable-next-line no-shadow
<del> function XRef(stream, pdfManager) {
<add>class XRef {
<add> constructor(stream, pdfManager) {
<ide> this.stream = stream;
<ide> this.pdfManager = pdfManager;
<ide> this.entries = [];
<ide> var XRef = (function XRefClosure() {
<ide> this._newRefNum = null;
<ide> }
<ide>
<del> XRef.prototype = {
<del> getNewRef: function XRef_getNewRef() {
<del> if (this._newRefNum === null) {
<del> this._newRefNum = this.entries.length;
<del> }
<del> return Ref.get(this._newRefNum++, 0);
<del> },
<add> getNewRef() {
<add> if (this._newRefNum === null) {
<add> this._newRefNum = this.entries.length;
<add> }
<add> return Ref.get(this._newRefNum++, 0);
<add> }
<ide>
<del> resetNewRef: function XRef_resetNewRef() {
<del> this._newRefNum = null;
<del> },
<add> resetNewRef() {
<add> this._newRefNum = null;
<add> }
<ide>
<del> setStartXRef: function XRef_setStartXRef(startXRef) {
<del> // Store the starting positions of xref tables as we process them
<del> // so we can recover from missing data errors
<del> this.startXRefQueue = [startXRef];
<del> },
<add> setStartXRef(startXRef) {
<add> // Store the starting positions of xref tables as we process them
<add> // so we can recover from missing data errors
<add> this.startXRefQueue = [startXRef];
<add> }
<ide>
<del> parse: function XRef_parse(recoveryMode) {
<del> var trailerDict;
<add> parse(recoveryMode = false) {
<add> var trailerDict;
<add> if (!recoveryMode) {
<add> trailerDict = this.readXRef();
<add> } else {
<add> warn("Indexing all PDF objects");
<add> trailerDict = this.indexObjects();
<add> }
<add> trailerDict.assignXref(this);
<add> this.trailer = trailerDict;
<add>
<add> let encrypt;
<add> try {
<add> encrypt = trailerDict.get("Encrypt");
<add> } catch (ex) {
<add> if (ex instanceof MissingDataException) {
<add> throw ex;
<add> }
<add> warn(`XRef.parse - Invalid "Encrypt" reference: "${ex}".`);
<add> }
<add> if (isDict(encrypt)) {
<add> var ids = trailerDict.get("ID");
<add> var fileId = ids && ids.length ? ids[0] : "";
<add> // The 'Encrypt' dictionary itself should not be encrypted, and by
<add> // setting `suppressEncryption` we can prevent an infinite loop inside
<add> // of `XRef_fetchUncompressed` if the dictionary contains indirect
<add> // objects (fixes issue7665.pdf).
<add> encrypt.suppressEncryption = true;
<add> this.encrypt = new CipherTransformFactory(
<add> encrypt,
<add> fileId,
<add> this.pdfManager.password
<add> );
<add> }
<add>
<add> // Get the root dictionary (catalog) object, and do some basic validation.
<add> let root;
<add> try {
<add> root = trailerDict.get("Root");
<add> } catch (ex) {
<add> if (ex instanceof MissingDataException) {
<add> throw ex;
<add> }
<add> warn(`XRef.parse - Invalid "Root" reference: "${ex}".`);
<add> }
<add> if (isDict(root) && root.has("Pages")) {
<add> this.root = root;
<add> } else {
<ide> if (!recoveryMode) {
<del> trailerDict = this.readXRef();
<del> } else {
<del> warn("Indexing all PDF objects");
<del> trailerDict = this.indexObjects();
<add> throw new XRefParseException();
<ide> }
<del> trailerDict.assignXref(this);
<del> this.trailer = trailerDict;
<add> throw new FormatError("Invalid root reference");
<add> }
<add> }
<ide>
<del> let encrypt;
<del> try {
<del> encrypt = trailerDict.get("Encrypt");
<del> } catch (ex) {
<del> if (ex instanceof MissingDataException) {
<del> throw ex;
<del> }
<del> warn(`XRef.parse - Invalid "Encrypt" reference: "${ex}".`);
<del> }
<del> if (isDict(encrypt)) {
<del> var ids = trailerDict.get("ID");
<del> var fileId = ids && ids.length ? ids[0] : "";
<del> // The 'Encrypt' dictionary itself should not be encrypted, and by
<del> // setting `suppressEncryption` we can prevent an infinite loop inside
<del> // of `XRef_fetchUncompressed` if the dictionary contains indirect
<del> // objects (fixes issue7665.pdf).
<del> encrypt.suppressEncryption = true;
<del> this.encrypt = new CipherTransformFactory(
<del> encrypt,
<del> fileId,
<del> this.pdfManager.password
<del> );
<del> }
<add> processXRefTable(parser) {
<add> if (!("tableState" in this)) {
<add> // Stores state of the table as we process it so we can resume
<add> // from middle of table in case of missing data error
<add> this.tableState = {
<add> entryNum: 0,
<add> streamPos: parser.lexer.stream.pos,
<add> parserBuf1: parser.buf1,
<add> parserBuf2: parser.buf2,
<add> };
<add> }
<add>
<add> var obj = this.readXRefTable(parser);
<add>
<add> // Sanity check
<add> if (!isCmd(obj, "trailer")) {
<add> throw new FormatError(
<add> "Invalid XRef table: could not find trailer dictionary"
<add> );
<add> }
<add> // Read trailer dictionary, e.g.
<add> // trailer
<add> // << /Size 22
<add> // /Root 20R
<add> // /Info 10R
<add> // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
<add> // >>
<add> // The parser goes through the entire stream << ... >> and provides
<add> // a getter interface for the key-value table
<add> var dict = parser.getObj();
<add>
<add> // The pdflib PDF generator can generate a nested trailer dictionary
<add> if (!isDict(dict) && dict.dict) {
<add> dict = dict.dict;
<add> }
<add> if (!isDict(dict)) {
<add> throw new FormatError(
<add> "Invalid XRef table: could not parse trailer dictionary"
<add> );
<add> }
<add> delete this.tableState;
<ide>
<del> // Get the root dictionary (catalog) object, and do some basic validation.
<del> let root;
<del> try {
<del> root = trailerDict.get("Root");
<del> } catch (ex) {
<del> if (ex instanceof MissingDataException) {
<del> throw ex;
<del> }
<del> warn(`XRef.parse - Invalid "Root" reference: "${ex}".`);
<del> }
<del> if (isDict(root) && root.has("Pages")) {
<del> this.root = root;
<del> } else {
<del> if (!recoveryMode) {
<del> throw new XRefParseException();
<add> return dict;
<add> }
<add>
<add> readXRefTable(parser) {
<add> // Example of cross-reference table:
<add> // xref
<add> // 0 1 <-- subsection header (first obj #, obj count)
<add> // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
<add> // 23 2 <-- subsection header ... and so on ...
<add> // 0000025518 00002 n
<add> // 0000025635 00000 n
<add> // trailer
<add> // ...
<add>
<add> var stream = parser.lexer.stream;
<add> var tableState = this.tableState;
<add> stream.pos = tableState.streamPos;
<add> parser.buf1 = tableState.parserBuf1;
<add> parser.buf2 = tableState.parserBuf2;
<add>
<add> // Outer loop is over subsection headers
<add> var obj;
<add>
<add> while (true) {
<add> if (!("firstEntryNum" in tableState) || !("entryCount" in tableState)) {
<add> if (isCmd((obj = parser.getObj()), "trailer")) {
<add> break;
<ide> }
<del> throw new FormatError("Invalid root reference");
<del> }
<del> },
<del>
<del> processXRefTable: function XRef_processXRefTable(parser) {
<del> if (!("tableState" in this)) {
<del> // Stores state of the table as we process it so we can resume
<del> // from middle of table in case of missing data error
<del> this.tableState = {
<del> entryNum: 0,
<del> streamPos: parser.lexer.stream.pos,
<del> parserBuf1: parser.buf1,
<del> parserBuf2: parser.buf2,
<del> };
<add> tableState.firstEntryNum = obj;
<add> tableState.entryCount = parser.getObj();
<ide> }
<ide>
<del> var obj = this.readXRefTable(parser);
<del>
<del> // Sanity check
<del> if (!isCmd(obj, "trailer")) {
<del> throw new FormatError(
<del> "Invalid XRef table: could not find trailer dictionary"
<del> );
<del> }
<del> // Read trailer dictionary, e.g.
<del> // trailer
<del> // << /Size 22
<del> // /Root 20R
<del> // /Info 10R
<del> // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
<del> // >>
<del> // The parser goes through the entire stream << ... >> and provides
<del> // a getter interface for the key-value table
<del> var dict = parser.getObj();
<del>
<del> // The pdflib PDF generator can generate a nested trailer dictionary
<del> if (!isDict(dict) && dict.dict) {
<del> dict = dict.dict;
<del> }
<del> if (!isDict(dict)) {
<add> var first = tableState.firstEntryNum;
<add> var count = tableState.entryCount;
<add> if (!Number.isInteger(first) || !Number.isInteger(count)) {
<ide> throw new FormatError(
<del> "Invalid XRef table: could not parse trailer dictionary"
<add> "Invalid XRef table: wrong types in subsection header"
<ide> );
<ide> }
<del> delete this.tableState;
<del>
<del> return dict;
<del> },
<del>
<del> readXRefTable: function XRef_readXRefTable(parser) {
<del> // Example of cross-reference table:
<del> // xref
<del> // 0 1 <-- subsection header (first obj #, obj count)
<del> // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
<del> // 23 2 <-- subsection header ... and so on ...
<del> // 0000025518 00002 n
<del> // 0000025635 00000 n
<del> // trailer
<del> // ...
<del>
<del> var stream = parser.lexer.stream;
<del> var tableState = this.tableState;
<del> stream.pos = tableState.streamPos;
<del> parser.buf1 = tableState.parserBuf1;
<del> parser.buf2 = tableState.parserBuf2;
<del>
<del> // Outer loop is over subsection headers
<del> var obj;
<del>
<del> while (true) {
<del> if (!("firstEntryNum" in tableState) || !("entryCount" in tableState)) {
<del> if (isCmd((obj = parser.getObj()), "trailer")) {
<del> break;
<add> // Inner loop is over objects themselves
<add> for (var i = tableState.entryNum; i < count; i++) {
<add> tableState.streamPos = stream.pos;
<add> tableState.entryNum = i;
<add> tableState.parserBuf1 = parser.buf1;
<add> tableState.parserBuf2 = parser.buf2;
<add>
<add> var entry = {};
<add> entry.offset = parser.getObj();
<add> entry.gen = parser.getObj();
<add> var type = parser.getObj();
<add>
<add> if (type instanceof Cmd) {
<add> switch (type.cmd) {
<add> case "f":
<add> entry.free = true;
<add> break;
<add> case "n":
<add> entry.uncompressed = true;
<add> break;
<ide> }
<del> tableState.firstEntryNum = obj;
<del> tableState.entryCount = parser.getObj();
<ide> }
<ide>
<del> var first = tableState.firstEntryNum;
<del> var count = tableState.entryCount;
<del> if (!Number.isInteger(first) || !Number.isInteger(count)) {
<add> // Validate entry obj
<add> if (
<add> !Number.isInteger(entry.offset) ||
<add> !Number.isInteger(entry.gen) ||
<add> !(entry.free || entry.uncompressed)
<add> ) {
<ide> throw new FormatError(
<del> "Invalid XRef table: wrong types in subsection header"
<add> `Invalid entry in XRef subsection: ${first}, ${count}`
<ide> );
<ide> }
<del> // Inner loop is over objects themselves
<del> for (var i = tableState.entryNum; i < count; i++) {
<del> tableState.streamPos = stream.pos;
<del> tableState.entryNum = i;
<del> tableState.parserBuf1 = parser.buf1;
<del> tableState.parserBuf2 = parser.buf2;
<del>
<del> var entry = {};
<del> entry.offset = parser.getObj();
<del> entry.gen = parser.getObj();
<del> var type = parser.getObj();
<del>
<del> if (type instanceof Cmd) {
<del> switch (type.cmd) {
<del> case "f":
<del> entry.free = true;
<del> break;
<del> case "n":
<del> entry.uncompressed = true;
<del> break;
<del> }
<del> }
<del>
<del> // Validate entry obj
<del> if (
<del> !Number.isInteger(entry.offset) ||
<del> !Number.isInteger(entry.gen) ||
<del> !(entry.free || entry.uncompressed)
<del> ) {
<del> throw new FormatError(
<del> `Invalid entry in XRef subsection: ${first}, ${count}`
<del> );
<del> }
<del>
<del> // The first xref table entry, i.e. obj 0, should be free. Attempting
<del> // to adjust an incorrect first obj # (fixes issue 3248 and 7229).
<del> if (i === 0 && entry.free && first === 1) {
<del> first = 0;
<del> }
<ide>
<del> if (!this.entries[i + first]) {
<del> this.entries[i + first] = entry;
<del> }
<add> // The first xref table entry, i.e. obj 0, should be free. Attempting
<add> // to adjust an incorrect first obj # (fixes issue 3248 and 7229).
<add> if (i === 0 && entry.free && first === 1) {
<add> first = 0;
<ide> }
<ide>
<del> tableState.entryNum = 0;
<del> tableState.streamPos = stream.pos;
<del> tableState.parserBuf1 = parser.buf1;
<del> tableState.parserBuf2 = parser.buf2;
<del> delete tableState.firstEntryNum;
<del> delete tableState.entryCount;
<add> if (!this.entries[i + first]) {
<add> this.entries[i + first] = entry;
<add> }
<ide> }
<ide>
<del> // Sanity check: as per spec, first object must be free
<del> if (this.entries[0] && !this.entries[0].free) {
<del> throw new FormatError("Invalid XRef table: unexpected first object");
<del> }
<del> return obj;
<del> },
<del>
<del> processXRefStream: function XRef_processXRefStream(stream) {
<del> if (!("streamState" in this)) {
<del> // Stores state of the stream as we process it so we can resume
<del> // from middle of stream in case of missing data error
<del> var streamParameters = stream.dict;
<del> var byteWidths = streamParameters.get("W");
<del> var range = streamParameters.get("Index");
<del> if (!range) {
<del> range = [0, streamParameters.get("Size")];
<del> }
<add> tableState.entryNum = 0;
<add> tableState.streamPos = stream.pos;
<add> tableState.parserBuf1 = parser.buf1;
<add> tableState.parserBuf2 = parser.buf2;
<add> delete tableState.firstEntryNum;
<add> delete tableState.entryCount;
<add> }
<ide>
<del> this.streamState = {
<del> entryRanges: range,
<del> byteWidths,
<del> entryNum: 0,
<del> streamPos: stream.pos,
<del> };
<del> }
<del> this.readXRefStream(stream);
<del> delete this.streamState;
<add> // Sanity check: as per spec, first object must be free
<add> if (this.entries[0] && !this.entries[0].free) {
<add> throw new FormatError("Invalid XRef table: unexpected first object");
<add> }
<add> return obj;
<add> }
<add>
<add> processXRefStream(stream) {
<add> if (!("streamState" in this)) {
<add> // Stores state of the stream as we process it so we can resume
<add> // from middle of stream in case of missing data error
<add> var streamParameters = stream.dict;
<add> var byteWidths = streamParameters.get("W");
<add> var range = streamParameters.get("Index");
<add> if (!range) {
<add> range = [0, streamParameters.get("Size")];
<add> }
<add>
<add> this.streamState = {
<add> entryRanges: range,
<add> byteWidths,
<add> entryNum: 0,
<add> streamPos: stream.pos,
<add> };
<add> }
<add> this.readXRefStream(stream);
<add> delete this.streamState;
<add>
<add> return stream.dict;
<add> }
<ide>
<del> return stream.dict;
<del> },
<add> readXRefStream(stream) {
<add> var i, j;
<add> var streamState = this.streamState;
<add> stream.pos = streamState.streamPos;
<ide>
<del> readXRefStream: function XRef_readXRefStream(stream) {
<del> var i, j;
<del> var streamState = this.streamState;
<del> stream.pos = streamState.streamPos;
<add> var byteWidths = streamState.byteWidths;
<add> var typeFieldWidth = byteWidths[0];
<add> var offsetFieldWidth = byteWidths[1];
<add> var generationFieldWidth = byteWidths[2];
<ide>
<del> var byteWidths = streamState.byteWidths;
<del> var typeFieldWidth = byteWidths[0];
<del> var offsetFieldWidth = byteWidths[1];
<del> var generationFieldWidth = byteWidths[2];
<add> var entryRanges = streamState.entryRanges;
<add> while (entryRanges.length > 0) {
<add> var first = entryRanges[0];
<add> var n = entryRanges[1];
<ide>
<del> var entryRanges = streamState.entryRanges;
<del> while (entryRanges.length > 0) {
<del> var first = entryRanges[0];
<del> var n = entryRanges[1];
<add> if (!Number.isInteger(first) || !Number.isInteger(n)) {
<add> throw new FormatError(`Invalid XRef range fields: ${first}, ${n}`);
<add> }
<add> if (
<add> !Number.isInteger(typeFieldWidth) ||
<add> !Number.isInteger(offsetFieldWidth) ||
<add> !Number.isInteger(generationFieldWidth)
<add> ) {
<add> throw new FormatError(
<add> `Invalid XRef entry fields length: ${first}, ${n}`
<add> );
<add> }
<add> for (i = streamState.entryNum; i < n; ++i) {
<add> streamState.entryNum = i;
<add> streamState.streamPos = stream.pos;
<ide>
<del> if (!Number.isInteger(first) || !Number.isInteger(n)) {
<del> throw new FormatError(`Invalid XRef range fields: ${first}, ${n}`);
<add> var type = 0,
<add> offset = 0,
<add> generation = 0;
<add> for (j = 0; j < typeFieldWidth; ++j) {
<add> type = (type << 8) | stream.getByte();
<ide> }
<del> if (
<del> !Number.isInteger(typeFieldWidth) ||
<del> !Number.isInteger(offsetFieldWidth) ||
<del> !Number.isInteger(generationFieldWidth)
<del> ) {
<del> throw new FormatError(
<del> `Invalid XRef entry fields length: ${first}, ${n}`
<del> );
<add> // if type field is absent, its default value is 1
<add> if (typeFieldWidth === 0) {
<add> type = 1;
<ide> }
<del> for (i = streamState.entryNum; i < n; ++i) {
<del> streamState.entryNum = i;
<del> streamState.streamPos = stream.pos;
<del>
<del> var type = 0,
<del> offset = 0,
<del> generation = 0;
<del> for (j = 0; j < typeFieldWidth; ++j) {
<del> type = (type << 8) | stream.getByte();
<del> }
<del> // if type field is absent, its default value is 1
<del> if (typeFieldWidth === 0) {
<del> type = 1;
<del> }
<del> for (j = 0; j < offsetFieldWidth; ++j) {
<del> offset = (offset << 8) | stream.getByte();
<del> }
<del> for (j = 0; j < generationFieldWidth; ++j) {
<del> generation = (generation << 8) | stream.getByte();
<del> }
<del> var entry = {};
<del> entry.offset = offset;
<del> entry.gen = generation;
<del> switch (type) {
<del> case 0:
<del> entry.free = true;
<del> break;
<del> case 1:
<del> entry.uncompressed = true;
<del> break;
<del> case 2:
<del> break;
<del> default:
<del> throw new FormatError(`Invalid XRef entry type: ${type}`);
<del> }
<del> if (!this.entries[first + i]) {
<del> this.entries[first + i] = entry;
<del> }
<add> for (j = 0; j < offsetFieldWidth; ++j) {
<add> offset = (offset << 8) | stream.getByte();
<ide> }
<del>
<del> streamState.entryNum = 0;
<del> streamState.streamPos = stream.pos;
<del> entryRanges.splice(0, 2);
<del> }
<del> },
<del>
<del> indexObjects: function XRef_indexObjects() {
<del> // Simple scan through the PDF content to find objects,
<del> // trailers and XRef streams.
<del> var TAB = 0x9,
<del> LF = 0xa,
<del> CR = 0xd,
<del> SPACE = 0x20;
<del> var PERCENT = 0x25,
<del> LT = 0x3c;
<del>
<del> function readToken(data, offset) {
<del> var token = "",
<del> ch = data[offset];
<del> while (ch !== LF && ch !== CR && ch !== LT) {
<del> if (++offset >= data.length) {
<add> for (j = 0; j < generationFieldWidth; ++j) {
<add> generation = (generation << 8) | stream.getByte();
<add> }
<add> var entry = {};
<add> entry.offset = offset;
<add> entry.gen = generation;
<add> switch (type) {
<add> case 0:
<add> entry.free = true;
<ide> break;
<del> }
<del> token += String.fromCharCode(ch);
<del> ch = data[offset];
<add> case 1:
<add> entry.uncompressed = true;
<add> break;
<add> case 2:
<add> break;
<add> default:
<add> throw new FormatError(`Invalid XRef entry type: ${type}`);
<ide> }
<del> return token;
<del> }
<del> function skipUntil(data, offset, what) {
<del> var length = what.length,
<del> dataLength = data.length;
<del> var skipped = 0;
<del> // finding byte sequence
<del> while (offset < dataLength) {
<del> var i = 0;
<del> while (i < length && data[offset + i] === what[i]) {
<del> ++i;
<del> }
<del> if (i >= length) {
<del> break; // sequence found
<del> }
<del> offset++;
<del> skipped++;
<add> if (!this.entries[first + i]) {
<add> this.entries[first + i] = entry;
<ide> }
<del> return skipped;
<ide> }
<del> var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
<del> const endobjRegExp = /\bendobj[\b\s]$/;
<del> const nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s<])$/;
<del> const CHECK_CONTENT_LENGTH = 25;
<del>
<del> var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
<del> // prettier-ignore
<del> var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
<del> 101, 102]);
<del> const objBytes = new Uint8Array([111, 98, 106]);
<del> var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
<del>
<del> // Clear out any existing entries, since they may be bogus.
<del> this.entries.length = 0;
<del>
<del> var stream = this.stream;
<del> stream.pos = 0;
<del> var buffer = stream.getBytes();
<del> var position = stream.start,
<del> length = buffer.length;
<del> var trailers = [],
<del> xrefStms = [];
<del> while (position < length) {
<del> var ch = buffer[position];
<del> if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
<del> ++position;
<del> continue;
<add>
<add> streamState.entryNum = 0;
<add> streamState.streamPos = stream.pos;
<add> entryRanges.splice(0, 2);
<add> }
<add> }
<add>
<add> indexObjects() {
<add> // Simple scan through the PDF content to find objects,
<add> // trailers and XRef streams.
<add> var TAB = 0x9,
<add> LF = 0xa,
<add> CR = 0xd,
<add> SPACE = 0x20;
<add> var PERCENT = 0x25,
<add> LT = 0x3c;
<add>
<add> function readToken(data, offset) {
<add> var token = "",
<add> ch = data[offset];
<add> while (ch !== LF && ch !== CR && ch !== LT) {
<add> if (++offset >= data.length) {
<add> break;
<ide> }
<del> if (ch === PERCENT) {
<del> // %-comment
<del> do {
<del> ++position;
<del> if (position >= length) {
<del> break;
<del> }
<del> ch = buffer[position];
<del> } while (ch !== LF && ch !== CR);
<del> continue;
<add> token += String.fromCharCode(ch);
<add> ch = data[offset];
<add> }
<add> return token;
<add> }
<add> function skipUntil(data, offset, what) {
<add> var length = what.length,
<add> dataLength = data.length;
<add> var skipped = 0;
<add> // finding byte sequence
<add> while (offset < dataLength) {
<add> var i = 0;
<add> while (i < length && data[offset + i] === what[i]) {
<add> ++i;
<ide> }
<del> var token = readToken(buffer, position);
<del> var m;
<del> if (
<del> token.startsWith("xref") &&
<del> (token.length === 4 || /\s/.test(token[4]))
<del> ) {
<del> position += skipUntil(buffer, position, trailerBytes);
<del> trailers.push(position);
<del> position += skipUntil(buffer, position, startxrefBytes);
<del> } else if ((m = objRegExp.exec(token))) {
<del> const num = m[1] | 0,
<del> gen = m[2] | 0;
<del> if (!this.entries[num] || this.entries[num].gen === gen) {
<del> this.entries[num] = {
<del> offset: position - stream.start,
<del> gen,
<del> uncompressed: true,
<del> };
<add> if (i >= length) {
<add> break; // sequence found
<add> }
<add> offset++;
<add> skipped++;
<add> }
<add> return skipped;
<add> }
<add> var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
<add> const endobjRegExp = /\bendobj[\b\s]$/;
<add> const nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s<])$/;
<add> const CHECK_CONTENT_LENGTH = 25;
<add>
<add> var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
<add> // prettier-ignore
<add> var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
<add> 101, 102]);
<add> const objBytes = new Uint8Array([111, 98, 106]);
<add> var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
<add>
<add> // Clear out any existing entries, since they may be bogus.
<add> this.entries.length = 0;
<add>
<add> var stream = this.stream;
<add> stream.pos = 0;
<add> var buffer = stream.getBytes();
<add> var position = stream.start,
<add> length = buffer.length;
<add> var trailers = [],
<add> xrefStms = [];
<add> while (position < length) {
<add> var ch = buffer[position];
<add> if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
<add> ++position;
<add> continue;
<add> }
<add> if (ch === PERCENT) {
<add> // %-comment
<add> do {
<add> ++position;
<add> if (position >= length) {
<add> break;
<ide> }
<del> let contentLength,
<del> startPos = position + token.length;
<add> ch = buffer[position];
<add> } while (ch !== LF && ch !== CR);
<add> continue;
<add> }
<add> var token = readToken(buffer, position);
<add> var m;
<add> if (
<add> token.startsWith("xref") &&
<add> (token.length === 4 || /\s/.test(token[4]))
<add> ) {
<add> position += skipUntil(buffer, position, trailerBytes);
<add> trailers.push(position);
<add> position += skipUntil(buffer, position, startxrefBytes);
<add> } else if ((m = objRegExp.exec(token))) {
<add> const num = m[1] | 0,
<add> gen = m[2] | 0;
<add> if (!this.entries[num] || this.entries[num].gen === gen) {
<add> this.entries[num] = {
<add> offset: position - stream.start,
<add> gen,
<add> uncompressed: true,
<add> };
<add> }
<add> let contentLength,
<add> startPos = position + token.length;
<ide>
<del> // Find the next "obj" string, rather than "endobj", to ensure that
<del> // we won't skip over a new 'obj' operator in corrupt files where
<del> // 'endobj' operators are missing (fixes issue9105_reduced.pdf).
<del> while (startPos < buffer.length) {
<del> const endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
<del> contentLength = endPos - position;
<add> // Find the next "obj" string, rather than "endobj", to ensure that
<add> // we won't skip over a new 'obj' operator in corrupt files where
<add> // 'endobj' operators are missing (fixes issue9105_reduced.pdf).
<add> while (startPos < buffer.length) {
<add> const endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
<add> contentLength = endPos - position;
<ide>
<del> const checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
<del> const tokenStr = bytesToString(buffer.subarray(checkPos, endPos));
<add> const checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
<add> const tokenStr = bytesToString(buffer.subarray(checkPos, endPos));
<ide>
<del> // Check if the current object ends with an 'endobj' operator.
<del> if (endobjRegExp.test(tokenStr)) {
<add> // Check if the current object ends with an 'endobj' operator.
<add> if (endobjRegExp.test(tokenStr)) {
<add> break;
<add> } else {
<add> // Check if an "obj" occurrence is actually a new object,
<add> // i.e. the current object is missing the 'endobj' operator.
<add> const objToken = nestedObjRegExp.exec(tokenStr);
<add>
<add> if (objToken && objToken[1]) {
<add> warn(
<add> 'indexObjects: Found new "obj" inside of another "obj", ' +
<add> 'caused by missing "endobj" -- trying to recover.'
<add> );
<add> contentLength -= objToken[1].length;
<ide> break;
<del> } else {
<del> // Check if an "obj" occurrence is actually a new object,
<del> // i.e. the current object is missing the 'endobj' operator.
<del> const objToken = nestedObjRegExp.exec(tokenStr);
<del>
<del> if (objToken && objToken[1]) {
<del> warn(
<del> 'indexObjects: Found new "obj" inside of another "obj", ' +
<del> 'caused by missing "endobj" -- trying to recover.'
<del> );
<del> contentLength -= objToken[1].length;
<del> break;
<del> }
<ide> }
<del> startPos = endPos;
<del> }
<del> const content = buffer.subarray(position, position + contentLength);
<del>
<del> // checking XRef stream suspect
<del> // (it shall have '/XRef' and next char is not a letter)
<del> var xrefTagOffset = skipUntil(content, 0, xrefBytes);
<del> if (
<del> xrefTagOffset < contentLength &&
<del> content[xrefTagOffset + 5] < 64
<del> ) {
<del> xrefStms.push(position - stream.start);
<del> this.xrefstms[position - stream.start] = 1; // Avoid recursion
<ide> }
<del>
<del> position += contentLength;
<del> } else if (
<del> token.startsWith("trailer") &&
<del> (token.length === 7 || /\s/.test(token[7]))
<del> ) {
<del> trailers.push(position);
<del> position += skipUntil(buffer, position, startxrefBytes);
<del> } else {
<del> position += token.length + 1;
<add> startPos = endPos;
<add> }
<add> const content = buffer.subarray(position, position + contentLength);
<add>
<add> // checking XRef stream suspect
<add> // (it shall have '/XRef' and next char is not a letter)
<add> var xrefTagOffset = skipUntil(content, 0, xrefBytes);
<add> if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
<add> xrefStms.push(position - stream.start);
<add> this.xrefstms[position - stream.start] = 1; // Avoid recursion
<ide> }
<add>
<add> position += contentLength;
<add> } else if (
<add> token.startsWith("trailer") &&
<add> (token.length === 7 || /\s/.test(token[7]))
<add> ) {
<add> trailers.push(position);
<add> position += skipUntil(buffer, position, startxrefBytes);
<add> } else {
<add> position += token.length + 1;
<add> }
<add> }
<add> // reading XRef streams
<add> for (let i = 0, ii = xrefStms.length; i < ii; ++i) {
<add> this.startXRefQueue.push(xrefStms[i]);
<add> this.readXRef(/* recoveryMode */ true);
<add> }
<add> // finding main trailer
<add> let trailerDict;
<add> for (let i = 0, ii = trailers.length; i < ii; ++i) {
<add> stream.pos = trailers[i];
<add> const parser = new Parser({
<add> lexer: new Lexer(stream),
<add> xref: this,
<add> allowStreams: true,
<add> recoveryMode: true,
<add> });
<add> var obj = parser.getObj();
<add> if (!isCmd(obj, "trailer")) {
<add> continue;
<ide> }
<del> // reading XRef streams
<del> for (let i = 0, ii = xrefStms.length; i < ii; ++i) {
<del> this.startXRefQueue.push(xrefStms[i]);
<del> this.readXRef(/* recoveryMode */ true);
<add> // read the trailer dictionary
<add> const dict = parser.getObj();
<add> if (!isDict(dict)) {
<add> continue;
<ide> }
<del> // finding main trailer
<del> let trailerDict;
<del> for (let i = 0, ii = trailers.length; i < ii; ++i) {
<del> stream.pos = trailers[i];
<del> const parser = new Parser({
<del> lexer: new Lexer(stream),
<del> xref: this,
<del> allowStreams: true,
<del> recoveryMode: true,
<del> });
<del> var obj = parser.getObj();
<del> if (!isCmd(obj, "trailer")) {
<add> // Do some basic validation of the trailer/root dictionary candidate.
<add> try {
<add> const rootDict = dict.get("Root");
<add> if (!(rootDict instanceof Dict)) {
<ide> continue;
<ide> }
<del> // read the trailer dictionary
<del> const dict = parser.getObj();
<del> if (!isDict(dict)) {
<add> const pagesDict = rootDict.get("Pages");
<add> if (!(pagesDict instanceof Dict)) {
<ide> continue;
<ide> }
<del> // Do some basic validation of the trailer/root dictionary candidate.
<del> try {
<del> const rootDict = dict.get("Root");
<del> if (!(rootDict instanceof Dict)) {
<del> continue;
<del> }
<del> const pagesDict = rootDict.get("Pages");
<del> if (!(pagesDict instanceof Dict)) {
<del> continue;
<del> }
<del> const pagesCount = pagesDict.get("Count");
<del> if (!Number.isInteger(pagesCount)) {
<del> continue;
<del> }
<del> // The top-level /Pages dictionary isn't obviously corrupt.
<del> } catch (ex) {
<add> const pagesCount = pagesDict.get("Count");
<add> if (!Number.isInteger(pagesCount)) {
<ide> continue;
<ide> }
<del> // taking the first one with 'ID'
<del> if (dict.has("ID")) {
<del> return dict;
<del> }
<del> // The current dictionary is a candidate, but continue searching.
<del> trailerDict = dict;
<del> }
<del> // No trailer with 'ID', taking last one (if exists).
<del> if (trailerDict) {
<del> return trailerDict;
<del> }
<del> // nothing helps
<del> throw new InvalidPDFException("Invalid PDF structure.");
<del> },
<add> // The top-level /Pages dictionary isn't obviously corrupt.
<add> } catch (ex) {
<add> continue;
<add> }
<add> // taking the first one with 'ID'
<add> if (dict.has("ID")) {
<add> return dict;
<add> }
<add> // The current dictionary is a candidate, but continue searching.
<add> trailerDict = dict;
<add> }
<add> // No trailer with 'ID', taking last one (if exists).
<add> if (trailerDict) {
<add> return trailerDict;
<add> }
<add> // nothing helps
<add> throw new InvalidPDFException("Invalid PDF structure.");
<add> }
<ide>
<del> readXRef: function XRef_readXRef(recoveryMode) {
<del> var stream = this.stream;
<del> // Keep track of already parsed XRef tables, to prevent an infinite loop
<del> // when parsing corrupt PDF files where e.g. the /Prev entries create a
<del> // circular dependency between tables (fixes bug1393476.pdf).
<del> const startXRefParsedCache = new Set();
<add> readXRef(recoveryMode = false) {
<add> var stream = this.stream;
<add> // Keep track of already parsed XRef tables, to prevent an infinite loop
<add> // when parsing corrupt PDF files where e.g. the /Prev entries create a
<add> // circular dependency between tables (fixes bug1393476.pdf).
<add> const startXRefParsedCache = new Set();
<ide>
<del> try {
<del> while (this.startXRefQueue.length) {
<del> var startXRef = this.startXRefQueue[0];
<add> try {
<add> while (this.startXRefQueue.length) {
<add> var startXRef = this.startXRefQueue[0];
<ide>
<del> if (startXRefParsedCache.has(startXRef)) {
<del> warn("readXRef - skipping XRef table since it was already parsed.");
<del> this.startXRefQueue.shift();
<del> continue;
<del> }
<del> startXRefParsedCache.add(startXRef);
<del>
<del> stream.pos = startXRef + stream.start;
<del>
<del> const parser = new Parser({
<del> lexer: new Lexer(stream),
<del> xref: this,
<del> allowStreams: true,
<del> });
<del> var obj = parser.getObj();
<del> var dict;
<del>
<del> // Get dictionary
<del> if (isCmd(obj, "xref")) {
<del> // Parse end-of-file XRef
<del> dict = this.processXRefTable(parser);
<del> if (!this.topDict) {
<del> this.topDict = dict;
<del> }
<add> if (startXRefParsedCache.has(startXRef)) {
<add> warn("readXRef - skipping XRef table since it was already parsed.");
<add> this.startXRefQueue.shift();
<add> continue;
<add> }
<add> startXRefParsedCache.add(startXRef);
<ide>
<del> // Recursively get other XRefs 'XRefStm', if any
<del> obj = dict.get("XRefStm");
<del> if (Number.isInteger(obj)) {
<del> var pos = obj;
<del> // ignore previously loaded xref streams
<del> // (possible infinite recursion)
<del> if (!(pos in this.xrefstms)) {
<del> this.xrefstms[pos] = 1;
<del> this.startXRefQueue.push(pos);
<del> }
<del> }
<del> } else if (Number.isInteger(obj)) {
<del> // Parse in-stream XRef
<del> if (
<del> !Number.isInteger(parser.getObj()) ||
<del> !isCmd(parser.getObj(), "obj") ||
<del> !isStream((obj = parser.getObj()))
<del> ) {
<del> throw new FormatError("Invalid XRef stream");
<del> }
<del> dict = this.processXRefStream(obj);
<del> if (!this.topDict) {
<del> this.topDict = dict;
<del> }
<del> if (!dict) {
<del> throw new FormatError("Failed to read XRef stream");
<del> }
<del> } else {
<del> throw new FormatError("Invalid XRef stream header");
<add> stream.pos = startXRef + stream.start;
<add>
<add> const parser = new Parser({
<add> lexer: new Lexer(stream),
<add> xref: this,
<add> allowStreams: true,
<add> });
<add> var obj = parser.getObj();
<add> var dict;
<add>
<add> // Get dictionary
<add> if (isCmd(obj, "xref")) {
<add> // Parse end-of-file XRef
<add> dict = this.processXRefTable(parser);
<add> if (!this.topDict) {
<add> this.topDict = dict;
<ide> }
<ide>
<del> // Recursively get previous dictionary, if any
<del> obj = dict.get("Prev");
<add> // Recursively get other XRefs 'XRefStm', if any
<add> obj = dict.get("XRefStm");
<ide> if (Number.isInteger(obj)) {
<del> this.startXRefQueue.push(obj);
<del> } else if (isRef(obj)) {
<del> // The spec says Prev must not be a reference, i.e. "/Prev NNN"
<del> // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
<del> this.startXRefQueue.push(obj.num);
<add> var pos = obj;
<add> // ignore previously loaded xref streams
<add> // (possible infinite recursion)
<add> if (!(pos in this.xrefstms)) {
<add> this.xrefstms[pos] = 1;
<add> this.startXRefQueue.push(pos);
<add> }
<ide> }
<del>
<del> this.startXRefQueue.shift();
<add> } else if (Number.isInteger(obj)) {
<add> // Parse in-stream XRef
<add> if (
<add> !Number.isInteger(parser.getObj()) ||
<add> !isCmd(parser.getObj(), "obj") ||
<add> !isStream((obj = parser.getObj()))
<add> ) {
<add> throw new FormatError("Invalid XRef stream");
<add> }
<add> dict = this.processXRefStream(obj);
<add> if (!this.topDict) {
<add> this.topDict = dict;
<add> }
<add> if (!dict) {
<add> throw new FormatError("Failed to read XRef stream");
<add> }
<add> } else {
<add> throw new FormatError("Invalid XRef stream header");
<ide> }
<ide>
<del> return this.topDict;
<del> } catch (e) {
<del> if (e instanceof MissingDataException) {
<del> throw e;
<add> // Recursively get previous dictionary, if any
<add> obj = dict.get("Prev");
<add> if (Number.isInteger(obj)) {
<add> this.startXRefQueue.push(obj);
<add> } else if (isRef(obj)) {
<add> // The spec says Prev must not be a reference, i.e. "/Prev NNN"
<add> // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
<add> this.startXRefQueue.push(obj.num);
<ide> }
<del> info("(while reading XRef): " + e);
<del> }
<ide>
<del> if (recoveryMode) {
<del> return undefined;
<add> this.startXRefQueue.shift();
<ide> }
<del> throw new XRefParseException();
<del> },
<ide>
<del> getEntry: function XRef_getEntry(i) {
<del> var xrefEntry = this.entries[i];
<del> if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
<del> return xrefEntry;
<add> return this.topDict;
<add> } catch (e) {
<add> if (e instanceof MissingDataException) {
<add> throw e;
<ide> }
<del> return null;
<del> },
<add> info("(while reading XRef): " + e);
<add> }
<ide>
<del> fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
<del> if (obj instanceof Ref) {
<del> return this.fetch(obj, suppressEncryption);
<del> }
<del> return obj;
<del> },
<add> if (recoveryMode) {
<add> return undefined;
<add> }
<add> throw new XRefParseException();
<add> }
<ide>
<del> fetch: function XRef_fetch(ref, suppressEncryption) {
<del> if (!(ref instanceof Ref)) {
<del> throw new Error("ref object is not a reference");
<del> }
<del> const num = ref.num;
<del>
<del> // The XRef cache is populated with objects which are obtained through
<del> // `Parser.getObj`, and indirectly via `Lexer.getObj`. Neither of these
<del> // methods should ever return `undefined` (note the `assert` calls below).
<del> const cacheEntry = this._cacheMap.get(num);
<del> if (cacheEntry !== undefined) {
<del> // In documents with Object Streams, it's possible that cached `Dict`s
<del> // have not been assigned an `objId` yet (see e.g. issue3115r.pdf).
<del> if (cacheEntry instanceof Dict && !cacheEntry.objId) {
<del> cacheEntry.objId = ref.toString();
<del> }
<del> return cacheEntry;
<del> }
<del> let xrefEntry = this.getEntry(num);
<add> getEntry(i) {
<add> var xrefEntry = this.entries[i];
<add> if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
<add> return xrefEntry;
<add> }
<add> return null;
<add> }
<ide>
<del> if (xrefEntry === null) {
<del> // The referenced entry can be free.
<del> this._cacheMap.set(num, xrefEntry);
<del> return xrefEntry;
<del> }
<add> fetchIfRef(obj, suppressEncryption = false) {
<add> if (obj instanceof Ref) {
<add> return this.fetch(obj, suppressEncryption);
<add> }
<add> return obj;
<add> }
<ide>
<del> if (xrefEntry.uncompressed) {
<del> xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
<del> } else {
<del> xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
<add> fetch(ref, suppressEncryption = false) {
<add> if (!(ref instanceof Ref)) {
<add> throw new Error("ref object is not a reference");
<add> }
<add> const num = ref.num;
<add>
<add> // The XRef cache is populated with objects which are obtained through
<add> // `Parser.getObj`, and indirectly via `Lexer.getObj`. Neither of these
<add> // methods should ever return `undefined` (note the `assert` calls below).
<add> const cacheEntry = this._cacheMap.get(num);
<add> if (cacheEntry !== undefined) {
<add> // In documents with Object Streams, it's possible that cached `Dict`s
<add> // have not been assigned an `objId` yet (see e.g. issue3115r.pdf).
<add> if (cacheEntry instanceof Dict && !cacheEntry.objId) {
<add> cacheEntry.objId = ref.toString();
<add> }
<add> return cacheEntry;
<add> }
<add> let xrefEntry = this.getEntry(num);
<add>
<add> if (xrefEntry === null) {
<add> // The referenced entry can be free.
<add> this._cacheMap.set(num, xrefEntry);
<add> return xrefEntry;
<add> }
<add>
<add> if (xrefEntry.uncompressed) {
<add> xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
<add> } else {
<add> xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
<add> }
<add> if (isDict(xrefEntry)) {
<add> xrefEntry.objId = ref.toString();
<add> } else if (isStream(xrefEntry)) {
<add> xrefEntry.dict.objId = ref.toString();
<add> }
<add> return xrefEntry;
<add> }
<add>
<add> fetchUncompressed(ref, xrefEntry, suppressEncryption = false) {
<add> var gen = ref.gen;
<add> var num = ref.num;
<add> if (xrefEntry.gen !== gen) {
<add> throw new XRefEntryException(`Inconsistent generation in XRef: ${ref}`);
<add> }
<add> var stream = this.stream.makeSubStream(
<add> xrefEntry.offset + this.stream.start
<add> );
<add> const parser = new Parser({
<add> lexer: new Lexer(stream),
<add> xref: this,
<add> allowStreams: true,
<add> });
<add> var obj1 = parser.getObj();
<add> var obj2 = parser.getObj();
<add> var obj3 = parser.getObj();
<add>
<add> if (obj1 !== num || obj2 !== gen || !(obj3 instanceof Cmd)) {
<add> throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
<add> }
<add> if (obj3.cmd !== "obj") {
<add> // some bad PDFs use "obj1234" and really mean 1234
<add> if (obj3.cmd.startsWith("obj")) {
<add> num = parseInt(obj3.cmd.substring(3), 10);
<add> if (!Number.isNaN(num)) {
<add> return num;
<add> }
<ide> }
<del> if (isDict(xrefEntry)) {
<del> xrefEntry.objId = ref.toString();
<del> } else if (isStream(xrefEntry)) {
<del> xrefEntry.dict.objId = ref.toString();
<add> throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
<add> }
<add> if (this.encrypt && !suppressEncryption) {
<add> xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
<add> } else {
<add> xrefEntry = parser.getObj();
<add> }
<add> if (!isStream(xrefEntry)) {
<add> if (
<add> typeof PDFJSDev === "undefined" ||
<add> PDFJSDev.test("!PRODUCTION || TESTING")
<add> ) {
<add> assert(
<add> xrefEntry !== undefined,
<add> 'fetchUncompressed: The "xrefEntry" cannot be undefined.'
<add> );
<ide> }
<del> return xrefEntry;
<del> },
<add> this._cacheMap.set(num, xrefEntry);
<add> }
<add> return xrefEntry;
<add> }
<ide>
<del> fetchUncompressed(ref, xrefEntry, suppressEncryption = false) {
<del> var gen = ref.gen;
<del> var num = ref.num;
<del> if (xrefEntry.gen !== gen) {
<del> throw new XRefEntryException(`Inconsistent generation in XRef: ${ref}`);
<add> fetchCompressed(ref, xrefEntry, suppressEncryption = false) {
<add> const tableOffset = xrefEntry.offset;
<add> const stream = this.fetch(Ref.get(tableOffset, 0));
<add> if (!isStream(stream)) {
<add> throw new FormatError("bad ObjStm stream");
<add> }
<add> const first = stream.dict.get("First");
<add> const n = stream.dict.get("N");
<add> if (!Number.isInteger(first) || !Number.isInteger(n)) {
<add> throw new FormatError("invalid first and n parameters for ObjStm stream");
<add> }
<add> let parser = new Parser({
<add> lexer: new Lexer(stream),
<add> xref: this,
<add> allowStreams: true,
<add> });
<add> const nums = new Array(n);
<add> const offsets = new Array(n);
<add> // read the object numbers to populate cache
<add> for (let i = 0; i < n; ++i) {
<add> const num = parser.getObj();
<add> if (!Number.isInteger(num)) {
<add> throw new FormatError(
<add> `invalid object number in the ObjStm stream: ${num}`
<add> );
<ide> }
<del> var stream = this.stream.makeSubStream(
<del> xrefEntry.offset + this.stream.start
<del> );
<del> const parser = new Parser({
<del> lexer: new Lexer(stream),
<add> const offset = parser.getObj();
<add> if (!Number.isInteger(offset)) {
<add> throw new FormatError(
<add> `invalid object offset in the ObjStm stream: ${offset}`
<add> );
<add> }
<add> nums[i] = num;
<add> offsets[i] = offset;
<add> }
<add>
<add> const start = (stream.start || 0) + first;
<add> const entries = new Array(n);
<add> // read stream objects for cache
<add> for (let i = 0; i < n; ++i) {
<add> const length = i < n - 1 ? offsets[i + 1] - offsets[i] : undefined;
<add> if (length < 0) {
<add> throw new FormatError("Invalid offset in the ObjStm stream.");
<add> }
<add> parser = new Parser({
<add> lexer: new Lexer(
<add> stream.makeSubStream(start + offsets[i], length, stream.dict)
<add> ),
<ide> xref: this,
<ide> allowStreams: true,
<ide> });
<del> var obj1 = parser.getObj();
<del> var obj2 = parser.getObj();
<del> var obj3 = parser.getObj();
<ide>
<del> if (obj1 !== num || obj2 !== gen || !(obj3 instanceof Cmd)) {
<del> throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
<del> }
<del> if (obj3.cmd !== "obj") {
<del> // some bad PDFs use "obj1234" and really mean 1234
<del> if (obj3.cmd.startsWith("obj")) {
<del> num = parseInt(obj3.cmd.substring(3), 10);
<del> if (!Number.isNaN(num)) {
<del> return num;
<del> }
<del> }
<del> throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
<add> const obj = parser.getObj();
<add> entries[i] = obj;
<add> if (isStream(obj)) {
<add> continue;
<ide> }
<del> if (this.encrypt && !suppressEncryption) {
<del> xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
<del> } else {
<del> xrefEntry = parser.getObj();
<del> }
<del> if (!isStream(xrefEntry)) {
<add> const num = nums[i],
<add> entry = this.entries[num];
<add> if (entry && entry.offset === tableOffset && entry.gen === i) {
<ide> if (
<ide> typeof PDFJSDev === "undefined" ||
<ide> PDFJSDev.test("!PRODUCTION || TESTING")
<ide> ) {
<ide> assert(
<del> xrefEntry !== undefined,
<del> 'fetchUncompressed: The "xrefEntry" cannot be undefined.'
<add> obj !== undefined,
<add> 'fetchCompressed: The "obj" cannot be undefined.'
<ide> );
<ide> }
<del> this._cacheMap.set(num, xrefEntry);
<del> }
<del> return xrefEntry;
<del> },
<del>
<del> fetchCompressed(ref, xrefEntry, suppressEncryption = false) {
<del> const tableOffset = xrefEntry.offset;
<del> const stream = this.fetch(Ref.get(tableOffset, 0));
<del> if (!isStream(stream)) {
<del> throw new FormatError("bad ObjStm stream");
<del> }
<del> const first = stream.dict.get("First");
<del> const n = stream.dict.get("N");
<del> if (!Number.isInteger(first) || !Number.isInteger(n)) {
<del> throw new FormatError(
<del> "invalid first and n parameters for ObjStm stream"
<del> );
<del> }
<del> let parser = new Parser({
<del> lexer: new Lexer(stream),
<del> xref: this,
<del> allowStreams: true,
<del> });
<del> const nums = new Array(n);
<del> const offsets = new Array(n);
<del> // read the object numbers to populate cache
<del> for (let i = 0; i < n; ++i) {
<del> const num = parser.getObj();
<del> if (!Number.isInteger(num)) {
<del> throw new FormatError(
<del> `invalid object number in the ObjStm stream: ${num}`
<del> );
<del> }
<del> const offset = parser.getObj();
<del> if (!Number.isInteger(offset)) {
<del> throw new FormatError(
<del> `invalid object offset in the ObjStm stream: ${offset}`
<del> );
<del> }
<del> nums[i] = num;
<del> offsets[i] = offset;
<del> }
<del>
<del> const start = (stream.start || 0) + first;
<del> const entries = new Array(n);
<del> // read stream objects for cache
<del> for (let i = 0; i < n; ++i) {
<del> const length = i < n - 1 ? offsets[i + 1] - offsets[i] : undefined;
<del> if (length < 0) {
<del> throw new FormatError("Invalid offset in the ObjStm stream.");
<del> }
<del> parser = new Parser({
<del> lexer: new Lexer(
<del> stream.makeSubStream(start + offsets[i], length, stream.dict)
<del> ),
<del> xref: this,
<del> allowStreams: true,
<del> });
<del>
<del> const obj = parser.getObj();
<del> entries[i] = obj;
<del> if (isStream(obj)) {
<del> continue;
<del> }
<del> const num = nums[i],
<del> entry = this.entries[num];
<del> if (entry && entry.offset === tableOffset && entry.gen === i) {
<del> if (
<del> typeof PDFJSDev === "undefined" ||
<del> PDFJSDev.test("!PRODUCTION || TESTING")
<del> ) {
<del> assert(
<del> obj !== undefined,
<del> 'fetchCompressed: The "obj" cannot be undefined.'
<del> );
<del> }
<del> this._cacheMap.set(num, obj);
<del> }
<del> }
<del> xrefEntry = entries[xrefEntry.gen];
<del> if (xrefEntry === undefined) {
<del> throw new XRefEntryException(`Bad (compressed) XRef entry: ${ref}`);
<del> }
<del> return xrefEntry;
<del> },
<add> this._cacheMap.set(num, obj);
<add> }
<add> }
<add> xrefEntry = entries[xrefEntry.gen];
<add> if (xrefEntry === undefined) {
<add> throw new XRefEntryException(`Bad (compressed) XRef entry: ${ref}`);
<add> }
<add> return xrefEntry;
<add> }
<ide>
<del> async fetchIfRefAsync(obj, suppressEncryption) {
<del> if (obj instanceof Ref) {
<del> return this.fetchAsync(obj, suppressEncryption);
<del> }
<del> return obj;
<del> },
<add> async fetchIfRefAsync(obj, suppressEncryption) {
<add> if (obj instanceof Ref) {
<add> return this.fetchAsync(obj, suppressEncryption);
<add> }
<add> return obj;
<add> }
<ide>
<del> async fetchAsync(ref, suppressEncryption) {
<del> try {
<del> return this.fetch(ref, suppressEncryption);
<del> } catch (ex) {
<del> if (!(ex instanceof MissingDataException)) {
<del> throw ex;
<del> }
<del> await this.pdfManager.requestRange(ex.begin, ex.end);
<del> return this.fetchAsync(ref, suppressEncryption);
<add> async fetchAsync(ref, suppressEncryption) {
<add> try {
<add> return this.fetch(ref, suppressEncryption);
<add> } catch (ex) {
<add> if (!(ex instanceof MissingDataException)) {
<add> throw ex;
<ide> }
<del> },
<del>
<del> getCatalogObj: function XRef_getCatalogObj() {
<del> return this.root;
<del> },
<del> };
<add> await this.pdfManager.requestRange(ex.begin, ex.end);
<add> return this.fetchAsync(ref, suppressEncryption);
<add> }
<add> }
<ide>
<del> return XRef;
<del>})();
<add> getCatalogObj() {
<add> return this.root;
<add> }
<add>}
<ide>
<ide> export { XRef }; | 1 |
PHP | PHP | add email config for transferencoding | 2023b4ea69a30481d40e37030688efe6a8b00f8f | <ide><path>src/Mailer/Email.php
<ide> class Email implements JsonSerializable, Serializable
<ide> */
<ide> public $headerCharset;
<ide>
<add> /**
<add> * The email transfer encoding used.
<add> * If null, the $charset property is used for determined the transfer encoding.
<add> *
<add> * @var string|null
<add> */
<add> public $transferEncoding;
<add>
<ide> /**
<ide> * The application wide charset, used to encode headers and body
<ide> *
<ide> public function headerCharset($charset = null)
<ide> return $this->headerCharset;
<ide> }
<ide>
<add> /**
<add> * TransportCharset setter.
<add> *
<add> * @param string|null $encoding Character set.
<add> * @return $this
<add> */
<add> public function setTransferEncoding($encoding) {
<add> $this->transferEncoding = $encoding;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * TransportCharset getter.
<add> *
<add> * @return string|null Encoding
<add> */
<add> public function getTransferEncoding() {
<add> return $this->transferEncoding;
<add> }
<add>
<ide> /**
<ide> * EmailPattern setter/getter
<ide> *
<ide> public function reset()
<ide> $this->_priority = null;
<ide> $this->charset = 'utf-8';
<ide> $this->headerCharset = null;
<add> $this->transferEncoding = null;
<ide> $this->_attachments = [];
<ide> $this->_profile = [];
<ide> $this->_emailPattern = self::EMAIL_PATTERN;
<ide> protected function _renderTemplates($content)
<ide> */
<ide> protected function _getContentTransferEncoding()
<ide> {
<add> if ($this->transferEncoding) {
<add> return $this->transferEncoding;
<add> }
<add>
<ide> $charset = strtoupper($this->charset);
<ide> if (in_array($charset, $this->_charset8bit)) {
<ide> return '8bit';
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function render($content)
<ide> {
<ide> return $this->_render($content);
<ide> }
<add>
<add> /**
<add> * GetContentTransferEncoding to protected method
<add> *
<add> * @return string
<add> */
<add> public function getContentTransferEncoding() {
<add> return $this->_getContentTransferEncoding();
<add> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testHeaderCharset()
<ide> $this->assertSame($charset, 'Shift_JIS');
<ide> }
<ide>
<add> /**
<add> * Test transferEncoding
<add> */
<add> public function testTransferEncoding(){
<add> // Test new transport encoding
<add> $this->Email->setTransferEncoding('quoted-printable');
<add> $this->assertSame($this->Email->getTransferEncoding(), 'quoted-printable');
<add> $this->assertSame($this->Email->getContentTransferEncoding(), 'quoted-printable');
<add>
<add> // Test default charset/encoding : utf8/8bit
<add> $this->Email->reset();
<add> $this->assertNull($this->Email->getTransferEncoding());
<add> $this->assertSame($this->Email->getContentTransferEncoding(), '8bit');
<add> }
<add>
<ide> /**
<ide> * Tests for compatible check.
<ide> * charset property and charset() method. | 2 |
PHP | PHP | set the router on the controller | 789a9b3667d4b6a70d2c4892cc2c675e6129a40b | <ide><path>src/Illuminate/Routing/ControllerServiceProvider.php
<ide> public function register()
<ide> {
<ide> $this->app->singleton('illuminate.route.dispatcher', function($app)
<ide> {
<add> Controller::setRouter($app['router']);
<add>
<ide> return new ControllerDispatcher($app['router'], $app);
<ide> });
<ide> } | 1 |
Ruby | Ruby | remove unnecessary is_a check | 0ee351b428e038394d495c20a868d40ad3032e83 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def reflect_on_all_associations(macro = nil)
<ide> # Invoice.reflect_on_association(:line_items).macro # returns :has_many
<ide> #
<ide> def reflect_on_association(association)
<del> reflection = reflections[association]
<del> reflection if reflection.is_a?(AssociationReflection)
<add> reflections[association]
<ide> end
<ide>
<ide> # Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled. | 1 |
Javascript | Javascript | remove unused function | 3ed094d14259f6bb1eb8c7614e988b770c002613 | <ide><path>src/ng/sce.js
<ide> function $SceDelegateProvider() {
<ide> return resourceUrlBlacklist;
<ide> };
<ide>
<del> // Helper functions for matching resource urls by policy.
<del> function isCompatibleProtocol(documentProtocol, resourceProtocol) {
<del> return ((documentProtocol === resourceProtocol) ||
<del> (documentProtocol === "http:" && resourceProtocol === "https:"));
<del> }
<del>
<ide> this.$get = ['$log', '$document', '$injector', '$$urlUtils', function(
<ide> $log, $document, $injector, $$urlUtils) {
<ide> | 1 |
Javascript | Javascript | use module.unsafecache only for node_modules | 3b35fd478cb4bbe6315a7d30cf8a1c383950914c | <ide><path>lib/NormalModuleFactory.js
<ide> class NormalModuleFactory {
<ide> });
<ide> this.resolverFactory = resolverFactory;
<ide> this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules));
<add> this.unsafeCache = !!options.unsafeCache;
<ide> this.cachePredicate =
<ide> typeof options.unsafeCache === "function"
<ide> ? options.unsafeCache
<del> : Boolean.bind(null, options.unsafeCache);
<add> : () => true;
<ide> this.context = context || "";
<ide> this.parserCache = Object.create(null);
<ide> this.generatorCache = Object.create(null);
<ide> class NormalModuleFactory {
<ide>
<ide> create(data, callback) {
<ide> const dependencies = data.dependencies;
<del> const cacheEntry = dependencyCache.get(dependencies[0]);
<del> if (cacheEntry) return callback(null, cacheEntry);
<add> if (this.unsafeCache) {
<add> const cacheEntry = dependencyCache.get(dependencies[0]);
<add> if (cacheEntry) return callback(null, cacheEntry);
<add> }
<ide> const context = data.context || this.context;
<ide> const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS;
<ide> const request = dependencies[0].request;
<ide> class NormalModuleFactory {
<ide> factory(result, (err, module) => {
<ide> if (err) return callback(err);
<ide>
<del> if (module && this.cachePredicate(module)) {
<add> if (this.unsafeCache && module && this.cachePredicate(module)) {
<ide> for (const d of dependencies) {
<ide> dependencyCache.set(d, module);
<ide> }
<ide><path>lib/WebpackOptionsDefaulter.js
<ide> "use strict";
<ide>
<ide> const path = require("path");
<del>
<ide> const OptionsDefaulter = require("./OptionsDefaulter");
<ide> const Template = require("./Template");
<ide>
<add>const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
<add>
<ide> const isProductionLikeMode = options => {
<ide> return options.mode === "production" || !options.mode;
<ide> };
<ide> class WebpackOptionsDefaulter extends OptionsDefaulter {
<ide> this.set("module.wrappedContextCritical", false);
<ide> this.set("module.strictExportPresence", false);
<ide> this.set("module.strictThisContextOnImports", false);
<del> this.set("module.unsafeCache", "make", options => !!options.cache);
<add> this.set("module.unsafeCache", "make", options => {
<add> if (options.cache) {
<add> return module => {
<add> const name = module.nameForCondition();
<add> return name && NODE_MODULES_REGEXP.test(name);
<add> };
<add> }
<add> });
<ide> this.set("module.rules", []);
<ide> this.set("module.defaultRules", "make", options => [
<ide> {
<ide> class WebpackOptionsDefaulter extends OptionsDefaulter {
<ide> });
<ide> this.set("optimization.splitChunks.cacheGroups.defaultVendors", {
<ide> automaticNamePrefix: "vendors",
<del> test: /[\\/]node_modules[\\/]/,
<add> test: NODE_MODULES_REGEXP,
<ide> priority: -10
<ide> });
<ide> this.set("optimization.runtimeChunk", "call", value => {
<ide> class WebpackOptionsDefaulter extends OptionsDefaulter {
<ide> return ["module", "main"];
<ide> }
<ide> });
<del> this.set("resolve.cacheWithContext", "make", options => {
<del> return (
<del> Array.isArray(options.resolve.plugins) &&
<del> options.resolve.plugins.length > 0
<del> );
<del> });
<ide>
<ide> this.set("resolveLoader", "call", value => Object.assign({}, value));
<del> this.set("resolveLoader.unsafeCache", true);
<ide> this.set("resolveLoader.mainFields", ["loader", "main"]);
<ide> this.set("resolveLoader.extensions", [".js", ".json"]);
<ide> this.set("resolveLoader.mainFiles", ["index"]);
<del> this.set("resolveLoader.cacheWithContext", "make", options => {
<del> return (
<del> Array.isArray(options.resolveLoader.plugins) &&
<del> options.resolveLoader.plugins.length > 0
<del> );
<del> });
<ide> }
<ide> }
<ide> | 2 |
PHP | PHP | read content type in a more compatible way | 56634c792fd96f3875010532bf9fd262ff73a7cd | <ide><path>src/Network/Request.php
<ide> protected function _processPost($data)
<ide> {
<ide> $method = $this->env('REQUEST_METHOD');
<ide> if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
<del> strpos($this->env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
<add> strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
<ide> ) {
<ide> $data = $this->input();
<ide> parse_str($data, $data);
<ide> protected function _processFileData($data, $post, $path = '', $field = '')
<ide> return $data;
<ide> }
<ide>
<add> /**
<add> * Get the content type used in this request.
<add> *
<add> * @return string
<add> */
<add> public function contentType()
<add> {
<add> $type = $this->env('CONTENT_TYPE');
<add> if ($type) {
<add> return $type;
<add> }
<add> return $this->env('HTTP_CONTENT_TYPE');
<add> }
<add>
<ide> /**
<ide> * Returns the instance of the Session object for this request
<ide> *
<ide><path>tests/TestCase/Network/RequestTest.php
<ide> public function testSession()
<ide> $this->assertEquals($session, $request->session());
<ide> }
<ide>
<add> /**
<add> * Test the content type method.
<add> *
<add> * @return void
<add> */
<add> public function testContentType()
<add> {
<add> $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
<add> $request = Request::createFromGlobals();
<add> $this->assertEquals('application/json', $request->contentType());
<add>
<add> $_SERVER['CONTENT_TYPE'] = 'application/xml';
<add> $request = Request::createFromGlobals();
<add> $this->assertEquals('application/xml', $request->contentType(), 'prefer non http header.');
<add> }
<add>
<ide> /**
<ide> * loadEnvironment method
<ide> * | 2 |
Go | Go | fix multiple copy from | b50ade0bfb67dae7867f4f5c3da12c1f778b6c7e | <ide><path>image/image.go
<ide> type ChildConfig struct {
<ide> // NewChildImage creates a new Image as a child of this image.
<ide> func NewChildImage(img *Image, child ChildConfig, platform string) *Image {
<ide> isEmptyLayer := layer.IsEmpty(child.DiffID)
<del> rootFS := img.RootFS
<del> if rootFS == nil {
<add> var rootFS *RootFS
<add> if img.RootFS != nil {
<add> rootFS = img.RootFS.Clone()
<add> } else {
<ide> rootFS = NewRootFS()
<ide> }
<add>
<ide> if !isEmptyLayer {
<ide> rootFS.Append(child.DiffID)
<ide> }
<ide><path>image/image_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/api/types/container"
<add> "github.com/docker/docker/layer"
<ide> "github.com/stretchr/testify/assert"
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide> func TestMarshalKeyOrder(t *testing.T) {
<ide> t.Fatal("invalid key order in JSON: ", string(b))
<ide> }
<ide> }
<add>
<add>func TestNewChildImageFromImageWithRootFS(t *testing.T) {
<add> rootFS := NewRootFS()
<add> rootFS.Append(layer.DiffID("ba5e"))
<add> parent := &Image{
<add> RootFS: rootFS,
<add> History: []History{
<add> NewHistory("a", "c", "r", false),
<add> },
<add> }
<add> childConfig := ChildConfig{
<add> DiffID: layer.DiffID("abcdef"),
<add> Author: "author",
<add> Comment: "comment",
<add> ContainerConfig: &container.Config{
<add> Cmd: []string{"echo", "foo"},
<add> },
<add> Config: &container.Config{},
<add> }
<add>
<add> newImage := NewChildImage(parent, childConfig, "platform")
<add> expectedDiffIDs := []layer.DiffID{layer.DiffID("ba5e"), layer.DiffID("abcdef")}
<add> assert.Equal(t, expectedDiffIDs, newImage.RootFS.DiffIDs)
<add> assert.Equal(t, childConfig.Author, newImage.Author)
<add> assert.Equal(t, childConfig.Config, newImage.Config)
<add> assert.Equal(t, *childConfig.ContainerConfig, newImage.ContainerConfig)
<add> assert.Equal(t, "platform", newImage.OS)
<add> assert.Equal(t, childConfig.Config, newImage.Config)
<add>
<add> assert.Len(t, newImage.History, 2)
<add> assert.Equal(t, childConfig.Comment, newImage.History[1].Comment)
<add>
<add> // RootFS should be copied not mutated
<add> assert.NotEqual(t, parent.RootFS.DiffIDs, newImage.RootFS.DiffIDs)
<add>}
<ide><path>image/rootfs.go
<ide> func (r *RootFS) Append(id layer.DiffID) {
<ide> r.DiffIDs = append(r.DiffIDs, id)
<ide> }
<ide>
<add>// Clone returns a copy of the RootFS
<add>func (r *RootFS) Clone() *RootFS {
<add> newRoot := NewRootFS()
<add> newRoot.Type = r.Type
<add> newRoot.DiffIDs = append(r.DiffIDs)
<add> return newRoot
<add>}
<add>
<ide> // ChainID returns the ChainID for the top layer in RootFS.
<ide> func (r *RootFS) ChainID() layer.ChainID {
<ide> if runtime.GOOS == "windows" && r.Type == typeLayersWithBase { | 3 |
Javascript | Javascript | remove unnecessary parameter | d6a6bcdc47c0c0e31e24bba0e8e26ee0da5b7eb0 | <ide><path>lib/_stream_readable.js
<ide> Readable.prototype.on = function(ev, fn) {
<ide> if (!state.reading) {
<ide> process.nextTick(nReadingNextTick, this);
<ide> } else if (state.length) {
<del> emitReadable(this, state);
<add> emitReadable(this);
<ide> }
<ide> }
<ide> } | 1 |
Ruby | Ruby | relocate libtool files | de6a9ff055f9f691f132b03d297268590a42a541 | <ide><path>Library/Homebrew/keg_relocate.rb
<ide> def relocate_install_names old_prefix, new_prefix, old_cellar, new_cellar, optio
<ide> end
<ide> end
<ide>
<del> text_files.group_by { |f| f.stat.ino }.each_value do |first, *rest|
<add> files = text_files | libtool_files
<add>
<add> files.group_by { |f| f.stat.ino }.each_value do |first, *rest|
<ide> s = first.open("rb", &:read)
<ide> changed = s.gsub!(old_cellar, new_cellar)
<ide> changed = s.gsub!(old_prefix, new_prefix) || changed
<ide> def text_files
<ide>
<ide> text_files
<ide> end
<add>
<add> def libtool_files
<add> libtool_files = []
<add>
<add> # find .la files, which are stored in lib/
<add> lib.find do |pn|
<add> next if pn.symlink? or pn.directory? or pn.extname != '.la'
<add> libtool_files << pn
<add> end if lib.directory?
<add> libtool_files
<add> end
<ide> end | 1 |
Javascript | Javascript | change app name | 94a2a9dcde718fe15ef4b08a4839a69462c868d3 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> author: 'Steve Ng'
<ide> },
<ide> {
<del> name: 'ShareHows',
<add> name: '쉐어하우스',
<ide> icon: 'http://a4.mzstatic.com/us/r30/Purple5/v4/78/1c/83/781c8325-a1e1-4afc-f106-a629bcf3c6ef/icon175x175.png',
<ide> linkAppStore: 'https://itunes.apple.com/kr/app/sweeohauseu-sesang-ui-modeun/id1060914858?mt=8',
<ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=kr.dobbit.sharehows', | 1 |
Javascript | Javascript | remove unused argument | 3ca4ca463c97a2bbca09f0366d2a753a13751143 | <ide><path>src/ngMessages/messages.js
<ide> angular.module('ngMessages', [])
<ide> *
<ide> * @param {expression} ngMessage|when a string value corresponding to the message key.
<ide> */
<del> .directive('ngMessage', ngMessageDirectiveFactory('AE'))
<add> .directive('ngMessage', ngMessageDirectiveFactory())
<ide>
<ide>
<ide> /**
<ide> angular.module('ngMessages', [])
<ide> *
<ide> * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.
<ide> */
<del> .directive('ngMessageExp', ngMessageDirectiveFactory('A'));
<add> .directive('ngMessageExp', ngMessageDirectiveFactory());
<ide>
<del>function ngMessageDirectiveFactory(restrict) {
<add>function ngMessageDirectiveFactory() {
<ide> return ['$animate', function($animate) {
<ide> return {
<ide> restrict: 'AE', | 1 |
PHP | PHP | add tests for single parameter routing | e8baa62405001f22ae0f7080550882c4d8edb9a2 | <ide><path>tests/Routing/RoutingUrlGeneratorTest.php
<ide> public function testBasicRouteGeneration()
<ide> $route = new Illuminate\Routing\Route(array('GET'), 'foo/bar/{baz}/breeze/{boom}', array('as' => 'bar'));
<ide> $routes->add($route);
<ide>
<add> /**
<add> * Single Parameter...
<add> */
<add> $route = new Illuminate\Routing\Route(array('GET'), 'foo/bar/{baz}', array('as' => 'foobar'));
<add> $routes->add($route);
<add>
<ide> /**
<ide> * HTTPS...
<ide> */
<ide> public function testBasicRouteGeneration()
<ide> $this->assertEquals('/foo/bar?foo=bar', $url->route('foo', array('foo' => 'bar'), false));
<ide> $this->assertEquals('http://www.foo.com/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', array('taylor', 'otwell', 'fly' => 'wall')));
<ide> $this->assertEquals('http://www.foo.com/foo/bar/otwell/breeze/taylor?fly=wall', $url->route('bar', array('boom' => 'taylor', 'baz' => 'otwell', 'fly' => 'wall')));
<add> $this->assertEquals('http://www.foo.com/foo/bar/2', $url->route('foobar', 2));
<add> $this->assertEquals('http://www.foo.com/foo/bar/taylor', $url->route('foobar', 'taylor'));
<ide> $this->assertEquals('/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', array('taylor', 'otwell', 'fly' => 'wall'), false));
<ide> $this->assertEquals('https://www.foo.com/foo/bar', $url->route('baz'));
<ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->action('foo@bar'));
<ide> public function testControllerRoutesWithADefaultNamespace()
<ide> $this->assertEquals('http://www.foo.com/something/else', $url->action('\something\foo@bar'));
<ide> }
<ide>
<add>
<ide> public function testRoutableInterfaceRouting()
<ide> {
<ide> $url = new UrlGenerator(
<ide> public function testRoutableInterfaceRouting()
<ide> }
<ide>
<ide>
<add> public function testRoutableInterfaceRoutingWithSingleParameter()
<add> {
<add> $url = new UrlGenerator(
<add> $routes = new Illuminate\Routing\RouteCollection,
<add> $request = Illuminate\Http\Request::create('http://www.foo.com/')
<add> );
<add>
<add> $route = new Illuminate\Routing\Route(array('GET'), 'foo/{bar}', array('as' => 'routable'));
<add> $routes->add($route);
<add>
<add> $model = new RoutableInterfaceStub;
<add> $model->key = 'routable';
<add>
<add> $this->assertEquals('/foo/routable', $url->route('routable', $model, false));
<add> }
<add>
<add>
<ide> public function testRoutesMaintainRequestScheme()
<ide> {
<ide> $url = new UrlGenerator( | 1 |
Text | Text | use singular package | 292ff0de52d7f0b979703c522b0c17b6c1ff3d14 | <ide><path>docs/README.md
<ide> overview of the main editor API.
<ide> Check out the [Atom][Atom] class docs to see what globals are available and
<ide> what they provide.
<ide>
<del>You can also require many of these classes in your packages via:
<add>You can also require many of these classes in your package via:
<ide>
<ide> ```coffee
<ide> {EditorView} = require 'atom' | 1 |
Python | Python | replace python with sys.executable | 82a03ee18e8f2ca3982646c1076c1edf02ce0698 | <ide><path>spacy/cli/project.py
<ide> import os
<ide> import re
<ide> import shutil
<add>import sys
<ide>
<ide> from ._app import app, Arg, Opt, COMMAND
<ide> from .. import about
<ide> def run_commands(commands: List[str] = tuple(), variables: Dict[str, str] = {})
<ide> for command in commands:
<ide> # Substitute variables, e.g. "./{NAME}.json"
<ide> command = command.format(**variables)
<del> print(command)
<del> run_command(shlex.split(command))
<add> command = shlex.split(command)
<add> # TODO: is this needed / a good idea?
<add> if len(command) and command[0] == "python":
<add> command[0] = sys.executable
<add> print(" ".join(command))
<add> run_command(command)
<ide>
<ide>
<ide> def check_asset(url: str) -> None: | 1 |
Javascript | Javascript | change `ticks.mode` to `scale.distribution` | 97e23737210bbfb5612b41e2573430350f1aeee6 | <ide><path>src/scales/scale.time.js
<ide> function sorter(a, b) {
<ide> return a - b;
<ide> }
<ide>
<add>function arrayUnique(items) {
<add> var hash = {};
<add> var out = [];
<add> var i, ilen, item;
<add>
<add> for (i = 0, ilen = items.length; i < ilen; ++i) {
<add> item = items[i];
<add> if (!hash[item]) {
<add> hash[item] = true;
<add> out.push(item);
<add> }
<add> }
<add>
<add> return out;
<add>}
<add>
<ide> /**
<ide> * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
<ide> * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
<ide> function sorter(a, b) {
<ide> * to create the lookup table. The table ALWAYS contains at least two items: min and max.
<ide> *
<ide> * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
<del> * @param {Boolean} linear - If true, timestamps will be spread linearly along the min/max
<del> * range, so basically, the table will contains only two items: {min, 0} and {max, 1}. If
<del> * false, timestamps will be positioned at the same distance from each other. In this case,
<del> * only timestamps that break the time linearity are registered, meaning that in the best
<del> * case, all timestamps are linear, the table contains only min and max.
<add> * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
<add> * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
<add> * If 'series', timestamps will be positioned at the same distance from each other. In this
<add> * case, only timestamps that break the time linearity are registered, meaning that in the
<add> * best case, all timestamps are linear, the table contains only min and max.
<ide> */
<del>function buildLookupTable(timestamps, min, max, linear) {
<del> if (linear || !timestamps.length) {
<add>function buildLookupTable(timestamps, min, max, distribution) {
<add> if (distribution === 'linear' || !timestamps.length) {
<ide> return [
<ide> {time: min, pos: 0},
<ide> {time: max, pos: 1}
<ide> ];
<ide> }
<ide>
<ide> var table = [];
<del> var items = timestamps.slice(0);
<add> var items = [min];
<ide> var i, ilen, prev, curr, next;
<ide>
<del> if (min < timestamps[0]) {
<del> items.unshift(min);
<del> }
<del> if (max > timestamps[timestamps.length - 1]) {
<del> items.push(max);
<add> for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
<add> curr = timestamps[i];
<add> if (curr > min && curr < max) {
<add> items.push(curr);
<add> }
<ide> }
<ide>
<add> items.push(max);
<add>
<ide> for (i = 0, ilen = items.length; i < ilen; ++i) {
<ide> next = items[i + 1];
<ide> prev = items[i - 1];
<ide> module.exports = function(Chart) {
<ide> var defaultConfig = {
<ide> position: 'bottom',
<ide>
<add> /**
<add> * Data distribution along the scale:
<add> * - 'linear': data are spread according to their time (distances can vary),
<add> * - 'series': data are spread at the same distance from each other.
<add> * @see https://github.com/chartjs/Chart.js/pull/4507
<add> * @since 2.7.0
<add> */
<add> distribution: 'linear',
<add>
<ide> time: {
<ide> parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
<ide> format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
<ide> module.exports = function(Chart) {
<ide> ticks: {
<ide> autoSkip: false,
<ide>
<del> /**
<del> * Ticks distribution along the scale:
<del> * - 'linear': ticks and data are spread according to their time (distances can vary),
<del> * - 'series': ticks and data are spread at the same distance from each other.
<del> * @see https://github.com/chartjs/Chart.js/pull/4507
<del> * @since 2.7.0
<del> */
<del> mode: 'linear',
<del>
<ide> /**
<ide> * Ticks generation input values:
<ide> * - 'auto': generates "optimal" ticks based on scale size and time options.
<ide> module.exports = function(Chart) {
<ide> var me = this;
<ide> var chart = me.chart;
<ide> var options = me.options;
<del> var datasets = chart.data.datasets || [];
<ide> var min = parse(options.time.min, me) || MAX_INTEGER;
<ide> var max = parse(options.time.max, me) || MIN_INTEGER;
<ide> var timestamps = [];
<add> var datasets = [];
<ide> var labels = [];
<ide> var i, j, ilen, jlen, data, timestamp;
<ide>
<ide> // Convert labels to timestamps
<ide> for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
<del> timestamp = parse(chart.data.labels[i], me);
<del> min = Math.min(min, timestamp);
<del> max = Math.max(max, timestamp);
<del> labels.push(timestamp);
<add> labels.push(parse(chart.data.labels[i], me));
<ide> }
<ide>
<ide> // Convert data to timestamps
<del> for (i = 0, ilen = datasets.length; i < ilen; ++i) {
<add> for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
<ide> if (chart.isDatasetVisible(i)) {
<del> data = datasets[i].data;
<add> data = chart.data.datasets[i].data;
<ide>
<ide> // Let's consider that all data have the same format.
<ide> if (helpers.isObject(data[0])) {
<del> timestamps[i] = [];
<add> datasets[i] = [];
<ide>
<ide> for (j = 0, jlen = data.length; j < jlen; ++j) {
<ide> timestamp = parse(data[j], me);
<del> min = Math.min(min, timestamp);
<del> max = Math.max(max, timestamp);
<del> timestamps[i][j] = timestamp;
<add> timestamps.push(timestamp);
<add> datasets[i][j] = timestamp;
<ide> }
<ide> } else {
<del> timestamps[i] = labels.slice(0);
<add> timestamps.push.apply(timestamps, labels);
<add> datasets[i] = labels.slice(0);
<ide> }
<ide> } else {
<del> timestamps[i] = [];
<add> datasets[i] = [];
<ide> }
<ide> }
<ide>
<add> if (labels.length) {
<add> // Sort labels **after** data have been converted
<add> labels = arrayUnique(labels).sort(sorter);
<add> min = Math.min(min, labels[0]);
<add> max = Math.max(max, labels[labels.length - 1]);
<add> }
<add>
<add> if (timestamps.length) {
<add> timestamps = arrayUnique(timestamps).sort(sorter);
<add> min = Math.min(min, timestamps[0]);
<add> max = Math.max(max, timestamps[timestamps.length - 1]);
<add> }
<add>
<ide> // In case there is no valid min/max, let's use today limits
<ide> min = min === MAX_INTEGER ? +moment().startOf('day') : min;
<ide> max = max === MIN_INTEGER ? +moment().endOf('day') + 1 : max;
<ide> module.exports = function(Chart) {
<ide> me.max = Math.max(min + 1, max);
<ide>
<ide> // PRIVATE
<del> me._datasets = timestamps;
<ide> me._horizontal = me.isHorizontal();
<del> me._labels = labels.sort(sorter); // Sort labels **after** data have been converted
<ide> me._table = [];
<add> me._timestamps = {
<add> data: timestamps,
<add> datasets: datasets,
<add> labels: labels
<add> };
<ide> },
<ide>
<ide> buildTicks: function() {
<ide> var me = this;
<ide> var min = me.min;
<ide> var max = me.max;
<del> var timeOpts = me.options.time;
<del> var ticksOpts = me.options.ticks;
<add> var options = me.options;
<add> var timeOpts = options.time;
<add> var ticksOpts = options.ticks;
<ide> var formats = timeOpts.displayFormats;
<ide> var capacity = me.getLabelCapacity(min);
<ide> var unit = timeOpts.unit || determineUnit(timeOpts.minUnit, min, max, capacity);
<ide> var majorUnit = determineMajorUnit(unit);
<ide> var timestamps = [];
<ide> var ticks = [];
<del> var hash = {};
<ide> var i, ilen, timestamp;
<ide>
<ide> switch (ticksOpts.source) {
<ide> case 'data':
<del> for (i = 0, ilen = me._datasets.length; i < ilen; ++i) {
<del> timestamps.push.apply(timestamps, me._datasets[i]);
<del> }
<del> timestamps.sort(sorter);
<add> timestamps = me._timestamps.data;
<ide> break;
<ide> case 'labels':
<del> timestamps = me._labels;
<add> timestamps = me._timestamps.labels;
<ide> break;
<ide> case 'auto':
<ide> default:
<ide> module.exports = function(Chart) {
<ide> min = parse(timeOpts.min, me) || min;
<ide> max = parse(timeOpts.max, me) || max;
<ide>
<del> // Remove ticks outside the min/max range and duplicated entries
<add> // Remove ticks outside the min/max range
<ide> for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
<ide> timestamp = timestamps[i];
<del> if (timestamp >= min && timestamp <= max && !hash[timestamp]) {
<del> // hash is used to efficiently detect timestamp duplicates
<del> hash[timestamp] = true;
<add> if (timestamp >= min && timestamp <= max) {
<ide> ticks.push(timestamp);
<ide> }
<ide> }
<ide> module.exports = function(Chart) {
<ide> me._majorUnit = majorUnit;
<ide> me._minorFormat = formats[unit];
<ide> me._majorFormat = formats[majorUnit];
<del> me._table = buildLookupTable(ticks, min, max, ticksOpts.mode === 'linear');
<add> me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
<ide>
<ide> return ticksFromTimestamps(ticks, majorUnit);
<ide> },
<ide> module.exports = function(Chart) {
<ide> var time = null;
<ide>
<ide> if (index !== undefined && datasetIndex !== undefined) {
<del> time = me._datasets[datasetIndex][index];
<add> time = me._timestamps.datasets[datasetIndex][index];
<ide> }
<ide>
<ide> if (time === null) {
<ide><path>test/specs/scale.time.tests.js
<ide> describe('Time scale tests', function() {
<ide> return scale.ticks;
<ide> }
<ide>
<del> function fetchTickPositions(scale) {
<del> return scale.ticks.map(function(tick, index) {
<del> return scale.getPixelForTick(index);
<del> });
<del> }
<del>
<ide> beforeEach(function() {
<ide> // Need a time matcher for getValueFromPixel
<ide> jasmine.addMatchers({
<ide> describe('Time scale tests', function() {
<ide> labelString: '',
<ide> lineHeight: 1.2
<ide> },
<add> distribution: 'linear',
<ide> ticks: {
<ide> beginAtZero: false,
<ide> minRotation: 0,
<ide> maxRotation: 50,
<ide> mirror: false,
<del> mode: 'linear',
<ide> source: 'auto',
<ide> bounds: 'data',
<ide> padding: 0,
<ide> describe('Time scale tests', function() {
<ide> });
<ide> });
<ide>
<del> describe('when ticks.mode', function() {
<add> describe('when distribution', function() {
<ide> describe('is "series"', function() {
<ide> beforeEach(function() {
<ide> this.chart = window.acquireChart({
<ide> describe('Time scale tests', function() {
<ide> time: {
<ide> parser: 'YYYY'
<ide> },
<add> distribution: 'series',
<ide> ticks: {
<del> mode: 'series',
<ide> source: 'labels'
<ide> }
<ide> }],
<ide> describe('Time scale tests', function() {
<ide> });
<ide> });
<ide>
<del> it ('should space ticks out with the same gap, whatever their time values', function() {
<add> it ('should space data out with the same gap, whatever their time values', function() {
<ide> var scale = this.chart.scales.x;
<ide> var start = scale.left;
<ide> var slice = scale.width / 4;
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start);
<del> expect(pixels[1]).toBeCloseToPixel(start + slice);
<del> expect(pixels[2]).toBeCloseToPixel(start + slice * 2);
<del> expect(pixels[3]).toBeCloseToPixel(start + slice * 3);
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * 4);
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * 2);
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * 3);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 4);
<ide> });
<del> it ('should add a step before if scale.min is before the first tick', function() {
<add> it ('should add a step before if scale.min is before the first data', function() {
<ide> var chart = this.chart;
<ide> var scale = chart.scales.x;
<ide> var options = chart.options.scales.xAxes[0];
<ide> describe('Time scale tests', function() {
<ide>
<ide> var start = scale.left;
<ide> var slice = scale.width / 5;
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start + slice);
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * 5);
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 5);
<ide> });
<del> it ('should add a step after if scale.max is after the last tick', function() {
<add> it ('should add a step after if scale.max is after the last data', function() {
<ide> var chart = this.chart;
<ide> var scale = chart.scales.x;
<ide> var options = chart.options.scales.xAxes[0];
<ide> describe('Time scale tests', function() {
<ide>
<ide> var start = scale.left;
<ide> var slice = scale.width / 5;
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start);
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * 4);
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 4);
<ide> });
<del> it ('should add steps before and after if scale.min/max are outside the labels range', function() {
<add> it ('should add steps before and after if scale.min/max are outside the data range', function() {
<ide> var chart = this.chart;
<ide> var scale = chart.scales.x;
<ide> var options = chart.options.scales.xAxes[0];
<ide> describe('Time scale tests', function() {
<ide>
<ide> var start = scale.left;
<ide> var slice = scale.width / 6;
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start + slice);
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * 5);
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice);
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 5);
<ide> });
<ide> });
<ide> describe('is "linear"', function() {
<ide> describe('Time scale tests', function() {
<ide> time: {
<ide> parser: 'YYYY'
<ide> },
<add> distribution: 'linear',
<ide> ticks: {
<del> mode: 'linear',
<ide> source: 'labels'
<ide> }
<ide> }],
<ide> describe('Time scale tests', function() {
<ide> });
<ide> });
<ide>
<del> it ('should space ticks out with a gap relative to their time values', function() {
<add> it ('should space data out with a gap relative to their time values', function() {
<ide> var scale = this.chart.scales.x;
<ide> var start = scale.left;
<ide> var slice = scale.width / (2042 - 2017);
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start);
<del> expect(pixels[1]).toBeCloseToPixel(start + slice * (2019 - 2017));
<del> expect(pixels[2]).toBeCloseToPixel(start + slice * (2020 - 2017));
<del> expect(pixels[3]).toBeCloseToPixel(start + slice * (2025 - 2017));
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * (2042 - 2017));
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2019 - 2017));
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2020 - 2017));
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2025 - 2017));
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * (2042 - 2017));
<ide> });
<ide> it ('should take in account scale min and max if outside the ticks range', function() {
<ide> var chart = this.chart;
<ide> describe('Time scale tests', function() {
<ide>
<ide> var start = scale.left;
<ide> var slice = scale.width / (2050 - 2012);
<del> var pixels = fetchTickPositions(scale);
<ide>
<del> expect(pixels[0]).toBeCloseToPixel(start + slice * (2017 - 2012));
<del> expect(pixels[1]).toBeCloseToPixel(start + slice * (2019 - 2012));
<del> expect(pixels[2]).toBeCloseToPixel(start + slice * (2020 - 2012));
<del> expect(pixels[3]).toBeCloseToPixel(start + slice * (2025 - 2012));
<del> expect(pixels[4]).toBeCloseToPixel(start + slice * (2042 - 2012));
<add> expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * (2017 - 2012));
<add> expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2019 - 2012));
<add> expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2020 - 2012));
<add> expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2025 - 2012));
<add> expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * (2042 - 2012));
<ide> });
<ide> });
<ide> }); | 2 |
Text | Text | improve doc for disabling repl history on windows | 303585eb293e1d6aa2c13d2cf47fa7285732237f | <ide><path>doc/api/repl.md
<ide> environment variables:
<ide>
<ide> - `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history
<ide> will be saved to the specified file rather than `.node_repl_history` in the
<del> user's home directory. Setting this value to `''` will disable persistent
<del> REPL history. Whitespace will be trimmed from the value.
<add> user's home directory. Setting this value to `''` (an empty string) will
<add> disable persistent REPL history. Whitespace will be trimmed from the value.
<add> On Windows platforms environment variables with empty values are invalid so
<add> set this variable to one or more spaces to disable persistent REPL history.
<ide> - `NODE_REPL_HISTORY_SIZE` - Controls how many lines of history will be
<ide> persisted if history is available. Must be a positive number.
<ide> **Default:** `1000`. | 1 |
PHP | PHP | correct doc blocks and default values | 0efad4f6ee02cf771f1bb3c41caf526414a95236 | <ide><path>src/Database/Connection.php
<ide> public function configName() {
<ide> *
<ide> * If no params are passed it will return the current driver instance.
<ide> *
<del> * @param string|\Cake\Database\Driver $driver The driver instance to use.
<add> * @param \Cake\Database\Driver|string|null $driver The driver instance to use.
<ide> * @param array|null $config Either config for a new driver or null.
<ide> * @throws \Cake\Database\Exception\MissingDriverException When a driver class is missing.
<ide> * @throws \Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing.
<ide> * @return \Cake\Database\Driver
<ide> */
<del> public function driver($driver = null, $config = null) {
<add> public function driver($driver = null, $config = []) {
<ide> if ($driver === null) {
<ide> return $this->_driver;
<ide> }
<ide> public function newQuery() {
<ide> /**
<ide> * Gets or sets a Schema\Collection object for this connection.
<ide> *
<del> * @param \Cake\Database\Schema\Collection $collection The schema collection object
<add> * @param \Cake\Database\Schema\Collection|null $collection The schema collection object
<ide> * @return \Cake\Database\Schema\Collection
<ide> */
<ide> public function schemaCollection(SchemaCollection $collection = null) {
<ide><path>src/Database/Driver/PDODriverTrait.php
<ide> public function quote($value, $type) {
<ide> /**
<ide> * Returns last id generated for a table or sequence in database
<ide> *
<del> * @param string $table table name or sequence to get last insert value from
<del> * @param string $column the name of the column representing the primary key
<add> * @param string|null $table table name or sequence to get last insert value from
<add> * @param string|null $column the name of the column representing the primary key
<ide> * @return string|int
<ide> */
<ide> public function lastInsertId($table = null, $column = null) {
<ide><path>src/Database/Expression/CaseExpression.php
<ide> protected function _addExpressions($conditions, $values, $types) {
<ide> /**
<ide> * Sets the default value
<ide> *
<del> * @param string|ExpressionInterface|array $value Value to set
<add> * @param \Cake\Database\ExpressionInterface|string|array|null $value Value to set
<ide> * @param string $type Type of value
<ide> *
<ide> * @return void
<ide> public function elseValue($value = null, $type = null) {
<ide> /**
<ide> * Compiles the relevant parts into sql
<ide> *
<del> * @param array|string|ExpressionInterface $part The part to compile
<add> * @param array|string|\Cake\Database\ExpressionInterface $part The part to compile
<ide> * @param ValueBinder $generator Sql generator
<ide> *
<ide> * @return string
<ide><path>src/Database/Query.php
<ide> public function from($tables = [], $overwrite = false) {
<ide> * $query->join(['something' => 'different_table'], [], true); // resets joins list
<ide> * }}}
<ide> *
<del> * @param array|string $tables list of tables to be joined in the query
<add> * @param array|string|null $tables list of tables to be joined in the query
<ide> * @param array $types associative array of type names used to bind values to query
<ide> * @param bool $overwrite whether to reset joins with passed list or not
<ide> * @see \Cake\Database\Type
<ide> protected function _makeJoin($table, $conditions, $type) {
<ide> * If you use string conditions make sure that your values are correctly quoted.
<ide> * The safest thing you can do is to never use string conditions.
<ide> *
<del> * @param string|array|ExpressionInterface|callback $conditions The conditions to filter on.
<add> * @param string|array|\Cake\Database\ExpressionInterface|callback|null $conditions The conditions to filter on.
<ide> * @param array $types associative array of type names used to bind values to query
<ide> * @param bool $overwrite whether to reset conditions with passed list or not
<ide> * @see \Cake\Database\Type
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function describeColumnSql($tableName, $config) {
<ide> * Cake\Database\Type can handle.
<ide> *
<ide> * @param string $col The column type
<del> * @param int $length the column length
<del> * @param int $precision The column precision
<del> * @param int $scale The column scale
<add> * @param int|null $length the column length
<add> * @param int|null $precision The column precision
<add> * @param int|null $scale The column scale
<ide> * @return array Array of column information.
<ide> * @link http://technet.microsoft.com/en-us/library/ms187752.aspx
<ide> */
<ide><path>src/Database/Statement/BufferedStatement.php
<ide> class BufferedStatement extends StatementDecorator {
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Database\StatementInterface $statement Statement implementation such as PDOStatement
<del> * @param \Cake\Database\Driver $driver Driver instance
<add> * @param \Cake\Database\StatementInterface|null $statement Statement implementation such as PDOStatement
<add> * @param \Cake\Database\Driver|null $driver Driver instance
<ide> */
<ide> public function __construct($statement = null, $driver = null) {
<ide> parent::__construct($statement, $driver);
<ide> public function __construct($statement = null, $driver = null) {
<ide> /**
<ide> * Execute the statement and return the results.
<ide> *
<del> * @param array $params list of values to be bound to query
<add> * @param array|null $params list of values to be bound to query
<ide> * @return bool true on success, false otherwise
<ide> */
<ide> public function execute($params = null) {
<ide><path>src/Database/Statement/PDOStatement.php
<ide> class PDOStatement extends StatementDecorator {
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \PDOStatement $statement Original statement to be decorated.
<del> * @param \Cake\Database\Driver $driver Driver instance.
<add> * @param \PDOStatement|null $statement Original statement to be decorated.
<add> * @param \Cake\Database\Driver|null $driver Driver instance.
<ide> */
<ide> public function __construct(Statement $statement = null, $driver = null) {
<ide> $this->_statement = $statement;
<ide><path>src/Database/Statement/StatementDecorator.php
<ide> class StatementDecorator implements StatementInterface, \Countable, \IteratorAgg
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Database\StatementInterface $statement Statement implementation such as PDOStatement
<del> * @param \Cake\Database\Driver $driver Driver instance
<add> * @param \Cake\Database\StatementInterface|null $statement Statement implementation such as PDOStatement
<add> * @param \Cake\Database\Driver|null $driver Driver instance
<ide> */
<ide> public function __construct($statement = null, $driver = null) {
<ide> $this->_statement = $statement;
<ide> public function errorInfo() {
<ide> * that binding parameters from this method will not perform any custom type conversion
<ide> * as it would normally happen when calling `bindValue`.
<ide> *
<del> * @param array $params list of values to be bound to query
<add> * @param array|null $params list of values to be bound to query
<ide> * @return bool true on success, false otherwise
<ide> */
<ide> public function execute($params = null) {
<ide> public function bind($params, $types) {
<ide> /**
<ide> * Returns the latest primary inserted using this statement.
<ide> *
<del> * @param string $table table name or sequence to get last insert value from
<del> * @param string $column the name of the column representing the primary key
<add> * @param string|null $table table name or sequence to get last insert value from
<add> * @param string|null $column the name of the column representing the primary key
<ide> * @return string
<ide> */
<ide> public function lastInsertId($table = null, $column = null) {
<ide><path>src/Database/StatementInterface.php
<ide> public function bind($params, $types);
<ide> /**
<ide> * Returns the latest primary inserted using this statement
<ide> *
<del> * @param string $table table name or sequence to get last insert value from
<del> * @param string $column the name of the column representing the primary key
<add> * @param string|null $table table name or sequence to get last insert value from
<add> * @param string|null $column the name of the column representing the primary key
<ide> * @return string
<ide> */
<ide> public function lastInsertId($table = null, $column = null);
<ide><path>src/Database/Type.php
<ide> public static function build($name) {
<ide> * If called with no arguments it will return current types map array
<ide> * If $className is omitted it will return mapped class for $type
<ide> *
<del> * @param string|array $type if string name of type to map, if array list of arrays to be mapped
<del> * @param string $className The classname to register.
<add> * @param string|array|null $type if string name of type to map, if array list of arrays to be mapped
<add> * @param string|null $className The classname to register.
<ide> * @return array|string|null if $type is null then array with current map, if $className is null string
<ide> * configured class name for give $type, null otherwise
<ide> */ | 10 |
Javascript | Javascript | fix crash when passing null to clearimmediate | 44fcf22074ca32e5f6869b88f7b6c00ea990cb08 | <ide><path>Libraries/JavaScriptAppEngine/System/JSTimers/JSTimers.js
<ide> var JSTimers = {
<ide>
<ide> clearImmediate: function(timerID) {
<ide> JSTimers._clearTimerID(timerID);
<del> JSTimersExecution.immediates.splice(
<del> JSTimersExecution.immediates.indexOf(timerID),
<del> 1
<del> );
<add> var index = JSTimersExecution.immediates.indexOf(timerID);
<add> if (index !== -1) {
<add> JSTimersExecution.immediates.splice(index, 1);
<add> }
<ide> },
<ide>
<ide> cancelAnimationFrame: function(timerID) { | 1 |
PHP | PHP | pass session to formrequest | 3a06c91468cc2453a82590208c06bd4037c421f4 | <ide><path>src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php
<ide> protected function initializeRequest(FormRequest $form, Request $current)
<ide> $current->cookies->all(), $files, $current->server->all(), $current->getContent()
<ide> );
<ide>
<add> $form->setSession($current->getSession());
<add>
<ide> $form->setUserResolver($current->getUserResolver());
<ide>
<ide> $form->setRouteResolver($current->getRouteResolver()); | 1 |
Text | Text | move gibfahn to tsc emeritus | 2ebdba12297348649620e3d302b156c149d85a6e | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Jeremiah Senkpiel** <fishrock123@rocketmail.com>
<ide> * [gabrielschulhof](https://github.com/gabrielschulhof) -
<ide> **Gabriel Schulhof** <gabriel.schulhof@intel.com>
<del>* [gibfahn](https://github.com/gibfahn) -
<del>**Gibson Fahnestock** <gibfahn@gmail.com> (he/him)
<ide> * [jasnell](https://github.com/jasnell) -
<ide> **James M Snell** <jasnell@gmail.com> (he/him)
<ide> * [joyeecheung](https://github.com/joyeecheung) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Chris Dickinson** <christopher.s.dickinson@gmail.com>
<ide> * [evanlucas](https://github.com/evanlucas) -
<ide> **Evan Lucas** <evanlucas@me.com> (he/him)
<add>* [gibfahn](https://github.com/gibfahn) -
<add>**Gibson Fahnestock** <gibfahn@gmail.com> (he/him)
<ide> * [indutny](https://github.com/indutny) -
<ide> **Fedor Indutny** <fedor.indutny@gmail.com>
<ide> * [isaacs](https://github.com/isaacs) - | 1 |
Javascript | Javascript | fix codeclimate issues | 47d23601b1e3cfc18c7a661ff56c4545c8e6a29d | <ide><path>gulpfile.js
<ide> var srcDir = './src/';
<ide> gulp.task('build', function(){
<ide>
<ide> // Default to all of the chart types, with Chart.Core first
<del> var srcFiles = [FileName('Core')],
<add> var srcFiles = [new FileName('Core')],
<ide> isCustom = !!(util.env.types),
<ide> outputDir = (isCustom) ? 'custom' : '.';
<ide> if (isCustom){
<del> util.env.types.split(',').forEach(function(type){ return srcFiles.push(FileName(type))});
<add> util.env.types.split(',').forEach(function(type){ return srcFiles.push(new FileName(type));});
<ide> }
<ide> else{
<ide> // Seems gulp-concat remove duplicates - nice!
<ide> gulp.task('build', function(){
<ide>
<ide> function FileName(moduleName){
<ide> return srcDir+'Chart.'+moduleName+'.js';
<del> };
<add> }
<ide> });
<ide>
<ide> /*
<ide> gulp.task('module-sizes', function(){
<ide> .pipe(size({
<ide> showFiles: true,
<ide> gzip: true
<del> }))
<add> }));
<ide> });
<ide>
<ide> gulp.task('watch', function(){
<ide><path>src/Chart.Core.js
<ide> {
<ide> return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
<ide> }
<del> }
<add> };
<ide>
<ide> var width = this.width = computeDimension(context.canvas,'Width') || context.canvas.width;
<ide> var height = this.height = computeDimension(context.canvas,'Height') || context.canvas.height;
<ide> context.canvas.width = width;
<ide> context.canvas.height = height;
<ide>
<del> var width = this.width = context.canvas.width;
<del> var height = this.height = context.canvas.height;
<add> width = this.width = context.canvas.width;
<add> height = this.height = context.canvas.height;
<ide> this.aspectRatio = this.width / this.height;
<ide> //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
<ide> helpers.retinaScale(this);
<ide> clone = helpers.clone = function(obj){
<ide> var objClone = {};
<ide> each(obj,function(value,key){
<del> if (obj.hasOwnProperty(key)) objClone[key] = value;
<add> if (obj.hasOwnProperty(key)){
<add> objClone[key] = value;
<add> }
<ide> });
<ide> return objClone;
<ide> },
<ide> extend = helpers.extend = function(base){
<ide> each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
<ide> each(extensionObject,function(value,key){
<del> if (extensionObject.hasOwnProperty(key)) base[key] = value;
<add> if (extensionObject.hasOwnProperty(key)){
<add> base[key] = value;
<add> }
<ide> });
<ide> });
<ide> return base;
<ide> })(),
<ide> warn = helpers.warn = function(str){
<ide> //Method for warning of errors
<del> if (window.console && typeof window.console.warn == "function") console.warn(str);
<add> if (window.console && typeof window.console.warn === "function") console.warn(str);
<ide> },
<del> amd = helpers.amd = (typeof define == 'function' && define.amd),
<add> amd = helpers.amd = (typeof define === 'function' && define.amd),
<ide> //-- Math methods
<ide> isNumber = helpers.isNumber = function(n){
<ide> return !isNaN(parseFloat(n)) && isFinite(n);
<ide> return -1 * t * (t - 2);
<ide> },
<ide> easeInOutQuad: function (t) {
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * t * t;
<add> }
<ide> return -1 / 2 * ((--t) * (t - 2) - 1);
<ide> },
<ide> easeInCubic: function (t) {
<ide> return 1 * ((t = t / 1 - 1) * t * t + 1);
<ide> },
<ide> easeInOutCubic: function (t) {
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * t * t * t;
<add> }
<ide> return 1 / 2 * ((t -= 2) * t * t + 2);
<ide> },
<ide> easeInQuart: function (t) {
<ide> return -1 * ((t = t / 1 - 1) * t * t * t - 1);
<ide> },
<ide> easeInOutQuart: function (t) {
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * t * t * t * t;
<add> }
<ide> return -1 / 2 * ((t -= 2) * t * t * t - 2);
<ide> },
<ide> easeInQuint: function (t) {
<ide> return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
<ide> },
<ide> easeInOutQuint: function (t) {
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * t * t * t * t * t;
<add> }
<ide> return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
<ide> },
<ide> easeInSine: function (t) {
<ide> return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
<ide> },
<ide> easeInOutExpo: function (t) {
<del> if (t === 0) return 0;
<del> if (t === 1) return 1;
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
<add> if (t === 0){
<add> return 0;
<add> }
<add> if (t === 1){
<add> return 1;
<add> }
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * Math.pow(2, 10 * (t - 1));
<add> }
<ide> return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
<ide> },
<ide> easeInCirc: function (t) {
<del> if (t >= 1) return t;
<add> if (t >= 1){
<add> return t;
<add> }
<ide> return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
<ide> },
<ide> easeOutCirc: function (t) {
<ide> return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
<ide> },
<ide> easeInOutCirc: function (t) {
<del> if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
<add> if ((t /= 1 / 2) < 1){
<add> return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
<add> }
<ide> return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
<ide> },
<ide> easeInElastic: function (t) {
<ide> var s = 1.70158;
<ide> var p = 0;
<ide> var a = 1;
<del> if (t === 0) return 0;
<del> if ((t /= 1) == 1) return 1;
<del> if (!p) p = 1 * 0.3;
<add> if (t === 0){
<add> return 0;
<add> }
<add> if ((t /= 1) == 1){
<add> return 1;
<add> }
<add> if (!p){
<add> p = 1 * 0.3;
<add> }
<ide> if (a < Math.abs(1)) {
<ide> a = 1;
<ide> s = p / 4;
<del> } else s = p / (2 * Math.PI) * Math.asin(1 / a);
<add> } else{
<add> s = p / (2 * Math.PI) * Math.asin(1 / a);
<add> }
<ide> return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
<ide> },
<ide> easeOutElastic: function (t) {
<ide> var s = 1.70158;
<ide> var p = 0;
<ide> var a = 1;
<del> if (t === 0) return 0;
<del> if ((t /= 1) == 1) return 1;
<del> if (!p) p = 1 * 0.3;
<add> if (t === 0){
<add> return 0;
<add> }
<add> if ((t /= 1) == 1){
<add> return 1;
<add> }
<add> if (!p){
<add> p = 1 * 0.3;
<add> }
<ide> if (a < Math.abs(1)) {
<ide> a = 1;
<ide> s = p / 4;
<del> } else s = p / (2 * Math.PI) * Math.asin(1 / a);
<add> } else{
<add> s = p / (2 * Math.PI) * Math.asin(1 / a);
<add> }
<ide> return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
<ide> },
<ide> easeInOutElastic: function (t) {
<ide> var s = 1.70158;
<ide> var p = 0;
<ide> var a = 1;
<del> if (t === 0) return 0;
<del> if ((t /= 1 / 2) == 2) return 1;
<del> if (!p) p = 1 * (0.3 * 1.5);
<add> if (t === 0){
<add> return 0;
<add> }
<add> if ((t /= 1 / 2) == 2){
<add> return 1;
<add> }
<add> if (!p){
<add> p = 1 * (0.3 * 1.5);
<add> }
<ide> if (a < Math.abs(1)) {
<ide> a = 1;
<ide> s = p / 4;
<del> } else s = p / (2 * Math.PI) * Math.asin(1 / a);
<del> if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
<add> } else {
<add> s = p / (2 * Math.PI) * Math.asin(1 / a);
<add> }
<add> if (t < 1){
<add> return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));}
<ide> return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
<ide> },
<ide> easeInBack: function (t) {
<ide> },
<ide> easeInOutBack: function (t) {
<ide> var s = 1.70158;
<del> if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
<add> if ((t /= 1 / 2) < 1){
<add> return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
<add> }
<ide> return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
<ide> },
<ide> easeInBounce: function (t) {
<ide> }
<ide> },
<ide> easeInOutBounce: function (t) {
<del> if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
<add> if (t < 1 / 2){
<add> return easingEffects.easeInBounce(t * 2) * 0.5;
<add> }
<ide> return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
<ide> }
<ide> }, | 2 |
Ruby | Ruby | use guard clause instead of `||` | ad7be58655e260adda6a9e4d33365148d22463db | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def clear_cache
<ide>
<ide> def safe_system(*args)
<ide> if @shutup
<del> quiet_system(*args) || raise(ErrorDuringExecution.new(args, status: $CHILD_STATUS))
<add> return if quiet_system(*args)
<add> raise(ErrorDuringExecution.new(args, status: $CHILD_STATUS))
<ide> else
<ide> super(*args)
<ide> end
<ide><path>Library/Homebrew/utils.rb
<ide> def run_as_not_developer
<ide>
<ide> # Kernel.system but with exceptions
<ide> def safe_system(cmd, *args, **options)
<del> Homebrew.system(cmd, *args, **options) || raise(ErrorDuringExecution.new([cmd, *args], status: $CHILD_STATUS))
<add> return if Homebrew.system(cmd, *args, **options)
<add> raise(ErrorDuringExecution.new([cmd, *args], status: $CHILD_STATUS))
<ide> end
<ide>
<ide> # prints no output | 2 |
Ruby | Ruby | add method `ensure_executable!` | c0826f1890eaf11ddc1d9e1dfd83a44fc218d91b | <ide><path>Library/Homebrew/github_packages.rb
<ide> def upload_bottles(bottles_hash, keep_old:, dry_run:, warn_on_error:)
<ide> raise UsageError, "HOMEBREW_GITHUB_PACKAGES_USER is unset." if user.blank?
<ide> raise UsageError, "HOMEBREW_GITHUB_PACKAGES_TOKEN is unset." if token.blank?
<ide>
<del> skopeo = [
<del> which("skopeo"),
<del> which("skopeo", ENV["HOMEBREW_PATH"]),
<del> HOMEBREW_PREFIX/"bin/skopeo",
<del> ].compact.first
<del> skopeo = ensure_formula_installed!("skopeo",
<del> reason: "for upload").opt_bin/"skopeo" unless skopeo.exist?
<add> skopeo = ensure_executable!("skopeo", reason: "for upload")
<ide>
<ide> require "json_schemer"
<ide>
<ide><path>Library/Homebrew/utils.rb
<ide> def ensure_formula_installed!(formula_or_name, latest: false, reason: "",
<ide> formula
<ide> end
<ide>
<add> # Ensure the given executable is exist otherwise install the brewed version
<add> def ensure_executable!(name, formula_name = nil, reason: "")
<add> formula_name ||= name
<add>
<add> executable = [
<add> which(name),
<add> which(name, ENV["HOMEBREW_PATH"]),
<add> HOMEBREW_PREFIX/"bin/#{name}",
<add> ].compact.first
<add> return executable if executable.exist?
<add>
<add> ensure_formula_installed!(formula_name, reason: reason).opt_bin/name
<add> end
<add>
<ide> def paths
<ide> @paths ||= PATH.new(ENV["HOMEBREW_PATH"]).map do |p|
<ide> File.expand_path(p).chomp("/") | 2 |
Javascript | Javascript | remove the `function.prototype.bind` polyfill | 4b15e8566b5c454f26ee4b2da57c3d726e6c019c | <ide><path>src/shared/compatibility.js
<ide> PDFJS.compatibilityChecked = true;
<ide> });
<ide> })();
<ide>
<del>// Function.prototype.bind?
<del>// Support: Android<4.0, iOS<6.0
<del>(function checkFunctionPrototypeBindCompatibility() {
<del> if (typeof Function.prototype.bind !== 'undefined') {
<del> return;
<del> }
<del>
<del> Function.prototype.bind = function functionPrototypeBind(obj) {
<del> var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
<del> var bound = function functionPrototypeBindBound() {
<del> var args = headArgs.concat(Array.prototype.slice.call(arguments));
<del> return fn.apply(obj, args);
<del> };
<del> return bound;
<del> };
<del>})();
<del>
<ide> // HTMLElement dataset property
<ide> // Support: IE<11, Safari<5.1, Android<4.0
<ide> (function checkDatasetProperty() { | 1 |
PHP | PHP | resolve psalm error | f633d0aa79c108fdc1ceb6bf9ca4630169861c8f | <ide><path>src/Shell/Helper/TableHelper.php
<ide> protected function _calculateWidths(array $rows): array
<ide> /**
<ide> * Get the width of a cell exclusive of style tags.
<ide> *
<del> * @param string|null $text The text to calculate a width for.
<add> * @param string $text The text to calculate a width for.
<ide> * @return int The width of the textual content in visible characters.
<ide> */
<del> protected function _cellWidth(?string $text): int
<add> protected function _cellWidth(string $text): int
<ide> {
<del> if ($text === null) {
<add> if (strlen($text) === 0) {
<ide> return 0;
<ide> }
<ide>
<ide> protected function _render(array $row, array $widths, array $options = []): void
<ide> if (!empty($options['style'])) {
<ide> $column = $this->_addStyle($column, $options['style']);
<ide> }
<del> if ($column !== null && preg_match('#(.*)<text-right>.+</text-right>(.*)#', $column, $matches)) {
<add> if (strlen($column) > 0 && preg_match('#(.*)<text-right>.+</text-right>(.*)#', $column, $matches)) {
<ide> if ($matches[1] !== '' || $matches[2] !== '') {
<ide> throw new UnexpectedValueException('You cannot include text before or after the text-right tag.');
<ide> }
<ide><path>tests/TestCase/Shell/Helper/TableHelperTest.php
<ide> public function testRowValueInteger()
<ide>
<ide> $this->assertEquals($expected, $this->stub->messages());
<ide> }
<add>
<add> /**
<add> * Table row column of type null should be cast to empty string
<add> */
<add> public function testRowValueNull()
<add> {
<add> $data = [
<add> ['Item', 'Quantity'],
<add> ['Cakes', null],
<add> ];
<add> $this->helper->output($data);
<add> $expected = [
<add> '+-------+----------+',
<add> '| <info>Item</info> | <info>Quantity</info> |',
<add> '+-------+----------+',
<add> '| Cakes | |',
<add> '+-------+----------+',
<add> ];
<add>
<add> $this->assertEquals($expected, $this->stub->messages());
<add> }
<ide> } | 2 |
Text | Text | remove extraneous comma in tutorial | 246fdebf82624eb1300a0a63cc6aea110e0cc50e | <ide><path>docs/docs/tutorial.md
<ide> prev: getting-started.html
<ide> next: thinking-in-react.html
<ide> ---
<ide>
<del>We'll be building a simple, but realistic comments box that you can drop into a blog, a basic version of the realtime comments offered by Disqus, LiveFyre or Facebook comments.
<add>We'll be building a simple but realistic comments box that you can drop into a blog, a basic version of the realtime comments offered by Disqus, LiveFyre or Facebook comments.
<ide>
<ide> We'll provide:
<ide> | 1 |
PHP | PHP | use variadic isset | 5fd031e041844cd35e9d4d9afc2698b84b3f0d5b | <ide><path>src/ORM/EagerLoader.php
<ide> protected function _reformatContain($associations, $original)
<ide>
<ide> $pointer += [$table => []];
<ide>
<del> if (isset($options['queryBuilder']) && isset($pointer[$table]['queryBuilder'])) {
<add> if (isset($options['queryBuilder'], $pointer[$table]['queryBuilder'])) {
<ide> $first = $pointer[$table]['queryBuilder'];
<ide> $second = $options['queryBuilder'];
<ide> $options['queryBuilder'] = function ($query) use ($first, $second) {
<ide><path>src/Validation/Validation.php
<ide> public static function imageSize($file, $options)
<ide> if (isset($options['width'])) {
<ide> $validWidth = self::comparison($width, $options['width'][0], $options['width'][1]);
<ide> }
<del> if (isset($validHeight) && isset($validWidth)) {
<add> if (isset($validHeight, $validWidth)) {
<ide> return ($validHeight && $validWidth);
<ide> }
<ide> if (isset($validHeight)) { | 2 |
Go | Go | remove unnecessary variable idx | 730e0994c8ceec64e753562c648e57e0a7ead6b4 | <ide><path>oci/namespaces.go
<ide> import specs "github.com/opencontainers/runtime-spec/specs-go"
<ide>
<ide> // RemoveNamespace removes the `nsType` namespace from OCI spec `s`
<ide> func RemoveNamespace(s *specs.Spec, nsType specs.NamespaceType) {
<del> idx := -1
<ide> for i, n := range s.Linux.Namespaces {
<ide> if n.Type == nsType {
<del> idx = i
<add> s.Linux.Namespaces = append(s.Linux.Namespaces[:i], s.Linux.Namespaces[i+1:]...)
<add> return
<ide> }
<ide> }
<del> if idx >= 0 {
<del> s.Linux.Namespaces = append(s.Linux.Namespaces[:idx], s.Linux.Namespaces[idx+1:]...)
<del> }
<ide> } | 1 |
Ruby | Ruby | remove another unnecessary dup | 8ef780c3e2df86fa678982a5db80421ccf4d4dee | <ide><path>actionpack/lib/action_dispatch/journey/formatter.rb
<ide> def clear
<ide> private
<ide>
<ide> def extract_parameterized_parts(route, options, recall, parameterize = nil)
<del> data = recall.merge(options)
<add> parameterized_parts = recall.merge(options)
<ide>
<ide> keys_to_keep = route.parts.reverse.drop_while { |part|
<ide> !options.key?(part) || (options[part] || recall[part]).nil?
<ide> } | route.required_parts
<ide>
<del> (data.keys - keys_to_keep).each do |bad_key|
<del> data.delete(bad_key)
<add> (parameterized_parts.keys - keys_to_keep).each do |bad_key|
<add> parameterized_parts.delete(bad_key)
<ide> end
<ide>
<del> parameterized_parts = data.dup
<del>
<ide> if parameterize
<ide> parameterized_parts.each do |k, v|
<ide> parameterized_parts[k] = parameterize.call(k, v) | 1 |
Python | Python | use future for urlparse | 697c8fa0265ce70b1e777d4e2d6a38fde3a834e2 | <ide><path>airflow/models.py
<ide> from __future__ import print_function
<add>from future.standard_library import install_aliases
<add>install_aliases()
<ide> from builtins import str
<ide> from past.builtins import basestring
<ide> from builtins import object, bytes
<ide> import signal
<ide> import socket
<ide> import sys
<del>from urlparse import urlparse
<add>from urllib.parse import urlparse
<ide>
<ide> from sqlalchemy import (
<ide> Column, Integer, String, DateTime, Text, Boolean, ForeignKey, PickleType, | 1 |
PHP | PHP | throw exception on pusher broadcaster error | 67e7beb119b40abf31a65affa0abe0c9cb9463ac | <ide><path>src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php
<ide> namespace Illuminate\Broadcasting\Broadcasters;
<ide>
<ide> use Pusher;
<add>use RuntimeException;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use Symfony\Component\HttpKernel\Exception\HttpException;
<ide> public function broadcast(array $channels, $event, array $payload = [])
<ide> {
<ide> $socket = Arr::pull($payload, 'socket');
<ide>
<del> $this->pusher->trigger($this->formatChannels($channels), $event, $payload, $socket);
<add> if (true === $response = $this->pusher->trigger($this->formatChannels($channels), $event, $payload, $socket)) {
<add> return;
<add> }
<add>
<add> throw new RuntimeException(
<add> is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
<add> );
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | add setformattime for overriding the time format | 2f96914b8e570fc16d19b546fa0bfe26ab0b727c | <ide><path>src/js/utils/format-time.js
<ide> /**
<ide> * @file format-time.js
<del> * @module Format-time
<add> * @module format-time
<ide> */
<ide>
<del>/**
<add> /**
<ide> * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds)
<ide> * will force a number of leading zeros to cover the length of the guide.
<ide> *
<ide> * @return {string}
<ide> * Time formatted as H:MM:SS or M:SS
<ide> */
<del>function formatTime(seconds, guide = seconds) {
<add>const defaultImplementation = function(seconds, guide) {
<ide> seconds = seconds < 0 ? 0 : seconds;
<ide> let s = Math.floor(seconds % 60);
<ide> let m = Math.floor(seconds / 60 % 60);
<ide> function formatTime(seconds, guide = seconds) {
<ide> s = (s < 10) ? '0' + s : s;
<ide>
<ide> return h + m + s;
<add>};
<add>
<add>let implementation = defaultImplementation;
<add>
<add>/**
<add> * Replaces the default formatTime implementation with a custom implementation.
<add> *
<add> * @param {Function} customImplementation
<add> * A function which will be used in place of the default formatTime implementation.
<add> * Will receive the current time in seconds and the guide (in seconds) as arguments.
<add> */
<add>export function setFormatTime(customImplementation) {
<add> implementation = customImplementation;
<ide> }
<ide>
<del>export default formatTime;
<add>/**
<add> * Resets formatTime to the default implementation.
<add> */
<add>export function resetFormatTime() {
<add> implementation = defaultImplementation;
<add>}
<add>
<add>export default function(seconds, guide = seconds) {
<add> return implementation(seconds, guide);
<add>}
<ide><path>src/js/video.js
<ide> import AudioTrack from './tracks/audio-track.js';
<ide> import VideoTrack from './tracks/video-track.js';
<ide>
<ide> import { createTimeRanges } from './utils/time-ranges.js';
<del>import formatTime from './utils/format-time.js';
<add>import formatTime, { setFormatTime, resetFormatTime } from './utils/format-time.js';
<ide> import log from './utils/log.js';
<ide> import * as Dom from './utils/dom.js';
<ide> import * as browser from './utils/browser.js';
<ide> videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
<ide> */
<ide> videojs.formatTime = formatTime;
<ide>
<add>/**
<add> * Replaces format-time with a custom implementation, to be used in place of the default.
<add> *
<add> * @borrows format-time:setFormatTime as videojs.setFormatTime
<add> *
<add> * @method setFormatTime
<add> *
<add> * @param {Function} customFn
<add> * A custom format-time function which will be called with the current time and guide (in seconds) as arguments.
<add> * Passed fn should return a string.
<add> */
<add>videojs.setFormatTime = setFormatTime;
<add>
<add>/**
<add> * Resets format-time to the default implementation.
<add> *
<add> * @borrows format-time:resetFormatTime as videojs.resetFormatTime
<add> *
<add> * @method resetFormatTime
<add> */
<add>videojs.resetFormatTime = resetFormatTime;
<add>
<ide> /**
<ide> * Resolve and parse the elements of a URL
<ide> *
<ide> * @borrows url:parseUrl as videojs.parseUrl
<add> *
<ide> */
<ide> videojs.parseUrl = Url.parseUrl;
<ide>
<ide><path>test/unit/utils/format-time.test.js
<ide> /* eslint-env qunit */
<del>import formatTime from '../../../src/js/utils/format-time.js';
<add>import formatTime, { setFormatTime, resetFormatTime } from '../../../src/js/utils/format-time.js';
<ide>
<del>QUnit.module('format-time');
<add>QUnit.module('format-time standard implementation', {
<add> afterEach: resetFormatTime()
<add>});
<ide>
<ide> QUnit.test('should format time as a string', function(assert) {
<ide> assert.ok(formatTime(1) === '0:01');
<ide> QUnit.test('should format invalid times as dashes', function(assert) {
<ide> assert.equal(formatTime(10, Infinity), '0:00:10');
<ide> assert.equal(formatTime(90, NaN), '1:30');
<ide> });
<add>
<add>QUnit.test('setFormatTime', function(assert) {
<add> setFormatTime((seconds, guide) => `custom:${seconds}:${guide}`);
<add> assert.equal(formatTime(1, 2), 'custom:1:2', 'it should replace the default formatTime implementation');
<add>});
<add>
<add>QUnit.test('resetFormatTime ', function(assert) {
<add> setFormatTime((seconds, guide) => `custom:${seconds}:${guide}`);
<add> assert.equal(formatTime(1, 2), 'custom:1:2');
<add> resetFormatTime();
<add> assert.equal(formatTime(1), '0:01', 'it should reset formatTime to the default implementation');
<add>});
<add> | 3 |
Ruby | Ruby | modify syntax for readability / consistency | dce6b77ad05ce23850fecdafb007cd261108a30a | <ide><path>Library/Homebrew/extend/os/mac/caveats.rb
<ide> def plist_caveats
<ide>
<ide> if f.plist_manual || f.service?
<ide> command = if f.service?
<del> f.service.command
<del> .map { |arg| (arg =~ /\s/) ? "'#{arg}'" : arg } # wrap multi-word arguments in quotes
<del> .join(" ")
<add> f.service
<add> .command
<add> .map do |arg|
<add> next arg unless arg.match?(/\s/)
<add>
<add> # quote multi-word arguments
<add> "'#{arg}'"
<add> end.join(" ")
<ide> else
<ide> f.plist_manual
<ide> end | 1 |
PHP | PHP | remove comments (missing commit) | c7da89d4d45e69c5302551854962a65948e38401 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function insert($query, $bindings = [])
<ide> *
<ide> * @param string $query
<ide> * @param array $bindings
<del> * @return int Number of rows affected by the query
<add> * @return int
<ide> */
<ide> public function update($query, $bindings = [])
<ide> {
<ide> public function update($query, $bindings = [])
<ide> *
<ide> * @param string $query
<ide> * @param array $bindings
<del> * @return int Number of rows affected by the query
<add> * @return int
<ide> */
<ide> public function delete($query, $bindings = [])
<ide> {
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function insertGetId(array $values, $sequence = null)
<ide> * Update a record in the database.
<ide> *
<ide> * @param array $values
<del> * @return int Number of rows affected by the query
<add> * @return int
<ide> */
<ide> public function update(array $values)
<ide> { | 2 |
Javascript | Javascript | update swipeablelistview props and more | 395122354f00483673fdaf5aec8c1e15e59d617b | <ide><path>Libraries/Experimental/SwipeableRow/SwipeableListView.js
<ide> type Props = {
<ide> bounceFirstRowOnMount: boolean,
<ide> dataSource: SwipeableListViewDataSource,
<ide> maxSwipeDistance: number | (rowData: any, sectionID: string, rowID: string) => number,
<del> onScroll: ?Function,
<add> onScroll?: ?Function,
<ide> renderRow: Function,
<ide> renderQuickActions: Function,
<ide> };
<ide> class SwipeableListView extends React.Component {
<ide> }
<ide>
<ide> // This enables rows having variable width slideoutView.
<del> _getMaxSwipeDistance = (rowData: Object, sectionID: string, rowID: string): number => {
<add> _getMaxSwipeDistance(rowData: Object, sectionID: string, rowID: string): number {
<ide> if (typeof this.props.maxSwipeDistance === 'function') {
<ide> return this.props.maxSwipeDistance(rowData, sectionID, rowID);
<ide> }
<ide>
<ide> return this.props.maxSwipeDistance;
<del> };
<add> }
<ide>
<ide> _renderRow = (rowData: Object, sectionID: string, rowID: string): React.Element<any> => {
<ide> const slideoutView = this.props.renderQuickActions(rowData, sectionID, rowID); | 1 |
Python | Python | fix documentation of flow_from_directory() | a053416a310868971a5ec743e714961e28d78c79 | <ide><path>keras/preprocessing/image.py
<ide> def flow_from_directory(self, directory,
<ide> The dimensions to which all images found will be resized.
<ide> color_mode: one of "grayscale", "rbg". Default: "rgb".
<ide> Whether the images will be converted to have 1 or 3 color channels.
<del> classes: optional list of class subdirectories (e.g. `['dogs', 'cats']`).
<del> Default: None. If not provided, the list of classes will
<del> be automatically inferred from the subdirectory names/structure under `directory`,
<add> classes: optional list of class subdirectories (e.g. `['dogs', 'cats']`). Default: None.
<add> If not provided, the list of classes will be automatically
<add> inferred from the subdirectory names/structure under `directory`,
<ide> where each subdirectory will be treated as a different class
<ide> (and the order of the classes, which will map to the label indices, will be alphanumeric).
<ide> The dictionary containing the mapping from class names to class
<ide> indices can be obtained via the attribute `class_indices`.
<del> class_mode: one of "categorical", "binary", "sparse", "input" or None.
<del> Default: "categorical". Determines the type of label arrays that are
<del> returned: "categorical" will be 2D one-hot encoded labels, "binary" will be 1D binary labels,
<del> "sparse" will be 1D integer labels, "input" will be images identical to input images (mainly used to work with autoencoders).
<add> class_mode: one of "categorical", "binary", "sparse", "input" or None. Default: "categorical".
<add> Determines the type of label arrays that are returned: "categorical" will be 2D one-hot encoded labels,
<add> "binary" will be 1D binary labels, "sparse" will be 1D integer labels, "input" will be images identical
<add> to input images (mainly used to work with autoencoders).
<ide> If None, no labels are returned (the generator will only yield batches of image data, which is useful to use
<ide> `model.predict_generator()`, `model.evaluate_generator()`, etc.).
<ide> Please note that in case of class_mode None,
<ide> def flow_from_directory(self, directory,
<ide> `"hamming"` are also supported. By default, `"nearest"` is used.
<ide>
<ide> # Returns
<del> A DirectoryIterator yielding tuples of `(x, y)` where `x` is a numpy array of image data and
<del> `y` is a numpy array of corresponding labels.
<add> A DirectoryIterator yielding tuples of `(x, y)` where `x` is a numpy array containing a batch
<add> of images with shape `(batch_size, *target_size, channels)` and `y` is a numpy array of corresponding labels.
<ide> """
<ide> return DirectoryIterator(
<ide> directory, self, | 1 |
Python | Python | make username optional in hub_model_id | 32634bce3312cb3827d3fec80ecb33206f7ae7be | <ide><path>src/transformers/keras_callbacks.py
<ide> def __init__(
<ide> tokenizer (:obj:`PreTrainedTokenizerBase`, `optional`):
<ide> The tokenizer used by the model. If supplied, will be uploaded to the repo alongside the weights.
<ide> hub_model_id (:obj:`str`, `optional`):
<del> The name of the repository to keep in sync with the local `output_dir`. Should be the whole repository
<del> name, for instance :obj:`"user_name/model"`, which allows you to push to an organization you are a member
<del> of with :obj:`"organization_name/model"`. Will default to :obj:`user_name/output_dir_name` with
<del> `output_dir_name` being the name of :obj:`output_dir`.
<add> The name of the repository to keep in sync with the local `output_dir`. It can be a simple model ID in
<add> which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
<add> for instance :obj:`"user_name/model"`, which allows you to push to an organization you are a member of with
<add> :obj:`"organization_name/model"`.
<add>
<add> Will default to to the name of :obj:`output_dir`.
<ide> hub_token (:obj:`str`, `optional`):
<ide> The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
<ide> :obj:`huggingface-cli login`.
<ide> def __init__(
<ide> self.save_steps = save_steps
<ide> output_dir = Path(output_dir)
<ide> if hub_model_id is None:
<del> repo_name = get_full_repo_name(output_dir.absolute().name, token=hub_token)
<del> else:
<del> repo_name = hub_model_id
<add> hub_model_id = output_dir.absolute().name
<add> if "/" not in hub_model_id:
<add> hub_model_id = get_full_repo_name(hub_model_id, token=hub_token)
<ide> self.output_dir = output_dir
<del> self.repo = Repository(str(output_dir), clone_from=repo_name)
<add> self.repo = Repository(str(output_dir), clone_from=hub_model_id)
<ide> self.tokenizer = tokenizer
<ide> self.last_job = None
<ide>
<ide><path>src/transformers/trainer.py
<ide> def init_git_repo(self):
<ide> return
<ide> use_auth_token = True if self.args.hub_token is None else self.args.hub_token
<ide> if self.args.hub_model_id is None:
<del> repo_name = get_full_repo_name(Path(self.args.output_dir).name, token=self.args.hub_token)
<add> repo_name = Path(self.args.output_dir).absolute().name
<ide> else:
<ide> repo_name = self.args.hub_model_id
<add> if "/" not in repo_name:
<add> repo_name = get_full_repo_name(repo_name, token=self.args.hub_token)
<ide>
<ide> try:
<ide> self.repo = Repository(
<ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> the `example scripts <https://github.com/huggingface/transformers/tree/master/examples>`__ for more
<ide> details.
<ide> hub_model_id (:obj:`str`, `optional`):
<del> The name of the repository to keep in sync with the local `output_dir`. Should be the whole repository
<del> name, for instance :obj:`"user_name/model"`, which allows you to push to an organization you are a member
<del> of with :obj:`"organization_name/model"`.
<add> The name of the repository to keep in sync with the local `output_dir`. It can be a simple model ID in
<add> which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
<add> for instance :obj:`"user_name/model"`, which allows you to push to an organization you are a member of with
<add> :obj:`"organization_name/model"`. Will default to :obj:`user_name/output_dir_name` with `output_dir_name`
<add> being the name of :obj:`output_dir`.
<ide>
<del> Will default to :obj:`user_name/output_dir_name` with `output_dir_name` being the name of
<del> :obj:`output_dir`.
<add> Will default to to the name of :obj:`output_dir`.
<ide> hub_strategy (:obj:`str` or :class:`~transformers.trainer_utils.HubStrategy`, `optional`, defaults to :obj:`"every_save"`):
<ide> Defines the scope of what is pushed to the Hub and when. Possible values are:
<ide> | 3 |
Javascript | Javascript | add end instructions | 0bb563f07310719ec599d01d85b87408b17ac51a | <ide><path>lib/wasm/WebAssemblyGenerator.js
<ide> const rewriteImportedGlobals = state => bin => {
<ide>
<ide> globalType.mutability = "var";
<ide>
<del> const init = createDefaultInitForGlobal(globalType);
<add> const init = [
<add> createDefaultInitForGlobal(globalType),
<add> t.instruction("end")
<add> ];
<ide>
<del> newGlobals.push(t.global(globalType, [init]));
<add> newGlobals.push(t.global(globalType, init));
<ide>
<ide> path.remove();
<ide> }
<ide> const rewriteImportedGlobals = state => bin => {
<ide>
<ide> const initialGlobalidx = init.args[0];
<ide>
<del> node.init = [createDefaultInitForGlobal(node.globalType)];
<add> node.init = [
<add> createDefaultInitForGlobal(node.globalType),
<add> t.instruction("end")
<add> ];
<ide>
<ide> additionalInitCode.push(
<ide> /**
<ide> const addInitFunction = ({
<ide> funcBody.push(instr);
<ide> }
<ide>
<add> funcBody.push(t.instruction("end"));
<add>
<ide> const funcResults = [];
<ide>
<ide> // Code section | 1 |
PHP | PHP | use is_dir instead of file_exists | 5fc99089db0ebe5b3f2983e8f24a52e6b01140c9 | <ide><path>src/Illuminate/Database/Eloquent/Factory.php
<ide> public static function construct($pathToFactories = null)
<ide>
<ide> $factory = new static;
<ide>
<del> if (file_exists($pathToFactories)) {
<add> if (is_dir($pathToFactories)) {
<ide> foreach (Finder::create()->files()->in($pathToFactories) as $file) {
<ide> require $file->getRealPath();
<ide> } | 1 |
PHP | PHP | output the command list when no command is given | 3f08be54fb23941c2bafcaadda6e623eb3905e35 | <ide><path>src/Console/CommandRunner.php
<ide> public function run(array $argv, ConsoleIo $io = null)
<ide> */
<ide> protected function getShell(ConsoleIo $io, CommandCollection $commands, $name)
<ide> {
<add> if (!$name) {
<add> $io->err('<error>No command provided. Choose one of the available commands.</error>', 2);
<add> $name = 'help';
<add> }
<ide> if (isset($this->aliases[$name])) {
<ide> $name = $this->aliases[$name];
<ide> }
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunHelpShortOption()
<ide> $this->assertContains('Available Commands', $messages);
<ide> }
<ide>
<add> /**
<add> * Test that no command outputs the command list
<add> *
<add> * @return void
<add> */
<add> public function testRunNoCommand()
<add> {
<add> $app = $this->getMockBuilder(BaseApplication::class)
<add> ->setMethods(['middleware', 'bootstrap'])
<add> ->setConstructorArgs([$this->config])
<add> ->getMock();
<add>
<add> $output = new ConsoleOutput();
<add> $runner = new CommandRunner($app);
<add> $result = $runner->run(['cake'], $this->getMockIo($output));
<add>
<add> $this->assertSame(0, $result, 'help output is success.');
<add> $messages = implode("\n", $output->messages());
<add> $this->assertContains('No command provided. Choose one of the available commands', $messages);
<add> $this->assertContains('- i18n', $messages);
<add> $this->assertContains('Available Commands', $messages);
<add> }
<add>
<ide> /**
<ide> * Test using `cake --verson` invokes the version command
<ide> * | 2 |
Python | Python | reuse ex_deploy_node when instatiating a new node | 8892bbcbda533ffdea2d7b5f3658bf9b825bd58a | <ide><path>libcloud/compute/drivers/vcloud.py
<ide> def create_node(self, **kwargs):
<ide>
<ide> # Power on the VM.
<ide> if ex_deploy:
<add> res = self.connection.request(get_url_path(vapp_href))
<add> node = self._to_node(res.object)
<ide> # Retry 3 times: when instantiating large number of VMs at the same
<ide> # time some may fail on resource allocation
<ide> retry = 3
<ide> while True:
<ide> try:
<del> res = self.connection.request(
<del> '%s/power/action/powerOn' % get_url_path(vapp_href),
<del> method='POST')
<del> self._wait_for_task_completion(res.object.get('href'))
<add> self.ex_deploy_node(node, ex_force_customization)
<ide> break
<ide> except Exception:
<ide> if retry <= 0: | 1 |
Python | Python | add chroot detection | 8b63d555e3e1d5b29d4bff81679deb36980f664c | <ide><path>setup.py
<ide>
<ide> from setuptools import setup
<ide>
<add>is_chroot = os.stat('/').st_ino != 2
<add>
<ide>
<ide> def get_data_files():
<ide> data_files = [
<ide> def get_data_files():
<ide> ('share/man/man1', ['man/glances.1'])
<ide> ]
<ide>
<del> if os.name == 'posix' and os.getuid() == 0: # Unix-like + root privileges
<add> if hasattr(sys, 'real_prefix'): # virtualenv
<add> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<add> elif os.name == 'posix' and (os.getuid() == 0 or is_chroot):
<add> # Unix-like + root privileges/chroot environment
<ide> if 'bsd' in sys.platform:
<ide> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<ide> elif 'linux' in sys.platform:
<ide> conf_path = os.path.join('/etc', 'glances')
<ide> elif 'darwin' in sys.platform:
<ide> conf_path = os.path.join('/usr/local', 'etc', 'glances')
<del> elif hasattr(sys, 'real_prefix'): # virtualenv
<del> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<ide> elif 'win32' in sys.platform: # windows
<ide> conf_path = os.path.join(os.environ.get('APPDATA'), 'glances')
<ide> else: # Unix-like + per-user install | 1 |
Python | Python | update the doc string for t5withlmheadmodel | 62f58046088061314545411135a43a0ee8ddf6ba | <ide><path>src/transformers/modeling_t5.py
<ide> class T5WithLMHeadModel(T5PreTrainedModel):
<ide> r"""
<ide> **lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Labels for computing the masked language modeling loss.
<del> Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
<del> Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels
<del> in ``[0, ..., config.vocab_size]``
<add> Indices should either be in ``[0, ..., config.vocab_size]`` or -100 (see ``input_ids`` docstring).
<add> Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
<add> in ``[0, ..., config.vocab_size]``.
<ide>
<ide> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
<ide> **loss**: (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: | 1 |
Ruby | Ruby | decorate process._fork if available | fe4ead7fc62900ca4bceebc73c57e9be8f1156e4 | <ide><path>activesupport/lib/active_support/fork_tracker.rb
<ide>
<ide> module ActiveSupport
<ide> module ForkTracker # :nodoc:
<add> module ModernCoreExt
<add> def _fork
<add> pid = super
<add> if pid == 0
<add> ForkTracker.check!
<add> end
<add> pid
<add> end
<add> end
<add>
<ide> module CoreExt
<ide> def fork(...)
<ide> if block_given?
<ide> module CoreExtPrivate
<ide>
<ide> class << self
<ide> def check!
<del> if @pid != Process.pid
<add> new_pid = Process.pid
<add> if @pid != new_pid
<ide> @callbacks.each(&:call)
<del> @pid = Process.pid
<add> @pid = new_pid
<ide> end
<ide> end
<ide>
<ide> def hook!
<del> if Process.respond_to?(:fork)
<add> if Process.respond_to?(:_fork) # Ruby 3.1+
<add> ::Process.singleton_class.prepend(ModernCoreExt)
<add> elsif Process.respond_to?(:fork)
<ide> ::Object.prepend(CoreExtPrivate) if RUBY_VERSION < "3.0"
<ide> ::Kernel.prepend(CoreExtPrivate)
<ide> ::Kernel.singleton_class.prepend(CoreExt) | 1 |
Javascript | Javascript | remove extraneous file | 850b3f775bd08a52b1d9a1febcd567c841c02e2b | <ide><path>gulpfile.js
<ide> gulp.task('lint', function() {
<ide> gulp.task('test', function () {
<ide> return gulp.src('./')
<ide> .pipe(jest({
<del> scriptPreprocessor: './resources/jest-preprocessor.js',
<add> scriptPreprocessor: './resources/jestPreprocessor.js',
<ide> unmockedModulePathPatterns: ['./node_modules/react'],
<ide> }))
<ide> .on('error', handleError);
<ide><path>resources/jest-preprocessor.js
<del>var reactTools = require('react-tools');
<del>
<del>module.exports = {
<del> process: function(src, path) {
<del> if (path.match(/\.js$/)) {
<del> return reactTools.transform(src, { harmony: true });
<del> }
<del> return src;
<del> }
<del>}; | 2 |
Javascript | Javascript | remove ajax requirement for simple xml tests | 6bc08c2b2f04629114ae7ca79c3c2c54320e4908 | <ide><path>test/data/testinit.js
<add>/*jshint multistr:true*/
<add>
<ide> var jQuery = this.jQuery || "jQuery", // For testing .noConflict()
<ide> $ = this.$ || "$",
<ide> originaljQuery = jQuery,
<ide> function t(a,b,c) {
<ide> deepEqual(f, q.apply(q,c), a + " (" + b + ")");
<ide> }
<ide>
<add>
<add>var createDashboardXML = function() {
<add> var string = '<?xml version="1.0" encoding="UTF-8"?> \
<add> <dashboard> \
<add> <locations class="foo"> \
<add> <location for="bar" checked="different"> \
<add> <infowindowtab> \
<add> <tab title="Location"><![CDATA[blabla]]></tab> \
<add> <tab title="Users"><![CDATA[blublu]]></tab> \
<add> </infowindowtab> \
<add> </location> \
<add> </locations> \
<add> </dashboard>';
<add>
<add> return jQuery.parseXML(string);
<add>};
<add>
<add>var createWithFriesXML = function() {
<add> var string = '<?xml version="1.0" encoding="UTF-8"?> \
<add> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" \
<add> xmlns:xsd="http://www.w3.org/2001/XMLSchema" \
<add> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> \
<add> <soap:Body> \
<add> <jsconf xmlns="http://www.example.com/ns1"> \
<add> <response xmlns:ab="http://www.example.com/ns2"> \
<add> <meta> \
<add> <component id="seite1" class="component"> \
<add> <properties xmlns:cd="http://www.example.com/ns3"> \
<add> <property name="prop1"> \
<add> <thing /> \
<add> <value>1</value> \
<add> </property> \
<add> <property name="prop2"> \
<add> <thing att="something" /> \
<add> </property> \
<add> <foo_bar>foo</foo_bar> \
<add> </properties> \
<add> </component> \
<add> </meta> \
<add> </response> \
<add> </jsconf> \
<add> </soap:Body> \
<add> </soap:Envelope>';
<add>
<add> return jQuery.parseXML(string);
<add>};
<add>
<ide> var fireNative;
<ide> if ( document.createEvent ) {
<ide> fireNative = function( node, type ) {
<ide> function url(value) {
<ide> window.start = function() {
<ide> oldStart();
<ide> };
<del>})();
<ide>\ No newline at end of file
<add>})();
<ide><path>test/unit/attributes.js
<ide> test("attr(String)", function() {
<ide> equal( $form.prop("enctype"), "multipart/form-data", "Set the enctype of a form (encoding in IE6/7 #6743)" );
<ide> });
<ide>
<del>if ( !isLocal ) {
<del> test("attr(String) in XML Files", function() {
<del> expect(3);
<del> stop();
<del> jQuery.get("data/dashboard.xml", function( xml ) {
<del> equal( jQuery( "locations", xml ).attr("class"), "foo", "Check class attribute in XML document" );
<del> equal( jQuery( "location", xml ).attr("for"), "bar", "Check for attribute in XML document" );
<del> equal( jQuery( "location", xml ).attr("checked"), "different", "Check that hooks are not attached in XML document" );
<del> start();
<del> });
<del> });
<del>}
<add>test("attr(String) in XML Files", function() {
<add> expect(3);
<add> var xml = createDashboardXML();
<add> equal( jQuery( "locations", xml ).attr("class"), "foo", "Check class attribute in XML document" );
<add> equal( jQuery( "location", xml ).attr("for"), "bar", "Check for attribute in XML document" );
<add> equal( jQuery( "location", xml ).attr("checked"), "different", "Check that hooks are not attached in XML document" );
<add>});
<ide>
<ide> test("attr(String, Function)", function() {
<ide> expect(2);
<ide><path>test/unit/core.js
<ide> test("XSS via location.hash", function() {
<ide> jQuery( '#<img id="check9521" src="no-such-.gif" onerror="jQuery._check9521(false)">' ).appendTo("#qunit-fixture");
<ide> } catch (err) {
<ide> jQuery._check9521(true);
<del> };
<add> }
<ide> });
<ide>
<del>if ( !isLocal ) {
<ide> test("isXMLDoc - XML", function() {
<ide> expect(3);
<del> stop();
<del> jQuery.get("data/dashboard.xml", function(xml) {
<del> ok( jQuery.isXMLDoc( xml ), "XML document" );
<del> ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
<del> ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
<del> start();
<del> });
<add> var xml = createXMLDocument();
<add> xml.documentElement.appendChild( xml.createElement( "tab" ) );
<add> ok( jQuery.isXMLDoc( xml ), "XML document" );
<add> ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
<add> ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
<ide> });
<del>}
<ide>
<ide> test("isWindow", function() {
<ide> expect( 14 );
<ide> test("jQuery('html', context)", function() {
<ide> equal($span.length, 1, "Verify a span created with a div context works, #1763");
<ide> });
<ide>
<del>if ( !isLocal ) {
<ide> test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
<ide> expect(2);
<del> stop();
<del> jQuery.get("data/dashboard.xml", function(xml) {
<del> // tests for #1419 where IE was a problem
<del> var tab = jQuery("tab", xml).eq(0);
<del> equal( tab.text(), "blabla", "Verify initial text correct" );
<del> tab.text("newtext");
<del> equal( tab.text(), "newtext", "Verify new text correct" );
<del> start();
<del> });
<add>
<add> var xml = createDashboardXML();
<add> // tests for #1419 where IE was a problem
<add> var tab = jQuery("tab", xml).eq(0);
<add> equal( tab.text(), "blabla", "Verify initial text correct" );
<add> tab.text("newtext");
<add> equal( tab.text(), "newtext", "Verify new text correct" );
<ide> });
<del>}
<ide>
<ide> test("end()", function() {
<ide> expect(3);
<ide><path>test/unit/manipulation.js
<ide> test("clone(multiple selected options) (Bug #8129)", function() {
<ide>
<ide> });
<ide>
<del>if (!isLocal) {
<ide> test("clone() on XML nodes", function() {
<ide> expect(2);
<del> stop();
<del> jQuery.get("data/dashboard.xml", function (xml) {
<del> var root = jQuery(xml.documentElement).clone();
<del> var origTab = jQuery("tab", xml).eq(0);
<del> var cloneTab = jQuery("tab", root).eq(0);
<del> origTab.text("origval");
<del> cloneTab.text("cloneval");
<del> equal(origTab.text(), "origval", "Check original XML node was correctly set");
<del> equal(cloneTab.text(), "cloneval", "Check cloned XML node was correctly set");
<del> start();
<del> });
<add> var xml = createDashboardXML();
<add> var root = jQuery(xml.documentElement).clone();
<add> var origTab = jQuery("tab", xml).eq(0);
<add> var cloneTab = jQuery("tab", root).eq(0);
<add> origTab.text("origval");
<add> cloneTab.text("cloneval");
<add> equal(origTab.text(), "origval", "Check original XML node was correctly set");
<add> equal(cloneTab.text(), "cloneval", "Check cloned XML node was correctly set");
<ide> });
<del>}
<ide>
<ide> test("clone() on local XML nodes with html5 nodename", function() {
<ide> expect(2); | 4 |
Text | Text | use sentence-case for governance.md headers | 7c02446aa777d3994b6a950c1dcf1bf2b6e97905 | <ide><path>GOVERNANCE.md
<ide>
<ide> * [Triagers](#triagers)
<ide> * [Collaborators](#collaborators)
<del> * [Collaborator Activities](#collaborator-activities)
<del>* [Technical Steering Committee](#technical-steering-committee)
<del> * [TSC Meetings](#tsc-meetings)
<del>* [Collaborator Nominations](#collaborator-nominations)
<add> * [Collaborator activities](#collaborator-activities)
<add>* [Technical steering committee](#technical-steering-committee)
<add> * [TSC meetings](#tsc-meetings)
<add>* [Collaborator nominations](#collaborator-nominations)
<ide> * [Onboarding](#onboarding)
<del>* [Consensus Seeking Process](#consensus-seeking-process)
<add>* [Consensus seeking process](#consensus-seeking-process)
<ide>
<ide> <!-- /TOC -->
<ide>
<ide> See:
<ide> * [List of Collaborators](./README.md#current-project-team-members)
<ide> * [A guide for Collaborators](./doc/guides/collaborator-guide.md)
<ide>
<del>### Collaborator Activities
<add>### Collaborator activities
<ide>
<ide> * Helping users and novice contributors
<ide> * Contributing code and documentation changes that improve the project
<ide> The current list of TSC members is in
<ide> The [TSC Charter][] governs the operations of the TSC. All changes to the
<ide> Charter need approval by the OpenJS Foundation Board of Directors.
<ide>
<del>### TSC Meetings
<add>### TSC meetings
<ide>
<ide> The TSC meets in a voice conference call. Each year, the TSC elects a chair to
<ide> run the meetings. The TSC streams its meetings for public viewing on YouTube or
<ide> the issue tracker is:
<ide> and no TSC opposition.
<ide> * If there is an extended impasse, a TSC member may make a motion for a vote.
<ide>
<del>## Collaborator Nominations
<add>## Collaborator nominations
<ide>
<ide> Existing Collaborators can nominate someone to become a Collaborator. Nominees
<ide> should have significant and valuable contributions across the Node.js
<ide> After the nomination passes, a TSC member onboards the new Collaborator. See
<ide> [the onboarding guide](./onboarding.md) for details of the onboarding
<ide> process.
<ide>
<del>## Consensus Seeking Process
<add>## Consensus seeking process
<ide>
<ide> The TSC follows a [Consensus Seeking][] decision-making model per the
<ide> [TSC Charter][]. | 1 |
Javascript | Javascript | allow deps to be empty in loader | 3bb454762ce7d62f03bb6f778f9a3831829b72fa | <ide><path>packages/loader/lib/main.js
<ide> var mainContext = this;
<ide> var seen = {};
<ide>
<ide> define = function(name, deps, callback) {
<del> registry[name] = { deps: deps, callback: callback };
<add> var value = { };
<add>
<add> if (!callback) {
<add> value.deps = [];
<add> value.callback = deps;
<add> } else {
<add> value.deps = deps;
<add> value.callback = callback;
<add> }
<add>
<add> registry[name] = value;
<ide> };
<ide>
<ide> requirejs = require = requireModule = function(name) { | 1 |
Text | Text | fix punctuation error in reducers.md | 89571cd6049252fff57fb013e92bf4b853e23803 | <ide><path>docs/basics/Reducers.md
<ide> In Redux, all the application state is stored as a single object. It's a good id
<ide>
<ide> For our todo app, we want to store two different things:
<ide>
<del>* The currently selected visibility filter;
<add>* The currently selected visibility filter.
<ide> * The actual list of todos.
<ide>
<ide> You'll often find that you need to store some data, as well as some UI state, in the state tree. This is fine, but try to keep the data separate from the UI state. | 1 |
Python | Python | expose flag to log model flops and parameters | 24ae1f51df065e38e89c3bda5e4a53448f40b426 | <ide><path>official/vision/serving/export_saved_model.py
<ide>
<ide> FLAGS = flags.FLAGS
<ide>
<del>
<del>flags.DEFINE_string(
<del> 'experiment', None, 'experiment type, e.g. retinanet_resnetfpn_coco')
<add>flags.DEFINE_string('experiment', None,
<add> 'experiment type, e.g. retinanet_resnetfpn_coco')
<ide> flags.DEFINE_string('export_dir', None, 'The export directory.')
<ide> flags.DEFINE_string('checkpoint_path', None, 'Checkpoint path.')
<ide> flags.DEFINE_multi_string(
<ide> 'params_override', '',
<ide> 'The JSON/YAML file or string which specifies the parameter to be overriden'
<ide> ' on top of `config_file` template.')
<del>flags.DEFINE_integer(
<del> 'batch_size', None, 'The batch size.')
<add>flags.DEFINE_integer('batch_size', None, 'The batch size.')
<ide> flags.DEFINE_string(
<ide> 'input_type', 'image_tensor',
<ide> 'One of `image_tensor`, `image_bytes`, `tf_example` and `tflite`.')
<ide> 'The subdirectory for checkpoints.')
<ide> flags.DEFINE_string('export_saved_model_subdir', 'saved_model',
<ide> 'The subdirectory for saved model.')
<add>flags.DEFINE_bool('log_model_flops_and_params', False,
<add> 'If true, logs model flops and parameters.')
<ide>
<ide>
<ide> def main(_):
<ide> def main(_):
<ide> checkpoint_path=FLAGS.checkpoint_path,
<ide> export_dir=FLAGS.export_dir,
<ide> export_checkpoint_subdir=FLAGS.export_checkpoint_subdir,
<del> export_saved_model_subdir=FLAGS.export_saved_model_subdir)
<add> export_saved_model_subdir=FLAGS.export_saved_model_subdir,
<add> log_model_flops_and_params=FLAGS.log_model_flops_and_params)
<ide>
<ide>
<ide> if __name__ == '__main__': | 1 |
PHP | PHP | apply fixes from styleci | 8ca157bcc1c426db45a3088f971f6d962ee5d09b | <ide><path>src/Illuminate/Container/Container.php
<ide> public function get($id)
<ide> protected function resolve($abstract, $parameters = [], $raiseEvents = true)
<ide> {
<ide> $abstract = $this->getAlias($abstract);
<del>
<add>
<ide> $concrete = $this->getContextualConcrete($abstract);
<ide>
<ide> $needsContextualBuild = ! empty($parameters) || ! is_null($concrete); | 1 |
Javascript | Javascript | use getselection in ie where available | 6b46e80bb9c6e60eb743a7897ab8cf27d60d3faa | <ide><path>src/browser/ui/ReactDOMSelection.js
<ide> function setModernOffsets(node, offsets) {
<ide> }
<ide> }
<ide>
<del>var useIEOffsets = ExecutionEnvironment.canUseDOM && document.selection;
<add>var useIEOffsets = (
<add> ExecutionEnvironment.canUseDOM &&
<add> 'selection' in document &&
<add> !('getSelection' in window)
<add>);
<ide>
<ide> var ReactDOMSelection = {
<ide> /** | 1 |
Ruby | Ruby | raise argumenterror for argument errors | acc1c35f35fb86957d56e19988fd4aeabae57b9e | <ide><path>Library/Homebrew/software_spec.rb
<ide> def option_defined?(name)
<ide> def option name, description=nil
<ide> name = 'c++11' if name == :cxx11
<ide> name = name.to_s if Symbol === name
<del> raise "Option name is required." if name.empty?
<del> raise "Options should not start with dashes." if name[0, 1] == "-"
<add> raise ArgumentError, "option name is required" if name.empty?
<add> raise ArgumentError, "options should not start with dashes" if name.start_with?("-")
<ide> build.add(name, description)
<ide> end
<ide>
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> def test_option
<ide> end
<ide>
<ide> def test_option_raises_when_begins_with_dashes
<del> assert_raises(RuntimeError) { @spec.option('--foo') }
<add> assert_raises(ArgumentError) { @spec.option("--foo") }
<ide> end
<ide>
<ide> def test_option_raises_when_name_empty
<del> assert_raises(RuntimeError) { @spec.option('') }
<add> assert_raises(ArgumentError) { @spec.option("") }
<ide> end
<ide>
<ide> def test_option_accepts_symbols | 2 |
Go | Go | fix the comment for daemon/logger.copier | 518709a87e04f55babc5162861aa4ba9a423f0c8 | <ide><path>daemon/logger/copier.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> )
<ide>
<del>// Copier can copy logs from specified sources to Logger and attach
<del>// ContainerID and Timestamp.
<add>// Copier can copy logs from specified sources to Logger and attach Timestamp.
<ide> // Writes are concurrent, so you need implement some sync in your logger
<ide> type Copier struct {
<ide> // srcs is map of name -> reader pairs, for example "stdout", "stderr" | 1 |
Python | Python | fix whisper for `pipeline` | b722a6be72517054318d382662eed5e300c4f9c3 | <ide><path>src/transformers/models/whisper/feature_extraction_whisper.py
<ide> def __call__(
<ide> return_attention_mask: Optional[bool] = None,
<ide> padding: Optional[str] = "max_length",
<ide> max_length: Optional[int] = None,
<add> sampling_rate: Optional[int] = None,
<ide> **kwargs
<ide> ) -> BatchFeature:
<ide> """
<ide> def __call__(
<ide> The value that is used to fill the padding values / vectors.
<ide> """
<ide>
<add> if sampling_rate is not None:
<add> if sampling_rate != self.sampling_rate:
<add> raise ValueError(
<add> f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
<add> f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
<add> f" {self.sampling_rate} and not {sampling_rate}."
<add> )
<add> else:
<add> logger.warning(
<add> "It is strongly recommended to pass the `sampling_rate` argument to this function. "
<add> "Failing to do so can result in silent errors that might be hard to debug."
<add> )
<add>
<ide> is_batched = bool(
<ide> isinstance(raw_speech, (list, tuple))
<ide> and (isinstance(raw_speech[0], np.ndarray) or isinstance(raw_speech[0], (tuple, list)))
<ide><path>src/transformers/models/whisper/modeling_whisper.py
<ide> Seq2SeqModelOutput,
<ide> )
<ide> from ...modeling_utils import PreTrainedModel
<del>from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
<add>from ...utils import (
<add> add_code_sample_docstrings,
<add> add_start_docstrings,
<add> add_start_docstrings_to_model_forward,
<add> logging,
<add> replace_return_docstrings,
<add>)
<ide> from .configuration_whisper import WhisperConfig
<ide>
<ide>
<ide> logger = logging.get_logger(__name__)
<ide>
<ide> _CONFIG_FOR_DOC = "WhisperConfig"
<add>_CHECKPOINT_FOR_DOC = "openai/whisper-tiny"
<add>_PROCESSOR_FOR_DOC = "openai/whisper-tiny"
<add>_EXPECTED_OUTPUT_SHAPE = [1, 2, 512]
<ide>
<ide>
<ide> WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST = [
<ide> def get_decoder(self):
<ide> return self.decoder
<ide>
<ide> @add_start_docstrings_to_model_forward(WHISPER_INPUTS_DOCSTRING)
<del> @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
<add> @add_code_sample_docstrings(
<add> processor_class=_PROCESSOR_FOR_DOC,
<add> checkpoint=_CHECKPOINT_FOR_DOC,
<add> output_type=Seq2SeqModelOutput,
<add> config_class=_CONFIG_FOR_DOC,
<add> expected_output=_EXPECTED_OUTPUT_SHAPE,
<add> modality="audio",
<add> )
<ide> def forward(
<ide> self,
<ide> input_features=None,
<ide> def forward(
<ide> output_hidden_states=None,
<ide> return_dict=None,
<ide> ):
<del> r"""
<del> Returns:
<del>
<del> Example:
<del>
<del> ```python
<del> >>> import torch
<del> >>> from transformers import WhisperModel, WhisperFeatureExtractor
<del> >>> from datasets import load_dataset
<del>
<del> >>> model = WhisperModel.from_pretrained("openai/whisper-base")
<del> >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
<del> >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
<del> >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
<del> >>> input_features = inputs.input_features
<del> >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
<del> >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
<del> >>> list(last_hidden_state.shape)
<del> [1, 2, 512]
<del> ```"""
<ide>
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> output_hidden_states = (
<ide><path>tests/pipelines/test_pipelines_automatic_speech_recognition.py
<ide> AutoTokenizer,
<ide> Speech2TextForConditionalGeneration,
<ide> Wav2Vec2ForCTC,
<add> WhisperForConditionalGeneration,
<add> WhisperProcessor,
<ide> )
<ide> from transformers.pipelines import AutomaticSpeechRecognitionPipeline, pipeline
<ide> from transformers.pipelines.audio_utils import chunk_bytes_iter
<ide> def test_simple_s2t(self):
<ide> output = asr(data)
<ide> self.assertEqual(output, {"text": "Un uomo disse all'universo: \"Signore, io esisto."})
<ide>
<add> @slow
<add> @require_torch
<add> @require_torchaudio
<add> def test_simple_whisper_asr(self):
<add> speech_recognizer = pipeline(
<add> task="automatic-speech-recognition",
<add> model="openai/whisper-tiny.en",
<add> framework="pt",
<add> )
<add> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
<add> filename = ds[0]["file"]
<add> output = speech_recognizer(filename)
<add> self.assertEqual(output, {"text": " Mr. Quilter is the apostle of the middle classes, and we are glad to"})
<add>
<add> @slow
<add> @require_torch
<add> @require_torchaudio
<add> def test_simple_whisper_translation(self):
<add> speech_recognizer = pipeline(
<add> task="automatic-speech-recognition",
<add> model="openai/whisper-large",
<add> framework="pt",
<add> )
<add> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id")
<add> filename = ds[40]["file"]
<add> output = speech_recognizer(filename)
<add> self.assertEqual(output, {"text": " A man said to the universe, Sir, I exist."})
<add>
<add> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large")
<add> tokenizer = AutoTokenizer.from_pretrained("openai/whisper-large")
<add> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-large")
<add>
<add> speech_recognizer_2 = AutomaticSpeechRecognitionPipeline(
<add> model=model, tokenizer=tokenizer, feature_extractor=feature_extractor
<add> )
<add> output_2 = speech_recognizer_2(filename)
<add> self.assertEqual(output, output_2)
<add>
<add> processor = WhisperProcessor(feature_extractor, tokenizer)
<add> model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(task="transcribe", language="it")
<add> speech_translator = AutomaticSpeechRecognitionPipeline(
<add> model=model, tokenizer=tokenizer, feature_extractor=feature_extractor
<add> )
<add> output_3 = speech_translator(filename)
<add> self.assertEqual(output_3, {"text": " Un uomo ha detto allo universo, Sir, esiste."})
<add>
<ide> @slow
<ide> @require_torch
<ide> @require_torchaudio
<ide><path>tests/pipelines/test_pipelines_common.py
<ide> def __repr__(self):
<ide> class PipelineTestCaseMeta(type):
<ide> def __new__(mcs, name, bases, dct):
<ide> def gen_test(ModelClass, checkpoint, tiny_config, tokenizer_class, feature_extractor_class):
<del> @skipIf(tiny_config is None, "TinyConfig does not exist")
<del> @skipIf(checkpoint is None, "checkpoint does not exist")
<add> @skipIf(
<add> tiny_config is None,
<add> "TinyConfig does not exist, make sure that you defined a `_CONFIG_FOR_DOC` variable in the modeling"
<add> " file",
<add> )
<add> @skipIf(
<add> checkpoint is None,
<add> "checkpoint does not exist, make sure that you defined a `_CHECKPOINT_FOR_DOC` variable in the"
<add> " modeling file",
<add> )
<ide> def test(self):
<ide> if ModelClass.__name__.endswith("ForCausalLM"):
<ide> tiny_config.is_encoder_decoder = False | 4 |
Ruby | Ruby | fix uninitialized ivar warnings | 6033e8aeb003a37c0ebce8f6edb4349d94c8e712 | <ide><path>actionpack/lib/abstract_controller/base.rb
<ide> def abstract!
<ide> @abstract = true
<ide> end
<ide>
<add> def inherited(klass) # :nodoc:
<add> # define the abstract ivar on subclasses so that we don't get
<add> # uninitialized ivar warnings
<add> unless klass.instance_variable_defined?(:@abstract)
<add> klass.instance_variable_set(:@abstract, false)
<add> end
<add> super
<add> end
<add>
<ide> # A list of all internal methods for a controller. This finds the first
<ide> # abstract superclass of a controller, and gets a list of all public
<ide> # instance methods on that abstract class. Public instance methods of
<ide> def abstract!
<ide> # (ActionController::Metal and ActionController::Base are defined as abstract)
<ide> def internal_methods
<ide> controller = self
<add>
<ide> controller = controller.superclass until controller.abstract?
<ide> controller.public_instance_methods(true)
<ide> end | 1 |
PHP | PHP | add path searching for composer | d16af09bf7c75d2dc5741760637eb66812ce7991 | <ide><path>src/Console/Command/Task/ProjectTask.php
<ide> public function main() {
<ide> if (!preg_match('/^\w[\w\d_]+$/', $namespace)) {
<ide> $this->err(__d('cake_console', 'Project Name/Namespace needs to start with a letter and can only contain letters, digits and underscore'));
<ide> $this->args = [];
<del> return $this->execute();
<add> return $this->main();
<ide> }
<ide>
<ide> if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) {
<ide> public function main() {
<ide>
<ide> if ($this->bake($project)) {
<ide> $this->out(__d('cake_console', '<success>Project baked successfully!</success>'));
<del> return $path;
<add> return $project;
<ide> }
<ide> }
<ide>
<add>/**
<add> * Uses either the CLI option or looks in $PATH and cwd for composer.
<add> *
<add> * @return string|false Either the path to composer or false if it cannot be found.
<add> */
<add> public function findComposer() {
<add> if (!empty($this->params['composer'])) {
<add> $path = $this->params['composer'];
<add> if (file_exists($path)) {
<add> return $path;
<add> }
<add> return false;
<add> }
<add> $composer = false;
<add> if (!empty($_SERVER['PATH'])) {
<add> $path = explode(PATH_SEPARATOR, $_SERVER['PATH']);
<add> $composer = $this->_searchPath($path);
<add> }
<add> return $composer;
<add> }
<add>
<add>/**
<add> * Search the $PATH for composer.
<add> *
<add> * @param array $path The paths to search.
<add> * @return string|boolean
<add> */
<add> protected function _searchPath($path) {
<add> $composer = ['composer.phar', 'composer'];
<add> foreach ($path as $dir) {
<add> foreach ($composer as $cmd) {
<add> if (file_exists($dir . DS . $cmd)) {
<add> return $dir . DS . $cmd;
<add> }
<add> }
<add> }
<add> return false;
<add> }
<add>
<ide> /**
<ide> * Uses composer to generate a new package using the cakephp/app project.
<ide> *
<ide> * @param string $path Project path
<ide> * @return mixed
<ide> */
<ide> public function bake($path) {
<del> $composer = $this->params['composer'];
<del> if (!file_exists($composer)) {
<del> $this->error(__d('cake_console', 'Cannot bake project. Could not find composer at "%s".', $composer));
<add> $composer = $this->findComposer();
<add> if (!$composer) {
<add> $this->error(__d('cake_console', 'Cannot bake project. Could not find composer. Add composer to your PATH, or use the -composer option.'));
<ide> return false;
<ide> }
<ide> $this->out(__d('cake_console', '<info>Downloading a new cakephp app from packagist.org</info>')); | 1 |
Text | Text | fix variable name | 88cbcd3cb00137a6bd141dbf7402cbaf3998b5a7 | <ide><path>docs/advanced/Middleware.md
<ide> let createStoreWithMiddleware = applyMiddleware(
<ide> vanillaPromise,
<ide> readyStatePromise,
<ide> logger,
<del> errorHandler
<add> crashReporter
<ide> )(createStore);
<ide> let todoApp = combineReducers(reducers);
<ide> let store = createStoreWithMiddleware(todoApp); | 1 |
Ruby | Ruby | move the fixopt method into the build class | 8a971f72686298ba44d427ba65823a6e70b2a4d8 | <ide><path>Library/Homebrew/build.rb
<ide> def install
<ide> end
<ide> end
<ide> end
<del>end
<ide>
<del>def fixopt f
<del> path = if f.linked_keg.directory? and f.linked_keg.symlink?
<del> f.linked_keg.resolved_path
<del> elsif f.prefix.directory?
<del> f.prefix
<del> elsif (kids = f.rack.children).size == 1 and kids.first.directory?
<del> kids.first
<del> else
<del> raise
<add> def fixopt f
<add> path = if f.linked_keg.directory? and f.linked_keg.symlink?
<add> f.linked_keg.resolved_path
<add> elsif f.prefix.directory?
<add> f.prefix
<add> elsif (kids = f.rack.children).size == 1 and kids.first.directory?
<add> kids.first
<add> else
<add> raise
<add> end
<add> Keg.new(path).optlink
<add> rescue StandardError
<add> raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f}. Sorry :("
<ide> end
<del> Keg.new(path).optlink
<del>rescue StandardError
<del> raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f}. Sorry :("
<ide> end | 1 |
Python | Python | rewrite recursion when parsing dag into iteration | b92f6198d1944b0ae5e0b6ebc928f7cd3bdf39b0 | <ide><path>airflow/models/abstractoperator.py
<ide> def get_flat_relative_ids(
<ide> if not dag:
<ide> return set()
<ide>
<del> if not found_descendants:
<add> if found_descendants is None:
<ide> found_descendants = set()
<del> relative_ids = self.get_direct_relative_ids(upstream)
<ide>
<del> for relative_id in relative_ids:
<del> if relative_id not in found_descendants:
<del> found_descendants.add(relative_id)
<del> relative_task = dag.task_dict[relative_id]
<del> relative_task.get_flat_relative_ids(upstream, found_descendants)
<add> task_ids_to_trace = self.get_direct_relative_ids(upstream)
<add> while task_ids_to_trace:
<add> task_ids_to_trace_next: Set[str] = set()
<add> for task_id in task_ids_to_trace:
<add> if task_id in found_descendants:
<add> continue
<add> task_ids_to_trace_next.update(dag.task_dict[task_id].get_direct_relative_ids(upstream))
<add> found_descendants.add(task_id)
<add> task_ids_to_trace = task_ids_to_trace_next
<ide>
<ide> return found_descendants
<ide> | 1 |
PHP | PHP | extract a label widget | b3d943e76df2daa9c841054e7906d578d4d5489b | <ide><path>src/View/Input/Label.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\View\Input;
<add>
<add>/**
<add> * Form 'widget' for creating labels.
<add> *
<add> * Generally this element is used by other widgets,
<add> * and FormHelper itself.
<add> */
<add>class Label {
<add>
<add>/**
<add> * Templates
<add> *
<add> * @var Cake\View\StringTemplate
<add> */
<add> protected $_templates;
<add>
<add>/**
<add> * Constructor.
<add> *
<add> * @param Cake\View\StringTemplate $templates
<add> */
<add> public function __construct($templates) {
<add> $this->_templates = $templates;
<add> }
<add>
<add>/**
<add> * Render a label widget.
<add> *
<add> * Accepts the following keys in $data:
<add> *
<add> * - `text` The text for the label.
<add> * - `input` The input that can be formatted into the label if the template allows it.
<add> * - `escape` Set to false to disable HTML escaping.
<add> *
<add> * All other attributes will be converted into HTML attributes.
<add> *
<add> * @param array $data
<add> * @return string
<add> */
<add> public function render($data) {
<add> $data += [
<add> 'text' => '',
<add> 'input' => '',
<add> 'escape' => true,
<add> ];
<add>
<add> return $this->_templates->format('label', [
<add> 'text' => $data['escape'] ? h($data['text']) : $data['text'],
<add> 'input' => $data['input'],
<add> 'attrs' => $this->_templates->formatAttributes($data, ['text', 'input']),
<add> ]);
<add> }
<add>
<add>}
<ide><path>tests/TestCase/View/Input/LabelTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\View\Input;
<add>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\View\Input\Label;
<add>use Cake\View\StringTemplate;
<add>
<add>/**
<add> * Label test case.
<add> */
<add>class LabelTest extends TestCase {
<add>
<add>/**
<add> * setup method.
<add> *
<add> * @return void
<add> */
<add> public function setUp() {
<add> parent::setUp();
<add> $templates = [
<add> 'label' => '<label{{attrs}}>{{text}}</label>',
<add> ];
<add> $this->templates = new StringTemplate($templates);
<add> }
<add>
<add>/**
<add> * test render
<add> *
<add> * @return void
<add> */
<add> public function testRender() {
<add> $label = new Label($this->templates);
<add> $data = [
<add> 'text' => 'My text',
<add> ];
<add> $result = $label->render($data);
<add> $expected = [
<add> 'label' => [],
<add> 'My text',
<add> '/label'
<add> ];
<add> $this->assertTags($result, $expected);
<add> }
<add>
<add>/**
<add> * test render escape
<add> *
<add> * @return void
<add> */
<add> public function testRenderEscape() {
<add> $label = new Label($this->templates);
<add> $data = [
<add> 'text' => 'My > text',
<add> 'for' => 'Some > value',
<add> 'escape' => false,
<add> ];
<add> $result = $label->render($data);
<add> $expected = [
<add> 'label' => ['for' => 'Some > value'],
<add> 'My > text',
<add> '/label'
<add> ];
<add> $this->assertTags($result, $expected);
<add> }
<add>
<add>/**
<add> * test render escape
<add> *
<add> * @return void
<add> */
<add> public function testRenderAttributes() {
<add> $label = new Label($this->templates);
<add> $data = [
<add> 'text' => 'My > text',
<add> 'for' => 'some-id',
<add> 'id' => 'some-id',
<add> 'data-foo' => 'value',
<add> ];
<add> $result = $label->render($data);
<add> $expected = [
<add> 'label' => ['id' => 'some-id', 'data-foo' => 'value', 'for' => 'some-id'],
<add> 'My > text',
<add> '/label'
<add> ];
<add> $this->assertTags($result, $expected);
<add> }
<add>
<add>} | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.