content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
use element.matches if available
59db6aa4965981b1fcdbd7363fa55d2f61914002
<ide><path>d3.js <ide> return n.querySelector(s); <ide> }, d3_selectAll = function(s, n) { <ide> return n.querySelectorAll(s); <del> }, d3_selectMatcher = d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { <add> }, d3_selectMatcher = d3_documentElement.matches || d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { <ide> return d3_selectMatcher.call(n, s); <ide> }; <ide> if (typeof Sizzle === "function") {
1
PHP
PHP
call message method once only
a904322413bcf3abf2f8945192157e42714d50ce
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateUsingCustomRule($attribute, $value, $rule) <ide> if (! $rule->passes($attribute, $value)) { <ide> $this->failedRules[$attribute][get_class($rule)] = []; <ide> <del> $messages = $rule->message() ? (array) $rule->message() : [get_class($rule)]; <add> $messages = ($messages = $rule->message()) ? (array) $messages : [get_class($rule)]; <ide> <ide> foreach ($messages as $message) { <ide> $this->messages->add($attribute, $this->makeReplacements(
1
Java
Java
allow file locations for resource handling
6b07c53c61ed1c2dcd6c74bd64db7477bdafa424
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java <ide> else if (resource instanceof ServletContextResource) { <ide> resourcePath = resource.getURL().getPath(); <ide> locationPath = StringUtils.cleanPath(location.getURL().getPath()); <ide> } <del> locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/"); <add> locationPath = (StringUtils.getFilenameExtension(locationPath) != null <add> || locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/"); <ide> if (!resourcePath.startsWith(locationPath)) { <ide> return false; <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java <ide> public void checkRelativeLocation() throws Exception { <ide> assertNotNull(this.resolver.resolveResource(null, "main.css", Arrays.asList(location), null)); <ide> } <ide> <add> // SPR-12747 <add> @Test <add> public void checkFileLocation() throws Exception { <add> Resource resource = new ClassPathResource("test/main.css", PathResourceResolver.class); <add> assertTrue(this.resolver.checkResource(resource, resource)); <add> } <add> <ide> }
2
Text
Text
add french translation
1339849911c6cba989c80c0b594a478aa50d928e
<ide><path>threejs/lessons/fr/threejs-scenegraph.md <add>Title: Graphe de scène Three.js <add>Description: What's a scene graph? <add>TOC: Scenegraph <add> <add>Cet article fait partie d'une série consacrée à Three.js. <add>Le premier article s'intitule [Principes de base](threejs-fundamentals.html). <add>Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là. <add> <add>Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local. <add> <add><img src="resources/images/scenegraph-generic.svg" align="center"> <add> <add>C'est un peu abstrait, alors essayons de donner quelques exemples. <add> <add>On pourrait prendre comme exemple le système solaire, le soleil, la terre, la lune. <add> <add><img src="resources/images/scenegraph-solarsystem.svg" align="center"> <add> <add>La Terre tourne autour du Soleil. La Lune tourne autour de la Terre. La Lune se déplace en cercle autour de la Terre. Du point de vue de la Lune, elle tourne dans "l'espace local" de la Terre. Même si son mouvement par rapport au Soleil est une courbe folle comme un spirographe du point de vue de la Lune, il n'a qu'à se préoccuper de tourner autour de l'espace local de la Terre. <add> <add>{{{diagram url="resources/moon-orbit.html" }}} <add> <add>Pour le voir autrement, vous qui vivez sur Terre n'avez pas à penser à la rotation de la Terre sur son axe ni à sa rotation autour du Soleil. Vous marchez ou conduisez ou nagez ou courez comme si la Terre ne bougeait pas ou ne tournait pas du tout. Vous marchez, conduisez, nagez, courez et vivez dans "l'espace local" de la Terre même si par rapport au soleil, vous tournez autour de la terre à environ 1 600 km/h et autour du soleil à environ 107000km/h. Votre position dans le système solaire est similaire à celle de la lune au-dessus, mais vous n'avez pas à vous en préoccuper. Vous vous souciez simplement de votre position par rapport à la terre dans son "espace local". <add> <add>Allons-y une étape à la fois. Imaginez que nous voulions faire un diagramme du soleil, de la terre et de la lune. Nous allons commencer par le soleil en créant simplement une sphère et en la mettant à l'origine. Remarque : Nous utilisons le soleil, la terre et la lune comme démonstration de l'utilisation d'une scène. Bien sûr, le vrai soleil, la terre et la lune utilisent la physique, mais pour nos besoins, nous allons faire semblant. <add> <add>```js <add>// un tableau d'objets dont la rotation à mettre à jour <add>const objects = []; <add> <add>// utiliser une seule sphère pour tout <add>const radius = 1; <add>const widthSegments = 6; <add>const heightSegments = 6; <add>const sphereGeometry = new THREE.SphereGeometry( <add> radius, widthSegments, heightSegments); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); // agrandir le soleil <add>scene.add(sunMesh); <add>objects.push(sunMesh); <add>``` <add> <add>Nous utilisons une sphère à très faible polygone. Seulement 6 segments autour de son équateur. C'est ainsi qu'il est facile de voir la rotation. <add> <add>Nous allons réutiliser la même sphère pour tout, nous allons juste grossir la `sunMesh` 5 fois. <add> <add>Nous avons également défini la propriété `emissive` du matériau phong sur jaune. La propriété émissive d'un matériau phong est essentiellement la couleur qui sera dessinée sans que la lumière ne frappe la surface. La lumière est ajoutée à cette couleur. <add> <add>Mettons également une 'point light' au centre de la scène. Nous entrerons dans les détails plus tard, mais pour l'instant, la version simple est une lumière qui émane d'un seul point. <add> <add>```js <add>{ <add> const color = 0xFFFFFF; <add> const intensity = 3; <add> const light = new THREE.PointLight(color, intensity); <add> scene.add(light); <add>} <add>``` <add> <add>Pour faciliter la visualisation, nous allons placer la caméra directement au-dessus de l'origine en regardant vers le bas. Le moyen le plus simple de le faire est d'utiliser la fonction `lookAt`. Cette fonction oriente la caméra pour "regarder" vers la position que nous passons à `lookAt`. Avant de faire cela, nous devons cependant indiquer à la caméra dans quelle direction le haut de la caméra est orienté ou plutôt dans quelle direction est "vers le haut" pour la caméra. Pour la plupart des situations, un Y positif est suffisant, mais puisque nous regardons vers le bas, nous devons dire à la caméra que Z positif est levé. <add> <add>```js <add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <add>camera.position.set(0, 50, 0); <add>camera.up.set(0, 0, 1); <add>camera.lookAt(0, 0, 0); <add>``` <add> <add>Dans la boucle de rendu, issue des exemples précédents, nous faisons pivoter tous les objets de notre tableau `objects` avec ce code. <add> <add>```js <add>objects.forEach((obj) => { <add> obj.rotation.y = time; <add>}); <add>``` <add> <add>Ajouter la `sunMesh` au tableau `objects`, la fait pivoter. <add> <add>{{{example url="../threejs-scenegraph-sun.html" }}} <add> <add>Ajoutons maintenant la terre. <add> <add>```js <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>scene.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add> <add>Nous fabriquons un matériau bleu mais nous lui donnons une petite quantité de bleu émissif pour qu'il apparaisse sur notre fond noir. <add> <add>Nous utilisons la même `sphereGeometry` avec notre nouveau `EarthMaterial` bleu pour faire une `earthMesh`. <add>Nous positionnons ces 10 unités à gauche du soleil et l'ajoutons à la scène. L'ajouter à notre tableau `objects`, la met en mouvement également. <add> <add>{{{example url="../threejs-scenegraph-sun-earth.html" }}} <add> <add>Vous pouvez voir que le soleil et la terre tournent mais que la terre ne tourne pas autour du soleil. Faisons de la terre un enfant du soleil <add> <add>```js <add>-scene.add(earthMesh); <add>+sunMesh.add(earthMesh); <add>``` <add> <add>et... <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit.html" }}} <add> <add>Que s'est-il passé? Pourquoi la terre a-t-elle la même taille que le soleil et pourquoi est-elle si loin ? En fait, j'ai dû déplacer la caméra de 50 à 150 unités au-dessus pour voir la terre. <add> <add>Nous avons fait de `earthMesh` un enfant du `sunMesh`. <add>La `sunMesh` a son échelle définie sur 5x grâce à `sunMesh.scale.set(5, 5, 5)`. Cela signifie que l'espace local sunMeshs est 5 fois plus grand. <add>Tout ce qui est mis dans cet espace sera multiplié par 5. Cela signifie que la Terre est maintenant 5 fois plus grande et sa distance par rapport au soleil (`earthMesh.position.x = 10`) est également 5 fois plus grande. <add> <add> Notre scène ressemble maintenant à celà <add> <add><img src="resources/images/scenegraph-sun-earth.svg" align="center"> <add> <add>Pour résoudre ce problème, ajoutons un nœud vide. Nous lions le soleil et la terre à ce nœud. <add> <add>```js <add>+const solarSystem = new THREE.Object3D(); <add>+scene.add(solarSystem); <add>+objects.push(solarSystem); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); <add>-scene.add(sunMesh); <add>+solarSystem.add(sunMesh); <add>objects.push(sunMesh); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>-sunMesh.add(earthMesh); <add>+solarSystem.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add>Ici, nous avons fait un `Object3D`. Comme une `Mesh`, c'est aussi un nœud, mais contrairement à une `Mesh`, il n'a ni matériau ni géométrie. Il ne représente qu'un espace local. <add> <add>Notre nouvelle scène ressemble à ceci : <add> <add><img src="resources/images/scenegraph-sun-earth-fixed.svg" align="center"> <add> <add>La `sunMesh` et la `earthMesh` sont tous les deux des enfants de `solarSystem`. Les trois sont en train de tournés, et comme `earthMesh` n'est pas un enfant de `sunMesh`, elle n'est plus mise à l'échelle. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit-fixed.html" }}} <add> <add>Encore mieux. La Terre est plus petite que le Soleil, elle tourne autour de lui et sur elle-même. <add> <add>Sur le même schéma, ajoutons une Lune. <add> <add>```js <add>+const earthOrbit = new THREE.Object3D(); <add>+earthOrbit.position.x = 10; <add>+solarSystem.add(earthOrbit); <add>+objects.push(earthOrbit); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>-earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit" <add>-solarSystem.add(earthMesh); <add>+earthOrbit.add(earthMesh); <add>objects.push(earthMesh); <add> <add>+const moonOrbit = new THREE.Object3D(); <add>+moonOrbit.position.x = 2; <add>+earthOrbit.add(moonOrbit); <add> <add>+const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222}); <add>+const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial); <add>+moonMesh.scale.set(.5, .5, .5); <add>+moonOrbit.add(moonMesh); <add>+objects.push(moonMesh); <add>``` <add>XXXXXXXXXXXXXXXX <add> <add> <add>Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit` <add>and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh` <add>to the `moonOrbit`. The new scene graph looks like this. <add> <add><img src="resources/images/scenegraph-sun-earth-moon.svg" align="center"> <add> <add>and here's that <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}} <add> <add>You can see the moon follows the spirograph pattern shown at the top <add>of this article but we didn't have to manually compute it. We just <add>setup our scene graph to do it for us. <add> <add>It is often useful to draw something to visualize the nodes in the scene graph. <add>Three.js has some helpful ummmm, helpers to ummm, ... help with this. <add> <add>One is called an `AxesHelper`. It draws 3 lines representing the local <add><span style="color:red">X</span>, <add><span style="color:green">Y</span>, and <add><span style="color:blue">Z</span> axes. Let's add one to every node we <add>created. <add> <add>```js <add>// add an AxesHelper to each node <add>objects.forEach((node) => { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 1; <add> node.add(axes); <add>}); <add>``` <add> <add>On our case we want the axes to appear even though they are inside the spheres. <add>To do this we set their material's `depthTest` to false which means they will <add>not check to see if they are drawing behind something else. We also <add>set their `renderOrder` to 1 (the default is 0) so that they get drawn after <add>all the spheres. Otherwise a sphere might draw over them and cover them up. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} <add> <add>We can see the <add><span style="color:red">x (red)</span> and <add><span style="color:blue">z (blue)</span> axes. Since we are looking <add>straight down and each of our objects is only rotating around its <add>y axis we don't see much of the <span style="color:green">y (green)</span> axes. <add> <add>It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh` <add>and the `solarSystem` are at the same position. Similarly the `earthMesh` and <add>`earthOrbit` are at the same position. Let's add some simple controls to allow us <add>to turn them on/off for each node. <add>While we're at it let's also add another helper called the `GridHelper`. It <add>makes a 2D grid on the X,Z plane. By default the grid is 10x10 units. <add> <add>We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is <add>a UI library that is very popular with three.js projects. dat.GUI takes an <add>object and a property name on that object and based on the type of the property <add>automatically makes a UI to manipulate that property. <add> <add>We want to make both a `GridHelper` and an `AxesHelper` for each node. We need <add>a label for each node so we'll get rid of the old loop and switch to calling <add>some function to add the helpers for each node <add> <add>```js <add>-// add an AxesHelper to each node <add>-objects.forEach((node) => { <add>- const axes = new THREE.AxesHelper(); <add>- axes.material.depthTest = false; <add>- axes.renderOrder = 1; <add>- node.add(axes); <add>-}); <add> <add>+function makeAxisGrid(node, label, units) { <add>+ const helper = new AxisGridHelper(node, units); <add>+ gui.add(helper, 'visible').name(label); <add>+} <add>+ <add>+makeAxisGrid(solarSystem, 'solarSystem', 25); <add>+makeAxisGrid(sunMesh, 'sunMesh'); <add>+makeAxisGrid(earthOrbit, 'earthOrbit'); <add>+makeAxisGrid(earthMesh, 'earthMesh'); <add>+makeAxisGrid(moonOrbit, 'moonOrbit'); <add>+makeAxisGrid(moonMesh, 'moonMesh'); <add>``` <add> <add>`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create <add>to make dat.GUI happy. Like it says above dat.GUI <add>will automagically make a UI that manipulates the named property <add>of some object. It will create a different UI depending on the type <add>of property. We want it to create a checkbox so we need to specify <add>a `bool` property. But, we want both the axes and the grid <add>to appear/disappear based on a single property so we'll make a class <add>that has a getter and setter for a property. That way we can let dat.GUI <add>think it's manipulating a single property but internally we can set <add>the visible property of both the `AxesHelper` and `GridHelper` for a node. <add> <add>```js <add>// Turns both axes and grid visible on/off <add>// dat.GUI requires a property that returns a bool <add>// to decide to make a checkbox so we make a setter <add>// and getter for `visible` which we can tell dat.GUI <add>// to look at. <add>class AxisGridHelper { <add> constructor(node, units = 10) { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 2; // after the grid <add> node.add(axes); <add> <add> const grid = new THREE.GridHelper(units, units); <add> grid.material.depthTest = false; <add> grid.renderOrder = 1; <add> node.add(grid); <add> <add> this.grid = grid; <add> this.axes = axes; <add> this.visible = false; <add> } <add> get visible() { <add> return this._visible; <add> } <add> set visible(v) { <add> this._visible = v; <add> this.grid.visible = v; <add> this.axes.visible = v; <add> } <add>} <add>``` <add> <add>One thing to notice is we set the `renderOrder` of the `AxesHelper` <add>to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid. <add>Otherwise the grid might overwrite the axes. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}} <add> <add>Turn on the `solarSystem` and you'll see how the earth is exactly 10 <add>units out from the center just like we set above. You can see how the <add>earth is in the *local space* of the `solarSystem`. Similarly if you <add>turn on the `earthOrbit` you'll see how the moon is exactly 2 units <add>from the center of the *local space* of the `earthOrbit`. <add> <add>A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this <add> <add><img src="resources/images/scenegraph-car.svg" align="center"> <add> <add>If you move the car's body all the wheels will move with it. If you wanted the body <add>to bounce separate from the wheels you might parent the body and the wheels to a "frame" node <add>that represents the car's frame. <add> <add>Another example is a human in a game world. <add> <add><img src="resources/images/scenegraph-human.svg" align="center"> <add> <add>You can see the scene graph gets pretty complex for a human. In fact <add>that scene graph above is simplified. For example you might extend it <add>to cover every finger (at least another 28 nodes) and every toe <add>(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more. <add> <add>Let's make one semi-complex scene graph. We'll make a tank. The tank will have <add>6 wheels and a turret. The tank will follow a path. There will be a sphere that <add>moves around and the tank will target the sphere. <add> <add>Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue, <add>the lights in gold, and the cameras in purple. One camera has not been added <add>to the scene graph. <add> <add><div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div> <add> <add>Look in the code to see the setup of all of these nodes. <add> <add>For the target, the thing the tank is aiming at, there is a `targetOrbit` <add>(`Object3D`) which just rotates similar to the `earthOrbit` above. A <add>`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an <add>offset from the `targetOrbit` and a base elevation. Childed to that is another <add>`Object3D` called `targetBob` which just bobs up and down relative to the <add>`targetElevation`. Finally there's the `targetMesh` which is just a cube we <add>rotate and change its colors <add> <add>```js <add>// move target <add>targetOrbit.rotation.y = time * .27; <add>targetBob.position.y = Math.sin(time * 2) * 4; <add>targetMesh.rotation.x = time * 7; <add>targetMesh.rotation.y = time * 13; <add>targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25); <add>targetMaterial.color.setHSL(time * 10 % 1, 1, .25); <add>``` <add> <add>For the tank there's an `Object3D` called `tank` which is used to move everything <add>below it around. The code uses a `SplineCurve` which it can ask for positions <add>along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It <add>asks for the current position where it puts the tank. It then asks for a <add>position slightly further down the curve and uses that to point the tank in that <add>direction using `Object3D.lookAt`. <add> <add>```js <add>const tankPosition = new THREE.Vector2(); <add>const tankTarget = new THREE.Vector2(); <add> <add>... <add> <add>// move tank <add>const tankTime = time * .05; <add>curve.getPointAt(tankTime % 1, tankPosition); <add>curve.getPointAt((tankTime + 0.01) % 1, tankTarget); <add>tank.position.set(tankPosition.x, 0, tankPosition.y); <add>tank.lookAt(tankTarget.x, 0, tankTarget.y); <add>``` <add> <add>The turret on top of the tank is moved automatically by being a child <add>of the tank. To point it at the target we just ask for the target's world position <add>and then again use `Object3D.lookAt` <add> <add>```js <add>const targetPosition = new THREE.Vector3(); <add> <add>... <add> <add>// face turret at target <add>targetMesh.getWorldPosition(targetPosition); <add>turretPivot.lookAt(targetPosition); <add>``` <add> <add>There's a `turretCamera` which is a child of the `turretMesh` so <add>it will move up and down and rotate with the turret. We make that <add>aim at the target. <add> <add>```js <add>// make the turretCamera look at target <add>turretCamera.lookAt(targetPosition); <add>``` <add> <add>There is also a `targetCameraPivot` which is a child of `targetBob` so it floats <add>around with the target. We aim that back at the tank. Its purpose is to allow the <add>`targetCamera` to be offset from the target itself. If we instead made the camera <add>a child of `targetBob` and just aimed the camera itself it would be inside the <add>target. <add> <add>```js <add>// make the targetCameraPivot look at the tank <add>tank.getWorldPosition(targetPosition); <add>targetCameraPivot.lookAt(targetPosition); <add>``` <add> <add>Finally we rotate all the wheels <add> <add>```js <add>wheelMeshes.forEach((obj) => { <add> obj.rotation.x = time * 3; <add>}); <add>``` <add> <add>For the cameras we setup an array of all 4 cameras at init time with descriptions. <add> <add>```js <add>const cameras = [ <add> { cam: camera, desc: 'detached camera', }, <add> { cam: turretCamera, desc: 'on turret looking at target', }, <add> { cam: targetCamera, desc: 'near target looking at tank', }, <add> { cam: tankCamera, desc: 'above back of tank', }, <add>]; <add> <add>const infoElem = document.querySelector('#info'); <add>``` <add> <add>and cycle through our cameras at render time. <add> <add>```js <add>const camera = cameras[time * .25 % cameras.length | 0]; <add>infoElem.textContent = camera.desc; <add>``` <add> <add>{{{example url="../threejs-scenegraph-tank.html"}}} <add> <add>I hope this gives some idea of how scene graphs work and how you might use them. <add>Making `Object3D` nodes and parenting things to them is an important step to using <add>a 3D engine like three.js well. Often it might seem like some complex math is necessary <add>to make something move and rotate the way you want. For example without a scene graph <add>computing the motion of the moon or where to put the wheels of the car relative to its <add>body would be very complicated but using a scene graph it becomes much easier. <add> <add>[Next up we'll go over materials](threejs-materials.html).
1
Ruby
Ruby
simplify callbacks to use less metaprogramming
971e2438d98326c994ec6d3ef8e37b7e868ed6e2
<ide><path>actionpack/lib/action_controller/abstract/callbacks.rb <ide> def skip_filter(*names, &blk) <ide> skip_around_filter(*names, &blk) <ide> end <ide> <add> def _insert_callbacks(names, block) <add> options = names.last.is_a?(Hash) ? names.pop : {} <add> _normalize_callback_options(options) <add> names.push(block) if block <add> names.each do |name| <add> yield name, options <add> end <add> end <add> <ide> [:before, :after, :around].each do |filter| <ide> class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 <ide> def #{filter}_filter(*names, &blk) <del> options = names.last.is_a?(Hash) ? names.pop : {} <del> _normalize_callback_options(options) <del> names.push(blk) if block_given? <del> names.each do |name| <del> process_action_callback(:#{filter}, name, options) <add> _insert_callbacks(names, blk) do |name, options| <add> _set_callback(:process_action, :#{filter}, name, options) <ide> end <ide> end <ide> <ide> def prepend_#{filter}_filter(*names, &blk) <del> options = names.last.is_a?(Hash) ? names.pop : {} <del> _normalize_callback_options(options) <del> names.push(blk) if block_given? <del> names.each do |name| <del> process_action_callback(:#{filter}, name, options.merge(:prepend => true)) <add> _insert_callbacks(names, blk) do |name, options| <add> _set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) <ide> end <ide> end <ide> <ide> def skip_#{filter}_filter(*names, &blk) <del> options = names.last.is_a?(Hash) ? names.pop : {} <del> _normalize_callback_options(options) <del> names.push(blk) if block_given? <del> names.each do |name| <del> skip_process_action_callback(:#{filter}, name, options) <add> _insert_callbacks(names, blk) do |name, options| <add> _skip_callback(:process_action, :#{filter}, name, options) <ide> end <ide> end <ide> <ide><path>actionpack/test/abstract_controller/callbacks_test.rb <ide> class ControllerWithCallbacks < AbstractController::Base <ide> end <ide> <ide> class Callback1 < ControllerWithCallbacks <del> process_action_callback :before, :first <add> _set_callback :process_action, :before, :first <ide> <ide> def first <ide> @text = "Hello world" <ide><path>activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb <ide> def self.#{ivar}=(obj) <ide> def #{ivar}=(obj) self.class.#{ivar} = obj end <ide> RUBY <ide> end <add> <add> self.send("#{ivar}=", yield) if block_given? <ide> end <ide> end <ide> <ide> def #{ivar}=(obj) self.class.#{ivar} = obj end <ide> # @return <Array[#to_s]> An Array of attributes turned into inheritable accessors. <ide> # <ide> # @api public <del> def extlib_inheritable_accessor(*syms) <add> def extlib_inheritable_accessor(*syms, &block) <ide> extlib_inheritable_reader(*syms) <del> extlib_inheritable_writer(*syms) <add> extlib_inheritable_writer(*syms, &block) <ide> end <ide> end <ide><path>activesupport/lib/active_support/new_callbacks.rb <ide> module ClassMethods <ide> # The _run_save_callbacks method can optionally take a key, which <ide> # will be used to compile an optimized callback method for each <ide> # key. See #define_callbacks for more information. <del> def _define_runner(symbol, str, options) <del> str = <<-RUBY_EVAL <add> def _define_runner(symbol, callbacks, options) <add> body = callbacks.compile(nil, :terminator => send("_#{symbol}_terminator")) <add> <add> body = <<-RUBY_EVAL <ide> def _run_#{symbol}_callbacks(key = nil) <ide> if key <ide> key = key.hash.to_s.gsub(/-/, '_') <ide> def _run_#{symbol}_callbacks(key = nil) <ide> :#{symbol}, key, self) { yield if block_given? } <ide> end <ide> else <del> #{str} <add> #{body} <ide> end <ide> end <ide> RUBY_EVAL <ide> <ide> undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks") <del> class_eval str, __FILE__, __LINE__ <add> class_eval body, __FILE__, __LINE__ <ide> <ide> before_name, around_name, after_name = <ide> options.values_at(:before, :after, :around) <ide> def _run__#{klass.split("::").last}__#{kind}__#{key}__callbacks <ide> # In that case, each action_name would get its own compiled callback <ide> # method that took into consideration the per_key conditions. This <ide> # is a speed improvement for ActionPack. <add> def _update_callbacks(name, filters = CallbackChain.new(name), block = nil) <add> type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before <add> options = filters.last.is_a?(Hash) ? filters.pop : {} <add> filters.unshift(block) if block <add> <add> callbacks = send("_#{name}_callbacks") <add> yield callbacks, type, filters, options if block_given? <add> <add> _define_runner(name, callbacks, options) <add> end <add> <add> def _set_callback(name, *filters, &block) <add> _update_callbacks(name, filters, block) do |callbacks, type, filters, options| <add> filters.map! do |filter| <add> # overrides parent class <add> callbacks.delete_if do |c| <add> c.matches?(type, name, filter) <add> end <add> Callback.new(filter, type, options.dup, self, name) <add> end <add> <add> options[:prepend] ? callbacks.unshift(*filters) : callbacks.push(*filters) <add> end <add> end <add> <add> def _skip_callback(name, *filters, &block) <add> _update_callbacks(name, filters, block) do |callbacks, type, filters, options| <add> filters.each do |filter| <add> callbacks = send("_#{name}_callbacks=", callbacks.clone(self)) <add> <add> filter = callbacks.find {|c| c.matches?(type, name, filter) } <add> per_key = options[:per_key] || {} <add> if filter && options.any? <add> filter.recompile!(options, per_key) <add> else <add> callbacks.delete(filter) <add> end <add> end <add> end <add> end <add> <ide> def define_callbacks(*symbols) <ide> terminator = symbols.pop if symbols.last.is_a?(String) <ide> symbols.each do |symbol| <del> self.extlib_inheritable_accessor("_#{symbol}_terminator") <del> self.send("_#{symbol}_terminator=", terminator) <del> self.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 <del> extlib_inheritable_accessor :_#{symbol}_callbacks <del> self._#{symbol}_callbacks = CallbackChain.new(:#{symbol}) <add> extlib_inheritable_accessor("_#{symbol}_terminator") { terminator } <ide> <del> def self.#{symbol}_callback(*filters, &blk) <del> type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before <del> options = filters.last.is_a?(Hash) ? filters.pop : {} <del> filters.unshift(blk) if block_given? <del> <del> filters.map! do |filter| <del> # overrides parent class <del> self._#{symbol}_callbacks.delete_if {|c| c.matches?(type, :#{symbol}, filter)} <del> Callback.new(filter, type, options.dup, self, :#{symbol}) <del> end <del> options[:prepend] ? <del> self._#{symbol}_callbacks.unshift(*filters) : <del> self._#{symbol}_callbacks.push(*filters) <del> _define_runner(:#{symbol}, <del> self._#{symbol}_callbacks.compile(nil, :terminator => _#{symbol}_terminator), <del> options) <del> end <del> <del> def self.skip_#{symbol}_callback(*filters, &blk) <del> type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before <del> options = filters.last.is_a?(Hash) ? filters.pop : {} <del> filters.unshift(blk) if block_given? <del> filters.each do |filter| <del> self._#{symbol}_callbacks = self._#{symbol}_callbacks.clone(self) <del> <del> filter = self._#{symbol}_callbacks.find {|c| c.matches?(type, :#{symbol}, filter) } <del> per_key = options[:per_key] || {} <del> if filter && options.any? <del> filter.recompile!(options, per_key) <del> else <del> self._#{symbol}_callbacks.delete(filter) <del> end <del> _define_runner(:#{symbol}, <del> self._#{symbol}_callbacks.compile(nil, :terminator => _#{symbol}_terminator), <del> options) <del> end <del> <del> end <del> <add> extlib_inheritable_accessor("_#{symbol}_callbacks") do <add> CallbackChain.new(symbol) <add> end <add> <add> self.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 <ide> def self.reset_#{symbol}_callbacks <del> self._#{symbol}_callbacks = CallbackChain.new(:#{symbol}) <del> _define_runner(:#{symbol}, self._#{symbol}_callbacks.compile, {}) <add> _update_callbacks(:#{symbol}) <ide> end <ide> <del> self.#{symbol}_callback(:before) <add> self._set_callback(:#{symbol}, :before) <ide> RUBY_EVAL <ide> end <ide> end <ide><path>activesupport/test/new_callback_inheritance_test.rb <ide> def initialize(action_name) <ide> end <ide> <ide> define_callbacks :dispatch <del> dispatch_callback :before, :before1, :before2, :per_key => {:if => proc {|c| c.action_name == "index" || c.action_name == "update" }} <del> dispatch_callback :after, :after1, :after2, :per_key => {:if => proc {|c| c.action_name == "update" || c.action_name == "delete" }} <add> _set_callback :dispatch, :before, :before1, :before2, :per_key => {:if => proc {|c| c.action_name == "index" || c.action_name == "update" }} <add> _set_callback :dispatch, :after, :after1, :after2, :per_key => {:if => proc {|c| c.action_name == "update" || c.action_name == "delete" }} <ide> <ide> def before1 <ide> @log << "before1" <ide> def dispatch <ide> end <ide> <ide> class Parent < GrandParent <del> skip_dispatch_callback :before, :before2, :per_key => {:unless => proc {|c| c.action_name == "update" }} <del> skip_dispatch_callback :after, :after2, :per_key => {:unless => proc {|c| c.action_name == "delete" }} <add> _skip_callback :dispatch, :before, :before2, :per_key => {:unless => proc {|c| c.action_name == "update" }} <add> _skip_callback :dispatch, :after, :after2, :per_key => {:unless => proc {|c| c.action_name == "delete" }} <ide> end <ide> <ide> class Child < GrandParent <del> skip_dispatch_callback :before, :before2, :per_key => {:unless => proc {|c| c.action_name == "update" }}, :if => :state_open? <add> _skip_callback :dispatch, :before, :before2, :per_key => {:unless => proc {|c| c.action_name == "update" }}, :if => :state_open? <ide> <ide> def state_open? <ide> @state == :open <ide><path>activesupport/test/new_callbacks_test.rb <ide> class Record <ide> define_callbacks :save <ide> <ide> def self.before_save(*filters, &blk) <del> save_callback(:before, *filters, &blk) <add> _set_callback(:save, :before, *filters, &blk) <ide> end <ide> <ide> def self.after_save(*filters, &blk) <del> save_callback(:after, *filters, &blk) <add> _set_callback(:save, :after, *filters, &blk) <ide> end <ide> <ide> class << self <ide> def save <ide> end <ide> <ide> class PersonSkipper < Person <del> skip_save_callback :before, :before_save_method, :if => :yes <del> skip_save_callback :after, :before_save_method, :unless => :yes <del> skip_save_callback :after, :before_save_method, :if => :no <del> skip_save_callback :before, :before_save_method, :unless => :no <add> _skip_callback :save, :before, :before_save_method, :if => :yes <add> _skip_callback :save, :after, :before_save_method, :unless => :yes <add> _skip_callback :save, :after, :before_save_method, :if => :no <add> _skip_callback :save, :before, :before_save_method, :unless => :no <ide> def yes; true; end <ide> def no; false; end <ide> end <ide> class ParentController <ide> <ide> define_callbacks :dispatch <ide> <del> dispatch_callback :before, :log, :per_key => {:unless => proc {|c| c.action_name == :index || c.action_name == :show }} <del> dispatch_callback :after, :log2 <add> _set_callback :dispatch, :before, :log, :per_key => {:unless => proc {|c| c.action_name == :index || c.action_name == :show }} <add> _set_callback :dispatch, :after, :log2 <ide> <ide> attr_reader :action_name, :logger <ide> def initialize(action_name) <ide> def dispatch <ide> end <ide> <ide> class Child < ParentController <del> skip_dispatch_callback :before, :log, :per_key => {:if => proc {|c| c.action_name == :update} } <del> skip_dispatch_callback :after, :log2 <add> _skip_callback :dispatch, :before, :log, :per_key => {:if => proc {|c| c.action_name == :update} } <add> _skip_callback :dispatch, :after, :log2 <ide> end <ide> <ide> class OneTimeCompile < Record <ide> class MySuper <ide> class AroundPerson < MySuper <ide> attr_reader :history <ide> <del> save_callback :before, :nope, :if => :no <del> save_callback :before, :nope, :unless => :yes <del> save_callback :after, :tweedle <del> save_callback :before, "tweedle_dee" <del> save_callback :before, proc {|m| m.history << "yup" } <del> save_callback :before, :nope, :if => proc { false } <del> save_callback :before, :nope, :unless => proc { true } <del> save_callback :before, :yup, :if => proc { true } <del> save_callback :before, :yup, :unless => proc { false } <del> save_callback :around, :tweedle_dum <del> save_callback :around, :w0tyes, :if => :yes <del> save_callback :around, :w0tno, :if => :no <del> save_callback :around, :tweedle_deedle <add> _set_callback :save, :before, :nope, :if => :no <add> _set_callback :save, :before, :nope, :unless => :yes <add> _set_callback :save, :after, :tweedle <add> _set_callback :save, :before, "tweedle_dee" <add> _set_callback :save, :before, proc {|m| m.history << "yup" } <add> _set_callback :save, :before, :nope, :if => proc { false } <add> _set_callback :save, :before, :nope, :unless => proc { true } <add> _set_callback :save, :before, :yup, :if => proc { true } <add> _set_callback :save, :before, :yup, :unless => proc { false } <add> _set_callback :save, :around, :tweedle_dum <add> _set_callback :save, :around, :w0tyes, :if => :yes <add> _set_callback :save, :around, :w0tno, :if => :no <add> _set_callback :save, :around, :tweedle_deedle <ide> <ide> def no; false; end <ide> def yes; true; end <ide> class HyphenatedCallbacks <ide> define_callbacks :save <ide> attr_reader :stuff <ide> <del> save_callback :before, :omg, :per_key => {:if => :yes} <add> _set_callback :save, :before, :omg, :per_key => {:if => :yes} <ide> <ide> def yes() true end <ide> <ide> class CallbackTerminator <ide> <ide> define_callbacks :save, "result == :halt" <ide> <del> save_callback :before, :first <del> save_callback :before, :second <del> save_callback :around, :around_it <del> save_callback :before, :third <del> save_callback :after, :first <del> save_callback :around, :around_it <del> save_callback :after, :second <del> save_callback :around, :around_it <del> save_callback :after, :third <add> _set_callback :save, :before, :first <add> _set_callback :save, :before, :second <add> _set_callback :save, :around, :around_it <add> _set_callback :save, :before, :third <add> _set_callback :save, :after, :first <add> _set_callback :save, :around, :around_it <add> _set_callback :save, :after, :second <add> _set_callback :save, :around, :around_it <add> _set_callback :save, :after, :third <ide> <ide> <ide> attr_reader :history, :saved <ide> class UsingObjectBefore <ide> include ActiveSupport::NewCallbacks <ide> <ide> define_callbacks :save <del> save_callback :before, CallbackObject.new <add> _set_callback :save, :before, CallbackObject.new <ide> <ide> attr_accessor :record <ide> def initialize <ide> class UsingObjectAround <ide> include ActiveSupport::NewCallbacks <ide> <ide> define_callbacks :save <del> save_callback :around, CallbackObject.new <add> _set_callback :save, :around, CallbackObject.new <ide> <ide> attr_accessor :record <ide> def initialize
6
Text
Text
add v3.21.0-beta.6 to changelog
9ad9b7b2ff80e1100f6b278171412f4b558b111b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.21.0-beta.6 (August 17, 2020) <add> <add>- [#19087](https://github.com/emberjs/ember.js/pull/19087) [BUGFIX] Generated initializer tests no longer causes a deprecation warning <add>- [#19077](https://github.com/emberjs/ember.js/pull/19077) Simplify `get` and improve `computed` caching scheme. <add>- [#19082](https://github.com/emberjs/ember.js/pull/19082) Simplify mixin application <add>- [#19089](https://github.com/emberjs/ember.js/pull/19089) Update rendering engine to improve immediate encoding performance <add> <ide> ### v3.21.0-beta.5 (August 5, 2020) <ide> <ide> - [#19028](https://github.com/emberjs/ember.js/pull/19028) [BUGFIX] Ensure setter CP's with dependent keys on curly components can be two way bound
1
Javascript
Javascript
add srcset attribute
ec8b0d7fbf6edc8f707af06cf3d0088702dff285
<ide><path>src/browser/ui/dom/DefaultDOMPropertyConfig.js <ide> var DefaultDOMPropertyConfig = { <ide> spellCheck: null, <ide> src: null, <ide> srcDoc: MUST_USE_PROPERTY, <add> srcSet: null, <ide> step: null, <ide> style: null, <ide> tabIndex: null, <ide> var DefaultDOMPropertyConfig = { <ide> hrefLang: 'hreflang', <ide> radioGroup: 'radiogroup', <ide> spellCheck: 'spellcheck', <del> srcDoc: 'srcdoc' <add> srcDoc: 'srcdoc', <add> srcSet: 'srcset' <ide> } <ide> }; <ide>
1
Text
Text
create model card
c34010551a8c99ad8046082c53f2d263e12762cf
<ide><path>model_cards/mrm8488/t5-base-finetuned-sarcasm-twitter/README.md <add>-- <add>language: english <add>--- <add> <add># T5-base fine-tuned for Sarcasm Detection 🙄 <add>[Google's T5](https://ai.googleblog.com/2020/02/exploring-transfer-learning-with-t5.html) base fine-tuned on [ Twitter Sarcasm Dataset](https://github.com/EducationalTestingService/sarcasm) for **Sequence classification (as text generation)** downstream task. <add> <add>## Details of T5 <add> <add>The **T5** model was presented in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/pdf/1910.10683.pdf) by *Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu* in Here the abstract: <add> <add>Transfer learning, where a model is first pre-trained on a data-rich task before being fine-tuned on a downstream task, has emerged as a powerful technique in natural language processing (NLP). The effectiveness of transfer learning has given rise to a diversity of approaches, methodology, and practice. In this paper, we explore the landscape of transfer learning techniques for NLP by introducing a unified framework that converts every language problem into a text-to-text format. Our systematic study compares pre-training objectives, architectures, unlabeled datasets, transfer approaches, and other factors on dozens of language understanding tasks. By combining the insights from our exploration with scale and our new “Colossal Clean Crawled Corpus”, we achieve state-of-the-art results on many benchmarks covering summarization, question answering, text classification, and more. To facilitate future work on transfer learning for NLP, we release our dataset, pre-trained models, and code. <add> <add>![model image](https://camo.githubusercontent.com/623b4dea0b653f2ad3f36c71ebfe749a677ac0a1/68747470733a2f2f6d69726f2e6d656469756d2e636f6d2f6d61782f343030362f312a44304a31674e51663876727255704b657944387750412e706e67) <add> <add>## Details of the downstream task (Sequence Classification as Text generation) - Dataset 📚 <add> <add>[ Twitter Sarcasm Dataset](https://github.com/EducationalTestingService/sarcasm) <add> <add> <add>For Twitter training and testing datasets are provided for sarcasm detection tasks in jsonlines format. <add> <add>Each line contains a JSON object with the following fields : <add>- ***label*** : `SARCASM` or `NOT_SARCASM` <add> - **NOT** in test data <add>- ***id***: String identifier for sample. This id will be required when making submissions. <add> - **ONLY** in test data <add>- ***response*** : the sarcastic response, whether a sarcastic Tweet <add>- ***context*** : the conversation context of the ***response*** <add> - Note, the context is an ordered list of dialogue, i.e., if the context contains three elements, `c1`, `c2`, `c3`, in that order, then `c2` is a reply to `c1` and `c3` is a reply to `c2`. Further, if the sarcastic response is `r`, then `r` is a reply to `c3`. <add> <add>For instance, for the following training example : <add> <add>`"label": "SARCASM", "response": "Did Kelly just call someone else messy? Baaaahaaahahahaha", "context": ["X is looking a First Lady should . #classact, "didn't think it was tailored enough it looked messy"]` <add> <add>The response tweet, "Did Kelly..." is a reply to its immediate context "didn't think it was tailored..." which is a reply to "X is looking...". Your goal is to predict the label of the "response" while also using the context (i.e, the immediate or the full context). <add> <add>***Dataset size statistics*** : <add> <add>| | Train | Val | Test | <add>|---------|-------|------|------| <add>| Twitter | 4050 | 450 | 500 | <add> <add>The datasets was preprocessed to convert it to a **text-to-text** (classfication as generation task). <add> <add>## Model fine-tuning 🏋️‍ <add> <add>The training script is a slightly modified version of [this Colab Notebook](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) created by [Suraj Patil](https://github.com/patil-suraj), so all credits to him! <add> <add>## Test set metrics 🧾 <add> <add>| | precision| recall | f1-score |support| <add>|----------|----------|---------|----------|-------| <add>| derison | 0.84 | 0.80 | 0.82 | 246 | <add>| normal | 0.82 | 0.85 | 0.83 | 254 | <add>| | <add>|accuracy| | | 0.83| 500| <add>|macro avg| 0.83| 0.83| 0.83| 500| <add>|weighted avg| 0.83| 0.83| 0.83| 500| <add> <add> <add> <add>## Model in Action 🚀 <add> <add>```python <add>from transformers import AutoTokenizer, AutoModelWithLMHead <add>tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-base-finetuned-sarcasm-twitter") <add> <add>model = AutoModelWithLMHead.from_pretrained("mrm8488/t5-base-finetuned-sarcasm-twitter") <add> <add>def eval_conversation(text): <add> <add> input_ids = tokenizer.encode(text + '</s>', return_tensors='pt') <add> <add> output = model.generate(input_ids=input_ids, max_length=3) <add> <add> dec = [tokenizer.decode(ids) for ids in output] <add> <add> label = dec[0] <add> <add> return label <add> <add># For similarity with the training dataset we should replace users mentions in twits for @USER token and urls for URL token. <add> <add>twit1 = "Trump just suspended the visa program that allowed me to move to the US to start @USER!" + <add>" Unfortunately, I won’t be able to vote in a few months but if you can, please vote him out, " + <add>"he's destroying what made America great in so many different ways!" <add> <add>twit2 = "@USER @USER @USER We have far more cases than any other country, " + <add>"so leaving remote workers in would be disastrous. Makes Trump sense." <add> <add>twit3 = "My worry is that i wouldn’t be surprised if half the country actually agrees with this move..." <add> <add>me = "Trump doing so??? It must be a mistake... XDDD" <add> <add>conversation = twit1 + twit2 <add> <add>eval_conversation(conversation) #Output: 'derison' <add> <add>conversation = twit1 + twit3 <add> <add>eval_conversation(conversation) #Output: 'normal' <add> <add>conversation = twit1 + me <add> <add>eval_conversation(conversation) #Output: 'derison' <add> <add># We will get 'normal' when not sarcasm detected and 'derison' when detected <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Text
Text
make the redirect to slim notice more prominent
8fc75a8e2c2a16370479335f439e3cd301e221b0
<ide><path>research/inception/README.md <del>**NOTE**: For the most part, you will find a newer version of this code at [models/research/slim](https://github.com/tensorflow/models/tree/master/research/slim). In particular: <add>**NOTE: For the most part, you will find a newer version of this code at [models/research/slim](https://github.com/tensorflow/models/tree/master/research/slim).** In particular: <ide> <ide> * `inception_train.py` and `imagenet_train.py` should no longer be used. The slim editions for running on multiple GPUs are the current best examples. <ide> * `inception_distributed_train.py` and `imagenet_distributed_train.py` are still valid examples of distributed training. <ide> <ide> For performance benchmarking, please see https://www.tensorflow.org/performance/benchmarks. <ide> <add>--- <add> <ide> # Inception in TensorFlow <ide> <ide> [ImageNet](http://www.image-net.org/) is a common academic data set in machine
1
Go
Go
fix incorrect error type
bc4edbbe712a2d0fb839747814933916177daa74
<ide><path>integration/https_test.go <ide> func TestHttpsInfoRogueServerCert(t *testing.T) { <ide> } <ide> <ide> if !strings.Contains(err.Error(), errCaUnknown) { <del> t.Fatalf("Expected error: %s, got instead: %s", errBadCertificate, err) <add> t.Fatalf("Expected error: %s, got instead: %s", errCaUnknown, err) <ide> } <ide> <ide> })
1
Python
Python
fix meta.json validation
62eec33bc43150636b9c1a8be561cb9fb4f58425
<ide><path>spacy/schemas.py <ide> class ModelMetaSchema(BaseModel): <ide> url: StrictStr = Field("", title="Model author URL") <ide> sources: Optional[Union[List[StrictStr], List[Dict[str, str]]]] = Field(None, title="Training data sources") <ide> vectors: Dict[str, Any] = Field({}, title="Included word vectors") <del> labels: Dict[str, Dict[str, List[str]]] = Field({}, title="Component labels, keyed by component name") <add> labels: Dict[str, List[str]] = Field({}, title="Component labels, keyed by component name") <ide> accuracy: Dict[str, Union[float, Dict[str, float]]] = Field({}, title="Accuracy numbers") <ide> speed: Dict[str, Union[float, int]] = Field({}, title="Speed evaluation numbers") <ide> spacy_git_version: StrictStr = Field("", title="Commit of spaCy version used")
1
Javascript
Javascript
remove useless parentheses and spaces
3f319eb76ea2b631c7fe329796dc5d3663af4457
<ide><path>examples/todos/src/containers/VisibleTodoList.js <ide> const mapStateToProps = (state) => ({ <ide> todos: getVisibleTodos(state.todos, state.visibilityFilter) <ide> }) <ide> <del>const mapDispatchToProps = ({ <add>const mapDispatchToProps = { <ide> onTodoClick: toggleTodo <del>}) <add>} <ide> <ide> const VisibleTodoList = connect( <ide> mapStateToProps,
1
Text
Text
improve path.posix.normalize docs
cbd6fde9a38687491452e01927da0c69d2c37564
<ide><path>doc/api/path.md <ide> The `path.normalize()` method normalizes the given `path`, resolving `'..'` and <ide> `'.'` segments. <ide> <ide> When multiple, sequential path segment separation characters are found (e.g. <del>`/` on POSIX and `\` on Windows), they are replaced by a single instance of the <del>platform specific path segment separator. Trailing separators are preserved. <add>`/` on POSIX and either `\` or `/` on Windows), they are replaced by a single <add>instance of the platform specific path segment separator (`/` on POSIX and <add>`\` on Windows). Trailing separators are preserved. <ide> <ide> If the `path` is a zero-length string, `'.'` is returned, representing the <ide> current working directory. <ide> path.normalize('C:\\temp\\\\foo\\bar\\..\\'); <ide> // Returns: 'C:\\temp\\foo\\' <ide> ``` <ide> <add>Since Windows recognizes multiple path separators, both separators will be <add>replaced by instances of the Windows preferred separator (`\`): <add> <add>```js <add>path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); <add>// Returns: 'C:\\temp\\foo\\bar' <add>``` <add> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <ide> ## path.parse(path)
1
Ruby
Ruby
codify the token rules
4a24908fe4e54c8a3c44a44d8190ccf6e0d2cd23
<ide><path>Library/Homebrew/cask/audit.rb <ide> def run! <ide> check_sha256 <ide> check_url <ide> check_generic_artifacts <add> check_token_valid <add> check_token_bad_words <ide> check_token_conflicts <ide> check_download <ide> check_https_availability <ide> def check_token_conflicts <ide> add_warning "possible duplicate, cask token conflicts with Homebrew core formula: #{core_formula_url}" <ide> end <ide> <add> def check_token_valid <add> return unless @strict <add> <add> add_warning "cask token is not lowercase" if cask.token.downcase! <add> <add> add_warning "cask token contains non-ascii characters" unless cask.token.ascii_only? <add> <add> add_warning "cask token + should be replaced by -plus-" if cask.token.include? "+" <add> <add> add_warning "cask token @ should be replaced by -at-" if cask.token.include? "@" <add> <add> add_warning "cask token whitespace should be replaced by hyphens" if cask.token.include? " " <add> <add> add_warning "cask token underscores should be replaced by hyphens" if cask.token.include? "_" <add> <add> if cask.token.match?(/[^a-z0-9\-]/) <add> add_warning "cask token should only contain alphanumeric characters and hyphens" <add> end <add> <add> add_warning "cask token should not contain double hyphens" if cask.token.include? "--" <add> <add> return unless cask.token.end_with?("-") || cask.token.start_with?("-") <add> <add> add_warning "cask token should not have leading or trailing hyphens" <add> end <add> <add> def check_token_bad_words <add> return unless @strict <add> <add> token = cask.token <add> <add> add_warning "cask token contains .app" if token.end_with? ".app" <add> <add> if cask.token.end_with? "alpha", "beta", "release candidate" <add> add_warning "cask token contains version designation" <add> end <add> <add> add_warning "cask token mentions launcher" if token.end_with? "launcher" <add> <add> add_warning "cask token mentions desktop" if token.end_with? "desktop" <add> <add> add_warning "cask token mentions platform" if token.end_with? "mac", "osx", "macos" <add> <add> add_warning "cask token mentions architecture" if token.end_with? "x86", "32_bit", "x86_64", "64_bit" <add> <add> return unless token.end_with?("cocoa", "qt", "gtk", "wx", "java") && !%w[cocoa qt gtk wx java].include?(token) <add> <add> add_warning "cask token mentions framework" <add> end <add> <ide> def core_tap <ide> @core_tap ||= CoreTap.instance <ide> end <ide><path>Library/Homebrew/test/cask/audit_spec.rb <ide> def include_msg?(messages, msg) <ide> let(:cask) { instance_double(Cask::Cask) } <ide> let(:download) { false } <ide> let(:token_conflicts) { false } <add> let(:strict) { false } <ide> let(:fake_system_command) { class_double(SystemCommand) } <ide> let(:audit) { <ide> described_class.new(cask, download: download, <ide> token_conflicts: token_conflicts, <del> command: fake_system_command) <add> command: fake_system_command, <add> strict: strict) <ide> } <ide> <ide> describe "#result" do <ide> def include_msg?(messages, msg) <ide> describe "#run!" do <ide> subject { audit.run! } <ide> <add> def tmp_cask(name, text) <add> path = Pathname.new "#{dir}/#{name}.rb" <add> path.open("w") do |f| <add> f.write text <add> end <add> <add> Cask::CaskLoader.load(path) <add> end <add> <add> let(:dir) { mktmpdir } <ide> let(:cask) { Cask::CaskLoader.load(cask_token) } <ide> <ide> describe "required stanzas" do <ide> def include_msg?(messages, msg) <ide> end <ide> end <ide> <add> describe "token validation" do <add> let(:strict) { true } <add> let(:cask) do <add> tmp_cask cask_token.to_s, <<~RUBY <add> cask '#{cask_token}' do <add> version '1.0' <add> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a' <add> url "https://brew.sh/" <add> name 'Audit' <add> homepage 'https://brew.sh/' <add> app 'Audit.app' <add> end <add> RUBY <add> end <add> <add> context "when cask token is not lowercase" do <add> let(:cask_token) { "Upper-Case" } <add> <add> it "warns about lowercase" do <add> expect(subject).to warn_with(/token is not lowercase/) <add> end <add> end <add> <add> context "when cask token is not ascii" do <add> let(:cask_token) { "ascii⌘" } <add> <add> it "warns about ascii" do <add> expect(subject).to warn_with(/contains non-ascii characters/) <add> end <add> end <add> <add> context "when cask token has +" do <add> let(:cask_token) { "app++" } <add> <add> it "warns about +" do <add> expect(subject).to warn_with(/\+ should be replaced by -plus-/) <add> end <add> end <add> <add> context "when cask token has @" do <add> let(:cask_token) { "app@stuff" } <add> <add> it "warns about +" do <add> expect(subject).to warn_with(/@ should be replaced by -at-/) <add> end <add> end <add> <add> context "when cask token has whitespace" do <add> let(:cask_token) { "app stuff" } <add> <add> it "warns about whitespace" do <add> expect(subject).to warn_with(/whitespace should be replaced by hyphens/) <add> end <add> end <add> <add> context "when cask token has underscores" do <add> let(:cask_token) { "app_stuff" } <add> <add> it "warns about underscores" do <add> expect(subject).to warn_with(/underscores should be replaced by hyphens/) <add> end <add> end <add> <add> context "when cask token has non-alphanumeric characters" do <add> let(:cask_token) { "app(stuff)" } <add> <add> it "warns about non-alphanumeric characters" do <add> expect(subject).to warn_with(/should only contain alphanumeric characters and hyphens/) <add> end <add> end <add> <add> context "when cask token has double hyphens" do <add> let(:cask_token) { "app--stuff" } <add> <add> it "warns about double hyphens" do <add> expect(subject).to warn_with(/should not contain double hyphens/) <add> end <add> end <add> <add> context "when cask token has trailing hyphens" do <add> let(:cask_token) { "app-" } <add> <add> it "warns about trailing hyphens" do <add> expect(subject).to warn_with(/should not have leading or trailing hyphens/) <add> end <add> end <add> end <add> <add> describe "token bad words" do <add> let(:strict) { true } <add> let(:cask) do <add> tmp_cask cask_token.to_s, <<~RUBY <add> cask '#{cask_token}' do <add> version '1.0' <add> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a' <add> url "https://brew.sh/" <add> name 'Audit' <add> homepage 'https://brew.sh/' <add> app 'Audit.app' <add> end <add> RUBY <add> end <add> <add> context "when cask token contains .app" do <add> let(:cask_token) { "token.app" } <add> <add> it "warns about .app" do <add> expect(subject).to warn_with(/token contains .app/) <add> end <add> end <add> <add> context "when cask token contains version" do <add> let(:cask_token) { "token-beta" } <add> <add> it "warns about version in token" do <add> expect(subject).to warn_with(/token contains version/) <add> end <add> end <add> <add> context "when cask token contains launcher" do <add> let(:cask_token) { "token-launcher" } <add> <add> it "warns about launcher in token" do <add> expect(subject).to warn_with(/token mentions launcher/) <add> end <add> end <add> <add> context "when cask token contains desktop" do <add> let(:cask_token) { "token-desktop" } <add> <add> it "warns about desktop in token" do <add> expect(subject).to warn_with(/token mentions desktop/) <add> end <add> end <add> <add> context "when cask token contains platform" do <add> let(:cask_token) { "token-osx" } <add> <add> it "warns about platform in token" do <add> expect(subject).to warn_with(/token mentions platform/) <add> end <add> end <add> <add> context "when cask token contains architecture" do <add> let(:cask_token) { "token-x86" } <add> <add> it "warns about architecture in token" do <add> expect(subject).to warn_with(/token mentions architecture/) <add> end <add> end <add> <add> context "when cask token contains framework" do <add> let(:cask_token) { "token-java" } <add> <add> it "warns about framework in token" do <add> expect(subject).to warn_with(/cask token mentions framework/) <add> end <add> end <add> <add> context "when cask token is framework" do <add> let(:cask_token) { "java" } <add> <add> it "does not warn about framework" do <add> expect(subject).not_to warn_with(/token contains version/) <add> end <add> end <add> end <add> <ide> describe "pkg allow_untrusted checks" do <ide> let(:warning_msg) { "allow_untrusted is not permitted in official Homebrew Cask taps" } <ide>
2
Python
Python
fix mixed precision issue in tf distilbert
a75e31981915cbd072be7c4050a4b58c63ca6d33
<ide><path>src/transformers/modeling_tf_distilbert.py <ide> def gelu(x): <ide> 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) <ide> Also see https://arxiv.org/abs/1606.08415 <ide> """ <del> cdf = 0.5 * (1.0 + tf.math.erf(x / tf.math.sqrt(2.0))) <add> cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.math.sqrt(2.0), dtype=x.dtype))) <ide> return x * cdf <ide> <ide> <ide> def _embedding(self, input_ids, position_ids, inputs_embeds, training=False): <ide> <ide> if inputs_embeds is None: <ide> inputs_embeds = tf.gather(self.word_embeddings, input_ids) <del> position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim) <add> position_embeddings = tf.cast( <add> self.position_embeddings(position_ids), inputs_embeds.dtype <add> ) # (bs, max_seq_length, dim) <ide> <ide> embeddings = inputs_embeds + position_embeddings # (bs, max_seq_length, dim) <ide> embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim) <ide> def unshape(x): <ide> scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, q_length, k_length) <ide> mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen) <ide> # scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, q_length, k_length) <del> scores = scores - 1e30 * (1.0 - mask) <ide> <del> weights = tf.nn.softmax(scores, axis=-1) # (bs, n_heads, qlen, klen) <add> scores_dtype = scores.dtype <add> # calculate `scores` in `tf.float32` to avoid numeric overflow <add> scores = tf.cast(scores, dtype=tf.float32) - 1e30 * (1.0 - tf.cast(mask, dtype=tf.float32)) <add> <add> weights = tf.cast(tf.nn.softmax(scores, axis=-1), dtype=scores_dtype) # (bs, n_heads, qlen, klen) <ide> weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen) <ide> <ide> # Mask heads if we want to
1
Java
Java
resolve cglib core<->transform package cycle
4bb2e2323994791d23649ac9de4faf9b306498a2
<ide><path>spring-core/src/main/java/org/springframework/cglib/core/ClassEmitter.java <ide> */ <ide> package org.springframework.cglib.core; <ide> <del>import org.springframework.cglib.transform.ClassTransformer; <del> <ide> import org.springframework.asm.ClassVisitor; <ide> import org.springframework.asm.FieldVisitor; <ide> import org.springframework.asm.MethodVisitor; <add><path>spring-core/src/main/java/org/springframework/cglib/core/ClassTransformer.java <del><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassTransformer.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.cglib.transform; <add>package org.springframework.cglib.core; <ide> <del>import org.springframework.cglib.core.Constants; <ide> import org.springframework.asm.ClassVisitor; <ide> <ide> public abstract class ClassTransformer extends ClassVisitor { <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/AbstractClassFilterTransformer.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <del>import org.springframework.asm.*; <add>import org.springframework.asm.AnnotationVisitor; <add>import org.springframework.asm.Attribute; <add>import org.springframework.asm.ClassVisitor; <add>import org.springframework.asm.FieldVisitor; <add>import org.springframework.asm.MethodVisitor; <add>import org.springframework.cglib.core.ClassTransformer; <ide> <ide> abstract public class AbstractClassFilterTransformer extends AbstractClassTransformer { <ide> private ClassTransformer pass; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/AbstractClassTransformer.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.cglib.core.ClassTransformer; <ide> import org.springframework.cglib.core.Constants; <ide> import org.springframework.asm.ClassVisitor; <ide> <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassFilterTransformer.java <ide> <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.cglib.core.ClassTransformer; <add> <ide> public class ClassFilterTransformer extends AbstractClassFilterTransformer { <ide> private ClassFilter filter; <ide> <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassTransformerChain.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <del>import org.springframework.asm.*; <add>import org.springframework.asm.ClassVisitor; <add>import org.springframework.asm.MethodVisitor; <add>import org.springframework.cglib.core.ClassTransformer; <ide> <ide> public class ClassTransformerChain extends AbstractClassTransformer { <ide> private ClassTransformer[] chain; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassTransformerFactory.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.cglib.core.ClassTransformer; <add> <ide> public interface ClassTransformerFactory { <ide> ClassTransformer newInstance(); <ide> } <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassTransformerTee.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.cglib.core.ClassTransformer; <ide> import org.springframework.cglib.core.Constants; <ide> import org.springframework.asm.ClassVisitor; <ide> <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/ClassVisitorTee.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.asm.AnnotationVisitor; <add>import org.springframework.asm.Attribute; <add>import org.springframework.asm.ClassVisitor; <add>import org.springframework.asm.FieldVisitor; <add>import org.springframework.asm.MethodVisitor; <add>import org.springframework.asm.TypePath; <ide> import org.springframework.cglib.core.Constants; <del>import org.springframework.asm.*; <ide> <ide> public class ClassVisitorTee extends ClassVisitor { <ide> private ClassVisitor cv1, cv2; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/MethodFilterTransformer.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <del>import org.springframework.asm.*; <add>import org.springframework.asm.ClassVisitor; <add>import org.springframework.asm.MethodVisitor; <add>import org.springframework.cglib.core.ClassTransformer; <ide> <ide> public class MethodFilterTransformer extends AbstractClassTransformer { <ide> private MethodFilter filter; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/MethodVisitorTee.java <ide> */ <ide> package org.springframework.cglib.transform; <ide> <add>import org.springframework.asm.AnnotationVisitor; <add>import org.springframework.asm.Attribute; <add>import org.springframework.asm.Handle; <add>import org.springframework.asm.Label; <add>import org.springframework.asm.MethodVisitor; <add>import org.springframework.asm.TypePath; <ide> import org.springframework.cglib.core.Constants; <del>import org.springframework.asm.*; <ide> <ide> @SuppressWarnings("deprecation") <ide> public class MethodVisitorTee extends MethodVisitor { <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/TransformingClassGenerator.java <ide> <ide> import org.springframework.asm.ClassVisitor; <ide> import org.springframework.cglib.core.ClassGenerator; <add>import org.springframework.cglib.core.ClassTransformer; <ide> <ide> public class TransformingClassGenerator implements ClassGenerator { <ide> private final ClassGenerator gen; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/TransformingClassLoader.java <ide> <ide> import org.springframework.asm.ClassReader; <ide> import org.springframework.cglib.core.ClassGenerator; <add>import org.springframework.cglib.core.ClassTransformer; <ide> <ide> public class TransformingClassLoader extends AbstractClassLoader { <ide> private final ClassTransformerFactory t; <ide><path>spring-core/src/main/java/org/springframework/cglib/transform/impl/UndeclaredThrowableStrategy.java <ide> import org.springframework.cglib.core.DefaultGeneratorStrategy; <ide> import org.springframework.cglib.core.GeneratorStrategy; <ide> import org.springframework.cglib.core.TypeUtils; <del>import org.springframework.cglib.transform.ClassTransformer; <add>import org.springframework.cglib.core.ClassTransformer; <ide> import org.springframework.cglib.transform.MethodFilter; <ide> import org.springframework.cglib.transform.MethodFilterTransformer; <ide> import org.springframework.cglib.transform.TransformingClassGenerator;
14
Javascript
Javascript
handle async href on url change in <=ie9
404b95fe30a1bcd1313adafbd0018578d5b21d3d
<ide><path>src/ng/browser.js <ide> function Browser(window, document, $log, $sniffer) { <ide> <ide> function fireUrlChange() { <ide> newLocation = null; <add> checkUrlChange(); <add> } <add> <add> function checkUrlChange() { <ide> if (lastBrowserUrl == self.url()) return; <ide> <ide> lastBrowserUrl = self.url(); <ide> function Browser(window, document, $log, $sniffer) { <ide> * Needs to be exported to be able to check for changes that have been done in sync, <ide> * as hashchange/popstate events fire in async. <ide> */ <del> self.$$checkUrlChange = fireUrlChange; <add> self.$$checkUrlChange = checkUrlChange; <ide> <ide> ////////////////////////////////////////////////////////////// <ide> // Misc API <ide><path>test/ng/browserSpecs.js <ide> describe('browser', function() { <ide> expect($location.path()).toBe('/someTestHash'); <ide> }); <ide> }); <add> <add> }); <add> <add> describe('integration test with $rootScope', function() { <add> <add> beforeEach(module(function($provide, $locationProvider) { <add> $provide.value('$browser', browser); <add> browser.pollFns = []; <add> })); <add> <add> it('should not interfere with legacy browser url replace behavior', function() { <add> inject(function($rootScope) { <add> var current = fakeWindow.location.href; <add> var newUrl = 'notyet'; <add> sniffer.history = false; <add> browser.url(newUrl, true); <add> expect(browser.url()).toBe(newUrl); <add> $rootScope.$digest(); <add> expect(browser.url()).toBe(newUrl); <add> expect(fakeWindow.location.href).toBe(current); <add> }); <add> }); <add> <ide> }); <ide> <ide> });
2
Ruby
Ruby
convert `plist` test to spec
fe0b68a5ad76bc3a91518f54a97bdd7a9144eda5
<ide><path>Library/Homebrew/cask/spec/plist/parser_spec.rb <add>require "spec_helper" <add> <add>describe Plist do <add> subject { described_class.parse_xml(input) } <add> <add> describe "::parse_xml" do <add> context "given a hdiutil output as input" do <add> let(:input) { <add> <<-EOS.undent <add> <?xml version="1.0" encoding="UTF-8"?> <add> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <add> <plist version="1.0"> <add> <dict> <add> <key>system-entities</key> <add> <array> <add> <dict> <add> <key>content-hint</key> <add> <string>Apple_partition_map</string> <add> <key>dev-entry</key> <add> <string>/dev/disk3s1</string> <add> <key>potentially-mountable</key> <add> <false/> <add> <key>unmapped-content-hint</key> <add> <string>Apple_partition_map</string> <add> </dict> <add> <dict> <add> <key>content-hint</key> <add> <string>Apple_partition_scheme</string> <add> <key>dev-entry</key> <add> <string>/dev/disk3</string> <add> <key>potentially-mountable</key> <add> <false/> <add> <key>unmapped-content-hint</key> <add> <string>Apple_partition_scheme</string> <add> </dict> <add> <dict> <add> <key>content-hint</key> <add> <string>Apple_HFS</string> <add> <key>dev-entry</key> <add> <string>/dev/disk3s2</string> <add> <key>mount-point</key> <add> <string>/private/tmp/dmg.BhfS2g</string> <add> <key>potentially-mountable</key> <add> <true/> <add> <key>unmapped-content-hint</key> <add> <string>Apple_HFS</string> <add> <key>volume-kind</key> <add> <string>hfs</string> <add> </dict> <add> </array> <add> </dict> <add> </plist> <add> EOS <add> } <add> <add> it "successfully parses it" do <add> expect(subject.keys).to eq(["system-entities"]) <add> expect(subject["system-entities"].length).to eq(3) <add> expect(subject["system-entities"].map { |e| e["dev-entry"] }).to eq( <add> %w[ <add> /dev/disk3s1 <add> /dev/disk3 <add> /dev/disk3s2 <add> ] <add> ) <add> end <add> end <add> <add> context "given an empty input" do <add> let(:input) { "" } <add> <add> it { is_expected.to be_nil } <add> end <add> end <add>end <ide><path>Library/Homebrew/cask/test/plist/parser_test.rb <del>require "test_helper" <del> <del>describe Plist do <del> it "parses some hdiutil output okay" do <del> hdiutil_output = <<-EOS.undent <del> <?xml version="1.0" encoding="UTF-8"?> <del> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <del> <plist version="1.0"> <del> <dict> <del> <key>system-entities</key> <del> <array> <del> <dict> <del> <key>content-hint</key> <del> <string>Apple_partition_map</string> <del> <key>dev-entry</key> <del> <string>/dev/disk3s1</string> <del> <key>potentially-mountable</key> <del> <false/> <del> <key>unmapped-content-hint</key> <del> <string>Apple_partition_map</string> <del> </dict> <del> <dict> <del> <key>content-hint</key> <del> <string>Apple_partition_scheme</string> <del> <key>dev-entry</key> <del> <string>/dev/disk3</string> <del> <key>potentially-mountable</key> <del> <false/> <del> <key>unmapped-content-hint</key> <del> <string>Apple_partition_scheme</string> <del> </dict> <del> <dict> <del> <key>content-hint</key> <del> <string>Apple_HFS</string> <del> <key>dev-entry</key> <del> <string>/dev/disk3s2</string> <del> <key>mount-point</key> <del> <string>/private/tmp/dmg.BhfS2g</string> <del> <key>potentially-mountable</key> <del> <true/> <del> <key>unmapped-content-hint</key> <del> <string>Apple_HFS</string> <del> <key>volume-kind</key> <del> <string>hfs</string> <del> </dict> <del> </array> <del> </dict> <del> </plist> <del> EOS <del> <del> parsed = Plist.parse_xml(hdiutil_output) <del> <del> parsed.keys.must_equal ["system-entities"] <del> parsed["system-entities"].length.must_equal 3 <del> parsed["system-entities"].map { |e| e["dev-entry"] }.must_equal %w[ <del> /dev/disk3s1 <del> /dev/disk3 <del> /dev/disk3s2 <del> ] <del> end <del> <del> it "does not choke on empty input" do <del> Plist.parse_xml("").must_equal {} <del> end <del>end
2
Go
Go
remove push by id
db2d875b5e621378baf690d261969712fbfffcfd
<ide><path>graph/push.go <ide> func (s *TagStore) CmdPush(job *engine.Job) engine.Status { <ide> return job.Error(err) <ide> } <ide> <del> img, err := s.graph.Get(repoInfo.LocalName) <del> r, err2 := registry.NewSession(authConfig, registry.HTTPRequestFactory(metaHeaders), endpoint, false) <del> if err2 != nil { <del> return job.Error(err2) <add> r, err := registry.NewSession(authConfig, registry.HTTPRequestFactory(metaHeaders), endpoint, false) <add> if err != nil { <add> return job.Error(err) <ide> } <ide> <ide> if endpoint.Version == registry.APIVersion2 { <ide> func (s *TagStore) CmdPush(job *engine.Job) engine.Status { <ide> } <ide> } <ide> <del> if err != nil { <del> reposLen := 1 <del> if tag == "" { <del> reposLen = len(s.Repositories[repoInfo.LocalName]) <del> } <del> job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", repoInfo.CanonicalName, reposLen)) <del> // If it fails, try to get the repository <del> if localRepo, exists := s.Repositories[repoInfo.LocalName]; exists { <del> if err := s.pushRepository(r, job.Stdout, repoInfo, localRepo, tag, sf); err != nil { <del> return job.Error(err) <del> } <del> return engine.StatusOK <del> } <del> return job.Error(err) <add> reposLen := 1 <add> if tag == "" { <add> reposLen = len(s.Repositories[repoInfo.LocalName]) <ide> } <del> <del> var token []string <del> job.Stdout.Write(sf.FormatStatus("", "The push refers to an image: [%s]", repoInfo.CanonicalName)) <del> if _, err := s.pushImage(r, job.Stdout, img.ID, endpoint.String(), token, sf); err != nil { <add> job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", repoInfo.CanonicalName, reposLen)) <add> // If it fails, try to get the repository <add> localRepo, exists := s.Repositories[repoInfo.LocalName] <add> if !exists { <add> return job.Errorf("Repository does not exist: %s", repoInfo.LocalName) <add> } <add> if err := s.pushRepository(r, job.Stdout, repoInfo, localRepo, tag, sf); err != nil { <ide> return job.Error(err) <ide> } <ide> return engine.StatusOK <add> <ide> }
1
Javascript
Javascript
remove unused import
f91bff6264a0b07174a3c77e8c68500c84a27860
<ide><path>scripts/release-manager/commands/stable-prs.js <ide> 'use strict'; <ide> <ide> const chalk = require('chalk'); <del>const promisify = require('es6-promisify'); <ide> const pify = require('pify'); <ide> <ide> const git = require('./utils/git');
1
Ruby
Ruby
use explicit delegations
26d3e325cb85884504564b8af07dd083fc47d2a8
<ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> module Associations <ide> # is computed directly through SQL and does not trigger by itself the <ide> # instantiation of the actual post records. <ide> class CollectionProxy < Relation <del> delegate :target, :load_target, :loaded?, :to => :@association <add> def initialize(association) #:nodoc: <add> @association = association <add> super association.klass, association.klass.arel_table <add> merge! association.scoped <add> end <add> <add> def target <add> @association.target <add> end <add> <add> def load_target <add> @association.load_target <add> end <add> <add> def loaded? <add> @association.loaded? <add> end <ide> <ide> ## <del> # :method: select <del> # <del> # :call-seq: <del> # select(select = nil) <del> # select(&block) <del> # <ide> # Works in two ways. <ide> # <ide> # *First:* Specify a subset of fields to be selected from the result set. <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook">, <ide> # # #<Pet id: 3, name: "Choo-Choo"> <ide> # # ] <add> def select(select = nil, &block) <add> @association.select(select, &block) <add> end <ide> <ide> ## <del> # :method: find <del> # <del> # :call-seq: <del> # find(*args, &block) <del> # <ide> # Finds an object in the collection responding to the +id+. Uses the same <ide> # rules as +ActiveRecord::Base.find+. Returns +ActiveRecord::RecordNotFound++ <ide> # error if the object can not be found. <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook", person_id: 1>, <ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <ide> # # ] <add> def find(*args, &block) <add> @association.find(*args, &block) <add> end <ide> <ide> ## <del> # :method: first <del> # <del> # :call-seq: <del> # first(limit = nil) <del> # <ide> # Returns the first record, or the first +n+ records, from the collection. <ide> # If the collection is empty, the first form returns +nil+, and the second <ide> # form returns an empty array. <ide> class CollectionProxy < Relation <ide> # another_person_without.pets # => [] <ide> # another_person_without.pets.first # => nil <ide> # another_person_without.pets.first(3) # => [] <add> def first(*args) <add> @association.first(*args) <add> end <ide> <ide> ## <del> # :method: last <del> # <del> # :call-seq: <del> # last(limit = nil) <del> # <ide> # Returns the last record, or the last +n+ records, from the collection. <ide> # If the collection is empty, the first form returns +nil+, and the second <ide> # form returns an empty array. <ide> class CollectionProxy < Relation <ide> # another_person_without.pets # => [] <ide> # another_person_without.pets.last # => nil <ide> # another_person_without.pets.last(3) # => [] <add> def last(*args) <add> @association.last(*args) <add> end <ide> <ide> ## <del> # :method: build <del> # <del> # :call-seq: <del> # build(attributes = {}, options = {}, &block) <del> # <ide> # Returns a new object of the collection type that has been instantiated <ide> # with +attributes+ and linked to this object, but have not yet been saved. <ide> # You can pass an array of attributes hashes, this will return an array <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.size # => 5 # size of the collection <ide> # person.pets.count # => 0 # count from database <add> def build(attributes = {}, options = {}, &block) <add> @association.build(attributes, options, &block) <add> end <ide> <ide> ## <del> # :method: create <del> # <del> # :call-seq: <del> # create(attributes = {}, options = {}, &block) <del> # <ide> # Returns a new object of the collection type that has been instantiated with <ide> # attributes, linked to this object and that has already been saved (if it <ide> # passes the validations). <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook", person_id: 1>, <ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <ide> # # ] <add> def create(attributes = {}, options = {}, &block) <add> @association.create(attributes, options, &block) <add> end <ide> <ide> ## <del> # :method: create! <del> # <del> # :call-seq: <del> # create!(attributes = {}, options = {}, &block) <del> # <ide> # Like +create+, except that if the record is invalid, raises an exception. <ide> # <ide> # class Person <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.create!(name: nil) <ide> # # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank <add> def create!(attributes = {}, options = {}, &block) <add> @association.create!(attributes, options, &block) <add> end <ide> <ide> ## <del> # :method: concat <del> # <del> # :call-seq: <del> # concat(*records) <del> # <ide> # Add one or more records to the collection by setting their foreign keys <ide> # to the association's primary key. Since << flattens its argument list and <ide> # inserts each record, +push+ and +concat+ behave identically. Returns +self+ <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')]) <ide> # person.pets.size # => 5 <add> def concat(*records) <add> @association.concat(*records) <add> end <ide> <ide> ## <del> # :method: replace <del> # <del> # :call-seq: <del> # replace(other_array) <del> # <ide> # Replace this collection with +other_array+. This will perform a diff <ide> # and delete/add only records that have changed. <ide> # <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.replace(["doo", "ggie", "gaga"]) <ide> # # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String <add> def replace(other_array) <add> @association.replace(other_array) <add> end <ide> <ide> ## <del> # :method: delete_all <del> # <del> # :call-seq: <del> # delete_all() <del> # <ide> # Deletes all the records from the collection. For +has_many+ associations, <ide> # the deletion is done according to the strategy specified by the <tt>:dependent</tt> <ide> # option. Returns an array with the deleted records. <ide> class CollectionProxy < Relation <ide> # <ide> # Pet.find(1, 2, 3) <ide> # # => ActiveRecord::RecordNotFound <add> def delete_all <add> @association.delete_all <add> end <ide> <ide> ## <del> # :method: destroy_all <del> # <del> # :call-seq: <del> # destroy_all() <del> # <ide> # Deletes the records of the collection directly from the database. <ide> # This will _always_ remove the records ignoring the +:dependent+ <ide> # option. <ide> class CollectionProxy < Relation <ide> # person.pets # => [] <ide> # <ide> # Pet.find(1) # => Couldn't find Pet with id=1 <add> def destroy_all <add> @association.destroy_all <add> end <ide> <ide> ## <del> # :method: delete <del> # <del> # :call-seq: <del> # delete(*records) <del> # delete(*fixnum_ids) <del> # delete(*string_ids) <del> # <ide> # Deletes the +records+ supplied and removes them from the collection. For <ide> # +has_many+ associations, the deletion is done according to the strategy <ide> # specified by the <tt>:dependent</tt> option. Returns an array with the <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook", person_id: 1>, <ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <ide> # # ] <add> def delete(*records) <add> @association.delete(*records) <add> end <ide> <ide> ## <del> # :method: destroy <del> # <del> # :call-seq: <del> # destroy(*records) <del> # <ide> # Destroys the +records+ supplied and removes them from the collection. <ide> # This method will _always_ remove record from the database ignoring <ide> # the +:dependent+ option. Returns an array with the removed records. <ide> class CollectionProxy < Relation <ide> # person.pets # => [] <ide> # <ide> # Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6) <add> def destroy(*records) <add> @association.destroy(*records) <add> end <ide> <ide> ## <del> # :method: uniq <del> # <del> # :call-seq: <del> # uniq() <del> # <ide> # Specifies whether the records should be unique or not. <ide> # <ide> # class Person < ActiveRecord::Base <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.select(:name).uniq <ide> # # => [#<Pet name: "Fancy-Fancy">] <add> def uniq <add> @association.uniq <add> end <ide> <ide> ## <del> # :method: count <del> # <del> # :call-seq: <del> # count() <del> # <ide> # Count all records using SQL. <ide> # <ide> # class Person < ActiveRecord::Base <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook", person_id: 1>, <ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <ide> # # ] <add> def count(column_name = nil, options = {}) <add> @association.count(column_name, options) <add> end <ide> <ide> ## <del> # :method: size <del> # <del> # :call-seq: <del> # size() <del> # <ide> # Returns the size of the collection. If the collection hasn't been loaded, <ide> # it executes a <tt>SELECT COUNT(*)</tt> query. <ide> # <ide> class CollectionProxy < Relation <ide> # person.pets.size # => 3 <ide> # # Because the collection is already loaded, this will behave like <ide> # # collection.size and no SQL count query is executed. <add> def size <add> @association.size <add> end <ide> <ide> ## <del> # :method: length <del> # <del> # :call-seq: <del> # length() <del> # <ide> # Returns the size of the collection calling +size+ on the target. <ide> # If the collection has been already loaded, +length+ and +size+ are <ide> # equivalent. <ide> class CollectionProxy < Relation <ide> # # #<Pet id: 2, name: "Spook", person_id: 1>, <ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <ide> # # ] <add> def length <add> @association.length <add> end <ide> <ide> ## <del> # :method: empty? <del> # <ide> # Returns +true+ if the collection is empty. <ide> # <ide> # class Person < ActiveRecord::Base <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.count # => 0 <ide> # person.pets.empty? # => true <add> def empty? <add> @association.empty? <add> end <ide> <ide> ## <del> # :method: any? <del> # <del> # :call-seq: <del> # any? <del> # any?{|item| block} <del> # <ide> # Returns +true+ if the collection is not empty. <ide> # <ide> # class Person < ActiveRecord::Base <ide> class CollectionProxy < Relation <ide> # pet.group == 'dogs' <ide> # end <ide> # # => true <add> def any?(&block) <add> @association.any?(&block) <add> end <ide> <ide> ## <del> # :method: many? <del> # <del> # :call-seq: <del> # many? <del> # many?{|item| block} <del> # <ide> # Returns true if the collection has more than one record. <ide> # Equivalent to <tt>collection.size > 1</tt>. <ide> # <ide> class CollectionProxy < Relation <ide> # pet.group == 'cats' <ide> # end <ide> # # => true <add> def many?(&block) <add> @association.many?(&block) <add> end <ide> <ide> ## <del> # :method: include? <del> # <del> # :call-seq: <del> # include?(record) <del> # <ide> # Returns +true+ if the given object is present in the collection. <ide> # <ide> # class Person < ActiveRecord::Base <ide> class CollectionProxy < Relation <ide> # <ide> # person.pets.include?(Pet.find(20)) # => true <ide> # person.pets.include?(Pet.find(21)) # => false <del> delegate :select, :find, :first, :last, <del> :build, :create, :create!, <del> :concat, :replace, :delete_all, :destroy_all, :delete, :destroy, :uniq, <del> :sum, :count, :size, :length, :empty?, <del> :any?, :many?, :include?, <del> :to => :@association <del> <del> def initialize(association) #:nodoc: <del> @association = association <del> super association.klass, association.klass.arel_table <del> merge! association.scoped <add> def include?(record) <add> @association.include?(record) <ide> end <ide> <ide> alias_method :new, :build
1
Ruby
Ruby
change time.zone= docs
3a29bfae2cbb956e469942ed1d4ea8c702085a1a
<ide><path>activesupport/lib/active_support/core_ext/time/zones.rb <ide> def zone <ide> # * A TZInfo::Timezone object. <ide> # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). <ide> # <del> # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt> <del> # just needs to return a string identifying the user's preferred TimeZone: <add> # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done. <add> # <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone: <ide> # <ide> # class ApplicationController < ActionController::Base <del> # before_filter :set_time_zone <add> # around_filter :set_time_zone <ide> # <ide> # def set_time_zone <del> # Time.zone = current_user.time_zone <add> # old_time_zone = Time.zone <add> # Time.zone = current_user.time_zone if logged_in? <add> # yield <add> # ensure <add> # Time.zone = old_time_zone <ide> # end <ide> # end <ide> def zone=(time_zone)
1
Go
Go
construct used device id map from device hash map
6b8b4feaa165af630dd33423f0538a0b987703ae
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) lookupDeviceWithLock(hash string) (*devInfo, error) { <ide> return info, err <ide> } <ide> <add>// This function relies on that device hash map has been loaded in advance. <add>// Should be called with devices.Lock() held. <add>func (devices *DeviceSet) constructDeviceIDMap() { <add> logrus.Debugf("[deviceset] constructDeviceIDMap()") <add> defer logrus.Debugf("[deviceset] constructDeviceIDMap() END") <add> <add> for _, info := range devices.Devices { <add> devices.markDeviceIDUsed(info.DeviceID) <add> logrus.Debugf("Added deviceId=%d to DeviceIdMap", info.DeviceID) <add> } <add>} <add> <ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) error { <ide> <ide> // Skip some of the meta files which are not device files. <ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) <ide> hash = "" <ide> } <ide> <del> dinfo := devices.loadMetadata(hash) <del> if dinfo == nil { <del> return fmt.Errorf("Error loading device metadata file %s", hash) <add> if _, err := devices.lookupDevice(hash); err != nil { <add> return fmt.Errorf("Error looking up device %s:%v", hash, err) <ide> } <ide> <del> devices.markDeviceIDUsed(dinfo.DeviceID) <del> logrus.Debugf("Added deviceID=%d to DeviceIDMap", dinfo.DeviceID) <ide> return nil <ide> } <ide> <del>func (devices *DeviceSet) constructDeviceIDMap() error { <del> logrus.Debugf("[deviceset] constructDeviceIDMap()") <del> defer logrus.Debugf("[deviceset] constructDeviceIDMap() END") <add>func (devices *DeviceSet) loadDeviceFilesOnStart() error { <add> logrus.Debugf("[deviceset] loadDeviceFilesOnStart()") <add> defer logrus.Debugf("[deviceset] loadDeviceFilesOnStart() END") <ide> <ide> var scan = func(path string, info os.FileInfo, err error) error { <ide> if err != nil { <ide> func (devices *DeviceSet) initMetaData() error { <ide> <ide> devices.TransactionID = transactionID <ide> <del> if err := devices.constructDeviceIDMap(); err != nil { <del> return err <add> if err := devices.loadDeviceFilesOnStart(); err != nil { <add> return fmt.Errorf("devmapper: Failed to load device files:%v", err) <ide> } <ide> <add> devices.constructDeviceIDMap() <add> <ide> if err := devices.processPendingTransaction(); err != nil { <ide> return err <ide> }
1
Ruby
Ruby
fix failing request test
4e7d94ea2ca9f368ab929d0bcbd7565f80659ad6
<ide><path>actionpack/test/dispatch/request_test.rb <ide> def url_for(options = {}) <ide> 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 67.205.106.73' <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '67.205.106.73, 10.0.0.1, 9.9.9.9, 3.4.5.6' <ide> assert_equal '10.0.0.1', request.remote_ip <ide> end <ide>
1
Text
Text
add hotfix help
751c7e0f003e27d7c862ff91ca85f300bfcbf2cc
<ide><path>hack/RELEASE-CHECKLIST.md <ide> git fetch origin <ide> git branch -D release || true <ide> git checkout --track origin/release <ide> git checkout -b bump_$VERSION <add>``` <add> <add>If it's a regular release, we usually merge master <add>```bash <ide> git merge origin/master <ide> ``` <add>Otherwise, if it is a hotfix release, we cherry-pick only the commits we want <add>```bash <add>#get the commits ids we want to cherry-pick <add>git log <add>#cherry-pick the commits starting from the oldest one, without including merge commits <add>git cherry-pick <commit-id> <add>git cherry-pick <commit-id> <add>... <add>``` <ide> <ide> ### 2. Update CHANGELOG.md <ide>
1
Python
Python
remove deprecated applications adapter code
2d2fb47e321faa032c98e92d34e6215b6026f1f0
<ide><path>keras/applications/__init__.py <ide> <ide> import keras_applications <ide> <del>if not hasattr(keras_applications, 'get_submodules_from_kwargs'): <del> keras_applications.set_keras_submodules( <del> backend=backend, <del> layers=layers, <del> models=models, <del> utils=utils) <del> <ide> <ide> def keras_modules_injection(base_fun): <ide> <ide> def wrapper(*args, **kwargs): <del> if hasattr(keras_applications, 'get_submodules_from_kwargs'): <del> kwargs['backend'] = backend <del> kwargs['layers'] = layers <del> kwargs['models'] = models <del> kwargs['utils'] = utils <add> kwargs['backend'] = backend <add> kwargs['layers'] = layers <add> kwargs['models'] = models <add> kwargs['utils'] = utils <ide> return base_fun(*args, **kwargs) <ide> <ide> return wrapper <ide> def wrapper(*args, **kwargs): <ide> from .nasnet import NASNetMobile, NASNetLarge <ide> from .resnet import ResNet101, ResNet152 <ide> from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2 <del>from .resnext import ResNeXt50, ResNeXt101
1
Go
Go
fix output in the login command
9740102990b059d014fad5f8652306cf7ff62d94
<ide><path>commands.go <ide> import ( <ide> "sync" <ide> "text/tabwriter" <ide> "time" <add> "unicode" <ide> ) <ide> <ide> const VERSION = "0.1.0" <ide> func (srv *Server) Help() string { <ide> <ide> // 'docker login': login / register a user to registry service. <ide> func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout io.Writer, args ...string) error { <add> // Read a line on raw terminal with support for simple backspace <add> // sequences and echo. <add> // <add> // This function is necessary because the login command must be done a <add> // raw terminal for two reasons: <add> // - we have to read a password (without echoing it); <add> // - the rcli "protocol" only supports cannonical and raw modes and you <add> // can't tune it once the command as been started. <add> var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string { <add> char := make([]byte, 1) <add> buffer := make([]byte, 64) <add> var i = 0 <add> for i < len(buffer) { <add> n, err := stdin.Read(char) <add> if n > 0 { <add> if char[0] == '\r' || char[0] == '\n' { <add> stdout.Write([]byte{'\n'}) <add> break <add> } else if char[0] == 127 || char[0] == '\b' { <add> if i > 0 { <add> if echo { <add> stdout.Write([]byte{'\b', ' ', '\b'}) <add> } <add> i-- <add> } <add> } else if !unicode.IsSpace(rune(char[0])) && <add> !unicode.IsControl(rune(char[0])) { <add> if echo { <add> stdout.Write(char) <add> } <add> buffer[i] = char[0] <add> i++ <add> } <add> } <add> if err != nil { <add> if err != io.EOF { <add> fmt.Fprint(stdout, "Read error: %v\n", err) <add> } <add> break <add> } <add> } <add> return string(buffer[:i]) <add> } <add> var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string { <add> return readStringOnRawTerminal(stdin, stdout, true) <add> } <add> var readString = func(stdin io.Reader, stdout io.Writer) string { <add> return readStringOnRawTerminal(stdin, stdout, false) <add> } <add> <ide> cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <add> <ide> var username string <ide> var password string <ide> var email string <ide> <ide> fmt.Fprint(stdout, "Username (", srv.runtime.authConfig.Username, "): ") <del> fmt.Fscanf(stdin, "%s", &username) <add> username = readAndEchoString(stdin, stdout) <ide> if username == "" { <ide> username = srv.runtime.authConfig.Username <ide> } <ide> if username != srv.runtime.authConfig.Username { <ide> fmt.Fprint(stdout, "Password: ") <del> fmt.Fscanf(stdin, "%s", &password) <add> password = readString(stdin, stdout) <ide> <ide> if password == "" { <ide> return errors.New("Error : Password Required\n") <ide> } <ide> <ide> fmt.Fprint(stdout, "Email (", srv.runtime.authConfig.Email, "): ") <del> fmt.Fscanf(stdin, "%s", &email) <add> email = readAndEchoString(stdin, stdout) <ide> if email == "" { <ide> email = srv.runtime.authConfig.Email <ide> }
1
PHP
PHP
update doc block
5394b1d537dfbee9e374f164d279389b0fe68f51
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function method_field($method) <ide> * @param string $path <ide> * @return \Illuminate\Support\HtmlString <ide> * <del> * @throws \InvalidArgumentException <add> * @throws \Exception <ide> */ <ide> function mix($path) <ide> {
1
Text
Text
remove unused import from docs example
b7438184308aac6a5c208a16e11bdeca12b4ae52
<ide><path>docs/tutorial/2-requests-and-responses.md <ide> and <ide> <ide> Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs. <ide> <del> from django.conf.urls import patterns, url <add> from django.conf.urls import url <ide> from rest_framework.urlpatterns import format_suffix_patterns <ide> from snippets import views <ide>
1
Python
Python
set version to v2.1.0a7.dev1
2ef227c313a4fe6c2dbd2e2c1728d299be02c93f
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a7.dev9" <add>__version__ = "2.1.0a7.dev10" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Python
Python
add failing test for mismatch of key type
e6e0de242ba6f22e0bc3792db4dc64d6b6053d16
<ide><path>numpy/lib/tests/test_recfunctions.py <ide> import numpy.ma as ma <ide> from numpy.ma.mrecords import MaskedRecords <ide> from numpy.ma.testutils import assert_equal <del>from numpy.testing import TestCase, run_module_suite, assert_, assert_raises <add>from numpy.testing import ( <add> TestCase, run_module_suite, assert_, assert_raises, dec <add>) <ide> from numpy.lib.recfunctions import ( <ide> drop_fields, rename_fields, get_fieldstructure, recursive_fill_fields, <ide> find_duplicates, merge_arrays, append_fields, stack_arrays, join_by <ide> def test_duplicate_keys(self): <ide> b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')]) <ide> assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b) <ide> <add> @dec.knownfailureif(True) <add> def test_same_name_different_dtypes_key(self): <add> a_dtype = np.dtype([('key', 'S5'), ('value', '<f4')]) <add> b_dtype = np.dtype([('key', 'S10'), ('value', '<f4')]) <add> expected_dtype = np.dtype([ <add> ('key', 'S10'), ('value1', '<f4'), ('value2', '<f4')]) <add> <add> a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype) <add> b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype) <add> res = join_by('key', a, b) <add> <add> assert_equal(res.dtype, expected_dtype) <add> <ide> def test_same_name_different_dtypes(self): <ide> # gh-9338 <ide> a_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])
1
Javascript
Javascript
fix typos on react-devtools comments
206d61f72214e8ae5b935f0bf8628491cb7f0797
<ide><path>packages/react-devtools-shared/src/backend/console.js <ide> export function dangerous_setTargetConsoleForTesting( <ide> <ide> // v16 renderers should use this method to inject internals necessary to generate a component stack. <ide> // These internals will be used if the console is patched. <del>// Injecting them separately allows the console to easily be patched or unpacted later (at runtime). <add>// Injecting them separately allows the console to easily be patched or un-patched later (at runtime). <ide> export function registerRenderer(renderer: ReactRenderer): void { <ide> const {getCurrentFiber, findFiberByHostInstance, version} = renderer; <ide> <ide><path>packages/react-devtools-shared/src/backend/describeComponentFrame.js <ide> // This file was forked from the React GitHub repo: <ide> // https://raw.githubusercontent.com/facebook/react/master/packages/shared/describeComponentFrame.js <ide> // <del>// It has been modified sligthly to add a zero width space as commented below. <add>// It has been modified slightly to add a zero width space as commented below. <ide> <ide> const BEFORE_SLASH_RE = /^(.*)[\\/]/; <ide> <ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/AutoSizeInput.js <ide> export default function AutoSizeInput({ <ide> } <ide> }; <ide> <del> // Copy text stlyes from <input> to hidden sizing <div> <add> // Copy text styles from <input> to hidden sizing <div> <ide> useLayoutEffect(() => { <ide> if ( <ide> typeof window.getComputedStyle !== 'function' || <ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js <ide> function NativeStyleContextController({children}: Props) { <ide> } else { <ide> resource.write(element, styleAndLayout); <ide> <del> // Schedule update with React if the curently-selected element has been invalidated. <add> // Schedule update with React if the currently-selected element has been invalidated. <ide> if (id === selectedElementID) { <ide> setCurrentStyleAndLayout(styleAndLayout); <ide> } <ide><path>packages/react-devtools-shared/src/devtools/views/DevTools.js <ide> */ <ide> <ide> // Reach styles need to come before any component styles. <del>// This makes overridding the styles simpler. <add>// This makes overriding the styles simpler. <ide> import '@reach/menu-button/styles.css'; <ide> import '@reach/tooltip/styles.css'; <ide>
5
PHP
PHP
remove cachehelper and related features
38efb0790f6cb5aa3000a52376042534c4871a51
<ide><path>src/Controller/Controller.php <ide> class Controller implements EventListener { <ide> */ <ide> protected $_validViewOptions = [ <ide> 'viewVars', 'autoLayout', 'helpers', 'view', 'layout', 'name', 'theme', 'layoutPath', <del> 'viewPath', 'plugin', 'passedArgs', 'cacheAction' <add> 'viewPath', 'plugin', 'passedArgs' <ide> ]; <ide> <ide> /** <ide><path>src/Routing/Filter/CacheFilter.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 2.2.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Routing\Filter; <del> <del>use Cake\Core\Configure; <del>use Cake\Event\Event; <del>use Cake\Routing\DispatcherFilter; <del>use Cake\Utility\Inflector; <del>use Cake\View\View; <del> <del>/** <del> * This filter will check whether the response was previously cached in the file system <del> * and served it back to the client if appropriate. <del> * <del> */ <del>class CacheFilter extends DispatcherFilter { <del> <del>/** <del> * Default priority for all methods in this filter <del> * This filter should run before the request gets parsed by router <del> * <del> * @var int <del> */ <del> protected $_priority = 9; <del> <del>/** <del> * Checks whether the response was cached and set the body accordingly. <del> * <del> * @param \Cake\Event\Event $event containing the request and response object <del> * @return \Cake\Network\Response with cached content if found, null otherwise <del> */ <del> public function beforeDispatch(Event $event) { <del> if (Configure::read('Cache.check') !== true) { <del> return; <del> } <del> <del> $path = $event->data['request']->here(); <del> if ($path === '/') { <del> $path = 'home'; <del> } <del> $prefix = Configure::read('Cache.viewPrefix'); <del> if ($prefix) { <del> $path = $prefix . '_' . $path; <del> } <del> $path = strtolower(Inflector::slug($path)); <del> <del> $filename = CACHE . 'views/' . $path . '.php'; <del> <del> if (!file_exists($filename)) { <del> $filename = CACHE . 'views/' . $path . '_index.php'; <del> } <del> if (file_exists($filename)) { <del> $controller = null; <del> $view = new View($controller); <del> $view->response = $event->data['response']; <del> $result = $view->renderCache($filename, microtime(true)); <del> if ($result !== false) { <del> $event->stopPropagation(); <del> $event->data['response']->body($result); <del> return $event->data['response']; <del> } <del> } <del> } <del> <del>} <ide><path>src/View/Helper/CacheHelper.php <del><?php <del>/** <del> * CacheHelper helps create full page view caching. <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 1.0.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\View\Helper; <del> <del>use Cake\Core\Configure; <del>use Cake\Event\Event; <del>use Cake\Utility\Inflector; <del>use Cake\View\Helper; <del> <del>/** <del> * CacheHelper helps create full page view caching. <del> * <del> * When using CacheHelper you don't call any of its methods, they are all automatically <del> * called by View, and use the $cacheAction settings set in the controller. <del> * <del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html <del> */ <del>class CacheHelper extends Helper { <del> <del>/** <del> * Array of strings replaced in cached views. <del> * The strings are found between `<!--nocache--><!--/nocache-->` in views <del> * <del> * @var array <del> */ <del> protected $_replace = array(); <del> <del>/** <del> * Array of string that are replace with there var replace above. <del> * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views <del> * <del> * @var array <del> */ <del> protected $_match = array(); <del> <del>/** <del> * Counter used for counting nocache section tags. <del> * <del> * @var int <del> */ <del> protected $_counter = 0; <del> <del>/** <del> * Is CacheHelper enabled? should files + output be parsed. <del> * <del> * @return bool <del> */ <del> protected function _enabled() { <del> return $this->_View->cacheAction && (Configure::read('Cache.check') === true); <del> } <del> <del>/** <del> * Parses the view file and stores content for cache file building. <del> * <del> * @param \Cake\Event\Event $event The event instance. <del> * @param string $viewFile View file name. <del> * @param string $output The output for the file. <del> * @return string Updated content. <del> */ <del> public function afterRenderFile(Event $event, $viewFile, $output) { <del> if ($this->_enabled()) { <del> return $this->_parseContent($viewFile, $output); <del> } <del> } <del> <del>/** <del> * Parses the layout file and stores content for cache file building. <del> * <del> * @param \Cake\Event\Event $event The event instance. <del> * @param string $layoutFile Layout file name. <del> * @return void <del> */ <del> public function afterLayout(Event $event, $layoutFile) { <del> if ($this->_enabled()) { <del> $this->_View->assign( <del> 'content', <del> $this->cache($layoutFile, $this->_View->fetch('content')) <del> ); <del> } <del> $this->_View->assign( <del> 'content', <del> preg_replace('/<!--\/?nocache-->/', '', $this->_View->fetch('content')) <del> ); <del> } <del> <del>/** <del> * Parse a file + output. Matches nocache tags between the current output and the current file <del> * stores a reference of the file, so the generated can be swapped back with the file contents when <del> * writing the cache file. <del> * <del> * @param string $file The filename to process. <del> * @param string $out The output for the file. <del> * @return string Updated content. <del> */ <del> protected function _parseContent($file, $out) { <del> $out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out); <del> $this->_parseFile($file, $out); <del> return $out; <del> } <del> <del>/** <del> * Main method used to cache a view <del> * <del> * @param string $file File to cache <del> * @param string $out output to cache <del> * @return string view output <del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html <del> */ <del> public function cache($file, $out) { <del> $cacheTime = 0; <del> $useCallbacks = false; <del> $cacheAction = $this->_View->cacheAction; <del> <del> if (is_array($cacheAction)) { <del> $keys = array_keys($cacheAction); <del> $index = null; <del> <del> foreach ($keys as $action) { <del> if ($action == $this->request->params['action']) { <del> $index = $action; <del> break; <del> } <del> } <del> <del> if (!isset($index) && $this->request->params['action'] === 'index') { <del> $index = 'index'; <del> } <del> <del> $options = $cacheAction; <del> if (isset($cacheAction[$index])) { <del> if (is_array($cacheAction[$index])) { <del> $options = $cacheAction[$index] + array('duration' => 0, 'callbacks' => false); <del> } else { <del> $cacheTime = $cacheAction[$index]; <del> } <del> } <del> if (isset($options['duration'])) { <del> $cacheTime = $options['duration']; <del> } <del> if (isset($options['callbacks'])) { <del> $useCallbacks = $options['callbacks']; <del> } <del> } else { <del> $cacheTime = $cacheAction; <del> } <del> <del> if ($cacheTime && $cacheTime > 0) { <del> $cached = $this->_parseOutput($out); <del> try { <del> $this->_writeFile($cached, $cacheTime, $useCallbacks); <del> } catch (Exception $e) { <del> $message = sprintf( <del> 'Unable to write view cache file: "%s" for "%s"', <del> $e->getMessage(), <del> $this->request->here <del> ); <del> $this->log($message, 'error'); <del> } <del> $out = $this->_stripTags($out); <del> } <del> return $out; <del> } <del> <del>/** <del> * Parse file searching for no cache tags <del> * <del> * @param string $file The filename that needs to be parsed. <del> * @param string $cache The cached content <del> * @return void <del> */ <del> protected function _parseFile($file, $cache) { <del> if (is_file($file)) { <del> $file = file_get_contents($file); <del> } elseif ($file = fileExistsInPath($file)) { <del> $file = file_get_contents($file); <del> } <del> preg_match_all( <del> '/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', <del> $cache, <del> $outputResult, <del> PREG_PATTERN_ORDER <del> ); <del> preg_match_all( <del> '/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', <del> $file, <del> $fileResult, <del> PREG_PATTERN_ORDER <del> ); <del> $fileResult = $fileResult[0]; <del> $outputResult = $outputResult[0]; <del> <del> if (!empty($this->_replace)) { <del> foreach ($outputResult as $i => $element) { <del> $index = array_search($element, $this->_match); <del> if ($index !== false) { <del> unset($outputResult[$i]); <del> } <del> } <del> $outputResult = array_values($outputResult); <del> } <del> <del> if (!empty($fileResult)) { <del> $i = 0; <del> foreach ($fileResult as $cacheBlock) { <del> if (isset($outputResult[$i])) { <del> $this->_replace[] = $cacheBlock; <del> $this->_match[] = $outputResult[$i]; <del> } <del> $i++; <del> } <del> } <del> } <del> <del>/** <del> * Munges the output from a view with cache tags, and numbers the sections. <del> * This helps solve issues with empty/duplicate content. <del> * <del> * @return string The content with cake:nocache tags replaced. <del> */ <del> protected function _replaceSection() { <del> $this->_counter += 1; <del> return sprintf('<!--nocache:%03d-->', $this->_counter); <del> } <del> <del>/** <del> * Strip cake:nocache tags from a string. Since View::render() <del> * only removes un-numbered nocache tags, remove all the numbered ones. <del> * This is the complement to _replaceSection. <del> * <del> * @param string $content String to remove tags from. <del> * @return string String with tags removed. <del> */ <del> protected function _stripTags($content) { <del> return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content); <del> } <del> <del>/** <del> * Parse the output and replace cache tags <del> * <del> * @param string $cache Output to replace content in. <del> * @return string with all replacements made to <!--nocache--><!--nocache--> <del> */ <del> protected function _parseOutput($cache) { <del> $count = 0; <del> if (!empty($this->_match)) { <del> foreach ($this->_match as $found) { <del> $original = $cache; <del> $length = strlen($found); <del> $position = 0; <del> <del> for ($i = 1; $i <= 1; $i++) { <del> $position = strpos($cache, $found, $position); <del> <del> if ($position !== false) { <del> $cache = substr($original, 0, $position); <del> $cache .= $this->_replace[$count]; <del> $cache .= substr($original, $position + $length); <del> } else { <del> break; <del> } <del> } <del> $count++; <del> } <del> return $cache; <del> } <del> return $cache; <del> } <del> <del>/** <del> * Write a cached version of the file <del> * <del> * @param string $content view content to write to a cache file. <del> * @param string $timestamp Duration to set for cache file. <del> * @param bool $useCallbacks Whether to include statements in cached file which <del> * run callbacks. <del> * @return bool success of caching view. <del> */ <del> protected function _writeFile($content, $timestamp, $useCallbacks = false) { <del> $now = time(); <del> <del> if (is_numeric($timestamp)) { <del> $cacheTime = $now + $timestamp; <del> } else { <del> $cacheTime = strtotime($timestamp, $now); <del> } <del> $path = $this->request->here(); <del> if ($path === '/') { <del> $path = 'home'; <del> } <del> $prefix = Configure::read('Cache.viewPrefix'); <del> if ($prefix) { <del> $path = $prefix . '_' . $path; <del> } <del> $cache = strtolower(Inflector::slug($path)); <del> <del> if (empty($cache)) { <del> return; <del> } <del> $cache = $cache . '.php'; <del> $file = '<!--cachetime:' . $cacheTime . '--><?php'; <del> $file .= " <del> use Cake\\Core\\Configure; <del> use Cake\\Routing\\Router; <del> "; <del> $namespace = Configure::read('App.namespace'); <del> <del> if (empty($this->_View->plugin)) { <del> $file .= " <del> use $namespace\\Controller\\{$this->_View->name}Controller; <del> "; <del> } else { <del> $file .= " <del> use {$this->_View->plugin}\\Controller\\{$this->_View->name}Controller; <del> "; <del> } <del> <del> $file .= ' <del> $request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\')); <del> $response->type(\'' . $this->_View->response->type() . '\'); <del> $controller = new ' . $this->_View->name . 'Controller($request, $response); <del> $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\'; <del> $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\')); <del> $controller->layout = $this->layout = \'' . $this->_View->layout . '\'; <del> $controller->theme = $this->theme = \'' . $this->_View->theme . '\'; <del> $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\')); <del> Router::setRequestInfo($controller->request); <del> $this->request = $request;'; <del> <del> if ($useCallbacks) { <del> $file .= ' <del> $controller->constructClasses(); <del> $controller->startupProcess();'; <del> } <del> <del> $file .= ' <del> $this->viewVars = $controller->viewVars; <del> $this->loadHelpers(); <del> extract($this->viewVars, EXTR_SKIP); <del> ?>'; <del> $content = preg_replace("/(<\\?xml)/", "<?= '$1'; ?>", $content); <del> $file .= $content; <del> return cache('views/' . $cache, $file, $timestamp); <del> } <del> <del>} <ide><path>src/View/View.php <ide> class View { <ide> */ <ide> public $theme = null; <ide> <del>/** <del> * Used to define methods a controller that will be cached. To cache a <del> * single action, the value is set to an array containing keys that match <del> * action names and values that denote cache expiration times (in seconds). <del> * <del> * Example: <del> * <del> * {{{ <del> * public $cacheAction = array( <del> * 'view/23/' => 21600, <del> * 'recalled/' => 86400 <del> * ); <del> * }}} <del> * <del> * $cacheAction can also be set to a strtotime() compatible string. This <del> * marks all the actions in the controller for view caching. <del> * <del> * @var mixed <del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html#additional-configuration-options <del> */ <del> public $cacheAction = false; <del> <ide> /** <ide> * True when the view has been rendered. <ide> * <ide> class View { <ide> */ <ide> protected $_passedVars = array( <ide> 'viewVars', 'autoLayout', 'helpers', 'view', 'layout', 'name', 'theme', <del> 'layoutPath', 'viewPath', 'plugin', 'passedArgs', 'cacheAction' <add> 'layoutPath', 'viewPath', 'plugin', 'passedArgs' <ide> ); <ide> <ide> /** <ide> public function renderLayout($content, $layout = null) { <ide> return $this->Blocks->get('content'); <ide> } <ide> <del>/** <del> * Render cached view. Works in concert with CacheHelper and Dispatcher to <del> * render cached view files. <del> * <del> * @param string $filename the cache file to include <del> * @param string $timeStart the page render start time <del> * @return bool Success of rendering the cached file. <del> */ <del> public function renderCache($filename, $timeStart) { <del> $response = $this->response; <del> ob_start(); <del> include $filename; <del> <del> $type = $response->mapType($response->type()); <del> if (Configure::read('debug') && $type === 'html') { <del> echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->"; <del> } <del> $out = ob_get_clean(); <del> <del> if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) { <del> if (time() >= $match['1']) { <del> //@codingStandardsIgnoreStart <del> @unlink($filename); <del> //@codingStandardsIgnoreEnd <del> unset($out); <del> return false; <del> } <del> return substr($out, strlen($match[0])); <del> } <del> } <del> <ide> /** <ide> * Returns a list of variables available in the current View context <ide> * <ide><path>tests/TestCase/Routing/Filter/CacheFilterTest.php <del><?php <del>/** <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since 3.0.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Routing\Filter; <del> <del>use Cake\Cache\Cache; <del>use Cake\Core\Configure; <del>use Cake\Network\Request; <del>use Cake\Network\Response; <del>use Cake\Routing\Dispatcher; <del>use Cake\Routing\Filter\CacheFilter; <del>use Cake\Routing\Filter\ControllerFactoryFilter; <del>use Cake\Routing\Filter\RoutingFilter; <del>use Cake\Routing\Router; <del>use Cake\TestSuite\TestCase; <del>use Cake\Utility\Inflector; <del> <del>/** <del> * CacheFilterTest class <del> * <del> */ <del>class CacheFilterTest extends TestCase { <del> <del>/** <del> * setUp method <del> * <del> * @return void <del> */ <del> public function setUp() { <del> parent::setUp(); <del> $_GET = []; <del> <del> Configure::write('App.base', false); <del> Configure::write('App.baseUrl', false); <del> Configure::write('App.dir', 'app'); <del> Configure::write('App.webroot', 'webroot'); <del> Configure::write('App.namespace', 'TestApp'); <del> } <del> <del>/** <del> * Data provider for cached actions. <del> * <del> * - Test simple views <del> * - Test views with nocache tags <del> * - Test requests with named + passed params. <del> * - Test requests with query string params <del> * - Test themed views. <del> * <del> * @return array <del> */ <del> public static function cacheActionProvider() { <del> return array( <del> array('/'), <del> array('test_cached_pages/index'), <del> array('test_cached_pages/test_nocache_tags'), <del> array('test_cached_pages/view/param/param'), <del> array('test_cached_pages/view?q=cakephp'), <del> ); <del> } <del> <del>/** <del> * testFullPageCachingDispatch method <del> * <del> * @dataProvider cacheActionProvider <del> * @return void <del> */ <del> public function testFullPageCachingDispatch($url) { <del> Cache::enable(); <del> Configure::write('Cache.disable', false); <del> Configure::write('Cache.check', true); <del> Configure::write('debug', true); <del> <del> Router::connect('/', array('controller' => 'TestCachedPages', 'action' => 'index')); <del> Router::connect('/test_cached_pages/:action/*', ['controller' => 'TestCachedPages']); <del> <del> $dispatcher = new Dispatcher(); <del> $dispatcher->addFilter(new RoutingFilter()); <del> $dispatcher->addFilter(new ControllerFactoryFilter()); <del> $request = new Request($url); <del> $response = $this->getMock('Cake\Network\Response', array('send')); <del> <del> $dispatcher->dispatch($request, $response); <del> $out = $response->body(); <del> <del> $request = new Request($url); <del> $response = $this->getMock('Cake\Network\Response', array('send')); <del> $dispatcher = new Dispatcher(); <del> $dispatcher->addFilter(new RoutingFilter()); <del> $dispatcher->addFilter(new CacheFilter()); <del> $dispatcher->addFilter(new ControllerFactoryFilter()); <del> $dispatcher->dispatch($request, $response); <del> $cached = $response->body(); <del> <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> <del> $this->assertTextEquals($out, $cached); <del> <del> $filename = $this->_cachePath($request->here()); <del> unlink($filename); <del> } <del> <del>/** <del> * cachePath method <del> * <del> * @param string $here <del> * @return string <del> */ <del> protected function _cachePath($here) { <del> $path = $here; <del> if ($here === '/') { <del> $path = 'home'; <del> } <del> $path = strtolower(Inflector::slug($path)); <del> <del> $filename = CACHE . 'views/' . $path . '.php'; <del> <del> if (!file_exists($filename)) { <del> $filename = CACHE . 'views/' . $path . '_index.php'; <del> } <del> return $filename; <del> } <del> <del>} <ide><path>tests/TestCase/Utility/DebuggerTest.php <ide> public function testExportVar() { <ide> autoLayout => true <ide> subDir => null <ide> theme => null <del> cacheAction => false <ide> hasRendered => false <ide> uuids => [] <ide> request => object(Cake\Network\Request) {} <ide> public function testExportVar() { <ide> (int) 7 => 'layoutPath', <ide> (int) 8 => 'viewPath', <ide> (int) 9 => 'plugin', <del> (int) 10 => 'passedArgs', <del> (int) 11 => 'cacheAction' <add> (int) 10 => 'passedArgs' <ide> ] <ide> [protected] _paths => [] <ide> [protected] _pathsForPlugin => [] <ide><path>tests/TestCase/View/Helper/CacheHelperTest.php <del><?php <del>/** <del> * CacheHelperTest file <del> * <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since 1.2.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\View\Helper; <del> <del>use Cake\Cache\Cache; <del>use Cake\Controller\Controller; <del>use Cake\Core\App; <del>use Cake\Core\Configure; <del>use Cake\Model\Model; <del>use Cake\Network\Request; <del>use Cake\Routing\Router; <del>use Cake\TestSuite\TestCase; <del>use Cake\View\Helper\CacheHelper; <del>use Cake\View\View; <del> <del>/** <del> * CacheTestController class <del> * <del> */ <del>class CacheTestController extends Controller { <del> <del>/** <del> * helpers property <del> * <del> * @var array <del> */ <del> public $helpers = array('Html', 'Cache'); <del> <del>/** <del> * cache_parsing method <del> * <del> * @return void <del> */ <del> public function cache_parsing() { <del> $this->viewPath = 'Posts'; <del> $this->layout = 'cache_layout'; <del> $this->set('variable', 'variableValue'); <del> $this->set('superman', 'clark kent'); <del> $this->set('batman', 'bruce wayne'); <del> $this->set('spiderman', 'peter parker'); <del> } <del> <del>} <del> <del>/** <del> * CacheHelperTest class <del> * <del> */ <del>class CacheHelperTest extends TestCase { <del> <del>/** <del> * Checks if TMP/views is writable, and skips the case if it is not. <del> * <del> * @return void <del> */ <del> public function skip() { <del> if (!is_writable(TMP . 'cache/views/')) { <del> $this->markTestSkipped('TMP/views is not writable.'); <del> } <del> } <del> <del>/** <del> * setUp method <del> * <del> * @return void <del> */ <del> public function setUp() { <del> parent::setUp(); <del> $_GET = []; <del> $request = new Request(); <del> $this->Controller = new CacheTestController($request); <del> $View = $this->Controller->createView(); <del> $this->Cache = new CacheHelper($View); <del> Configure::write('Cache.check', true); <del> Cache::enable(); <del> } <del> <del>/** <del> * tearDown method <del> * <del> * @return void <del> */ <del> public function tearDown() { <del> clearCache(); <del> unset($this->Cache); <del> parent::tearDown(); <del> } <del> <del>/** <del> * test cache parsing with no cake:nocache tags in view file. <del> * <del> * @return void <del> */ <del> public function testLayoutCacheParsingNoTagsInView() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = 21600; <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->request->action = 'cache_parsing'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> $this->assertNotContains('cake:nocache', $result); <del> $this->assertNotContains('<?php echo', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> $contents = file_get_contents($filename); <del> $this->assertContains('<?= $variable', $contents); <del> $this->assertContains('<?= microtime()', $contents); <del> $this->assertContains('clark kent', $result); <del> <del> unlink($filename); <del> } <del> <del>/** <del> * test cache parsing with non-latin characters in current route <del> * <del> * @return void <del> */ <del> public function testCacheNonLatinCharactersInRoute() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array('風街ろまん'), <del> )); <del> $this->Controller->cacheAction = 21600; <del> $this->Controller->request->here = '/posts/view/風街ろまん'; <del> $this->Controller->action = 'view'; <del> <del> $View = $this->Controller->createView(); <del> $View->render('index'); <del> <del> $filename = CACHE . 'views/posts_view_風街ろまん.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> unlink($filename); <del> } <del> <del>/** <del> * Test cache parsing with cake:nocache tags in view file. <del> * <del> * @return void <del> */ <del> public function testLayoutCacheParsingWithTagsInView() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = 21600; <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->action = 'cache_parsing'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('test_nocache_tags'); <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> $contents = file_get_contents($filename); <del> $this->assertRegExp('/if \(is_writable\(TMP\)\)\:/', $contents); <del> $this->assertRegExp('/= \$variable/', $contents); <del> $this->assertRegExp('/= microtime()/', $contents); <del> $this->assertNotRegExp('/cake:nocache/', $contents); <del> <del> unlink($filename); <del> } <del> <del>/** <del> * test that multiple <!--nocache--> tags function with multiple nocache tags in the layout. <del> * <del> * @return void <del> */ <del> public function testMultipleNoCacheTagsInViewfile() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = 21600; <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->action = 'cache_parsing'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('multiple_nocache'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> $contents = file_get_contents($filename); <del> $this->assertNotRegExp('/cake:nocache/', $contents); <del> unlink($filename); <del> } <del> <del>/** <del> * testComplexNoCache method <del> * <del> * @return void <del> */ <del> public function testComplexNoCache() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_complex', <del> 'pass' => array(), <del> )); <del> $this->Controller->action = 'cache_complex'; <del> $this->Controller->request->here = '/cacheTest/cache_complex'; <del> $this->Controller->cacheAction = array('cache_complex' => 21600); <del> $this->Controller->layout = 'multi_cache'; <del> $this->Controller->viewPath = 'Posts'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('sequencial_nocache'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> $this->assertRegExp('/A\. Layout Before Content/', $result); <del> $this->assertRegExp('/B\. In Plain Element/', $result); <del> $this->assertRegExp('/C\. Layout After Test Element/', $result); <del> $this->assertRegExp('/D\. In View File/', $result); <del> $this->assertRegExp('/E\. Layout After Content/', $result); <del> $this->assertRegExp('/F\. In Element With No Cache Tags/', $result); <del> $this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $result); <del> $this->assertNotRegExp('/1\. layout before content/', $result); <del> $this->assertNotRegExp('/2\. in plain element/', $result); <del> $this->assertNotRegExp('/3\. layout after test element/', $result); <del> $this->assertNotRegExp('/4\. in view file/', $result); <del> $this->assertNotRegExp('/5\. layout after content/', $result); <del> $this->assertNotRegExp('/6\. in element with no cache tags/', $result); <del> $this->assertNotRegExp('/7\. layout after content and after element with no cache tags/', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_complex.php'; <del> $this->assertTrue(file_exists($filename)); <del> $contents = file_get_contents($filename); <del> unlink($filename); <del> <del> $this->assertRegExp('/A\. Layout Before Content/', $contents); <del> $this->assertNotRegExp('/B\. In Plain Element/', $contents); <del> $this->assertRegExp('/C\. Layout After Test Element/', $contents); <del> $this->assertRegExp('/D\. In View File/', $contents); <del> $this->assertRegExp('/E\. Layout After Content/', $contents); <del> $this->assertRegExp('/F\. In Element With No Cache Tags/', $contents); <del> $this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $contents); <del> $this->assertRegExp('/1\. layout before content/', $contents); <del> $this->assertNotRegExp('/2\. in plain element/', $contents); <del> $this->assertRegExp('/3\. layout after test element/', $contents); <del> $this->assertRegExp('/4\. in view file/', $contents); <del> $this->assertRegExp('/5\. layout after content/', $contents); <del> $this->assertRegExp('/6\. in element with no cache tags/', $contents); <del> $this->assertRegExp('/7\. layout after content and after element with no cache tags/', $contents); <del> } <del> <del>/** <del> * test cache of view vars <del> * <del> * @return void <del> */ <del> public function testCacheViewVars() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->cacheAction = 21600; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> $contents = file_get_contents($filename); <del> $this->assertRegExp('/\$this\-\>viewVars/', $contents); <del> $this->assertRegExp('/extract\(\$this\-\>viewVars, EXTR_SKIP\);/', $contents); <del> $this->assertRegExp('/= \$variable/', $contents); <del> <del> unlink($filename); <del> } <del> <del>/** <del> * Test that callback code is generated correctly. <del> * <del> * @return void <del> */ <del> public function testCacheCallbacks() { <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => array( <del> 'duration' => 21600, <del> 'callbacks' => true) <del> ); <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->cache_parsing(); <del> <del> $View = $this->Controller->createView(); <del> $View->render('index'); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> <del> $contents = file_get_contents($filename); <del> <del> $this->assertRegExp('/\$controller->startupProcess\(\);/', $contents); <del> <del> unlink($filename); <del> } <del> <del>/** <del> * test cacheAction set to a boolean <del> * <del> * @return void <del> */ <del> public function testCacheActionArray() { <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->request->here = '/cache_test/cache_parsing'; <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => 21600 <del> ); <del> <del> $this->Controller->cache_parsing(); <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cache_test_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> unlink($filename); <del> } <del> <del>/** <del> * Test that cacheAction works with camelcased controller names. <del> * <del> * @return void <del> */ <del> public function testCacheActionArrayCamelCase() { <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => 21600 <del> ); <del> $this->Controller->request->here = '/cacheTest/cache_parsing'; <del> $this->Controller->cache_parsing(); <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> unlink($filename); <del> } <del> <del>/** <del> * test with named and pass args. <del> * <del> * @return void <del> */ <del> public function testCacheWithNamedAndPassedArgs() { <del> Router::reload(); <del> <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(1, 2), <del> )); <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => 21600 <del> ); <del> $this->Controller->request->here = '/cache_test/cache_parsing/1/2/name:mark/ice:cream'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cache_test_cache_parsing_1_2_name_mark_ice_cream.php'; <del> $this->assertTrue(file_exists($filename)); <del> unlink($filename); <del> } <del> <del>/** <del> * Test that query string parameters are included in the cache filename. <del> * <del> * @return void <del> */ <del> public function testCacheWithQueryStringParams() { <del> Router::reload(); <del> <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->request->query = array('q' => 'cakephp'); <del> $this->Controller->request->here = '/cache_test/cache_parsing'; <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => 21600 <del> ); <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cache_test_cache_parsing_q_cakephp.php'; <del> $this->assertTrue(file_exists($filename), 'Missing cache file ' . $filename); <del> unlink($filename); <del> } <del> <del>/** <del> * test that custom routes are respected when generating cache files. <del> * <del> * @return void <del> */ <del> public function testCacheWithCustomRoutes() { <del> Router::reload(); <del> Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}')); <del> <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams(array( <del> 'lang' => 'en', <del> 'controller' => 'cache_test', <del> 'action' => 'cache_parsing', <del> 'pass' => array(), <del> )); <del> $this->Controller->cacheAction = array( <del> 'cache_parsing' => 21600 <del> ); <del> $this->Controller->request->here = '/en/cache_test/cache_parsing'; <del> $this->Controller->action = 'cache_parsing'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/en_cache_test_cache_parsing.php'; <del> $this->assertTrue(file_exists($filename)); <del> unlink($filename); <del> } <del> <del>/** <del> * test ControllerName contains AppName <del> * <del> * This test verifies view cache is created correctly when the app name is contained in part of the controller name. <del> * (webapp Name) base name is 'cache' controller is 'cacheTest' action is 'cache_name' <del> * apps URL would look something like http://localhost/cache/cacheTest/cache_name <del> * <del> * @return void <del> */ <del> public function testCacheBaseNameControllerName() { <del> $this->Controller->cache_parsing(); <del> $this->Controller->cacheAction = array( <del> 'cache_name' => 21600 <del> ); <del> $request = $this->Controller->request; <del> $request->params = array( <del> 'controller' => 'cacheTest', <del> 'action' => 'cache_name', <del> 'pass' => array(), <del> ); <del> $request->here = '/cache/cacheTest/cache_name'; <del> $request->base = '/cache'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('index'); <del> <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExp('/php echo/', $result); <del> <del> $filename = CACHE . 'views/cache_cachetest_cache_name.php'; <del> $this->assertTrue(file_exists($filename)); <del> unlink($filename); <del> } <del> <del>/** <del> * test that afterRender checks the conditions correctly. <del> * <del> * @return void <del> */ <del> public function testAfterRenderConditions() { <del> Configure::write('Cache.check', true); <del> $View = $this->Controller->createView(); <del> $View->cacheAction = '+1 day'; <del> $View->assign('content', 'test'); <del> <del> $Cache = $this->getMock('Cake\View\Helper\CacheHelper', array('_parseContent'), array($View)); <del> $Cache->expects($this->once()) <del> ->method('_parseContent') <del> ->with('posts/index', 'content') <del> ->will($this->returnValue('')); <del> <del> $event = $this->getMock('Cake\Event\Event', [], ['View.afterRenderFile']); <del> $Cache->afterRenderFile($event, 'posts/index', 'content'); <del> } <del> <del>/** <del> * test that afterRender checks the conditions correctly. <del> * <del> * @return void <del> */ <del> public function testAfterLayoutConditions() { <del> Configure::write('Cache.check', true); <del> $View = $this->Controller->createView(); <del> $View->cacheAction = '+1 day'; <del> $View->set('content', 'test'); <del> <del> $Cache = $this->getMock('Cake\View\Helper\CacheHelper', array('cache'), array($View)); <del> $Cache->expects($this->once()) <del> ->method('cache') <del> ->with('posts/index', $View->fetch('content')) <del> ->will($this->returnValue('')); <del> <del> $event = $this->getMock('Cake\Event\Event', [], ['View.afterLayout']); <del> $Cache->afterLayout($event, 'posts/index'); <del> <del> Configure::write('Cache.check', false); <del> $Cache->afterLayout($event, 'posts/index'); <del> <del> Configure::write('Cache.check', true); <del> $View->cacheAction = false; <del> $Cache->afterLayout($event, 'posts/index'); <del> } <del> <del>/** <del> * testCacheEmptySections method <del> * <del> * This test must be uncommented/fixed in next release (1.2+) <del> * <del> * @return void <del> */ <del> public function testCacheEmptySections() { <del> Configure::write('Cache.check', true); <del> $this->Controller->cache_parsing(); <del> $this->Controller->request->addParams([ <del> 'controller' => 'cacheTest', <del> 'action' => 'cache_empty_sections', <del> 'pass' => [], <del> ]); <del> $this->Controller->request->here = '/cacheTest/cache_empty_sections'; <del> $this->Controller->cacheAction = ['cache_empty_sections' => 21600]; <del> $this->Controller->layout = 'cache_empty_sections'; <del> $this->Controller->viewPath = 'Posts'; <del> <del> $View = $this->Controller->createView(); <del> $result = $View->render('cache_empty_sections'); <del> $this->assertNotContains('nocache', $result); <del> $this->assertNotContains('<?php echo', $result); <del> $this->assertRegExp( <del> '@</title>\s*</head>\s*' . <del> '<body>\s*' . <del> 'View Content\s*' . <del> 'cached count is: 3\s*' . <del> '</body>@', $result); <del> <del> $filename = CACHE . 'views/cachetest_cache_empty_sections.php'; <del> $this->assertTrue(file_exists($filename)); <del> $contents = file_get_contents($filename); <del> $this->assertNotContains('nocache', $contents); <del> $this->assertRegExp( <del> '@<head>\s*<title>Posts</title>\s*' . <del> '<\?php \$x \= 1; \?>\s*' . <del> '</head>\s*' . <del> '<body>\s*' . <del> '<\?php \$x\+\+; \?>\s*' . <del> '<\?php \$x\+\+; \?>\s*' . <del> 'View Content\s*' . <del> '<\?php \$y = 1; \?>\s*' . <del> '<\?= \'cached count is: \' . \$x; \?>\s*' . <del> '@', $contents); <del> unlink($filename); <del> } <del>} <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testRender() { <ide> <ide> $this->assertNull($View->render(false, 'ajax2')); <ide> <del> $this->PostsController->helpers = array('Session', 'Cache', 'Html'); <add> $this->PostsController->helpers = array('Session', 'Html'); <ide> $this->PostsController->constructClasses(); <del> $this->PostsController->cacheAction = array('index' => 3600); <ide> $this->PostsController->request->params['action'] = 'index'; <ide> Configure::write('Cache.check', true); <ide> <ide> public function testViewFileName() { <ide> $this->assertPathEquals($expected, $result); <ide> } <ide> <del>/** <del> * Test renderCache method <del> * <del> * @return void <del> */ <del> public function testRenderCache() { <del> $this->skipIf(!is_writable(CACHE . 'views/'), 'CACHE/views dir is not writable, cannot test renderCache.'); <del> <del> $view = 'test_view'; <del> $View = $this->PostsController->createView(); <del> $path = CACHE . 'views/view_cache_' . $view; <del> <del> $cacheText = '<!--cachetime:' . time() . '-->some cacheText'; <del> $f = fopen($path, 'w+'); <del> fwrite($f, $cacheText); <del> fclose($f); <del> <del> $result = $View->renderCache($path, '+1 second'); <del> $this->assertFalse($result); <del> if (file_exists($path)) { <del> unlink($path); <del> } <del> <del> $cacheText = '<!--cachetime:' . (time() + 10) . '-->some cacheText'; <del> $f = fopen($path, 'w+'); <del> fwrite($f, $cacheText); <del> fclose($f); <del> $result = $View->renderCache($path, '+1 second'); <del> <del> $this->assertRegExp('/^some cacheText/', $result); <del> <del> if (file_exists($path)) { <del> unlink($path); <del> } <del> } <del> <del>/** <del> * Test that render() will remove the cake:nocache tags when only the cachehelper is present. <del> * <del> * @return void <del> */ <del> public function testRenderStrippingNoCacheTagsOnlyCacheHelper() { <del> Configure::write('Cache.check', false); <del> $View = $this->PostsController->createView(); <del> $View->set(array('superman' => 'clark', 'variable' => 'var')); <del> $View->helpers = array('Html', 'Form', 'Cache'); <del> $View->layout = 'cache_layout'; <del> $result = $View->render('index'); <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> } <del> <del>/** <del> * Test that render() will remove the cake:nocache tags when only the Cache.check is true. <del> * <del> * @return void <del> */ <del> public function testRenderStrippingNoCacheTagsOnlyCacheCheck() { <del> Configure::write('Cache.check', true); <del> $View = $this->PostsController->createView(); <del> $View->set(array('superman' => 'clark', 'variable' => 'var')); <del> $View->helpers = array('Html', 'Form'); <del> $View->layout = 'cache_layout'; <del> $result = $View->render('index'); <del> $this->assertNotRegExp('/cake:nocache/', $result); <del> } <del> <ide> /** <ide> * Test creating a block with capturing output. <ide> *
8
Text
Text
update pr template to highlight lts mode
f76802369851296a635f48a0df24dec975ac152c
<ide><path>.github/PULL_REQUEST_TEMPLATE.md <add># AngularJS is in LTS mode <add>We are no longer accepting changes that are not critical bug fixes into this project. <add>See https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c for more detail. <add> <ide> <!-- General PR submission guidelines https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#submit-pr --> <del>**What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)** <add>**Does this PR fix a regression since 1.7.0, a security flaw, or a problem caused by a new browser version?** <ide> <add><!-- If the answer is no, then we will not merge this PR --> <ide> <ide> <ide> **What is the current behavior? (You can also link to an open issue here)**
1
Python
Python
fix newline in file
a2bf4cc7bff9508a6bbc3d97aeffaf815f50b662
<ide><path>spacy/lang/th/__init__.py <ide> from ...attrs import LANG, NORM <ide> from ...util import update_exc, add_lookups <ide> <del> <ide> class ThaiDefaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <ide> lex_attr_getters[LANG] = lambda text: 'th'
1
Javascript
Javascript
make favicon work
9b3d9f4255feb937e9d20cb5fb3522568fc69abf
<ide><path>packages/create-next-app/templates/default/pages/index.js <ide> const Home = () => ( <ide> <div> <ide> <Head> <ide> <title>Home</title> <add> <link rel='icon' href='/static/favicon.ico' /> <ide> </Head> <ide> <ide> <Nav />
1
Go
Go
improve godoc for seccomp fields
b309e96b11f221f9754d2842967ed24c0ae9a00b
<ide><path>profiles/seccomp/seccomp.go <ide> type Seccomp struct { <ide> <ide> // Architectures is kept to maintain backward compatibility with the old <ide> // seccomp profile. <del> Architectures []specs.Arch `json:"architectures,omitempty"` <del> ArchMap []Architecture `json:"archMap,omitempty"` <del> Syscalls []*Syscall `json:"syscalls"` <add> Architectures []specs.Arch `json:"architectures,omitempty"` <add> <add> // ArchMap contains a list of Architectures and Sub-architectures for the <add> // profile. When generating the profile, this list is expanded to a <add> // []specs.Arch, to propagate the Architectures field of the profile. <add> ArchMap []Architecture `json:"archMap,omitempty"` <add> <add> // Syscalls contains lists of syscall rules. Rules can define conditions <add> // for them to be included or excluded in the resulting profile (based on <add> // on kernel version, architecture, capabilities, etc.). These lists are <add> // expanded to an specs.Syscall When generating the profile, these lists <add> // are expanded to a []specs.LinuxSyscall. <add> Syscalls []*Syscall `json:"syscalls"` <ide> } <ide> <ide> // Architecture is used to represent a specific architecture
1
Text
Text
fix spanish grammar errors
dfb0edccb513aa41536d27c4926e557a7089d695
<ide><path>guide/spanish/vim/useful-commands/index.md <ide> localeTitle: Comandos útiles <ide> --- <ide> # Comandos útiles <ide> <del>## Funcionalidad basica <add>## Funcionalidad básica <ide> <ide> Lo más probable es que te encuentres en el modo "normal", te permite ingresar comandos presionando la tecla de dos puntos `:` . Para llegar aquí desde otros modos puede escribir `ctrl + c` o `escape` . <ide> <ide> Dependiendo de la configuración, puede ingresar a un explorador de archivos esc <ide> * puede usar `yy` y `dd` precedidos por un número para cortar o copiar varias líneas (por `13dd` , `13dd` cortará 13 líneas) <ide> * `p` pega todo desde el buffer de pasta <ide> <del>## Pegando bloques de codigo <add>## Pegando bloques de código <ide> <ide> Muy a menudo te encontrarás buscando soluciones a los problemas, y encontrar a alguien ha escrito un bloque de código que hace exactamente lo que quieres. Si intenta copiar y pegar el código directamente en Vim, es posible que el código tenga un formato extraño o que no se haya pegado correctamente. Esto se debe al hecho de que Vim lee cada carácter que pegue uno tras otro, lo que significa que cualquier combinación de teclas que active un acceso directo de Vim se ejecutará y Vim intentará (y fallará) sangrar automáticamente el código pegado. <ide> <ide> Lea el resto de nuestras guías Vim para comprender mejor este potente editor. <ide> <ide> * [Vim Golf](https://vimgolf.com/) : una buena manera de aprender de los desafíos de vim para obtener la menor cantidad de pulsaciones. Puede ver soluciones enviadas por otros si no puede resolver el desafío. <ide> * [Vim Adventures](https://vim-adventures.com/) : un enfoque divertido y gamificado para aprender Vim en el que se encuentran los diferentes golpes de tecla con cada nuevo nivel del juego. <del>* [Open Vim](http://www.openvim.com/) - Un tutorial interactivo de vim que enseña comandos básicos <ide>\ No newline at end of file <add>* [Open Vim](http://www.openvim.com/) - Un tutorial interactivo de vim que enseña comandos básicos
1
Mixed
Javascript
allow registering scale with single parameter
3c1e04f928f74356d81c12c2034b2bcfde4472ba
<ide><path>docs/developers/axes.md <ide> Axes in Chart.js can be individually extended. Axes should always derive from `C <ide> let MyScale = Chart.Scale.extend({ <ide> /* extensions ... */ <ide> }); <add>MyScale.id = 'myScale'; <add>MyScale.defaults = defaultConfigObject; <ide> <ide> // MyScale is now derived from Chart.Scale <ide> ``` <ide> <ide> Once you have created your scale class, you need to register it with the global chart object so that it can be used. A default config for the scale may be provided when registering the constructor. The first parameter to the register function is a string key that is used later to identify which scale type to use for a chart. <ide> <ide> ```javascript <del>Chart.scaleService.registerScaleType('myScale', MyScale, defaultConfigObject); <add>Chart.scaleService.registerScale(MyScale); <ide> ``` <ide> <ide> To use the new scale, simply pass in the string key to the config when creating a chart. <ide> var lineChart = new Chart(ctx, { <ide> options: { <ide> scales: { <ide> y: { <del> type: 'myScale' // this is the same key that was passed to the registerScaleType function <add> type: 'myScale' // this is the same id that was set on the scale <ide> } <ide> } <ide> } <ide><path>docs/getting-started/v3-migration.md <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> * `Scale.getLabelForIndex` was replaced by `scale.getLabelForValue` <ide> * `Scale.getPixelForValue` now has only one parameter. For the `TimeScale` that parameter must be millis since the epoch <add>* `ScaleService.registerScaleType` was renamed to `ScaleService.registerScale` and now takes a scale constructors which is expected to have `id` and `defaults` properties. <ide> <ide> ##### Ticks <ide> <ide><path>src/core/core.scaleService.js <ide> export default { <ide> <ide> // Scale config defaults <ide> defaults: {}, <del> registerScaleType(type, scaleConstructor, scaleDefaults) { <del> this.constructors[type] = scaleConstructor; <del> this.defaults[type] = clone(scaleDefaults); <add> registerScale(scaleConstructor) { <add> const me = this; <add> const type = scaleConstructor.id; <add> me.constructors[type] = scaleConstructor; <add> me.defaults[type] = clone(scaleConstructor.defaults); <ide> }, <ide> getScaleConstructor(type) { <ide> return Object.prototype.hasOwnProperty.call(this.constructors, type) ? this.constructors[type] : undefined; <ide><path>src/index.js <ide> Chart.scaleService = scaleService; <ide> Chart.Ticks = Ticks; <ide> <ide> // Register built-in scales <del>import scales from './scales/index'; <del>Object.keys(scales).forEach((type) => { <del> const scale = scales[type]; <del> Chart.scaleService.registerScaleType(type, scale, scale._defaults); <del>}); <add>import * as scales from './scales/index'; <add>Object.keys(scales).forEach(key => Chart.scaleService.registerScale(scales[key])); <ide> <ide> // Load to register built-in adapters (as side effects) <ide> import './adapters/index'; <ide><path>src/scales/index.js <del>import category from './scale.category'; <del>import linear from './scale.linear'; <del>import logarithmic from './scale.logarithmic'; <del>import radialLinear from './scale.radialLinear'; <del>import time from './scale.time'; <del> <del>export default { <del> category, <del> linear, <del> logarithmic, <del> radialLinear, <del> time <del>}; <add>export {default as CategoryScale} from './scale.category'; <add>export {default as LinearScale} from './scale.linear'; <add>export {default as LogarithmicScale} from './scale.logarithmic'; <add>export {default as RadialLinearScale} from './scale.radialLinear'; <add>export {default as TimeScale} from './scale.time'; <ide><path>src/scales/scale.category.js <ide> const defaultConfig = { <ide> <ide> export default class CategoryScale extends Scale { <ide> <add> static id = 'category'; <ide> // INTERNAL: static default options, registered in src/index.js <del> static _defaults = defaultConfig; <add> static defaults = defaultConfig; <ide> <ide> constructor(cfg) { <ide> super(cfg); <ide><path>src/scales/scale.linear.js <ide> const defaultConfig = { <ide> <ide> export default class LinearScale extends LinearScaleBase { <ide> <add> static id = 'linear'; <ide> // INTERNAL: static default options, registered in src/index.js <del> static _defaults = defaultConfig; <add> static defaults = defaultConfig; <ide> <ide> determineDataLimits() { <ide> const me = this; <ide><path>src/scales/scale.logarithmic.js <ide> const defaultConfig = { <ide> <ide> export default class LogarithmicScale extends Scale { <ide> <add> static id = 'logarithmic'; <ide> // INTERNAL: static default options, registered in src/index.js <del> static _defaults = defaultConfig; <add> static defaults = defaultConfig; <ide> <ide> constructor(cfg) { <ide> super(cfg); <ide><path>src/scales/scale.radialLinear.js <ide> function numberOrZero(param) { <ide> <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> <add> static id = 'radialLinear'; <ide> // INTERNAL: static default options, registered in src/index.js <del> static _defaults = defaultConfig; <add> static defaults = defaultConfig; <ide> <ide> constructor(cfg) { <ide> super(cfg); <ide><path>src/scales/scale.time.js <ide> const defaultConfig = { <ide> <ide> export default class TimeScale extends Scale { <ide> <add> static id = 'time'; <ide> // INTERNAL: static default options, registered in src/index.js <del> static _defaults = defaultConfig; <add> static defaults = defaultConfig; <ide> <ide> /** <ide> * @param {object} props <ide><path>test/specs/core.scale.tests.js <ide> describe('Core.scale', function() { <ide> return ['tick']; <ide> } <ide> }); <del> Chart.scaleService.registerScaleType('customScale', customScale, {}); <add> customScale.id = 'customScale'; <add> customScale.defaults = {}; <add> Chart.scaleService.registerScale(customScale); <ide> <ide> var chart = window.acquireChart({ <ide> type: 'line', <ide><path>test/specs/core.scaleService.tests.js <ide> describe('Test the scale service', function() { <ide> <ide> it('should update scale defaults', function() { <del> var defaults = { <del> testProp: true <del> }; <ide> var type = 'my_test_type'; <ide> var Constructor = function() { <ide> this.initialized = true; <ide> }; <del> Chart.scaleService.registerScaleType(type, Constructor, defaults); <add> Constructor.id = type; <add> Constructor.defaults = { <add> testProp: true <add> }; <add> Chart.scaleService.registerScale(Constructor); <ide> <ide> // Should equal defaults but not be an identical object <ide> expect(Chart.scaleService.getScaleDefaults(type)).toEqual(jasmine.objectContaining({
12
PHP
PHP
remove debug statement
490bbf836d36c2e42112b32d9394c4dc5ba9335b
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php <ide> public function testRadioDisabled() { <ide> 'separator' => '--separator--', <ide> 'between' => array('--between first--', '--between second--') <ide> )); <del> //die(debug($result, null, false)); <add> <ide> $expected = array( <ide> 'div' => array('class' => 'input radio'), <ide> '--before--',
1
Ruby
Ruby
call local_cache 1 time instead of 3 times
2c42404330a3e7a1648a01e072035c2bee9cc118
<ide><path>activesupport/lib/active_support/cache/strategy/local_cache.rb <ide> def decrement(name, amount = 1, options = nil) # :nodoc: <ide> <ide> protected <ide> def read_entry(key, options) # :nodoc: <del> if local_cache <del> local_cache.fetch(key) do <add> if cache = local_cache <add> cache.fetch(key) do <ide> entry = super <del> local_cache.write_entry(key, entry, options) <add> cache.write_entry(key, entry, options) <ide> entry <ide> end <ide> else
1
Python
Python
fix message in prepare_provider_packages.py
a7b1f62d9c9227e09c8a861febbb976b06c293da
<ide><path>dev/provider_packages/prepare_provider_packages.py <ide> def summarise_total_vs_bad_and_warnings(total: int, bad: int, warns: List[warnin <ide> console.print(f"[red]ERROR! There were {len(warns)} warnings generated during the import[/]") <ide> console.print() <ide> console.print("[yellow]Ideally, fix it, so that no warnings are generated during import.[/]") <del> console.print("[yellow]There are two cases that are legitimate deprecation warnings though:[/]") <add> console.print("[yellow]There are three cases that are legitimate deprecation warnings though:[/]") <ide> console.print("[yellow] 1) when you deprecate whole module or class and replace it in provider[/]") <ide> console.print("[yellow] 2) when 3rd-party module generates Deprecation and you cannot upgrade it[/]") <ide> console.print(
1
PHP
PHP
remove mock that wasn't necessary
55b5291c22a3cec2afc92947e0d21f981c4fda43
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddContextProviderInvalid() <ide> public function contextSelectionProvider() <ide> { <ide> $entity = new Article(); <del> $collection = $this->getMockBuilder('Cake\Collection\Collection') <del> ->setMethods(['extract']) <del> ->setConstructorArgs([[$entity]]) <del> ->getMock(); <add> $collection = new Collection([$entity]); <ide> $emptyCollection = new Collection([]); <ide> $emptyArray = []; <ide> $arrayObject = new \ArrayObject([]);
1
Go
Go
move job register into servapi
e743021193e589b1358d0eef0521e9d8878dd66d
<ide><path>api/api.go <ide> type HttpApiFunc func(eng *engine.Engine, version float64, w http.ResponseWriter <ide> <ide> func init() { <ide> engine.Register("serveapi", ServeApi) <del> engine.Register("acceptconnections", AcceptConnections) <ide> } <ide> <ide> func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) { <ide> func ServeApi(job *engine.Job) engine.Status { <ide> ) <ide> activationLock = make(chan struct{}) <ide> <add> if err := job.Eng.Register("acceptconnections", AcceptConnections); err != nil { <add> return job.Error(err) <add> } <add> <ide> for _, protoAddr := range protoAddrs { <ide> protoAddrParts := strings.SplitN(protoAddr, "://", 2) <ide> go func() {
1
Go
Go
provide tmpdir for applylayer
330171e1d9ec537d7f691fd63c697a0540589053
<ide><path>pkg/chrootarchive/diff.go <ide> package chrootarchive <ide> import ( <ide> "flag" <ide> "fmt" <add> "io/ioutil" <ide> "os" <ide> "runtime" <ide> "syscall" <ide> func applyLayer() { <ide> if err := syscall.Chdir("/"); err != nil { <ide> fatal(err) <ide> } <add> tmpDir, err := ioutil.TempDir("/", "temp-docker-extract") <add> if err != nil { <add> fatal(err) <add> } <add> os.Setenv("TMPDIR", tmpDir) <ide> if err := archive.ApplyLayer("/", os.Stdin); err != nil { <add> os.RemoveAll(tmpDir) <ide> fatal(err) <ide> } <add> os.RemoveAll(tmpDir) <ide> os.Exit(0) <ide> } <ide>
1
Python
Python
update typing tests for json
60b845ebabeb77e401186f4b83de21d3f9c6a9d7
<ide><path>src/flask/typing.py <ide> <ide> # The possible types that are directly convertible or are a Response object. <ide> ResponseValue = t.Union[ <del> "Response", str, bytes, list, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes] <add> "Response", <add> str, <add> bytes, <add> t.List[t.Any], <add> t.Dict[str, t.Any], <add> t.Iterator[str], <add> t.Iterator[bytes], <ide> ] <ide> <ide> # the possible types for an individual HTTP header <ide><path>tests/typing/typing_route.py <ide> def hello_bytes() -> bytes: <ide> <ide> @app.route("/json") <ide> def hello_json() -> Response: <del> return jsonify({"response": "Hello, World!"}) <add> return jsonify("Hello, World!") <add> <add> <add>@app.route("/json/dict") <add>def hello_json_dict() -> t.Dict[str, t.Any]: <add> return {"response": "Hello, World!"} <add> <add> <add>@app.route("/json/dict") <add>def hello_json_list() -> t.List[t.Any]: <add> return [{"message": "Hello"}, {"message": "World"}] <ide> <ide> <ide> @app.route("/generator")
2
PHP
PHP
apply fixes from styleci
be79e7625c55526db900f4e2105ac5d15a6b4633
<ide><path>src/Illuminate/Session/Middleware/StartSession.php <ide> use Illuminate\Support\Facades\Date; <ide> use Illuminate\Session\SessionManager; <ide> use Illuminate\Contracts\Session\Session; <del>use Illuminate\Session\CookieSessionHandler; <ide> use Symfony\Component\HttpFoundation\Cookie; <ide> use Symfony\Component\HttpFoundation\Response; <ide>
1
Text
Text
replace anonymous function with arrow function
6e4502c635d1e8b3fea514c2eac54a7d75780e6e
<ide><path>doc/guides/writing-tests.md <ide> process.on('exit', function() { <ide> assert.equal(response, 1, 'http request "response" callback was not called'); <ide> }); <ide> <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer((req, res) => { <ide> request++; <ide> res.end(); <ide> }).listen(0, function() { <ide> const options = { <ide> agent: null, <ide> port: this.address().port <ide> }; <del> http.get(options, function(res) { <add> http.get(options, (res) => { <ide> response++; <ide> res.resume(); <ide> server.close(); <ide> This test could be greatly simplified by using `common.mustCall` like this: <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>const server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall((req, res) => { <ide> res.end(); <ide> })).listen(0, function() { <ide> const options = { <ide> agent: null, <ide> port: this.address().port <ide> }; <del> http.get(options, common.mustCall(function(res) { <add> http.get(options, common.mustCall((res) => { <ide> res.resume(); <ide> server.close(); <ide> }));
1
Javascript
Javascript
add test case
97eaed1360c13defabc8ae6bcb07e7a6e3a8ccc1
<ide><path>test/configCases/externals/externals-in-commons-chunk/index.js <add>it("should not move externals into the commons chunk", function() { <add> require("should"); <add> var fs = require("fs"); <add> var source1 = fs.readFileSync(__dirname + "/main.js", "utf-8"); <add> var source2 = fs.readFileSync(__dirname + "/other.js", "utf-8"); <add> var source3 = fs.readFileSync(__dirname + "/common.js", "utf-8"); <add> source1.should.containEql("1+" + (1+1)); <add> source1.should.containEql("3+" + (2+2)); <add> source2.should.containEql("1+" + (1+1)); <add> source2.should.containEql("5+" + (3+3)); <add> source3.should.not.containEql("1+" + (1+1)); <add> source3.should.not.containEql("3+" + (2+2)); <add> source3.should.not.containEql("5+" + (3+3)); <add> <add> require("external"); <add> require("external2"); <add>}); <ide><path>test/configCases/externals/externals-in-commons-chunk/other.js <add>require("external"); <add>require("external3"); <ide><path>test/configCases/externals/externals-in-commons-chunk/test.config.js <add>module.exports = { <add> findBundle: function(i, options) { <add> return [ <add> "./common.js", <add> "./main.js" <add> ] <add> } <add>}; <ide><path>test/configCases/externals/externals-in-commons-chunk/webpack.config.js <add>var webpack = require("../../../../") <add>module.exports = { <add> entry: { <add> main: "./index", <add> other: "./other" <add> }, <add> externals: { <add> fs: "commonjs fs", <add> external: "1+2", <add> external2: "3+4", <add> external3: "5+6" <add> }, <add> target: "web", <add> output: { <add> filename: "[name].js" <add> }, <add> node: { <add> __dirname: false, <add> __filename: false <add> }, <add> plugins: [ <add> new webpack.optimize.CommonsChunkPlugin({ <add> name: "common" <add> }) <add> ] <add>};
4
Text
Text
add changes for 1.7.0-rc.0
b85c70a9584a636b31fba0d5d3c8136fbf73a125
<ide><path>CHANGELOG.md <add><a name="1.7.0-rc.0"></a> <add># 1.7.0-rc.0 maximum-overdrive (2018-04-19) <add> <add>## Bug Fixes <add>- **input:** <add> - listen on "change" instead of "click" for radio/checkbox ngModels <add> ([656c8f](https://github.com/angular/angular.js/commit/656c8fa8f23b1277cc5c214c4d0237f3393afa1e), <add> [#4516](https://github.com/angular/angular.js/issues/4516), <add> [#14667](https://github.com/angular/angular.js/issues/14667), <add> [#14685](https://github.com/angular/angular.js/issues/14685)) <add>- **input\[number\]:** validate min/max against viewValue <add> ([aa3f95](https://github.com/angular/angular.js/commit/aa3f951330ec7b10b43ea884d9b5754e296770ec), <add> [#12761](https://github.com/angular/angular.js/issues/12761), <add> [#16325](https://github.com/angular/angular.js/issues/16325)) <add>- **jqLite:** make removeData() not remove event handlers <add> ([b7d396](https://github.com/angular/angular.js/commit/b7d396b8b6e8f27a1f4556d58fc903321e8d532a), <add> [#15869](https://github.com/angular/angular.js/issues/15869), <add> [#16512](https://github.com/angular/angular.js/issues/16512)) <add>- **$compile:** <add> - remove the preAssignBindingsEnabled flag <add> ([38f8c9](https://github.com/angular/angular.js/commit/38f8c97af74649ce224b6dd45f433cc665acfbfb), <add> [#15782](https://github.com/angular/angular.js/issues/15782)) <add> - add `base[href]` to the list of RESOURCE_URL context attributes <add> ([1cf728](https://github.com/angular/angular.js/commit/1cf728e209a9e0016068fac2769827e8f747760e), <add> [#15597](https://github.com/angular/angular.js/issues/15597)) <add>- **$interval:** throw when trying to cancel non-$interval promise <add> ([a8bef9](https://github.com/angular/angular.js/commit/a8bef95127775d83d80daa4617c33227c4b443d4), <add> [#16476](https://github.com/angular/angular.js/issues/16476)) <add>- **$timeout:** throw when trying to cancel non-$timeout promise <add> ([336525](https://github.com/angular/angular.js/commit/3365256502344970f86355d3ace1cb4251ae9828), <add> [#16424](https://github.com/angular/angular.js/issues/16424)) <add>- **$cookies:** remove the deprecated $cookieStore factory <add> ([73c646](https://github.com/angular/angular.js/commit/73c6467f1468353215dc689c019ed83aa4993c77), <add> [#16465](https://github.com/angular/angular.js/issues/16465)) <add>- **$resource:** fix interceptors and success/error callbacks <add> ([ea0585](https://github.com/angular/angular.js/commit/ea0585773bb93fd891576e2271254a17e15f1ddd), <add> [#6731](https://github.com/angular/angular.js/issues/6731), <add> [#9334](https://github.com/angular/angular.js/issues/9334), <add> [#6865](https://github.com/angular/angular.js/issues/6865), <add> [#16446](https://github.com/angular/angular.js/issues/16446)) <add>- **$templateRequest:** <add> - give tpload error the correct namespace <add> ([c617d6](https://github.com/angular/angular.js/commit/c617d6dceee5b000bfceda44ced22fc16b48b18b)) <add> - always return the template that is stored in the cache <add> ([fb0099](https://github.com/angular/angular.js/commit/fb00991460cf69ae8bc7f1f826363d09c73c0d5e), <add> [#16225](https://github.com/angular/angular.js/issues/16225)) <add>- **$animate:** let cancel() reject the runner promise <add> ([16b82c](https://github.com/angular/angular.js/commit/16b82c6afe0ab916fef1d6ca78053b00bf5ada83), <add> [#14204](https://github.com/angular/angular.js/issues/14204), <add> [#16373](https://github.com/angular/angular.js/issues/16373)) <add>- **ngTouch:** <add> - deprecate the module and its contents <add> ([67f54b](https://github.com/angular/angular.js/commit/67f54b660038de2b4346b3e76d66a8dc8ccb1f9b), <add> [#16427](https://github.com/angular/angular.js/issues/16427), <add> [#16431](https://github.com/angular/angular.js/issues/16431)) <add> - remove ngClick override, `$touchProvider`, and `$touch` <add> ([11d9ad](https://github.com/angular/angular.js/commit/11d9ad1eb25eaf5967195e424108207427835d50), <add> [#15761](https://github.com/angular/angular.js/issues/15761), <add> [#15755](https://github.com/angular/angular.js/issues/15755)) <add>- **ngScenario:** completely remove the angular scenario runner <add> ([0cd392](https://github.com/angular/angular.js/commit/0cd39217828b0ad53eaf731576af17d66c18ff60), <add> [#9405](https://github.com/angular/angular.js/issues/9405)) <add>- **form:** set $submitted to true on child forms when parent is submitted <add> ([223de5](https://github.com/angular/angular.js/commit/223de59e988dc0cc8b4ec3a045b7c0735eba1c77), <add> [#10071](https://github.com/angular/angular.js/issues/10071)) <add>- **$rootScope:** <add> - provide correct value of one-time bindings in watchGroup <add> ([c2b8fa](https://github.com/angular/angular.js/commit/c2b8fab0a480204374d561d6b9b3d47347ac5570)) <add>- **ngAria:** do not set aria attributes on input[type="hidden"] <add> ([6d5ef3](https://github.com/angular/angular.js/commit/6d5ef34fc6a974cde73157ba94f9706723dd8f5b), <add> [#15113](https://github.com/angular/angular.js/issues/15113), <add> [#16367](https://github.com/angular/angular.js/issues/16367)) <add>- **ngModel, input:** improve handling of built-in named parsers <add> ([74b04c](https://github.com/angular/angular.js/commit/74b04c9403af4fc7df5b6420f22c9f45a3e84140), <add> [#14292](https://github.com/angular/angular.js/issues/14292), <add> [#10076](https://github.com/angular/angular.js/issues/10076), <add> [#16347](https://github.com/angular/angular.js/issues/16347)) <add>- **$httpParamSerializerJQLike:** <add> - call functions as jQuery does <add> ([a784fa](https://github.com/angular/angular.js/commit/a784fab605d825f1158c6292b3c42f8c4a502fdf), <add> [#16138](https://github.com/angular/angular.js/issues/16138), <add> [#16139](https://github.com/angular/angular.js/issues/16139)) <add> - follow jQuery for `null` and `undefined` <add> ([301fdd](https://github.com/angular/angular.js/commit/301fdda648680d89ccab607c413a7ddede7b0165)) <add>- **$parse:** <add> - do not pass scope/locals to interceptors of one-time bindings <add> ([87a586](https://github.com/angular/angular.js/commit/87a586eb9a23cfd0d0bb681cc778b4b8e5c8451d)) <add> - always pass the intercepted value to watchers <add> ([2ee503](https://github.com/angular/angular.js/commit/2ee5033967d5f87a516bad137686b0592e25d26b), <add> [#16021](https://github.com/angular/angular.js/issues/16021)) <add> - respect the interceptor.$stateful flag <add> ([de7403](https://github.com/angular/angular.js/commit/de74034ddf6f92505ccdb61be413a6df2c723f87)) <add>- **Angular:** remove `angular.lowercase` and `angular.uppercase` <add> ([1daa4f](https://github.com/angular/angular.js/commit/1daa4f2231a89ee88345689f001805ffffa9e7de), <add> [#15445](https://github.com/angular/angular.js/issues/15445)) <add>- **$controller:** remove instantiating controllers defined on window <add> ([e269c1](https://github.com/angular/angular.js/commit/e269c14425a3209040f65c022658770e00a36f16), <add> [#15349](https://github.com/angular/angular.js/issues/15349), <add> [#15762](https://github.com/angular/angular.js/issues/15762)) <add> <add> <add>## New Features <add>- **angular.isArray:** support Array subclasses in `angular.isArray()` <add> ([e3ece2](https://github.com/angular/angular.js/commit/e3ece2fad9e1e6d47b5f06815ff186d7e6f44948), <add> [#15533](https://github.com/angular/angular.js/issues/15533), <add> [#15541](https://github.com/angular/angular.js/issues/15541)) <add>- **$sce:** handle URL sanitization through the `$sce` service <add> ([1e9ead](https://github.com/angular/angular.js/commit/1e9eadcd72dbbd5c67dae8328a63e535cfa91ff9)) <add>- **orderBy:** consider `null` and `undefined` greater than other values <add> ([1d8046](https://github.com/angular/angular.js/commit/1d804645f7656d592c90216a0355b4948807f6b8), <add> [#15294](https://github.com/angular/angular.js/issues/15294), <add> [#16376](https://github.com/angular/angular.js/issues/16376)) <add>- **$resource:** add support for `request` and `requestError` interceptors (#15674) <add> ([240a3d](https://github.com/angular/angular.js/commit/240a3ddbf12a9bb79754031be95dae4b6bd2dded), <add> [#5146](https://github.com/angular/angular.js/issues/5146)) <add>- **ngModelOptions:** add debounce catch-all + allow debouncing 'default' only <add> ([55ba44](https://github.com/angular/angular.js/commit/55ba44913e02650b56410aa9ab5eeea5d3492b68), <add> [#15411](https://github.com/angular/angular.js/issues/15411), <add> [#16335](https://github.com/angular/angular.js/issues/16335)) <add>- **$compile:** lower the `xlink:href` security context for SVG's `a` and `image` elements <add> ([6ccbfa](https://github.com/angular/angular.js/commit/6ccbfa65d60a3dc396d0cf6da21b993ad74653fd), <add> [#15736](https://github.com/angular/angular.js/issues/15736)) <add> <add> <add>## Performance Improvements <add>- **$rootScope:** allow $watchCollection use of expression input watching <add> ([97b00c](https://github.com/angular/angular.js/commit/97b00ca497676aaff8a803762a9f8c7ff4aa24dd)) <add>- **ngStyle:** use $watchCollection <add> ([15bbd3](https://github.com/angular/angular.js/commit/15bbd3e18cd89b91f7206a06c73d40e54a8a48a0), <add> [#15947](https://github.com/angular/angular.js/issues/15947)) <add>- **$compile:** do not use deepWatch in literal one-way bindings <add> ([fd4f01](https://github.com/angular/angular.js/commit/fd4f0111188b62773b99ab6eab38b4d2b5d8d727), <add> [#15301](https://github.com/angular/angular.js/issues/15301)) <add> <add> <add> <add> <add>## Breaking Changes <add> <add>### **jqLite** due to: <add> - **[b7d396](https://github.com/angular/angular.js/commit/b7d396b8b6e8f27a1f4556d58fc903321e8d532a)**: make removeData() not remove event handlers <add> <add>Before this commit `removeData()` invoked on an element removed its event <add>handlers as well. If you want to trigger a full cleanup of an element, change: <add> <add>```js <add>elem.removeData(); <add>``` <add> <add>to: <add> <add>```js <add>angular.element.cleanData(elem); <add>``` <add> <add>In most cases, though, cleaning up after an element is supposed to be done <add>only when it's removed from the DOM as well; in such cases the following: <add> <add>```js <add>elem.remove(); <add>``` <add> <add>will remove event handlers as well. <add> <add>### **$cookies** due to: <add> - **[73c646](https://github.com/angular/angular.js/commit/73c6467f1468353215dc689c019ed83aa4993c77)**: remove the deprecated $cookieStore factory <add> <add>The $cookieStore has been removed. Migrate to the $cookies service. Note that <add>for object values you need to use the `putObject` & `getObject` methods as <add>`get`/`put` will not correctly save/retrieve them. <add> <add>Before: <add>```js <add>$cookieStore.put('name', {key: 'value'}); <add>$cookieStore.get('name'); // {key: 'value'} <add>$cookieStore.remove('name'); <add>``` <add> <add>After: <add>```js <add>$cookies.putObject('name', {key: 'value'}); <add>$cookies.getObject('name'); // {key: 'value'} <add>$cookies.remove('name'); <add>``` <add> <add>### **$resource** due to: <add> - **[ea0585](https://github.com/angular/angular.js/commit/ea0585773bb93fd891576e2271254a17e15f1ddd)**: fix interceptors and success/error callbacks <add> <add>If you are not using `success` or `error` callbacks with `$resource`, <add>your app should not be affected by this change. <add> <add>If you are using `success` or `error` callbacks (with or without <add>response interceptors), one (subtle) difference is that throwing an <add>error inside the callbacks will not propagate to the returned <add>`$promise`. Therefore, you should try to use the promises whenever <add>possible. E.g.: <add> <add>```js <add>// Avoid <add>User.query(function onSuccess(users) { throw new Error(); }). <add> $promise. <add> catch(function onError() { /* Will not be called. */ }); <add> <add>// Prefer <add>User.query(). <add> $promise. <add> then(function onSuccess(users) { throw new Error(); }). <add> catch(function onError() { /* Will be called. */ }); <add>``` <add> <add>Finally, if you are using `success` or `error` callbacks with response <add>interceptors, the callbacks will now always run _after_ the interceptors <add>(and wait for them to resolve in case they return a promise). <add>Previously, the `error` callback was called before the `responseError` <add>interceptor and the `success` callback was synchronously called after <add>the `response` interceptor. E.g.: <add> <add>```js <add>var User = $resource('/api/users/:id', {id: '@id'}, { <add> get: { <add> method: 'get', <add> interceptor: { <add> response: function(response) { <add> console.log('responseInterceptor-1'); <add> return $timeout(1000).then(function() { <add> console.log('responseInterceptor-2'); <add> return response.resource; <add> }); <add> }, <add> responseError: function(response) { <add> console.log('responseErrorInterceptor-1'); <add> return $timeout(1000).then(function() { <add> console.log('responseErrorInterceptor-2'); <add> return $q.reject('Ooops!'); <add> }); <add> } <add> } <add> } <add>}); <add>var onSuccess = function(value) { console.log('successCallback', value); }; <add>var onError = function(error) { console.log('errorCallback', error); }; <add> <add>// Assuming the following call is successful... <add>User.get({id: 1}, onSuccess, onError); <add> // Old behavior: <add> // responseInterceptor-1 <add> // successCallback, {/* Promise object */} <add> // responseInterceptor-2 <add> // New behavior: <add> // responseInterceptor-1 <add> // responseInterceptor-2 <add> // successCallback, {/* User object */} <add> <add>// Assuming the following call returns an error... <add>User.get({id: 2}, onSuccess, onError); <add> // Old behavior: <add> // errorCallback, {/* Response object */} <add> // responseErrorInterceptor-1 <add> // responseErrorInterceptor-2 <add> // New behavior: <add> // responseErrorInterceptor-1 <add> // responseErrorInterceptor-2 <add> // errorCallback, Ooops! <add>``` <add> <add> - **[240a3d](https://github.com/angular/angular.js/commit/240a3ddbf12a9bb79754031be95dae4b6bd2dded)**: add support for `request` and `requestError` interceptors (#15674) <add> <add>Previously, calling a `$resource` method would synchronously call <add>`$http`. Now, it will be called asynchronously (regardless if a <add>`request`/`requestError` interceptor has been defined. <add> <add>This is not expected to affect applications at runtime, since the <add>overall operation is asynchronous already, but may affect assertions in <add>tests. For example, if you want to assert that `$http` has been called <add>with specific arguments as a result of a `$resource` call, you now need <add>to run a `$digest` first, to ensure the (possibly empty) request <add>interceptor promise has been resolved. <add> <add>Before: <add>```js <add>it('...', function() { <add> $httpBackend.expectGET('/api/things').respond(...); <add> var Things = $resource('/api/things'); <add> Things.query(); <add> <add> expect($http).toHaveBeenCalledWith(...); <add>}); <add>``` <add> <add>After: <add>```js <add>it('...', function() { <add> $httpBackend.expectGET('/api/things').respond(...); <add> var Things = $resource('/api/things'); <add> Things.query(); <add> $rootScope.$digest(); <add> <add> expect($http).toHaveBeenCalledWith(...); <add>}); <add>``` <add> <add>### **$templateRequest**: <add> - due to **[c617d6](https://github.com/angular/angular.js/commit/c617d6dceee5b000bfceda44ced22fc16b48b18b)**: give tpload error the correct namespace <add> <add>Previously the `tpload` error was namespaced to `$compile`. If you have <add>code that matches errors of the form `[$compile:tpload]` it will no <add>longer run. You should change the code to match <add>`[$templateRequest:tpload]`. <add> <add> - due to **([fb0099](https://github.com/angular/angular.js/commit/fb00991460cf69ae8bc7f1f826363d09c73c0d5e)**: always return the template that is stored in the cache <add> <add>The service now returns the result of `$templateCache.put()` when making a server request to the <add>template. Previously it would return the content of the response directly. <add>This now means if you are decorating `$templateCache.put()` to manipulate the template, you will <add>now get this manipulated result also on the first `$templateRequest` rather than only on subsequent <add>calls (when the template is retrived from the cache). <add>In practice this should not affect any apps, as it is unlikely that they rely on the template being <add>different in the first and subsequent calls. <add> <add>### **$animate** due to: <add> - **[16b82c](https://github.com/angular/angular.js/commit/16b82c6afe0ab916fef1d6ca78053b00bf5ada83)**: let cancel() reject the runner promise <add> <add>$animate.cancel(runner) now rejects the underlying <add>promise and calls the catch() handler on the runner <add>returned by $animate functions (enter, leave, move, <add>addClass, removeClass, setClass, animate). <add>Previously it would resolve the promise as if the animation <add>had ended successfully. <add> <add>Example: <add> <add>```js <add>var runner = $animate.addClass('red'); <add>runner.then(function() { console.log('success')}); <add>runner.catch(function() { console.log('cancelled')}); <add> <add>runner.cancel(); <add>``` <add> <add>Pre-1.7.0, this logs 'success', 1.7.0 and later it logs 'cancelled'. <add>To migrate, add a catch() handler to your animation runners. <add> <add>### **angular.isArray** due to: <add> - **[e3ece2](https://github.com/angular/angular.js/commit/e3ece2fad9e1e6d47b5f06815ff186d7e6f44948)**: support Array subclasses in `angular.isArray()` <add> <add>Previously, `angular.isArray()` was an alias for `Array.isArray()`. <add>Therefore, objects that prototypally inherit from `Array` where not <add>considered arrays. Now such objects are considered arrays too. <add> <add>This change affects several other methods that use `angular.isArray()` <add>under the hood, such as `angular.copy()`, `angular.equals()`, <add>`angular.forEach()`, and `angular.merge()`. <add> <add>This in turn affects how dirty checking treats objects that prototypally <add>inherit from `Array` (e.g. MobX observable arrays). AngularJS will now <add>be able to handle these objects better when copying or watching. <add> <add>### **$sce** due to: <add> - **[1e9ead](https://github.com/angular/angular.js/commit/1e9eadcd72dbbd5c67dae8328a63e535cfa91ff9)**: handle URL sanitization through the `$sce` service <add> <add>If you use `attrs.$set` for URL attributes (a[href] and img[src]) there will no <add>longer be any automated sanitization of the value. This is in line with other <add>programmatic operations, such as writing to the innerHTML of an element. <add> <add>If you are programmatically writing URL values to attributes from untrusted <add>input then you must sanitize it yourself. You could write your own sanitizer or copy <add>the private `$$sanitizeUri` service. <add> <add>Note that values that have been passed through the `$interpolate` service within the <add>`URL` or `MEDIA_URL` will have already been sanitized, so you would not need to sanitize <add>these values again. <add> <add>### **orderBy** due to: <add> - **[1d8046](https://github.com/angular/angular.js/commit/1d804645f7656d592c90216a0355b4948807f6b8)**: consider `null` and `undefined` greater than other values <add> <add>When using `orderBy` to sort arrays containing `null` values, the `null` values <add>will be considered "greater than" all other values, except for `undefined`. <add>Previously, they were sorted as strings. This will result in different (but more <add>intuitive) sorting order. <add> <add>Before: <add>```js <add>orderByFilter(['a', undefined, 'o', null, 'z']); <add>//--> 'a', null, 'o', 'z', undefined <add>``` <add> <add>After: <add>```js <add>orderByFilter(['a', undefined, 'o', null, 'z']); <add>//--> 'a', 'o', 'z', null, undefined <add>``` <add> <add>### **ngScenario** due to: <add> - **[0cd392](https://github.com/angular/angular.js/commit/0cd39217828b0ad53eaf731576af17d66c18ff60)**: completely remove the angular scenario runner <add> <add>The angular scenario runner end-to-end test framework has been <add>removed from the project and will no longer be available on npm <add>or bower starting with 1.7.0. <add>It was deprecated and removed from the documentation in 2014. <add>Applications that still use it should migrate to <add>[Protractor](http://www.protractortest.org). <add>Technically, it should also be possible to continue using an <add>older version of the scenario runner, as the underlying APIs have <add>not changed. However, we do not guarantee future compatibility. <add> <add>### **form** due to: <add> - **[223de5](https://github.com/angular/angular.js/commit/223de59e988dc0cc8b4ec3a045b7c0735eba1c77)**: set $submitted to true on child forms when parent is submitted <add> <add>Forms will now set $submitted on child forms when they are submitted. <add>For example: <add>``` <add><form name="parentform" ng-submit="$ctrl.submit()"> <add> <ng-form name="childform"> <add> <input type="text" name="input" ng-model="my.model" /> <add> </ng-form> <add> <input type="submit" /> <add></form> <add>``` <add> <add>Submitting this form will set $submitted on "parentform" and "childform". <add>Previously, it was only set on "parentform". <add> <add>This change was introduced because mixing form and ngForm does not create <add>logically separate forms, but rather something like input groups. <add>Therefore, child forms should inherit the submission state from their parent form. <add> <add>### **ngAria** due to: <add> - **[6d5ef3](https://github.com/angular/angular.js/commit/6d5ef34fc6a974cde73157ba94f9706723dd8f5b)**: do not set aria attributes on input[type="hidden"] <add> <add>ngAria no longer sets aria-* attributes on input[type="hidden"] with ngModel. <add>This can affect apps that test for the presence of aria attributes on hidden inputs. <add>To migrate, remove these assertions. <add>In actual apps, this should not have a user-facing effect, as the previous behavior <add>was incorrect, and the new behavior is correct for accessibility. <add> <add>### **ngModel, input** due to: <add> - **[74b04c](https://github.com/angular/angular.js/commit/74b04c9403af4fc7df5b6420f22c9f45a3e84140)**: improve handling of built-in named parsers <add> <add>*Custom* parsers that fail to parse on input types "email", "url", "number", "date", "month", <add>"time", "datetime-local", "week", do no longer set `ngModelController.$error[inputType]`, and <add>the `ng-invalid-[inputType]` class. Also, custom parsers on input type "range" do no <add>longer set `ngModelController.$error.number` and the `ng-invalid-number` class. <add> <add>Instead, any custom parsers on these inputs set `ngModelController.$error.parse` and <add>`ng-invalid-parse`. This change was made to make distinguishing errors from built-in parsers <add>and custom parsers easier. <add> <add>### **ngModelOptions** due to: <add> - **[55ba44](https://github.com/angular/angular.js/commit/55ba44913e02650b56410aa9ab5eeea5d3492b68)**: add debounce catch-all + allow debouncing 'default' only <add> <add>the 'default' key in 'debounce' now only debounces the default event, i.e. the event <add>that is added as an update trigger by the different input directives automatically. <add> <add>Previously, it also applied to other update triggers defined in 'updateOn' that <add>did not have a corresponding key in the 'debounce'. <add> <add>This behavior is now supported via a special wildcard / catch-all key: '*'. <add> <add>See the following example: <add> <add>Pre-1.7: <add>'mouseup' is also debounced by 500 milliseconds because 'default' is applied: <add>``` <add>ng-model-options="{ <add> updateOn: 'default blur mouseup', <add> debounce: { 'default': 500, 'blur': 0 } <add>} <add>``` <add> <add>1.7: <add>The pre-1.7 behavior can be re-created by setting '*' as a catch-all debounce value: <add>``` <add>ng-model-options="{ <add> updateOn: 'default blur mouseup', <add> debounce: { '*': 500, 'blur': 0 } <add>} <add>``` <add> <add>In contrast, when only 'default' is used, 'blur' and 'mouseup' are not debounced: <add>``` <add>ng-model-options="{ <add> updateOn: 'default blur mouseup', <add> debounce: { 'default': 500 } <add>} <add>``` <add> <add>### **input\[number\]** due to: <add> - **[aa3f95](https://github.com/angular/angular.js/commit/aa3f951330ec7b10b43ea884d9b5754e296770ec)**: validate min/max against viewValue <add> <add>`input[type=number]` with `ngModel` now validates the input for the `max`/`min` restriction against <add>the `ngModelController.$viewValue` instead of against the `ngModelController.$modelValue`. <add> <add>This affects apps that use `$parsers` or `$formatters` to transform the input / model value. <add> <add>If you rely on the $modelValue validation, you can overwrite the `min`/`max` validator from a custom directive, as seen in the following example directive definition object: <add> <add>``` <add>{ <add> restrict: 'A', <add> require: 'ngModel', <add> link: function(scope, element, attrs, ctrl) { <add> var maxValidator = ctrl.$validators.max; <add> <add> ctrk.$validators.max = function(modelValue, viewValue) { <add> return maxValidator(modelValue, modelValue); <add> }; <add> } <add>} <add>``` <add> <add>### **input** due to: <add> - **[656c8f](https://github.com/angular/angular.js/commit/656c8fa8f23b1277cc5c214c4d0237f3393afa1e)**: listen on "change" instead of "click" for radio/checkbox ngModels <add> <add>`input[radio]` and `input[checkbox]` now listen to the "change" event instead of the "click" event. <add>Most apps should not be affected, as "change" is automatically fired by browsers after "click" <add>happens. <add> <add>Two scenarios might need migration: <add> <add>- Custom click events: <add> <add>Before this change, custom click event listeners on radio / checkbox would be called after the <add>input element and `ngModel` had been updated, unless they were specifically registered before <add>the built-in click handlers. <add>After this change, they are called before the input is updated, and can call event.preventDefault() <add>to prevent the input from updating. <add> <add>If an app uses a click event listener that expects ngModel to be updated when it is called, it now <add>needs to register a change event listener instead. <add> <add>- Triggering click events: <add> <add>Conventional trigger functions: <add> <add>The change event might not be fired when the input element is not attached to the document. This <add>can happen in **tests** that compile input elements and <add>trigger click events on them. Depending on the browser (Chrome and Safari) and the trigger method, <add>the change event will not be fired when the input isn't attached to the document. <add> <add>Before: <add> <add>```js <add> it('should update the model', inject(function($compile, $rootScope) { <add> var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope); <add> <add> inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger() <add> expect($rootScope.checkbox).toBe(true); <add> }); <add>``` <add> <add>With this patch, `$rootScope.checkbox` might not be true, because the click event <add>hasn't triggered the change event. To make the test, work append the inputElm to the app's <add>`$rootElement`, and the `$rootElement` to the `$document`. <add> <add>After: <add> <add>```js <add> it('should update the model', inject(function($compile, $rootScope, $rootElement, $document) { <add> var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope); <add> <add> $rootElement.append(inputElm); <add> $document.append($rootElement); <add> <add> inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger() <add> expect($rootScope.checkbox).toBe(true); <add> }); <add>``` <add> <add>`triggerHandler()`: <add> <add>If you are using this jQuery / jqLite function on the input elements, you don't have to attach <add>the elements to the document, but instead change the triggered event to "change". This is because <add>`triggerHandler(event)` only triggers the exact event when it has been added by jQuery / jqLite. <add> <add>### **ngStyle** due to: <add> - **[15bbd3](https://github.com/angular/angular.js/commit/15bbd3e18cd89b91f7206a06c73d40e54a8a48a0)**: use $watchCollection <add> <add>Previously the use of deep watch by ng-style would trigger styles to be <add>re-applied when nested state changed. Now only changes to direct <add>properties of the watched object will trigger changes. <add> <add>### **$compile** due to: <add> - **[38f8c9](https://github.com/angular/angular.js/commit/38f8c97af74649ce224b6dd45f433cc665acfbfb)**: remove the preAssignBindingsEnabled flag <add> <add>Previously, the `$compileProvider.preAssignBindingsEnabled` flag was supported. <add>The flag controlled whether bindings were available inside the controller <add>constructor or only in the `$onInit` hook. The bindings are now no longer <add>available in the constructor. <add> <add>To migrate your code: <add> <add>1. If you haven't invoked `$compileProvider.preAssignBindingsEnabled()` you <add>don't have to do anything to migrate. <add> <add>2. If you specified `$compileProvider.preAssignBindingsEnabled(false)`, you <add>can remove that statement - since AngularJS 1.6.0 this is the default so your <add>app should still work even in AngularJS 1.6 after such removal. Afterwards, <add>migrating to AngularJS 1.7.0 shouldn't require any further action. <add> <add>3. If you specified `$compileProvider.preAssignBindingsEnabled(true)` you need <add>to first migrate your code so that the flag can be flipped to `false`. The <add>instructions on how to do that are available in the "Migrating from 1.5 to 1.6" <add>guide: <add>https://docs.angularjs.org/guide/migration#migrating-from-1-5-to-1-6 <add>Afterwards, remove the `$compileProvider.preAssignBindingsEnabled(true)` <add>statement. <add> <add> - **[6ccbfa](https://github.com/angular/angular.js/commit/6ccbfa65d60a3dc396d0cf6da21b993ad74653fd)**: lower the `xlink:href` security context for SVG's `a` and `image` elements <add> <add>In the unlikely case that an app relied on RESOURCE_URL whitelisting for the <add>purpose of binding to the `xlink:href` property of SVG's `<a>` or `<image>` <add>elements and if the values do not pass the regular URL sanitization, they will <add>break. <add> <add>To fix this you need to ensure that the values used for binding to the affected <add>`xlink:href` contexts are considered safe URLs, e.g. by whitelisting them in <add>`$compileProvider`'s `aHrefSanitizationWhitelist` (for `<a>` elements) or <add>`imgSrcSanitizationWhitelist` (for `<image>` elements). <add> <add> - **[fd4f01](https://github.com/angular/angular.js/commit/fd4f0111188b62773b99ab6eab38b4d2b5d8d727)**: do not use deepWatch in literal one-way bindings <add> <add>Previously when a literal value was passed into a directive/component via <add>one-way binding it would be watched with a deep watcher. <add> <add>For example, for `<my-component input="[a]">`, a new instance of the array <add>would be passed into the directive/component (and trigger $onChanges) not <add>only if `a` changed but also if any sub property of `a` changed such as <add>`a.b` or `a.b.c.d.e` etc. <add> <add>This also means a new but equal value for `a` would NOT trigger such a <add>change. <add> <add>Now literal values use an input-based watch similar to other directive/component <add>one-way bindings. In this context inputs are the non-constant parts of the <add>literal. In the example above the input would be `a`. Changes are only <add>triggered when the inputs to the literal change. <add> <add> - **[1cf728](https://github.com/angular/angular.js/commit/1cf728e209a9e0016068fac2769827e8f747760e)**: add `base[href]` to the list of RESOURCE_URL context attributes <add> <add>Previously, `<base href="{{ $ctrl.baseUrl }}" />` would not require `baseUrl` to <add>be trusted as a RESOURCE_URL. Now, `baseUrl` will be sent to `$sce`'s <add>RESOURCE_URL checks. By default, it will break unless `baseUrl` is of the same <add>origin as the application document. <add> <add>Refer to the <add>[`$sce` API docs](https://code.angularjs.org/snapshot/docs/api/ng/service/$sce) <add>for more info on how to trust a value in a RESOURCE_URL context. <add> <add>Also, concatenation in trusted contexts is not allowed, which means that the <add>following won't work: `<base href="/something/{{ $ctrl.partialPath }}" />`. <add> <add>Either construct complex values in a controller (recommended): <add> <add>```js <add>this.baseUrl = '/something/' + this.partialPath; <add>``` <add>```html <add><base href="{{ $ctrl.baseUrl }}" /> <add>``` <add> <add>Or use string concatenation in the interpolation expression (not recommended <add>except for the simplest of cases): <add> <add>```html <add><base href="{{ '/something/' + $ctrl.partialPath }}" /> <add>``` <add> <add>### **ngTouch** due to: <add> - **[11d9ad](https://github.com/angular/angular.js/commit/11d9ad1eb25eaf5967195e424108207427835d50)**: remove ngClick override, `$touchProvider`, and `$touch` <add> <add>The `ngClick` directive from the ngTouch module has been removed, and with it the <add>corresponding `$touchProvider` and `$touch` service. <add> <add>If you have included ngTouch v1.5.0 or higher in your application, and have not <add>changed the value of `$touchProvider.ngClickOverrideEnabled()`, or injected and used the `$touch` <add>service, then there are no migration steps for your code. Otherwise you must remove references to <add>the provider and service. <add> <add>The `ngClick` override directive had been deprecated and by default disabled since v1.5.0, <add>because of buggy behavior in edge cases, and a general trend to avoid special touch based <add>overrides of click events. In modern browsers, it should not be necessary to use a touch override <add>library: <add> <add>- Chrome, Firefox, Edge, and Safari remove the 300ms delay when <add> `<meta name="viewport" content="width=device-width">` is set. <add>- Internet Explorer 10+, Edge, Safari, and Chrome remove the delay on elements that have the <add> `touch-action` css property is set to `manipulation`. <add> <add>You can find out more in these articles: <add>https://developers.google.com/web/updates/2013/12/300ms-tap-delay-gone-away <add>https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_9_1.html#//apple_ref/doc/uid/TP40014305-CH10-SW8 <add>https://blogs.msdn.microsoft.com/ie/2015/02/24/pointer-events-w3c-recommendation-interoperable-touch-and-removing-the-dreaded-300ms-tap-delay/ <add> <add>### **Angular** due to: <add> - **[1daa4f](https://github.com/angular/angular.js/commit/1daa4f2231a89ee88345689f001805ffffa9e7de)**: remove `angular.lowercase` and `angular.uppercase` <add> <add>The helper functions `angular.lowercase` `and angular.uppercase` have <add>been removed. <add> <add>These functions have been deprecated since 1.5.0. They are internally <add>used, but should not be exposed as they contain special locale handling <add>(for Turkish) to maintain internal consistency regardless of user-set locale. <add> <add>Developers should generally use the built-ins `toLowerCase` and `toUpperCase` <add>or `toLocaleLowerCase` and `toLocaleUpperCase` for special cases. <add> <add>Further, we generally discourage using the angular.x helpers in application code. <add> <add>### **$controller** due to: <add> - **[e269c1](https://github.com/angular/angular.js/commit/e269c14425a3209040f65c022658770e00a36f16)**: remove instantiating controllers defined on window <add> <add>The option to instantiate controllers from constructors on the global `window` object <add>has been removed. Likewise, the deprecated `$controllerProvider.allowGlobals()` <add>method that could enable this behavior, has been removed. <add> <add>This behavior had been deprecated since AngularJS v1.3.0, because polluting the global scope <add>is bad. To migrate, remove the call to $controllerProvider.allowGlobals() in the config, and <add>register your controller via the Module API or the $controllerProvider, e.g. <add> <add>``` <add>angular.module('myModule', []).controller('myController', function() {...}); <add> <add>angular.module('myModule', []).config(function($controllerProvider) { <add> $controllerProvider.register('myController', function() {...}); <add>}); <add> <add>``` <add> <add>### **$rootScope** due to: <add> - **([c2b8fa](https://github.com/angular/angular.js/commit/c2b8fab0a480204374d561d6b9b3d47347ac5570))**: provide correct value of one-time bindings in watchGroup <add> <add>Previously when using `$watchGroup` the entries in `newValues` and <add>`oldValues` represented the *most recent change of each entry*. <add> <add>Now the entries in `oldValues` will always equal the `newValues` of the previous <add>call of the listener. This means comparing the entries in `newValues` and <add>`oldValues` can be used to determine which individual expressions changed. <add> <add>For example `$scope.$watchGroup(['a', 'b'], fn)` would previously: <add> <add>| Action | newValue | oldValue | <add>|----------|------------|------------| <add>| (init) | [undefined, undefined] | [undefined, undefined] | <add>| `a=1` | [1, undefined] | [undefined, undefined] | <add>| `a=2` | [2, undefined] | [1, undefined] | <add>| `b=3` | [2, 3] | [1, undefined] | <add> <add> <add>Now the `oldValue` will always equal the previous `newValue`: <add> <add>| Action | newValue | oldValue | <add>|----------|------------|------------| <add>| (init) | [undefined, undefined] | [undefined, undefined] | <add>| `a=1` | [1, undefined] | [undefined, undefined] | <add>| `a=2` | [2, undefined] | [1, undefined] | <add>| `b=3` | [2, 3] | [2, undefined] | <add> <add>Note the last call now shows `a === 2` in the `oldValues` array. <add> <add>This also makes the `oldValue` of one-time watchers more clear. Previously <add>the `oldValue` of a one-time watcher would remain `undefined` forever. For <add>example `$scope.$watchGroup(['a', '::b'], fn)` would previously: <add> <add>| Action | newValue | oldValue | <add>|----------|------------|------------| <add>| (init) | [undefined, undefined] | [undefined, undefined] | <add>| `a=1` | [1, undefined] | [undefined, undefined] | <add>| `b=2` | [1, 2] | [undefined, undefined] | <add>| `a=b=3` | [3, 2] | [1, undefined] | <add> <add>Where now the `oldValue` will always equal the previous `newValue`: <add> <add>| Action | newValue | oldValue | <add>|----------|------------|------------| <add>| (init) | [undefined, undefined] | [undefined, undefined] | <add>| `a=1` | [1, undefined] | [undefined, undefined] | <add>| `b=2` | [1, 2] | [1, undefined] | <add>| `a=b=3` | [3, 2] | [1, 2] | <add> <ide> <a name="1.6.10"></a> <ide> # 1.6.10 crystalline-persuasion (2018-04-17) <ide>
1
Text
Text
fix typos in pr template
ff8c57b81e458f460af22ca16679f747b783215c
<ide><path>.github/PULL_REQUEST_TEMPLATE.md <ide> remember to adjust the documentation. <ide> <ide> Feel free to ping committers for the review! <ide> <del>In case of existing issue, reference it using one of the following: <add>In case of an existing issue, reference it using one of the following: <ide> <ide> closes: #ISSUE <ide> related: #ISSUE <ide> http://chris.beams.io/posts/git-commit/ <ide> **^ Add meaningful description above** <ide> <ide> Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information. <del>In case of fundamental code change, Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed. <add>In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed. <ide> In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x). <del>In case of backwards incompatible changes please leave a note in a newsfragement file, named `{pr_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments). <add>In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
1
Ruby
Ruby
move layouts to av
c48ce6e73d1f0765902779adab3242b5f4a893c6
<ide><path>actionpack/lib/abstract_controller.rb <ide> module AbstractController <ide> autoload :Callbacks <ide> autoload :Collector <ide> autoload :Helpers <del> autoload :Layouts <ide> autoload :Logger <ide> autoload :Translation <ide> autoload :AssetPaths <ide><path>actionpack/lib/action_controller/base.rb <add>require "action_view/layouts" <ide> require "action_controller/log_subscriber" <ide> require "action_controller/metal/params_wrapper" <ide> <ide> def self.without_modules(*modules) <ide> end <ide> <ide> MODULES = [ <del> AbstractController::Layouts, <ide> AbstractController::Translation, <ide> AbstractController::AssetPaths, <ide> <ide><path>actionview/lib/action_view.rb <ide> module ActionView <ide> autoload :Digestor <ide> autoload :Helpers <ide> autoload :LookupContext <add> autoload :Layout <ide> autoload :PathSet <ide> autoload :RecordIdentifier <ide> autoload :Rendering <ide><path>actionview/lib/action_view/layouts.rb <add>require "active_support/core_ext/module/remove_method" <add> <add> <add>module ActionView <add> # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in <add> # repeated setups. The inclusion pattern has pages that look like this: <add> # <add> # <%= render "shared/header" %> <add> # Hello World <add> # <%= render "shared/footer" %> <add> # <add> # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose <add> # and if you ever want to change the structure of these two includes, you'll have to change all the templates. <add> # <add> # With layouts, you can flip it around and have the common structure know where to insert changing content. This means <add> # that the header and footer are only mentioned in one place, like this: <add> # <add> # // The header part of this layout <add> # <%= yield %> <add> # // The footer part of this layout <add> # <add> # And then you have content pages that look like this: <add> # <add> # hello world <add> # <add> # At rendering time, the content page is computed and then inserted in the layout, like this: <add> # <add> # // The header part of this layout <add> # hello world <add> # // The footer part of this layout <add> # <add> # == Accessing shared variables <add> # <add> # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with <add> # references that won't materialize before rendering time: <add> # <add> # <h1><%= @page_title %></h1> <add> # <%= yield %> <add> # <add> # ...and content pages that fulfill these references _at_ rendering time: <add> # <add> # <% @page_title = "Welcome" %> <add> # Off-world colonies offers you a chance to start a new life <add> # <add> # The result after rendering is: <add> # <add> # <h1>Welcome</h1> <add> # Off-world colonies offers you a chance to start a new life <add> # <add> # == Layout assignment <add> # <add> # You can either specify a layout declaratively (using the #layout class method) or give <add> # it the same name as your controller, and place it in <tt>app/views/layouts</tt>. <add> # If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance. <add> # <add> # For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>, <add> # that template will be used for all actions in PostsController and controllers inheriting <add> # from PostsController. <add> # <add> # If you use a module, for instance Weblog::PostsController, you will need a template named <add> # <tt>app/views/layouts/weblog/posts.html.erb</tt>. <add> # <add> # Since all your controllers inherit from ApplicationController, they will use <add> # <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified <add> # or provided. <add> # <add> # == Inheritance Examples <add> # <add> # class BankController < ActionController::Base <add> # # bank.html.erb exists <add> # <add> # class ExchangeController < BankController <add> # # exchange.html.erb exists <add> # <add> # class CurrencyController < BankController <add> # <add> # class InformationController < BankController <add> # layout "information" <add> # <add> # class TellerController < InformationController <add> # # teller.html.erb exists <add> # <add> # class EmployeeController < InformationController <add> # # employee.html.erb exists <add> # layout nil <add> # <add> # class VaultController < BankController <add> # layout :access_level_layout <add> # <add> # class TillController < BankController <add> # layout false <add> # <add> # In these examples, we have three implicit lookup scenarios: <add> # * The BankController uses the "bank" layout. <add> # * The ExchangeController uses the "exchange" layout. <add> # * The CurrencyController inherits the layout from BankController. <add> # <add> # However, when a layout is explicitly set, the explicitly set layout wins: <add> # * The InformationController uses the "information" layout, explicitly set. <add> # * The TellerController also uses the "information" layout, because the parent explicitly set it. <add> # * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration. <add> # * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method. <add> # * The TillController does not use a layout at all. <add> # <add> # == Types of layouts <add> # <add> # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes <add> # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can <add> # be done either by specifying a method reference as a symbol or using an inline method (as a proc). <add> # <add> # The method reference is the preferred approach to variable layouts and is used like this: <add> # <add> # class WeblogController < ActionController::Base <add> # layout :writers_and_readers <add> # <add> # def index <add> # # fetching posts <add> # end <add> # <add> # private <add> # def writers_and_readers <add> # logged_in? ? "writer_layout" : "reader_layout" <add> # end <add> # end <add> # <add> # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing <add> # is logged in or not. <add> # <add> # If you want to use an inline method, such as a proc, do something like this: <add> # <add> # class WeblogController < ActionController::Base <add> # layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } <add> # end <add> # <add> # If an argument isn't given to the proc, it's evaluated in the context of <add> # the current controller anyway. <add> # <add> # class WeblogController < ActionController::Base <add> # layout proc { logged_in? ? "writer_layout" : "reader_layout" } <add> # end <add> # <add> # Of course, the most common way of specifying a layout is still just as a plain template name: <add> # <add> # class WeblogController < ActionController::Base <add> # layout "weblog_standard" <add> # end <add> # <add> # The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point <add> # <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>. <add> # <add> # Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists. <add> # Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent: <add> # <add> # class ApplicationController < ActionController::Base <add> # layout "application" <add> # end <add> # <add> # class PostsController < ApplicationController <add> # # Will use "application" layout <add> # end <add> # <add> # class CommentsController < ApplicationController <add> # # Will search for "comments" layout and fallback "application" layout <add> # layout nil <add> # end <add> # <add> # == Conditional layouts <add> # <add> # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering <add> # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The <add> # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example: <add> # <add> # class WeblogController < ActionController::Base <add> # layout "weblog_standard", except: :rss <add> # <add> # # ... <add> # <add> # end <add> # <add> # This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will <add> # be rendered directly, without wrapping a layout around the rendered view. <add> # <add> # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so <add> # #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>. <add> # <add> # == Using a different layout in the action render call <add> # <add> # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above. <add> # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller. <add> # You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example: <add> # <add> # class WeblogController < ActionController::Base <add> # layout "weblog_standard" <add> # <add> # def help <add> # render action: "help", layout: "help" <add> # end <add> # end <add> # <add> # This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead. <add> module Layouts <add> extend ActiveSupport::Concern <add> <add> include ActionView::Rendering <add> <add> included do <add> class_attribute :_layout, :_layout_conditions, :instance_accessor => false <add> self._layout = nil <add> self._layout_conditions = {} <add> _write_layout_method <add> end <add> <add> delegate :_layout_conditions, to: :class <add> <add> module ClassMethods <add> def inherited(klass) # :nodoc: <add> super <add> klass._write_layout_method <add> end <add> <add> # This module is mixed in if layout conditions are provided. This means <add> # that if no layout conditions are used, this method is not used <add> module LayoutConditions # :nodoc: <add> private <add> <add> # Determines whether the current action has a layout definition by <add> # checking the action name against the :only and :except conditions <add> # set by the <tt>layout</tt> method. <add> # <add> # ==== Returns <add> # * <tt> Boolean</tt> - True if the action has a layout definition, false otherwise. <add> def _conditional_layout? <add> return unless super <add> <add> conditions = _layout_conditions <add> <add> if only = conditions[:only] <add> only.include?(action_name) <add> elsif except = conditions[:except] <add> !except.include?(action_name) <add> else <add> true <add> end <add> end <add> end <add> <add> # Specify the layout to use for this class. <add> # <add> # If the specified layout is a: <add> # String:: the String is the template name <add> # Symbol:: call the method specified by the symbol, which will return the template name <add> # false:: There is no layout <add> # true:: raise an ArgumentError <add> # nil:: Force default layout behavior with inheritance <add> # <add> # ==== Parameters <add> # * <tt>layout</tt> - The layout to use. <add> # <add> # ==== Options (conditions) <add> # * :only - A list of actions to apply this layout to. <add> # * :except - Apply this layout to all actions but this one. <add> def layout(layout, conditions = {}) <add> include LayoutConditions unless conditions.empty? <add> <add> conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} } <add> self._layout_conditions = conditions <add> <add> self._layout = layout <add> _write_layout_method <add> end <add> <add> # If no layout is supplied, look for a template named the return <add> # value of this method. <add> # <add> # ==== Returns <add> # * <tt>String</tt> - A template name <add> def _implied_layout_name # :nodoc: <add> controller_path <add> end <add> <add> # Creates a _layout method to be called by _default_layout . <add> # <add> # If a layout is not explicitly mentioned then look for a layout with the controller's name. <add> # if nothing is found then try same procedure to find super class's layout. <add> def _write_layout_method # :nodoc: <add> remove_possible_method(:_layout) <add> <add> prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] <add> default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super" <add> name_clause = if name <add> default_behavior <add> else <add> <<-RUBY <add> super <add> RUBY <add> end <add> <add> layout_definition = case _layout <add> when String <add> _layout.inspect <add> when Symbol <add> <<-RUBY <add> #{_layout}.tap do |layout| <add> return #{default_behavior} if layout.nil? <add> unless layout.is_a?(String) || !layout <add> raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \ <add> "should have returned a String, false, or nil" <add> end <add> end <add> RUBY <add> when Proc <add> define_method :_layout_from_proc, &_layout <add> protected :_layout_from_proc <add> <<-RUBY <add> result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'}) <add> return #{default_behavior} if result.nil? <add> result <add> RUBY <add> when false <add> nil <add> when true <add> raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil" <add> when nil <add> name_clause <add> end <add> <add> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <add> def _layout <add> if _conditional_layout? <add> #{layout_definition} <add> else <add> #{name_clause} <add> end <add> end <add> private :_layout <add> RUBY <add> end <add> end <add> <add> def _normalize_options(options) # :nodoc: <add> super <add> <add> if _include_layout?(options) <add> layout = options.delete(:layout) { :default } <add> options[:layout] = _layout_for_option(layout) <add> end <add> end <add> <add> attr_internal_writer :action_has_layout <add> <add> def initialize(*) # :nodoc: <add> @_action_has_layout = true <add> super <add> end <add> <add> # Controls whether an action should be rendered using a layout. <add> # If you want to disable any <tt>layout</tt> settings for the <add> # current action so that it is rendered without a layout then <add> # either override this method in your controller to return false <add> # for that action or set the <tt>action_has_layout</tt> attribute <add> # to false before rendering. <add> def action_has_layout? <add> @_action_has_layout <add> end <add> <add> private <add> <add> def _conditional_layout? <add> true <add> end <add> <add> # This will be overwritten by _write_layout_method <add> def _layout; end <add> <add> # Determine the layout for a given name, taking into account the name type. <add> # <add> # ==== Parameters <add> # * <tt>name</tt> - The name of the template <add> def _layout_for_option(name) <add> case name <add> when String then _normalize_layout(name) <add> when Proc then name <add> when true then Proc.new { _default_layout(true) } <add> when :default then Proc.new { _default_layout(false) } <add> when false, nil then nil <add> else <add> raise ArgumentError, <add> "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}" <add> end <add> end <add> <add> def _normalize_layout(value) <add> value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value <add> end <add> <add> # Returns the default layout for this controller. <add> # Optionally raises an exception if the layout could not be found. <add> # <add> # ==== Parameters <add> # * <tt>require_layout</tt> - If set to true and layout is not found, <add> # an ArgumentError exception is raised (defaults to false) <add> # <add> # ==== Returns <add> # * <tt>template</tt> - The template object for the default layout (or nil) <add> def _default_layout(require_layout = false) <add> begin <add> value = _layout if action_has_layout? <add> rescue NameError => e <add> raise e, "Could not render layout: #{e.message}" <add> end <add> <add> if require_layout && action_has_layout? && !value <add> raise ArgumentError, <add> "There was no default layout for #{self.class} in #{view_paths.inspect}" <add> end <add> <add> _normalize_layout(value) <add> end <add> <add> def _include_layout?(options) <add> (options.keys & [:text, :inline, :partial]).empty? || options.key?(:layout) <add> end <add> end <add>end <ide><path>actionview/lib/action_view/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> end <ide> end <ide> end <add> <add> initializer "action_view.setup_action_controller" do |app| <add> ActiveSupport.on_load(:action_controller) do <add> ActionController::Base.send(:include, ActionView::Layouts) <add> end <add> end <ide> end <ide> end
5
Javascript
Javascript
handle errors of react lifecycle methods (#661)
8570d19af69e5ecfc4f0d4e8b2af937efbc860b7
<ide><path>client/next-dev.js <ide> import 'react-hot-loader/patch' <del>import * as next from './next' <add>import patch from './patch-react' <ide> <add>// apply patch first <add>patch((err) => { <add> console.error(err) <add> next.renderError(err) <add>}) <add> <add>const next = require('./next') <ide> window.next = next <ide><path>client/next.js <ide> import { createElement } from 'react' <del>import { render } from 'react-dom' <add>import ReactDOM from 'react-dom' <ide> import HeadManager from './head-manager' <ide> import { rehydrate } from '../lib/css' <ide> import { createRouter } from '../lib/router' <ide> export const router = createRouter(pathname, query, { <ide> <ide> const headManager = new HeadManager() <ide> const container = document.getElementById('__next') <del>const appProps = { Component, props, router, headManager } <add>const defaultProps = { Component, ErrorComponent, props, router, headManager } <ide> <ide> if (ids && ids.length) rehydrate(ids) <del>render(createElement(App, appProps), container) <add> <add>render() <add> <add>export function render (props = {}) { <add> try { <add> doRender(props) <add> } catch (err) { <add> renderError(err) <add> } <add>} <add> <add>export async function renderError (err) { <add> const { pathname, query } = router <add> const props = await ErrorComponent.getInitialProps({ err, pathname, query }) <add> try { <add> doRender({ Component: ErrorComponent, props }) <add> } catch (err2) { <add> console.error(err2) <add> } <add>} <add> <add>function doRender (props) { <add> const appProps = { ...defaultProps, ...props } <add> ReactDOM.render(createElement(App, appProps), container) <add>} <ide><path>client/patch-react.js <add>// monkeypatch React for fixing https://github.com/facebook/react/issues/2461 <add>// based on https://gist.github.com/Aldredcz/4d63b0a9049b00f54439f8780be7f0d8 <add> <add>import React from 'react' <add> <add>let patched = false <add> <add>export default (handleError = () => {}) => { <add> if (patched) { <add> throw new Error('React is already monkeypatched') <add> } <add> <add> patched = true <add> <add> const { createElement } = React <add> <add> React.createElement = function (Component, ...rest) { <add> if (typeof Component === 'function') { <add> const { prototype } = Component <add> if (prototype && prototype.render) { <add> prototype.render = wrapRender(prototype.render) <add> } else { <add> // stateless component <add> Component = wrapRender(Component) <add> } <add> } <add> <add> return createElement.call(this, Component, ...rest) <add> } <add> <add> const { Component: { prototype: componentPrototype } } = React <add> const { forceUpdate } = componentPrototype <add> <add> componentPrototype.forceUpdate = function (...args) { <add> if (this.render) { <add> this.render = wrapRender(this.render) <add> } <add> return forceUpdate.apply(this, args) <add> } <add> <add> function wrapRender (render) { <add> if (render.__wrapped) { <add> return render.__wrapped <add> } <add> <add> const _render = function (...args) { <add> try { <add> return render.apply(this, args) <add> } catch (err) { <add> handleError(err) <add> return null <add> } <add> } <add> <add> // copy all properties <add> Object.assign(_render, render) <add> <add> render.__wrapped = _render.__wrapped = _render <add> <add> return _render <add> } <add>} <ide><path>lib/app.js <ide> export default class App extends Component { <ide> try { <ide> this.setState(state) <ide> } catch (err) { <del> console.error(err) <add> this.handleError(err) <ide> } <ide> } <ide> <ide> export default class App extends Component { <ide> try { <ide> this.setState(state) <ide> } catch (err) { <del> console.error(err) <add> this.handleError(err) <ide> } <ide> }) <ide> } <ide> export default class App extends Component { <ide> <Component {...props} /> <ide> </AppContainer> <ide> } <add> <add> async handleError (err) { <add> console.error(err) <add> <add> const { router, ErrorComponent } = this.props <add> const { pathname, query } = router <add> const props = await ErrorComponent.getInitialProps({ err, pathname, query }) <add> const state = propsToState({ Component: ErrorComponent, props, router }) <add> <add> try { <add> this.setState(state) <add> } catch (err2) { <add> console.error(err2) <add> } <add> } <ide> } <ide> <ide> function propsToState (props) {
4
Javascript
Javascript
fix incorrect method name in code comment
1e54c6491a4c900822854127ae9a4166ca8e37c1
<ide><path>packages/ember-handlebars/lib/controls/text_support.js <ide> Ember.TextSupport = Ember.Mixin.create({ <ide> Called by the `Ember.TextSupport` mixin on keyUp if keycode matches 13. <ide> Uses sendAction to send the `enter` action to the controller. <ide> <del> @method insertNewLine <add> @method insertNewline <ide> @param {Event} event <ide> */ <ide> insertNewline: function(event) {
1
Python
Python
set port id
97ee8592b7186f4cde1140d16e9d4255ac753147
<ide><path>libcloud/compute/drivers/openstack.py <ide> def ex_attach_floating_ip_to_node(self, node, ip): <ide> resp = self.network_connection.request( <ide> "/v2.0/floatingips/%s" % ip.id, <ide> method="PUT", <del> data={"floatingip": {"port_id": ports[0]}}, <add> data={"floatingip": {"port_id": ports[0].id}}, <ide> ) <ide> return resp.status == httplib.ACCEPTED <ide> else:
1
Ruby
Ruby
add caveats to avoid scaring people
1c176348caf6f6d220a1f877433a3ea581ab3030
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def doctor <ide> methods.each do |method| <ide> out = checks.send(method) <ide> unless out.nil? or out.empty? <add> if first_warning <add> puts <<-EOS.undent <add> #{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers <add> with debugging if you file an issue. If everything you use Homebrew for is <add> working fine: please don't worry and just ignore them. Thanks!#{Tty.reset} <add> EOS <add> end <add> <ide> lines = out.to_s.split('\n') <del> puts unless first_warning <add> puts <ide> opoo lines.shift <ide> Homebrew.failed = true <ide> puts lines
1
Mixed
Ruby
fix migrations with enable_extension
40708c3670df44659235aade62f31c6c2a9af223
<ide><path>activerecord/CHANGELOG.md <add>* Fix bug that added `table_name_prefix` and `table_name_suffix` to <add> extension names in PostgreSQL when migrating. <add> <add> *Joao Carlos* <add> <ide> * Usage of `implicit_readonly` is being removed`. Please use `readonly` method <ide> explicitly to mark records as `readonly. <ide> Fixes #10615. <ide><path>activerecord/lib/active_record/migration.rb <ide> def method_missing(method, *arguments, &block) <ide> <ide> say_with_time "#{method}(#{arg_list})" do <ide> unless @connection.respond_to? :revert <del> unless arguments.empty? || method == :execute <add> unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method) <ide> arguments[0] = Migrator.proper_table_name(arguments.first) <ide> arguments[1] = Migrator.proper_table_name(arguments.second) if method == :rename_table <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/extension_migration_test.rb <add>require "cases/helper" <add>require "active_record/base" <add>require "active_record/connection_adapters/postgresql_adapter" <add> <add>class PostgresqlExtensionMigrationTest < ActiveRecord::TestCase <add> self.use_transactional_fixtures = false <add> <add> class EnableHstore < ActiveRecord::Migration <add> def change <add> enable_extension "hstore" <add> end <add> end <add> <add> class DisableHstore < ActiveRecord::Migration <add> def change <add> disable_extension "hstore" <add> end <add> end <add> <add> def setup <add> super <add> <add> @connection = ActiveRecord::Base.connection <add> <add> unless @connection.supports_extensions? <add> return skip("no extension support") <add> end <add> <add> ActiveRecord::Base.table_name_prefix = "p_" <add> ActiveRecord::Base.table_name_suffix = "_s" <add> ActiveRecord::SchemaMigration.delete_all rescue nil <add> ActiveRecord::Migration.verbose = false <add> end <add> <add> def teardown <add> ActiveRecord::Base.table_name_prefix = "" <add> ActiveRecord::Base.table_name_suffix = "" <add> ActiveRecord::SchemaMigration.delete_all rescue nil <add> ActiveRecord::Migration.verbose = true <add> <add> super <add> end <add> <add> def test_enable_extension_migration_ignores_prefix_and_suffix <add> @connection.disable_extension("hstore") <add> <add> migrations = [EnableHstore.new(nil, 1)] <add> ActiveRecord::Migrator.new(:up, migrations).migrate <add> assert @connection.extension_enabled?("hstore"), "extension hstore should be enabled" <add> end <add> <add> def test_disable_extension_migration_ignores_prefix_and_suffix <add> @connection.enable_extension("hstore") <add> <add> migrations = [DisableHstore.new(nil, 1)] <add> ActiveRecord::Migrator.new(:up, migrations).migrate <add> assert_not @connection.extension_enabled?("hstore"), "extension hstore should not be enabled" <add> end <add>end
3
Mixed
Javascript
use a shared symbol for util.inspect.custom
dadd6e16888baac8fd110432b81f3fd1237be3e1
<ide><path>doc/api/util.md <ide> terminals. <ide> <ide> <!-- type=misc --> <ide> <del>Objects may also define their own `[util.inspect.custom](depth, opts)` function <del>that `util.inspect()` will invoke and use the result of when inspecting the <del>object: <add>Objects may also define their own <add>[`[util.inspect.custom](depth, opts)`][util.inspect.custom] function, <add>which `util.inspect()` will invoke and use the result of when inspecting <add>the object: <ide> <ide> ```js <ide> const util = require('util'); <ide> util.inspect(obj); <ide> ### util.inspect.custom <ide> <!-- YAML <ide> added: v6.6.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/20857 <add> description: This is now defined as a shared symbol. <ide> --> <ide> <del>* {symbol} that can be used to declare custom inspect functions, see <del>[Custom inspection functions on Objects][]. <add>* {symbol} that can be used to declare custom inspect functions. <add> <add>In addition to being accessible through `util.inspect.custom`, this <add>symbol is [registered globally][global symbol registry] and can be <add>accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`. <add> <add>```js <add>const inspect = Symbol.for('nodejs.util.inspect.custom'); <add> <add>class Password { <add> constructor(value) { <add> this.value = value; <add> } <add> <add> toString() { <add> return 'xxxxxxxx'; <add> } <add> <add> [inspect]() { <add> return `Password <${this.toString()}>`; <add> } <add>} <add> <add>const password = new Password('r0sebud'); <add>console.log(password); <add>// Prints Password <xxxxxxxx> <add>``` <add> <add>See [Custom inspection functions on Objects][] for more details. <ide> <ide> ### util.inspect.defaultOptions <ide> <!-- YAML <ide> Deprecated predecessor of `console.log`. <ide> [`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray <ide> [`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer <ide> [`ArrayBuffer.isView()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView <del>[async function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function <ide> [`assert.deepStrictEqual()`]: assert.html#assert_assert_deepstrictequal_actual_expected_message <ide> [`Buffer.isBuffer()`]: buffer.html#buffer_class_method_buffer_isbuffer_obj <ide> [`console.error()`]: console.html#console_console_error_data_args <ide> Deprecated predecessor of `console.log`. <ide> [Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects <ide> [WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ <ide> [Common System Errors]: errors.html#errors_common_system_errors <add>[async function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function <ide> [constructor]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor <add>[global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for <ide> [list of deprecated APIS]: deprecations.html#deprecations_list_of_deprecated_apis <ide> [semantically incompatible]: https://github.com/nodejs/node/issues/4179 <add>[util.inspect.custom]: #util_util_inspect_custom <ide><path>lib/internal/util.js <ide> module.exports = { <ide> <ide> // Symbol used to provide a custom inspect function for an object as an <ide> // alternative to using 'inspect' <del> customInspectSymbol: Symbol('util.inspect.custom'), <add> customInspectSymbol: Symbol.for('nodejs.util.inspect.custom'), <ide> <ide> // Used by the buffer module to capture an internal reference to the <ide> // default isEncoding implementation, just in case userland overrides it. <ide><path>test/parallel/test-assert.js <ide> assert.throws( <ide> '+ {}\n' + <ide> '- {\n' + <ide> "- loop: 'forever',\n" + <del> '- [Symbol(util.inspect.custom)]: [Function]\n' + <add> '- [Symbol(nodejs.util.inspect.custom)]: [Function]\n' + <ide> '- }' <ide> }); <ide> <ide><path>test/parallel/test-console.js <ide> for (const expected of expectedStrings) { <ide> } <ide> <ide> assert.strictEqual(strings.shift(), <del> "{ foo: 'bar',\n [Symbol(util.inspect.custom)]: " + <del> '[Function: [util.inspect.custom]] }\n'); <add> "{ foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]: " + <add> '[Function: [nodejs.util.inspect.custom]] }\n'); <ide> assert.strictEqual(strings.shift(), <del> "{ foo: 'bar',\n [Symbol(util.inspect.custom)]: " + <del> '[Function: [util.inspect.custom]] }\n'); <add> "{ foo: 'bar',\n [Symbol(nodejs.util.inspect.custom)]: " + <add> '[Function: [nodejs.util.inspect.custom]] }\n'); <ide> assert.ok(strings.shift().includes('foo: [Object]')); <ide> assert.strictEqual(strings.shift().includes('baz'), false); <ide> assert.strictEqual(strings.shift(), 'inspect inspect\n'); <ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); <ide> { <ide> const x = { [util.inspect.custom]: util.inspect }; <ide> assert(util.inspect(x).includes( <del> '[Symbol(util.inspect.custom)]:\n { [Function: inspect]')); <add> '[Symbol(nodejs.util.inspect.custom)]:\n { [Function: inspect]')); <ide> } <ide> <ide> // `util.inspect` should display the escaped value of a key. <ide> util.inspect({ hasOwnProperty: null }); <ide> }; <ide> <ide> util.inspect(subject, { customInspectOptions: true }); <add> <add> // util.inspect.custom is a shared symbol which can be accessed as <add> // Symbol.for("nodejs.util.inspect.custom"). <add> const inspect = Symbol.for('nodejs.util.inspect.custom'); <add> <add> subject[inspect] = () => ({ baz: 'quux' }); <add> <add> assert.strictEqual(util.inspect(subject), '{ baz: \'quux\' }'); <add> <add> subject[inspect] = (depth, opts) => { <add> assert.strictEqual(opts.customInspectOptions, true); <add> }; <add> <add> util.inspect(subject, { customInspectOptions: true }); <ide> } <ide> <ide> { <ide> // Returning `this` from a custom inspection function works. <ide> const subject = { a: 123, [util.inspect.custom]() { return this; } }; <del> const UIC = 'util.inspect.custom'; <add> const UIC = 'nodejs.util.inspect.custom'; <ide> assert.strictEqual(util.inspect(subject), <ide> `{ a: 123,\n [Symbol(${UIC})]: [Function: [${UIC}]] }`); <ide> } <ide> util.inspect(process); <ide> const obj = { [util.inspect.custom]: 'fhqwhgads' }; <ide> assert.strictEqual( <ide> util.inspect(obj), <del> "{ [Symbol(util.inspect.custom)]: 'fhqwhgads' }" <add> "{ [Symbol(nodejs.util.inspect.custom)]: 'fhqwhgads' }" <ide> ); <ide> } <ide>
5
Javascript
Javascript
add extra tests for basename with ext option
cc506f33ab80d4b1c71c03d4511384ed2d4daf0f
<ide><path>test/parallel/test-path-basename.js <ide> const path = require('path'); <ide> assert.strictEqual(path.basename(__filename), 'test-path-basename.js'); <ide> assert.strictEqual(path.basename(__filename, '.js'), 'test-path-basename'); <ide> assert.strictEqual(path.basename('.js', '.js'), ''); <add>assert.strictEqual(path.basename('js', '.js'), 'js'); <add>assert.strictEqual(path.basename('file.js', '.ts'), 'file.js'); <add>assert.strictEqual(path.basename('file', '.js'), 'file'); <add>assert.strictEqual(path.basename('file.js.old', '.js.old'), 'file'); <ide> assert.strictEqual(path.basename(''), ''); <ide> assert.strictEqual(path.basename('/dir/basename.ext'), 'basename.ext'); <ide> assert.strictEqual(path.basename('/basename.ext'), 'basename.ext');
1
Java
Java
fix regression with raw responseentity type
c5e360d886931f761c2be5ff4b31d5df2042d415
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java <ide> protected <T> void writeWithMessageConverters(T returnValue, MethodParameter ret <ide> throws IOException, HttpMediaTypeNotAcceptableException { <ide> <ide> Class<?> returnValueClass = getReturnValueType(returnValue, returnType); <del> if (returnValue == null && Void.class.equals(returnValueClass)) { <del> return; <del> } <del> <ide> HttpServletRequest servletRequest = inputMessage.getServletRequest(); <ide> List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest); <ide> List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass); <ide> protected <T> void writeWithMessageConverters(T returnValue, MethodParameter ret <ide> } <ide> } <ide> if (compatibleMediaTypes.isEmpty()) { <del> throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes); <add> if (returnValue != null) { <add> throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes); <add> } <add> return; <ide> } <ide> <ide> List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes); <ide> else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICAT <ide> } <ide> } <ide> } <del> throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes); <add> <add> if (returnValue != null) { <add> throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes); <add> } <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java <ide> private Type getHttpEntityType(MethodParameter parameter) { <ide> Type parameterType = parameter.getGenericParameterType(); <ide> if (parameterType instanceof ParameterizedType) { <ide> ParameterizedType type = (ParameterizedType) parameterType; <del> if (type.getActualTypeArguments().length == 1) { <del> return type.getActualTypeArguments()[0]; <add> if (type.getActualTypeArguments().length != 1) { <add> throw new IllegalArgumentException("Expected single generic parameter on '" + <add> parameter.getParameterName() + "' in method " + parameter.getMethod()); <ide> } <add> return type.getActualTypeArguments()[0]; <add> } <add> else if (parameterType instanceof Class) { <add> return Object.class; <ide> } <ide> throw new IllegalArgumentException("HttpEntity parameter '" + parameter.getParameterName() + <del> "' in method " + parameter.getMethod() + " is not parameterized or has more than one parameter"); <add> "' in method " + parameter.getMethod() + " is not parameterized"); <ide> } <ide> <ide> @Override <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, <ide> } <ide> <ide> Object body = responseEntity.getBody(); <del> if (body != null || getAdviceChain().hasAdvice()) { <del> writeWithMessageConverters(body, returnType, inputMessage, outputMessage); <del> } <add> <add> // Try even with null body. ResponseBodyAdvice could get involved. <add> writeWithMessageConverters(body, returnType, inputMessage, outputMessage); <add> <ide> // Ensure headers are flushed even if no body was written <ide> outputMessage.getBody(); <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, <ide> throws IOException, HttpMediaTypeNotAcceptableException { <ide> <ide> mavContainer.setRequestHandled(true); <del> if (returnValue != null || getAdviceChain().hasAdvice()) { <del> writeWithMessageConverters(returnValue, returnType, webRequest); <del> } <add> <add> // Try even with null return value. ResponseBodyAdvice could get involved. <add> writeWithMessageConverters(returnValue, returnType, webRequest); <ide> } <ide> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java <ide> public void wrapConcurrentResult_ResponseEntity() throws Exception { <ide> List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); <ide> converters.add(new StringHttpMessageConverter()); <ide> this.returnValueHandlers.addHandler(new HttpEntityMethodProcessor(converters)); <del> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handle"); <add> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred"); <ide> handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>("bar", HttpStatus.OK)); <ide> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <ide> <ide> public void wrapConcurrentResult_ResponseEntityNullBody() throws Exception { <ide> List<Object> advice = Arrays.asList(mock(ResponseBodyAdvice.class)); <ide> HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters, null, advice); <ide> this.returnValueHandlers.addHandler(processor); <del> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handle"); <add> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred"); <ide> handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>(HttpStatus.OK)); <ide> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <ide> <ide> public void wrapConcurrentResult_ResponseEntityNullReturnValue() throws Exceptio <ide> List<Object> advice = Arrays.asList(mock(ResponseBodyAdvice.class)); <ide> HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters, null, advice); <ide> this.returnValueHandlers.addHandler(processor); <del> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handle"); <add> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred"); <ide> handlerMethod = handlerMethod.wrapConcurrentResult(null); <ide> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <ide> <ide> assertEquals(200, this.response.getStatus()); <ide> assertEquals("", this.response.getContentAsString()); <ide> } <ide> <add> // SPR-12287 (16/Oct/14 comments) <add> <add> @Test <add> public void responseEntityRawTypeWithNullBody() throws Exception { <add> List<HttpMessageConverter<?>> converters = Arrays.asList(new StringHttpMessageConverter()); <add> List<Object> advice = Arrays.asList(mock(ResponseBodyAdvice.class)); <add> HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters, null, advice); <add> this.returnValueHandlers.addHandler(processor); <add> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleRawType"); <add> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <add> <add> assertEquals(200, this.response.getStatus()); <add> assertEquals("", this.response.getContentAsString()); <add> } <add> <ide> private ServletInvocableHandlerMethod getHandlerMethod(Object controller, <ide> String methodName, Class<?>... argTypes) throws NoSuchMethodException { <ide> <ide> Method method = controller.getClass().getDeclaredMethod(methodName, argTypes); <ide> ServletInvocableHandlerMethod handlerMethod = new ServletInvocableHandlerMethod(controller, method); <del> handlerMethod.setHandlerMethodArgumentResolvers(argumentResolvers); <del> handlerMethod.setHandlerMethodReturnValueHandlers(returnValueHandlers); <add> handlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); <add> handlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers); <ide> return handlerMethod; <ide> } <ide> <ide> public DeferredResult<String> handle() { <ide> private static class ResponseEntityHandler { <ide> <ide> @SuppressWarnings("unused") <del> public DeferredResult<ResponseEntity<String>> handle() { <add> public DeferredResult<ResponseEntity<String>> handleDeferred() { <ide> return new DeferredResult<>(); <ide> } <add> <add> @SuppressWarnings("unused") <add> public ResponseEntity handleRawType() { <add> return ResponseEntity.ok().build(); <add> } <ide> } <ide> <ide> private static class ExceptionRaisingReturnValueHandler implements HandlerMethodReturnValueHandler {
4
PHP
PHP
add tests for data_get with null values
aceef36ebcc2e1e3bd9f10f628cf0f8ce4537d26
<ide><path>tests/Support/SupportHelpersTest.php <ide> public function testDataGet() <ide> { <ide> $object = (object) ['users' => ['name' => ['Taylor', 'Otwell']]]; <ide> $array = [(object) ['users' => [(object) ['name' => 'Taylor']]]]; <del> $dottedArray = ['users' => ['first.name' => 'Taylor']]; <del> $arrayAccess = new SupportTestArrayAccess(['price' => 56, 'user' => new SupportTestArrayAccess(['name' => 'John'])]); <add> $dottedArray = ['users' => ['first.name' => 'Taylor', 'middle.name' => null]]; <add> $arrayAccess = new SupportTestArrayAccess(['price' => 56, 'user' => new SupportTestArrayAccess(['name' => 'John']), 'email' => null]); <ide> <ide> $this->assertEquals('Taylor', data_get($object, 'users.name.0')); <ide> $this->assertEquals('Taylor', data_get($array, '0.users.0.name')); <ide> $this->assertNull(data_get($array, '0.users.3')); <ide> $this->assertEquals('Not found', data_get($array, '0.users.3', 'Not found')); <ide> $this->assertEquals('Not found', data_get($array, '0.users.3', function () { return 'Not found'; })); <ide> $this->assertEquals('Taylor', data_get($dottedArray, ['users', 'first.name'])); <add> $this->assertNull(data_get($dottedArray, ['users', 'middle.name'])); <ide> $this->assertEquals('Not found', data_get($dottedArray, ['users', 'last.name'], 'Not found')); <ide> $this->assertEquals(56, data_get($arrayAccess, 'price')); <ide> $this->assertEquals('John', data_get($arrayAccess, 'user.name')); <ide> $this->assertEquals('void', data_get($arrayAccess, 'foo', 'void')); <ide> $this->assertEquals('void', data_get($arrayAccess, 'user.foo', 'void')); <ide> $this->assertNull(data_get($arrayAccess, 'foo')); <ide> $this->assertNull(data_get($arrayAccess, 'user.foo')); <add> $this->assertNull(data_get($arrayAccess, 'email', 'Not found')); <ide> } <ide> <ide> public function testDataGetWithNestedArrays() <ide> public function __construct($attributes = []) <ide> <ide> public function offsetExists($offset) <ide> { <del> return isset($this->attributes[$offset]); <add> return array_key_exists($offset, $this->attributes); <ide> } <ide> <ide> public function offsetGet($offset)
1
Text
Text
add purpose section
cff232a8a2b34922ffc35908fa0d36bfa92582ef
<ide><path>README.md <ide> piece of cake. Best of all?? It makes development fun! <ide> * Developer Guide: http://docs.angularjs.org/guide <ide> * Contribution guidelines: [CONTRIBUTING.md](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md) <ide> * Dashboard: http://dashboard.angularjs.org <del> <add> <ide> Building AngularJS <ide> --------- <ide> [Once you have your environment set up](http://docs.angularjs.org/misc/contribute) just run: <ide> To learn more about the grunt tasks, run `grunt --help` and also read our <ide> <ide> [![Analytics](https://ga-beacon.appspot.com/UA-8594346-11/angular.js/README.md?pixel)](https://github.com/igrigorik/ga-beacon) <ide> <add>What to Use AngularJS for and When to Use it <add>--------- <add>AngularJS is the next generation framework where each component is designed to work with every other component in an interconnected way like a well-oiled machine. AngularJS is JavaScript MVC made easy and done right. (Well it is not really MVC, read on, to understand what this means.) <add> <add>#### MVC, no, MV* done the right way! <add>MVC, short for Model-View-Controller, is a design pattern, i.e. how the code should be organized and how the different parts of an application separated for proper readability and debugging. Model is the data and the database. View is the user interface and what the user sees. Controller is the main link between Model and View. These are the three pillars of major programming frameworks present on the market today. On the other hand AngularJS works on MV*, short for Model-View-_Whatever_. The _Whatever_ is AngularJS's way of telling that you may create any kind of linking between the Model and the View here. <add> <add>Unlike other frameworks in any programming language, where MVC, the three separate components, each one has to be written and then connected by the programmer, AngularJS helps the programmer by asking him/her to just create these and everything else will be taken care of by AngularJS. <add> <add>#### Interconnection with HTML at the root level <add>AngularJS uses HTML to define the user's interface. AngularJS also enables the programmer to write new HTML tags (AngularJS Directives) and increase the readability and understandability of the HTML code. Directives are AngularJS’s way of bringing additional functionality to HTML. Directives achieve this by enabling us to invent our own HTML elements. This also helps in making the code DRY (Don't Repeat Yourself), which means once created, a new directive can be used anywhere within the application. <add> <add>#### Data Handling made simple <add>Data and Data Models in AngularJS are plain JavaScript objects and one can add and change properties directly on it and loop over objects and arrays at will. <add> <add>#### Two-way Data Binding <add>One of AngularJS's strongest features. Two-way Data Binding means that if something changes in the Model, the change gets reflected in the View instantaneously, and the same happens the other way around. This is also referred to as Reactive Programming, i.e. suppose `a = b + c` is being programmed and after this, if the value of `b` and/or `c` is changed then the value of `a` will be automatically updated to reflect the change. AngularJS uses its "scopes" as a glue between the Model and View and makes these updates in one available for the other. <add> <add>#### Less Written Code and Easily Maintable Code <add>Everything in AngularJS is created to enable the programmer ends up writing less code that is easily maintainable and readable by any other new person on the team. Believe it or not, one can write a complete working two-way data binded application in less than 10 lines of code. Try and see for yourself! <add> <add>#### Testing Ready <add>AngularJS has Dependency Injection, i.e. it takes care of providing all the necessary dependencies to its controllers whenever required. This helps in making the AngularJS code ready for unit testing by making use of mock dependencies created and injected. This makes AngularJS more modular and easily testable thus in turn helping a team create more robust applications.
1
Go
Go
change placement of readonly filesystem
2c58a1e2886433a4266615b1f492f829e7a6f53f
<ide><path>pkg/libcontainer/nsinit/mount.go <ide> func setupNewMountNamespace(rootfs string, bindMounts []libcontainer.Mount, cons <ide> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, ""); err != nil { <ide> return fmt.Errorf("mouting %s as bind %s", rootfs, err) <ide> } <del> if readonly { <del> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, ""); err != nil { <del> return fmt.Errorf("mounting %s as readonly %s", rootfs, err) <del> } <del> } <ide> if err := mountSystem(rootfs); err != nil { <ide> return fmt.Errorf("mount system %s", err) <ide> } <ide> func setupNewMountNamespace(rootfs string, bindMounts []libcontainer.Mount, cons <ide> } <ide> } <ide> <add> if readonly { <add> if err := system.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, ""); err != nil { <add> return fmt.Errorf("mounting %s as readonly %s", rootfs, err) <add> } <add> } <add> <ide> system.Umask(0022) <ide> <ide> return nil
1
Ruby
Ruby
autosave => false on an association
580ec0dccde075330abe68eb13badb03b225f9b4
<ide><path>activerecord/lib/active_record/associations.rb <ide> def association_instance_set(name, association) <ide> # You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be <ide> # aware of, mostly involving the saving of associated objects. <ide> # <del> # Unless you enable the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>, <del> # <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association, <del> # in which case the members are always saved. <add> # Unless you set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>, <add> # <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it <add> # to +true+ will _always_ save the members, whereas setting it to +false+ will <add> # _never_ save the members. <ide> # <ide> # === One-to-one associations <ide> #
1
Text
Text
remove "related issues" from pull request template
576a1b547b19d9c6d9244eb1a7ac8f81c24ed3d2
<ide><path>.github/PULL_REQUEST_TEMPLATE.md <ide> Bug fixes and new features should include tests and possibly benchmarks. <ide> Contributors guide: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md <ide> --> <ide> <del>#### Related Issues <del> <del>Fixes: https://github.com/nodejs/node/issues/<issue_number> <del> <ide> ##### Checklist <ide> <!-- Remove items that do not apply. For completed items, change [ ] to [x]. --> <ide>
1
Ruby
Ruby
fix constant redefined warning
6be0b57a8237b113a27a5243bef9a5469f4cb031
<ide><path>Library/Homebrew/formulary.rb <ide> def self.load_formula(name, path, contents, namespace, flags:) <ide> require "formula" <ide> <ide> mod = Module.new <add> remove_const(namespace) if const_defined?(namespace) <ide> const_set(namespace, mod) <ide> <ide> begin
1
PHP
PHP
remove extra import
8c9a043bae8c806db94d2716b19baaec3de408c3
<ide><path>src/I18n/DateFormatTrait.php <ide> */ <ide> namespace Cake\I18n; <ide> <del>use Cake\I18n\RelativeTimeFormatter; <ide> use DateTime; <ide> use IntlDateFormatter; <ide>
1
Javascript
Javascript
fix merge error of prs
afd889a73504887860aa20d9cb6281a954259e23
<ide><path>test/watchCases/scope-hoisting/caching-inner-source/0/index.js <ide> it("should not crash when scope-hoisted modules change", function() { <del> require("./module").default.should.be.eql(WATCH_STEP); <del>}) <add> expect(require("./module").default).toBe(WATCH_STEP); <add>});
1
Text
Text
update docs to use correct import statement
d20918319a8bf546ca94862151ddd88c7347d93f
<ide><path>docs/Troubleshooting.md <ide> To revert the `User Search Header Paths` and `Header Search Paths` build setting <ide> <ide> ### No transports available <ide> <del>React Native implements a polyfill for WebSockets. These [polyfills](https://github.com/facebook/react-native/blob/master/Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js) are initialized as part of the react-native module that you include in your application through `import React from 'react-native'`. If you load another module that requires WebSockets, such as [Firebase](https://github.com/facebook/react-native/issues/3645), be sure to load/require it after react-native: <add>React Native implements a polyfill for WebSockets. These [polyfills](https://github.com/facebook/react-native/blob/master/Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js) are initialized as part of the react-native module that you include in your application through `import React from 'react'`. If you load another module that requires WebSockets, such as [Firebase](https://github.com/facebook/react-native/issues/3645), be sure to load/require it after react-native: <ide> <ide> ``` <del>import React from 'react-native'; <add>import React from 'react'; <ide> import Firebase from 'firebase'; <ide> ``` <ide>
1
PHP
PHP
use correct link to doc page
198c49a1dbda25bd725d3f7499dc71da20b30bb7
<ide><path>src/Console/Shell.php <ide> class Shell <ide> * Contains tasks to load and instantiate <ide> * <ide> * @var array|bool <del> * @link https://book.cakephp.org/4/en/console-and-shells.html#Shell::$tasks <add> * @link https://book.cakephp.org/4/en/console-commands/shells.html#shell-tasks <ide> */ <ide> public $tasks = []; <ide> <ide> class Shell <ide> * <ide> * @param \Cake\Console\ConsoleIo|null $io An io instance. <ide> * @param \Cake\ORM\Locator\LocatorInterface|null $locator Table locator instance. <del> * @link https://book.cakephp.org/4/en/console-and-shells.html#Shell <add> * @link https://book.cakephp.org/4/en/console-commands/shells.html <ide> */ <ide> public function __construct(?ConsoleIo $io = null, ?LocatorInterface $locator = null) <ide> {
1
Python
Python
avoid obscure error on certain non-image textures
1ce8842c75806521a811a3f2eafcc59ad0453fb2
<ide><path>utils/exporters/blender/addons/io_three/exporter/api/material.py <ide> def _valid_textures(material, strict_use=True): <ide> in_use = texture.use <ide> else: <ide> in_use = True <del> if texture.texture.type != IMAGE or not in_use: <add> if not in_use: <add> continue <add> if not texture.texture or texture.texture.type != IMAGE: <add> logger.warning("Unable to export non-image texture %s", texture) <ide> continue <ide> logger.debug("Valid texture found %s", texture) <ide> yield texture
1
Text
Text
fix linting errors
12c0fd4c9a0946dc821029738b80fd1998064125
<ide><path>doc/api/errors.md <ide> not capture any frames. <ide> * {string} <ide> <ide> The `error.code` property is a string label that identifies the kind of error. <del>`error.code` is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, `error.message` strings may change between any versions of Node.js. See [Node.js Error Codes][] for details about specific codes. <add>`error.code` is the most stable way to identify an error. It will only change <add>between major versions of Node.js. In contrast, `error.message` strings may <add>change between any versions of Node.js. See [Node.js Error Codes][] for details <add>about specific codes. <ide> <ide> ### error.message <ide> <ide> system error. <ide> <ide> * {string|number} <ide> <del>The `error.errno` property is a number or a string. If it is a number, it is a negative value which corresponds to the error code defined in <add>The `error.errno` property is a number or a string. If it is a number, it is a <add>negative value which corresponds to the error code defined in <ide> [`libuv Error handling`]. See the libuv `errno.h` header file <ide> (`deps/uv/include/uv/errno.h` in the Node.js source tree) for details. In case <ide> of a string, it is the same as `error.code`.
1
Text
Text
add some corrections to the translation
3794484e0b7debb1269794128551dd988dd68a88
<ide><path>guide/russian/working-in-tech/dunning-kruger-effect/index.md <ide> --- <ide> title: Dunning Kruger Effect <del>localeTitle: Эффект Дуннинга Крюгера <del>--- <ide>## Эффект Дуннинга Крюгера (DK) <del> <del>### Определение Википедии <del> <del>В области психологии эффект **Дуннинга-Крюгера** является когнитивным уклоном, когда люди с низкой способностью страдают от иллюзорного превосходства, ошибочно оценивая их познавательные способности как больше, чем он есть. Когнитивная предвзятость иллюзорного превосходства проистекает из метакогнитивной неспособности людей с низкой способностью признать свою собственную неумелость. <del> <del>### Почему это имеет значение в разработке программного обеспечения? <del> <del>Эффект DK является важным для разработчиков программного обеспечения. Это можно наблюдать среди разработчиков всех возрастов. Это более заметно среди начинающих и разработчиков промежуточного уровня. После первоначальной борьбы они могут быть уверены в языке или их дизайне. Это заставляет их недооценивать сложность системных требований или, что еще хуже, мешает им разрабатывать лучшие разработки программного обеспечения. Для более опытных разработчиков они, похоже, приобрели мудрость на протяжении многих лет. Они более скромны и лучше оценивают сложность системы. (Это может быть неверно для всех старших разработчиков). <del> <del>### Осторожно! <del> <del>Эффект DK полностью противоположный [синдрому Импостера](https://en.wikipedia.org/wiki/Impostor_syndrome) . Вам нужно добиться идеального баланса между обоими из них для вашего профессионального роста. <del> <del>### Как проверить, страдает ли я от эффекта DK? <del> <del>_Вы не можете!_ <del> <del>Извините, но на этот вопрос нет прямого ответа. Вы можете задать себе следующие вопросы: <del> <del>* Можете ли вы дать точные оценки? <del> <del>* Вы открыты для изучения новых концепций? <del> <del>* Вы открыты для реализации или реализации новых парадигм дизайна? <del> <del>* Вы скромны? <del> <del>* Можете ли вы критиковать и объективно оценивать обратную связь? <del> <del>* Вы хороший слушатель? <del> <del> Показания: <del> <del>* [Википедия](https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect) <ide>\ No newline at end of file <add>localeTitle: Эффект Даннинга — Крюгера <add>--- <add>## Эффект Даннинга — Крюгера (DK) <add> <add>### Определение Википедии <add> <add>В области психологии эффект **Даннинга — Крюгера** является когнитивным искажением, заключающимся в том, что люди с низким потенциалом страдают от иллюзорного превосходства, имея ошибочные представления о собственных способностях. Данная проблема проистекает из метакогнитивной неспособности осознать свои ошибки в силу низкого уровня своей квалификации. <add> <add>### Почему это имеет значение в разработке программного обеспечения? <add> <add>Эффект DK это важный урок для разработчиков программного обеспечения. Его можно наблюдать среди разработчиков всех возрастов. Он заметнее всего среди начинающих разработчиков и разработчиков среднего уровня. После первоначальной борьбы они могут быть чрезмерно уверены в знании языков или дизайне, что приводит к недооцениванию сложности системных требований или, что еще хуже, создает препятствия для разработки лучшего программного обеспечения. Более опытные разработчики приобретают мудрость на протяжении многих лет. Они более скромны и лучше оценивают сложность системы (хотя это может относиться не ко всем старшим разработчикам). <add> <add>### Осторожно! <add> <add>Эффект DK полностью противоположен [синдрому самозванца](https://en.wikipedia.org/wiki/Impostor_syndrome) . Вам нужно добиться идеального баланса между обоими из них для вашего профессионального роста. <add> <add>### Как проверить, страдаю ли я от эффекта DK? <add> <add>_Вы не можете!_ <add> <add>Извините, но на этот вопрос нет прямого ответа. Вы можете задать себе следующие вопросы: <add> <add>* В состоянии ли вы давать точные оценки? <add> <add>* Открыты ли вы для изучения новых концепций? <add> <add>* Открыты ли вы для реализации или тестирования новых парадигм дизайна? <add> <add>* Скромны ли вы? <add> <add>* Можете ли вы критиковать и объективно оценивать обратную связь? <add> <add>* Вы хороший слушатель? <add> <add> Показания: <add> <add>* [Википедия](https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect)
1
Text
Text
remove paragraphs with bad links
742a21345dd4df066351563ed2ad6c546f45202a
<ide><path>curriculum/challenges/english/08-coding-interview-prep/take-home-projects/build-a-nightlife-coordination-app.english.md <ide> forumTopicId: 302351 <ide> ## Description <ide> <section id='description'> <ide> <strong>Objective:</strong> Build a full stack JavaScript app that is functionally similar to this: <a href='http://whatsgoinontonight.herokuapp.com/' target='_blank'>http://whatsgoinontonight.herokuapp.com/</a> and deploy it to Heroku. <del>Note that for each project, you should create a new GitHub repository and a new Heroku project. If you can't remember how to do this, revisit <a href='/challenges/get-set-for-our-dynamic-web-application-projects'>https://freecodecamp.com/challenges/get-set-for-our-dynamic-web-application-projects</a>. <ide> Here are the specific user stories you should implement for this project: <ide> <strong>User Story:</strong> As an unauthenticated user, I can view all bars in my area. <ide> <strong>User Story:</strong> As an authenticated user, I can add myself to a bar to indicate I am going there tonight. <ide><path>curriculum/challenges/english/08-coding-interview-prep/take-home-projects/build-a-voting-app.english.md <ide> forumTopicId: 302359 <ide> ## Description <ide> <section id='description'> <ide> <strong>Objective:</strong> Build a full stack JavaScript app that is functionally similar to this: <a href='https://fcc-voting-arthow4n.herokuapp.com/' target='_blank'>https://fcc-voting-arthow4n.herokuapp.com/</a> and deploy it to Heroku. <del>Note that for each project, you should create a new GitHub repository and a new Heroku project. If you can't remember how to do this, revisit <a href='/challenges/get-set-for-our-dynamic-web-application-projects'>https://freecodecamp.com/challenges/get-set-for-our-dynamic-web-application-projects</a>. <ide> Here are the specific user stories you should implement for this project: <ide> <strong>User Story:</strong> As an authenticated user, I can keep my polls and come back later to access them. <ide> <strong>User Story:</strong> As an authenticated user, I can share my polls with my friends. <ide><path>curriculum/challenges/english/08-coding-interview-prep/take-home-projects/build-an-image-search-abstraction-layer.english.md <ide> forumTopicId: 302361 <ide> ## Description <ide> <section id='description'> <ide> <strong>Objective:</strong> Build a full stack JavaScript app that allows you to search for images like this: <a href='https://cryptic-ridge-9197.herokuapp.com/api/imagesearch/lolcats%20funny?offset=10' target='_blank'>https://cryptic-ridge-9197.herokuapp.com/api/imagesearch/lolcats%20funny?offset=10</a> and browse recent search queries like this: <a href='https://cryptic-ridge-9197.herokuapp.com/api/latest/imagesearch/' target='_blank'>https://cryptic-ridge-9197.herokuapp.com/api/latest/imagesearch/</a>. Then deploy it to Glitch. <del>Note that for each project, you should create a new GitHub repository and a new Glitch project. If you can't remember how to do this, revisit <a href='/challenges/get-set-for-our-api-development-projects'>https://freecodecamp.org/challenges/get-set-for-our-api-development-projects</a>. <ide> Here are the specific user stories you should implement for this project: <ide> <strong>User Story:</strong> I can get the image URLs, alt text and page urls for a set of images relating to a given search string. <ide> <strong>User Story:</strong> I can paginate through the responses by adding a ?offset=2 parameter to the URL. <ide><path>curriculum/challenges/english/08-coding-interview-prep/take-home-projects/chart-the-stock-market.english.md <ide> forumTopicId: 302363 <ide> ## Description <ide> <section id='description'> <ide> <strong>Objective:</strong> Build a full stack JavaScript app that is functionally similar to this: <a href='http://watchstocks.herokuapp.com/' target='_blank'>http://watchstocks.herokuapp.com/</a> and deploy it to Heroku. <del>Note that for each project, you should create a new GitHub repository and a new Heroku project. If you can't remember how to do this, revisit <a href='/challenges/get-set-for-our-dynamic-web-application-projects'>https://freecodecamp.com/challenges/get-set-for-our-dynamic-web-application-projects</a>. <ide> Here are the specific user stories you should implement for this project: <ide> <strong>User Story:</strong> I can view a graph displaying the recent trend lines for each added stock. <ide> <strong>User Story:</strong> I can add new stocks by their symbol name.
4
PHP
PHP
fix use of removed property
50e421c19fb77f2831adc77d90ce04e3b0e74dc6
<ide><path>src/View/Helper.php <ide> public function __get($name) <ide> public function __set($name, $value) <ide> { <ide> $removed = [ <del> 'template' => 'setTemplate', <add> 'theme' => 'setTheme', <ide> 'plugin' => 'setPlugin', <ide> ]; <ide> if (isset($removed[$name])) { <ide><path>src/View/Helper/UrlHelper.php <ide> public function webroot($file) <ide> $webPath = $this->request->getAttribute('webroot') . $asset[0]; <ide> $file = $asset[0]; <ide> <del> if (!empty($this->theme)) { <add> if (!empty($this->_View->getTheme())) { <ide> $file = trim($file, '/'); <del> $theme = $this->_inflectThemeName($this->theme) . '/'; <add> $theme = $this->_inflectThemeName($this->_View->getTheme()) . '/'; <ide> <ide> if (DIRECTORY_SEPARATOR === '\\') { <ide> $file = str_replace('/', '\\', $file); <ide> public function webroot($file) <ide> if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) { <ide> $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0]; <ide> } else { <del> $themePath = Plugin::path($this->theme); <add> $themePath = Plugin::path($this->_View->getTheme()); <ide> $path = $themePath . 'webroot/' . $file; <ide> if (file_exists($path)) { <ide> $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0]; <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function testImageTagWithTheme() <ide> Configure::write('debug', true); <ide> <ide> $this->Html->Url->request = $this->Html->request->withAttribute('webroot', '/'); <del> $this->Html->Url->theme = 'TestTheme'; <add> $this->Html->Url->getView()->setTheme('TestTheme'); <ide> $result = $this->Html->image('__cake_test_image.gif'); <ide> $expected = [ <ide> 'img' => [ <ide> public function testThemeAssetsInMainWebrootPath() <ide> { <ide> Configure::write('App.wwwRoot', TEST_APP . 'webroot/'); <ide> <del> $this->Html->Url->theme = 'TestTheme'; <add> $this->Html->Url->getView()->setTheme('TestTheme'); <ide> $result = $this->Html->css('webroot_test'); <ide> $expected = [ <ide> 'link' => ['rel' => 'stylesheet', 'href' => 'preg:/.*test_theme\/css\/webroot_test\.css/'] <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <del> $this->Html->theme = 'TestTheme'; <add> $this->Html->getView()->setTheme('TestTheme'); <ide> $result = $this->Html->css('theme_webroot'); <ide> $expected = [ <ide> 'link' => ['rel' => 'stylesheet', 'href' => 'preg:/.*test_theme\/css\/theme_webroot\.css/'] <ide> public function testScriptInTheme() <ide> $File = new File($testfile, true); <ide> <ide> $this->Html->Url->request = $this->Html->request->withAttribute('webroot', '/'); <del> $this->Html->Url->theme = 'TestTheme'; <add> $this->Html->Url->getView()->setTheme('TestTheme'); <ide> $result = $this->Html->script('__test_js.js'); <ide> $expected = [ <ide> 'script' => ['src' => '/test_theme/js/__test_js.js'] <ide> public function testMetaIcon() <ide> */ <ide> public function testMetaIconWithTheme() <ide> { <del> $this->Html->Url->theme = 'TestTheme'; <add> $this->Html->Url->getView()->setTheme('TestTheme'); <ide> <ide> $result = $this->Html->meta('icon', 'favicon.ico'); <ide> $expected = [ <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> public function testWebrootPaths() <ide> $expected = '/img/cake.power.gif'; <ide> $this->assertEquals($expected, $result); <ide> <del> $this->Helper->theme = 'TestTheme'; <add> $this->Helper->getView()->setTheme('TestTheme'); <ide> <ide> $result = $this->Helper->webroot('/img/cake.power.gif'); <ide> $expected = '/test_theme/img/cake.power.gif';
4
Python
Python
reduce memory usage of fft test
edb67b65cfc2143381fbcfae6569772cf37c2e3d
<ide><path>numpy/fft/tests/test_fftpack.py <ide> def test_basic(self): <ide> <ide> class TestFFTThreadSafe(TestCase): <ide> threads = 16 <del> input_shape = (1000, 1000) <add> input_shape = (800, 200) <ide> <ide> def _test_mtsame(self, func, *args): <ide> def worker(args, q): <ide> def worker(args, q): <ide> expected = func(*args) <ide> <ide> # Spin off a bunch of threads to call the same function simultaneously <del> for i in range(self.threads): <del> threading.Thread(target=worker, args=(args, q)).start() <add> t = [threading.Thread(target=worker, args=(args, q)) <add> for i in range(self.threads)] <add> [x.start() for x in t] <ide> <ide> # Make sure all threads returned the correct value <ide> for i in range(self.threads): <ide> assert_array_equal(q.get(timeout=5), expected, <ide> 'Function returned wrong value in multithreaded context') <add> [x.join() for x in t] <ide> <ide> def test_fft(self): <ide> a = np.ones(self.input_shape) * 1+0j
1
Python
Python
fix mypy errors in google cloud (again)
da88ed1943e85850fcdf32c663ec2940c65dbe75
<ide><path>airflow/providers/google/cloud/example_dags/example_datacatalog.py <ide> from datetime import datetime <ide> <ide> from google.cloud.datacatalog_v1beta1 import FieldType, TagField, TagTemplateField <add>from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow import models <ide> from airflow.models.baseoperator import chain <ide> task_id="get_entry_group", <ide> location=LOCATION, <ide> entry_group=ENTRY_GROUP_ID, <del> read_mask={"paths": ["name", "display_name"]}, <add> read_mask=FieldMask(paths=["name", "display_name"]), <ide> ) <ide> # [END howto_operator_gcp_datacatalog_get_entry_group] <ide> <ide><path>airflow/providers/google/cloud/example_dags/example_dataproc_metastore.py <ide> import datetime <ide> import os <ide> <add>from google.cloud.metastore_v1 import MetadataImport <add>from google.protobuf.field_mask_pb2 import FieldMask <add> <ide> from airflow import models <ide> from airflow.models.baseoperator import chain <ide> from airflow.providers.google.cloud.operators.dataproc_metastore import ( <ide> "systemtest": "systemtest", <ide> } <ide> } <del>UPDATE_MASK = {"paths": ["labels"]} <add>UPDATE_MASK = FieldMask(paths=["labels"]) <ide> # [END how_to_cloud_dataproc_metastore_update_service] <ide> <ide> # Backup definition <ide> <ide> # Metadata import definition <ide> # [START how_to_cloud_dataproc_metastore_create_metadata_import] <del>METADATA_IMPORT = { <del> "name": "test-metadata-import", <del> "database_dump": { <del> "gcs_uri": GCS_URI, <del> "database_type": DB_TYPE, <del> }, <del>} <add>METADATA_IMPORT = MetadataImport( <add> { <add> "name": "test-metadata-import", <add> "database_dump": { <add> "gcs_uri": GCS_URI, <add> "database_type": DB_TYPE, <add> }, <add> } <add>) <ide> # [END how_to_cloud_dataproc_metastore_create_metadata_import] <ide> <ide> <ide><path>airflow/providers/google/cloud/hooks/cloud_memorystore.py <ide> def update_parameters( <ide> parameters: Union[Dict, cloud_memcache.MemcacheParameters], <ide> project_id: str, <ide> location: str, <del> instance_id: Optional[str] = None, <add> instance_id: str, <ide> retry: Optional[Retry] = None, <ide> timeout: Optional[float] = None, <ide> metadata: Sequence[Tuple[str, str]] = (), <ide><path>airflow/providers/google/cloud/hooks/cloud_sql.py <ide> def _download_sql_proxy_if_needed(self) -> None: <ide> if "follow_redirects" in signature(httpx.get).parameters.keys(): <ide> response = httpx.get(download_url, follow_redirects=True) <ide> else: <del> response = httpx.get(download_url, allow_redirects=True) <add> response = httpx.get(download_url, allow_redirects=True) # type: ignore[call-arg] <ide> # Downloading to .tmp file first to avoid case where partially downloaded <ide> # binary is used by parallel operator which uses the same fixed binary path <ide> with open(proxy_path_tmp, 'wb') as file: <ide> file.write(response.content) <ide> if response.status_code != 200: <ide> raise AirflowException( <ide> "The cloud-sql-proxy could not be downloaded. " <del> f"Status code = {response.status_code}. Reason = {response.reason}" <add> f"Status code = {response.status_code}. Reason = {response.reason_phrase}" <ide> ) <ide> <ide> self.log.info("Moving sql_proxy binary from %s to %s", proxy_path_tmp, self.sql_proxy_path) <ide><path>airflow/providers/google/cloud/hooks/compute.py <ide> def get_instance_address( <ide> if use_internal_ip: <ide> return instance_info["networkInterfaces"][0].get("networkIP") <ide> <del> access_config = instance_info.get("networkInterfaces")[0].get("accessConfigs") <add> access_config = instance_info["networkInterfaces"][0].get("accessConfigs") <ide> if access_config: <ide> return access_config[0].get("natIP") <ide> raise AirflowException("The target instance does not have external IP") <ide><path>airflow/providers/google/cloud/hooks/dataflow.py <ide> def cancel(self) -> None: <ide> timeout_error_message = ( <ide> f"Canceling jobs failed due to timeout ({self._cancel_timeout}s): {', '.join(job_ids)}" <ide> ) <del> with timeout(seconds=self._cancel_timeout, error_message=timeout_error_message): <add> tm = timeout(seconds=self._cancel_timeout, error_message=timeout_error_message) <add> with tm: <ide> self._wait_for_states({DataflowJobStatus.JOB_STATE_CANCELLED}) <ide> else: <ide> self.log.info("No jobs to cancel") <ide><path>airflow/providers/google/cloud/operators/datacatalog.py <ide> def execute(self, context: dict): <ide> ) <ide> except AlreadyExists: <ide> self.log.info("Tag already exists. Skipping create operation.") <add> project_id = self.project_id or hook.project_id <add> if project_id is None: <add> raise RuntimeError("The project id must be set here") <ide> if self.template_id: <ide> template_name = DataCatalogClient.tag_template_path( <del> self.project_id or hook.project_id, self.location, self.template_id <add> project_id, self.location, self.template_id <ide> ) <ide> else: <ide> if isinstance(self.tag, Tag): <ide> def execute(self, context: dict): <ide> entry_group=self.entry_group, <ide> template_name=template_name, <ide> entry=self.entry, <del> project_id=self.project_id, <add> project_id=project_id, <ide> retry=self.retry, <ide> timeout=self.timeout, <ide> metadata=self.metadata, <ide> def __init__( <ide> *, <ide> location: str, <ide> entry_group: str, <del> read_mask: Union[Dict, FieldMask], <add> read_mask: FieldMask, <ide> project_id: Optional[str] = None, <ide> retry: Optional[Retry] = None, <ide> timeout: Optional[float] = None, <ide><path>airflow/providers/google/cloud/operators/dataprep.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> """This module contains a Google Dataprep operator.""" <add>from typing import TYPE_CHECKING <ide> <ide> from airflow.models import BaseOperator <ide> from airflow.providers.google.cloud.hooks.dataprep import GoogleDataprepHook <ide> <add>if TYPE_CHECKING: <add> from airflow.utils.context import Context <add> <ide> <ide> class DataprepGetJobsForJobGroupOperator(BaseOperator): <ide> """ <ide> def __init__(self, *, dataprep_conn_id: str = "dataprep_default", body_request: <ide> self.body_request = body_request <ide> self.dataprep_conn_id = dataprep_conn_id <ide> <del> def execute(self, context: None) -> dict: <add> def execute(self, context: "Context") -> dict: <ide> self.log.info("Creating a job...") <ide> hook = GoogleDataprepHook(dataprep_conn_id=self.dataprep_conn_id) <ide> response = hook.run_job_group(body_request=self.body_request) <ide><path>airflow/providers/google/cloud/operators/gcs.py <ide> import warnings <ide> from pathlib import Path <ide> from tempfile import NamedTemporaryFile, TemporaryDirectory <del>from typing import Dict, Iterable, List, Optional, Sequence, Union <add>from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Union <add> <add>if TYPE_CHECKING: <add> from airflow.utils.context import Context <ide> <ide> from google.api_core.exceptions import Conflict <ide> from google.cloud.exceptions import GoogleCloudError <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> list: <add> def execute(self, context: "Context") -> list: <ide> <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> def __init__( <ide> self, <ide> *, <ide> bucket_name: str, <del> objects: Optional[Iterable[str]] = None, <add> objects: Optional[List[str]] = None, <ide> prefix: Optional[str] = None, <ide> gcp_conn_id: str = 'google_cloud_default', <ide> google_cloud_storage_conn_id: Optional[str] = None, <ide> def __init__( <ide> <ide> super().__init__(**kwargs) <ide> <del> def execute(self, context): <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> impersonation_chain=self.impersonation_chain, <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> impersonation_chain=self.impersonation_chain, <ide> def __init__( <ide> self.output_encoding = sys.getdefaultencoding() <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context: dict) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) <ide> <ide> with NamedTemporaryFile() as source_file, NamedTemporaryFile() as destination_file: <ide> class GCSTimeSpanFileTransformOperator(BaseOperator): <ide> ) <ide> <ide> @staticmethod <del> def interpolate_prefix(prefix: str, dt: datetime.datetime) -> Optional[datetime.datetime]: <add> def interpolate_prefix(prefix: str, dt: datetime.datetime) -> Optional[str]: <ide> """Interpolate prefix with datetime. <ide> <ide> :param prefix: The prefix to interpolate <ide> def __init__( <ide> self.upload_continue_on_fail = upload_continue_on_fail <ide> self.upload_num_attempts = upload_num_attempts <ide> <del> def execute(self, context: dict) -> None: <add> def execute(self, context: "Context") -> List[str]: <ide> # Define intervals and prefixes. <ide> try: <ide> timespan_start = context["data_interval_start"] <ide> def execute(self, context: dict) -> None: <ide> ) <ide> <ide> with TemporaryDirectory() as temp_input_dir, TemporaryDirectory() as temp_output_dir: <del> temp_input_dir = Path(temp_input_dir) <del> temp_output_dir = Path(temp_output_dir) <add> temp_input_dir_path = Path(temp_input_dir) <add> temp_output_dir_path = Path(temp_output_dir) <ide> <ide> # TODO: download in parallel. <ide> for blob_to_transform in blobs_to_transform: <del> destination_file = temp_input_dir / blob_to_transform <add> destination_file = temp_input_dir_path / blob_to_transform <ide> destination_file.parent.mkdir(parents=True, exist_ok=True) <ide> try: <ide> source_hook.download( <ide> def execute(self, context: dict) -> None: <ide> self.log.info("Starting the transformation") <ide> cmd = [self.transform_script] if isinstance(self.transform_script, str) else self.transform_script <ide> cmd += [ <del> str(temp_input_dir), <del> str(temp_output_dir), <add> str(temp_input_dir_path), <add> str(temp_output_dir_path), <ide> timespan_start.replace(microsecond=0).isoformat(), <ide> timespan_end.replace(microsecond=0).isoformat(), <ide> ] <ide> def execute(self, context: dict) -> None: <ide> if process.returncode: <ide> raise AirflowException(f"Transform script failed: {process.returncode}") <ide> <del> self.log.info("Transformation succeeded. Output temporarily located at %s", temp_output_dir) <add> self.log.info("Transformation succeeded. Output temporarily located at %s", temp_output_dir_path) <ide> <ide> files_uploaded = [] <ide> <ide> # TODO: upload in parallel. <del> for upload_file in temp_output_dir.glob("**/*"): <add> for upload_file in temp_output_dir_path.glob("**/*"): <ide> if upload_file.is_dir(): <ide> continue <ide> <del> upload_file_name = str(upload_file.relative_to(temp_output_dir)) <add> upload_file_name = str(upload_file.relative_to(temp_output_dir_path)) <ide> <ide> if self.destination_prefix is not None: <ide> upload_file_name = f"{destination_prefix_interp}/{upload_file_name}" <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) <ide> hook.delete_bucket(bucket_name=self.bucket_name, force=self.force) <ide> <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.impersonation_chain = impersonation_chain <ide> <del> def execute(self, context) -> None: <add> def execute(self, context: "Context") -> None: <ide> hook = GCSHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide><path>airflow/providers/google/cloud/operators/mlengine.py <ide> def __init__( <ide> *, <ide> job_id: str, <ide> region: str, <del> package_uris: List[str] = None, <del> training_python_module: str = None, <del> training_args: List[str] = None, <add> package_uris: Optional[List[str]] = None, <add> training_python_module: Optional[str] = None, <add> training_args: Optional[List[str]] = None, <ide> scale_tier: Optional[str] = None, <ide> master_type: Optional[str] = None, <ide> master_config: Optional[Dict] = None, <ide><path>airflow/providers/google/cloud/sensors/datafusion.py <ide> def poke(self, context: dict) -> bool: <ide> pipeline_status = pipeline_workflow["status"] <ide> except AirflowException: <ide> pass # Because the pipeline may not be visible in system yet <del> <del> if self.failure_statuses and pipeline_status in self.failure_statuses: <del> raise AirflowException( <del> f"Pipeline with id '{self.pipeline_id}' state is: {pipeline_status}. " <del> f"Terminating sensor..." <del> ) <add> if pipeline_status is not None: <add> if self.failure_statuses and pipeline_status in self.failure_statuses: <add> raise AirflowException( <add> f"Pipeline with id '{self.pipeline_id}' state is: {pipeline_status}. " <add> f"Terminating sensor..." <add> ) <ide> <ide> self.log.debug( <ide> "Current status of the pipeline workflow for %s: %s.", self.pipeline_id, pipeline_status <ide><path>airflow/providers/google/cloud/sensors/dataproc.py <ide> # pylint: disable=C0302 <ide> import time <ide> import warnings <del>from typing import Dict, Optional <add>from typing import TYPE_CHECKING, Optional <ide> <ide> from google.api_core.exceptions import ServerError <ide> from google.cloud.dataproc_v1.types import JobStatus <ide> from airflow.providers.google.cloud.hooks.dataproc import DataprocHook <ide> from airflow.sensors.base import BaseSensorOperator <ide> <add>if TYPE_CHECKING: <add> from airflow.utils.context import Context <add> <ide> <ide> class DataprocJobSensor(BaseSensorOperator): <ide> """ <ide> def __init__( <ide> self.wait_timeout = wait_timeout <ide> self.start_sensor_time: Optional[float] = None <ide> <del> def execute(self, context: Dict): <add> def execute(self, context: "Context") -> None: <ide> self.start_sensor_time = time.monotonic() <ide> super().execute(context) <ide> <ide> def _duration(self): <ide> return time.monotonic() - self.start_sensor_time <ide> <del> def poke(self, context: Dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> hook = DataprocHook(gcp_conn_id=self.gcp_conn_id) <ide> if self.wait_timeout: <ide> try: <ide><path>airflow/providers/google/cloud/sensors/gcs.py <ide> import textwrap <ide> import warnings <ide> from datetime import datetime <del>from typing import Callable, List, Optional, Sequence, Set, Union <add>from typing import TYPE_CHECKING, Callable, List, Optional, Sequence, Set, Union <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.gcs import GCSHook <ide> from airflow.sensors.base import BaseSensorOperator, poke_mode_only <ide> <add>if TYPE_CHECKING: <add> from airflow.utils.context import Context <add> <ide> <ide> class GCSObjectExistenceSensor(BaseSensorOperator): <ide> """ <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.impersonation_chain = impersonation_chain <ide> <del> def poke(self, context: dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> self.log.info('Sensor checks existence of : %s, %s', self.bucket, self.object) <ide> hook = GCSHook( <ide> gcp_conn_id=self.google_cloud_conn_id, <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.impersonation_chain = impersonation_chain <ide> <del> def poke(self, context: dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> self.log.info('Sensor checks existence of : %s, %s', self.bucket, self.object) <ide> hook = GCSHook( <ide> gcp_conn_id=self.google_cloud_conn_id, <ide> def __init__( <ide> self._matches: List[str] = [] <ide> self.impersonation_chain = impersonation_chain <ide> <del> def poke(self, context: dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> self.log.info('Sensor checks existence of objects: %s, %s', self.bucket, self.prefix) <ide> hook = GCSHook( <ide> gcp_conn_id=self.google_cloud_conn_id, <ide> def poke(self, context: dict) -> bool: <ide> self._matches = hook.list(self.bucket, prefix=self.prefix) <ide> return bool(self._matches) <ide> <del> def execute(self, context: dict) -> List[str]: <add> def execute(self, context: "Context") -> List[str]: <ide> """Overridden to allow matches to be passed""" <ide> super().execute(context) <ide> return self._matches <ide> def is_bucket_updated(self, current_objects: Set[str]) -> bool: <ide> return False <ide> return False <ide> <del> def poke(self, context: dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> return self.is_bucket_updated( <ide> set(self._get_gcs_hook().list(self.bucket, prefix=self.prefix)) # type: ignore[union-attr] <ide> ) <ide><path>airflow/providers/google/cloud/sensors/pubsub.py <ide> # under the License. <ide> """This module contains a Google PubSub sensor.""" <ide> import warnings <del>from typing import Any, Callable, Dict, List, Optional, Sequence, Union <add>from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Union <ide> <ide> from google.cloud.pubsub_v1.types import ReceivedMessage <ide> <ide> from airflow.providers.google.cloud.hooks.pubsub import PubSubHook <ide> from airflow.sensors.base import BaseSensorOperator <ide> <add>if TYPE_CHECKING: <add> from airflow.utils.context import Context <add> <ide> <ide> class PubSubPullSensor(BaseSensorOperator): <ide> """Pulls messages from a PubSub subscription and passes them through XCom. <ide> def __init__( <ide> <ide> self._return_value = None <ide> <del> def execute(self, context: dict): <add> def execute(self, context: "Context") -> Any: <ide> """Overridden to allow messages to be passed""" <ide> super().execute(context) <ide> return self._return_value <ide> <del> def poke(self, context: dict) -> bool: <add> def poke(self, context: "Context") -> bool: <ide> hook = PubSubHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> def poke(self, context: dict) -> bool: <ide> def _default_message_callback( <ide> self, <ide> pulled_messages: List[ReceivedMessage], <del> context: Dict[str, Any], <add> context: "Context", <ide> ): <ide> """ <ide> This method can be overridden by subclasses or by `messages_callback` constructor argument. <ide><path>airflow/utils/timeout.py <ide> import os <ide> import signal <ide> from threading import Timer <del>from typing import ContextManager, Optional, Type <add>from typing import ContextManager, Optional, Type, Union <ide> <ide> from airflow.exceptions import AirflowTaskTimeout <ide> from airflow.utils.log.logging_mixin import LoggingMixin <ide> _timeout = ContextManager[None] <ide> <ide> <del>class _timeout_windows(_timeout, LoggingMixin): <add>class TimeoutWindows(_timeout, LoggingMixin): <add> """Windows timeout version: To be used in a ``with`` block and timeout its content.""" <add> <ide> def __init__(self, seconds=1, error_message='Timeout'): <ide> super().__init__() <ide> self._timer: Optional[Timer] = None <ide> def __exit__(self, type_, value, traceback): <ide> self._timer = None <ide> <ide> <del>class _timeout_posix(_timeout, LoggingMixin): <del> """To be used in a ``with`` block and timeout its content.""" <add>class TimeoutPosix(_timeout, LoggingMixin): <add> """POSIX Timeout version: To be used in a ``with`` block and timeout its content.""" <ide> <ide> def __init__(self, seconds=1, error_message='Timeout'): <ide> super().__init__() <ide> def __exit__(self, type_, value, traceback): <ide> <ide> <ide> if IS_WINDOWS: <del> timeout: Type[_timeout] = _timeout_windows <add> timeout: Type[Union[TimeoutWindows, TimeoutPosix]] = TimeoutWindows <ide> else: <del> timeout = _timeout_posix <add> timeout = TimeoutPosix
15
Python
Python
make debugfileskeyerror.__str__ return str on 3.x
4bea6bbe6d2200dfdbcca3dfc2fe561488c82a8e
<ide><path>flask/debughelpers.py <ide> :copyright: (c) 2011 by Armin Ronacher. <ide> :license: BSD, see LICENSE for more details. <ide> """ <add>from flask._compat import implements_to_string <ide> <ide> <ide> class UnexpectedUnicodeError(AssertionError, UnicodeError): <ide> class UnexpectedUnicodeError(AssertionError, UnicodeError): <ide> """ <ide> <ide> <add>@implements_to_string <ide> class DebugFilesKeyError(KeyError, AssertionError): <ide> """Raised from request.files during debugging. The idea is that it can <ide> provide a better error message than just a generic KeyError/BadRequest. <ide> def __init__(self, request, key): <ide> buf.append('\n\nThe browser instead transmitted some file names. ' <ide> 'This was submitted: %s' % ', '.join('"%s"' % x <ide> for x in form_matches)) <del> self.msg = ''.join(buf).encode('utf-8') <add> self.msg = ''.join(buf) <ide> <ide> def __str__(self): <ide> return self.msg
1
PHP
PHP
update error message
9d60a2785fcad3ea32acee59b341073f25e9ced1
<ide><path>lib/Cake/Cache/Cache.php <ide> class Cache { <ide> */ <ide> public static function config($name = null, $settings = array()) { <ide> trigger_error( <del> __d('cake_dev', 'You must use Configure::write() to define cache configuration now.'), <add> __d('cake_dev', 'You must use Configure::write() to define cache configuration. Or use engine() to inject new adapter.'), <ide> E_USER_WARNING <ide> ); <ide> }
1
Javascript
Javascript
improve graph view refresh
c3dd89c61bea72987a57e2c4ea7c4f5daee01a07
<ide><path>airflow/www/static/js/graph.js <ide> function setFocusMap(state) { <ide> <ide> const stateIsSet = () => !!Object.keys(stateFocusMap).find((key) => stateFocusMap[key]); <ide> <add>let prevTis; <add> <ide> function handleRefresh() { <ide> $('#loading-dots').css('display', 'inline-block'); <ide> $.get(getTaskInstanceURL) <ide> .done( <ide> (tis) => { <add> // only refresh if the data has changed <add> if (prevTis !== tis) { <ide> // eslint-disable-next-line no-global-assign <del> taskInstances = JSON.parse(tis); <del> updateNodesStates(taskInstances); <add> taskInstances = JSON.parse(tis); <add> const states = Object.values(taskInstances).map((ti) => ti.state); <add> updateNodesStates(taskInstances); <add> <add> // end refresh if all states are final <add> if (!states.some((state) => ( <add> ['success', 'failed', 'upstream_failed', 'skipped', 'removed'].indexOf(state) === -1)) <add> ) { <add> $('#auto_refresh').prop('checked', false); <add> clearInterval(refreshInterval); <add> } <add> } <add> prevTis = tis; <ide> setTimeout(() => { $('#loading-dots').hide(); }, 500); <ide> $('#error').hide(); <ide> }, <ide> $('#auto_refresh').change(() => { <ide> <ide> function initRefresh() { <ide> if (localStorage.getItem('disableAutoRefresh')) { <del> $('#auto_refresh').removeAttr('checked'); <add> $('#auto_refresh').prop('checked', false); <ide> } <ide> startOrStopRefresh(); <ide> d3.select('#refresh_button').on('click', () => handleRefresh()); <ide><path>airflow/www/static/js/tree.js <ide> document.addEventListener('DOMContentLoaded', () => { <ide> if (getActiveRuns()) { <ide> handleRefresh(); <ide> } else { <del> $('#auto_refresh').removeAttr('checked'); <add> $('#auto_refresh').prop('checked', false); <ide> } <ide> }, 3000); // run refresh every 3 seconds <ide> } else { <ide> document.addEventListener('DOMContentLoaded', () => { <ide> function initRefresh() { <ide> // default to auto-refresh if there are any active dag runs <ide> if (getActiveRuns() && !localStorage.getItem('disableAutoRefresh')) { <del> $('#auto_refresh').attr('checked', true); <add> $('#auto_refresh').prop('checked', true); <ide> } <ide> startOrStopRefresh(); <ide> d3.select('#refresh_button').on('click', () => handleRefresh());
2
Ruby
Ruby
use symbols instead of strings
748d3f38df5d32c5e1eb1d82c07b8abffbb44973
<ide><path>activesupport/lib/active_support/concern.rb <ide> def initialize <ide> end <ide> <ide> def self.extended(base) #:nodoc: <del> base.instance_variable_set("@_dependencies", []) <add> base.instance_variable_set(:@_dependencies, []) <ide> end <ide> <ide> def append_features(base) <del> if base.instance_variable_defined?("@_dependencies") <del> base.instance_variable_get("@_dependencies") << self <add> if base.instance_variable_defined?(:@_dependencies) <add> base.instance_variable_get(:@_dependencies) << self <ide> return false <ide> else <ide> return false if base < self <ide> @_dependencies.each { |dep| base.send(:include, dep) } <ide> super <del> base.extend const_get("ClassMethods") if const_defined?("ClassMethods") <del> base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block") <add> base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods) <add> base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block) <ide> end <ide> end <ide> <ide> def included(base = nil, &block) <ide> if base.nil? <del> raise MultipleIncludedBlocks if instance_variable_defined?("@_included_block") <add> raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block) <ide> <ide> @_included_block = block <ide> else
1
Python
Python
fix unknown task error typo
bdbf6d6ae1aca9addd81800b5dd2e8c3477afb18
<ide><path>celery/worker/consumer/consumer.py <ide> The full contents of the message body was: <ide> %s <ide> <del>Thw full contents of the message headers: <add>The full contents of the message headers: <ide> %s <ide> <ide> The delivery info for this task is:
1
Python
Python
add percent in the quicklook
7a95094068c8ae5b6d10666a409f109843e8406f
<ide><path>glances/outputs/glances_bars.py <ide> class Bar(object): <ide> def __init__(self, size, <ide> pre_char='[', <ide> post_char=']', <del> empty_char='_'): <add> empty_char='_', <add> with_text=True): <ide> # Bar size <ide> self.__size = size <ide> # Bar current percent <ide> def __init__(self, size, <ide> self.__pre_char = pre_char <ide> self.__post_char = post_char <ide> self.__empty_char = empty_char <add> self.__with_text = with_text <ide> <del> def get_size(self): <del> return self.__size <add> def get_size(self, with_decoration=False): <add> # Return the bar size, with or without decoration <add> if with_decoration: <add> return self.__size <add> if self.__with_text: <add> return self.__size - 6 <ide> <ide> def set_size(self, size): <ide> self.__size = size <ide> def __str__(self): <ide> ret += curses_bars[int(frac * 8)] <ide> whole += 1 <ide> ret += self.__empty_char * int(self.get_size() - whole) <add> if self.__with_text: <add> ret = '{0}{1:>5}%'.format(ret, self.get_percent()) <ide> return self.__pre_char + ret + self.__post_char
1
Ruby
Ruby
improve dependencies hash output
524379e89785865370dab5300a6e566bef0a0b81
<ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> "keg_only" => keg_only?, <ide> "options" => [], <ide> "build_dependencies" => dependencies.select(&:build?).map(&:name).uniq, <del> "dependencies" => dependencies.map(&:name).uniq, <add> "dependencies" => dependencies.reject(&:optional?).reject(&:recommended?).reject(&:build?).map(&:name).uniq, <ide> "recommended_dependencies" => dependencies.select(&:recommended?).map(&:name).uniq, <ide> "optional_dependencies" => dependencies.select(&:optional?).map(&:name).uniq, <ide> "requirements" => [],
1
Python
Python
fix pt tf vitmae
ee209d4d016e2ef1b2e73c4be64ad43895bc7e27
<ide><path>src/transformers/models/vit_mae/modeling_tf_vit_mae.py <ide> def __init__(self, config, num_patches, **kwargs): <ide> <ide> self.decoder_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="decoder_norm") <ide> self.decoder_pred = tf.keras.layers.Dense( <del> config.patch_size**2 * config.num_channels, name="decoder_pred" <add> config.patch_size**2 * config.num_channels, <add> kernel_initializer=get_initializer(config.initializer_range), <add> name="decoder_pred", <ide> ) # encoder to decoder <ide> self.config = config <ide> self.num_patches = num_patches <ide><path>src/transformers/models/vit_mae/modeling_vit_mae.py <ide> def __init__(self, config, num_patches): <ide> [ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)] <ide> ) <ide> <del> self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size) <add> self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps) <ide> self.decoder_pred = nn.Linear( <ide> config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True <ide> ) # encoder to decoder
2
PHP
PHP
apply fixes from styleci
f20a5ea8d106c8796aa5622e1bb3718b90833fe6
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php <ide> public function temporaryUrl($path, $expiration, array $options = []) <ide> <ide> if (method_exists($adapter, 'getTemporaryUrl')) { <ide> return $adapter->getTemporaryUrl($path, $expiration, $options); <del> } else if (! $adapter instanceof AwsS3Adapter) { <add> } elseif (! $adapter instanceof AwsS3Adapter) { <ide> throw new RuntimeException('This driver does not support creating temporary URLs.'); <ide> } <ide>
1
Text
Text
add hashseed to collaborators
3d7f0fe67fef206c1671269424b045727f0ea094
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> **Gibson Fahnestock** &lt;[email protected]&gt; (he/him) <ide> * [gireeshpunathil](https://github.com/gireeshpunathil) - <ide> **Gireesh Punathil** &lt;[email protected]&gt; (he/him) <add>* [hashseed](https://github.com/hashseed) - <add>**Yang Guo** &lt;[email protected]&gt; (he/him) <ide> * [iarna](https://github.com/iarna) - <ide> **Rebecca Turner** &lt;[email protected]&gt; <ide> * [imran-iq](https://github.com/imran-iq) -
1
Go
Go
remove some debug logs
ebeda658bcc91b6f4560e3777b735ee6396a8218
<ide><path>pkg/archive/archive.go <ide> func DetectCompression(source []byte) Compression { <ide> Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, <ide> } { <ide> if len(source) < len(m) { <del> logrus.Debug("Len too short") <ide> continue <ide> } <ide> if bytes.Equal(m, source[:len(m)]) { <ide> func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decomp <ide> // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. <ide> // If either Tar or Untar fails, TarUntar aborts and returns the error. <ide> func (archiver *Archiver) TarUntar(src, dst string) error { <del> logrus.Debugf("TarUntar(%s %s)", src, dst) <ide> archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) <ide> if err != nil { <ide> return err <ide> func (archiver *Archiver) CopyWithTar(src, dst string) error { <ide> // as owner <ide> rootIDs := archiver.IDMapping.RootPair() <ide> // Create dst, copy src's content into it <del> logrus.Debugf("Creating dest directory: %s", dst) <ide> if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { <ide> return err <ide> } <del> logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) <ide> return archiver.TarUntar(src, dst) <ide> } <ide> <ide> // CopyFileWithTar emulates the behavior of the 'cp' command-line <ide> // for a single file. It copies a regular file from path `src` to <ide> // path `dst`, and preserves all its metadata. <ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <del> logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) <ide> srcSt, err := os.Stat(src) <ide> if err != nil { <ide> return err
1
Text
Text
add table of content (preview)
bed67834526c837ca18eb5674f8c9dda09e18e17
<ide><path>README.md <ide> [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) <ide> <ide> Promise based HTTP client for the browser and node.js <add>## Table of Contents <add> <add> - [Features](#features) <add> - [Browser Support](#browser-support) <add> - [Installing](#installing) <add> - [Example](#example) <add> - [Axios API](#axios-api) <add> - [Request method aliases](#request-method-aliases) <add> - [Concurrency (Deprecated)](#concurrency-deprecated) <add> - [Creating an instance](#creating-an-instance) <add> - [Instance methods](#instance-methods) <add> - [Request Config](#request-config) <add> - [Response Schema](#response-schema) <add> - [Config Defaults](#config-defaults) <add> - [Global axios defaults](#global-axios-defaults) <add> - [Custom instance defaults](#custom-instance-defaults) <add> - [Config order of precedence](#config-order-of-precedence) <add> - [Interceptors](#interceptors) <add> - [Handling Errors](#handling-errors) <add> - [Cancellation](#cancellation) <add> - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) <add> - [Browser](#browser) <add> - [Node.js](#nodejs) <add> - [Query string](#query-string) <add> - [Form data](#form-data) <add> - [Semver](#semver) <add> - [Promises](#promises) <add> - [TypeScript](#typescript) <add> - [Resources](#resources) <add> - [Credits](#credits) <add> - [License](#license) <ide> <ide> ## Features <ide>
1
Javascript
Javascript
fix typo in error message ("assing" -> "assign")
70dac5ae82ffe9c6250681274905583747523b5d
<ide><path>src/ng/parse.js <ide> ASTCompiler.prototype = { <ide> right = this.nextId(); <ide> left = {}; <ide> if (!isAssignable(ast.left)) { <del> throw $parseMinErr('lval', 'Trying to assing a value to a non l-value'); <add> throw $parseMinErr('lval', 'Trying to assign a value to a non l-value'); <ide> } <ide> this.recurse(ast.left, undefined, left, function() { <ide> self.if_(self.notNull(left.context), function() {
1
Ruby
Ruby
add provided_pre_high_sierra keg_only
0a10ca61dc6d626bfe72b3a4e5501ebb6ad15a81
<ide><path>Library/Homebrew/formula_support.rb <ide> def valid? <ide> MacOS.version < :mavericks <ide> when :provided_pre_el_capitan <ide> MacOS.version < :el_capitan <add> when :provided_pre_high_sierra <add> MacOS.version < :high_sierra <ide> when :provided_until_xcode43 <ide> MacOS::Xcode.installed? && MacOS::Xcode.version < "4.3" <ide> when :provided_until_xcode5 <ide> def to_s <ide> when :provided_pre_el_capitan then <<-EOS.undent <ide> macOS already provides this software in versions before El Capitan <ide> EOS <add> when :provided_pre_high_sierra then <<-EOS.undent <add> macOS already provides this software in versions before High Sierra <add> EOS <ide> when :provided_until_xcode43 then <<-EOS.undent <ide> Xcode provides this software prior to version 4.3 <ide> EOS
1
Python
Python
add --v8-lite-mode flag
01c4455de7160999c236f287f0860aa2fb7ec284
<ide><path>configure.py <ide> default=False, <ide> help='compile V8 with debug checks and runtime debugging features enabled') <ide> <add>parser.add_option('--v8-lite-mode', <add> action='store_true', <add> dest='v8_lite_mode', <add> default=False, <add> help='compile V8 in lite mode for constrained environments (lowers V8 '+ <add> 'memory footprint, but also implies no just-in-time compilation ' + <add> 'support, thus much slower execution)') <add> <ide> parser.add_option('--node-builtin-modules-path', <ide> action='store', <ide> dest='node_builtin_modules_path', <ide> def configure_library(lib, output, pkgname=None): <ide> <ide> <ide> def configure_v8(o): <add> o['variables']['v8_enable_lite_mode'] = 1 if options.v8_lite_mode else 0 <ide> o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0 <ide> o['variables']['v8_no_strict_aliasing'] = 1 # Work around compiler bugs. <ide> o['variables']['v8_optimized_debug'] = 0 if options.v8_non_optimized_debug else 1
1
Python
Python
add dim_ordering tests
27dd1e939c03325e3b414dacb9d83cd7d3f07dea
<ide><path>tests/keras/layers/test_convolutional.py <ide> def test_convolution_2d(): <ide> layer.get_config() <ide> <ide> <add>def test_convolution_2d_dim_ordering(): <add> nb_filter = 4 <add> nb_row = 3 <add> nb_col = 2 <add> stack_size = 3 <add> <add> np.random.seed(1337) <add> weights = [np.random.random((nb_filter, stack_size, nb_row, nb_col)), <add> np.random.random(nb_filter)] <add> input = np.random.random((1, stack_size, 10, 10)) <add> <add> layer = convolutional.Convolution2D( <add> nb_filter, nb_row, nb_col, <add> weights=weights, <add> input_shape=input.shape[1:], <add> dim_ordering='th') <add> layer.input = K.variable(input) <add> out_th = K.eval(layer.get_output(False)) <add> <add> input = np.transpose(input, (0, 2, 3, 1)) <add> weights[0] = np.transpose(weights[0], (2, 3, 1, 0)) <add> layer = convolutional.Convolution2D( <add> nb_filter, nb_row, nb_col, <add> weights=weights, <add> input_shape=input.shape[1:], <add> dim_ordering='tf') <add> layer.input = K.variable(input) <add> out_tf = K.eval(layer.get_output(False)) <add> <add> assert_allclose(out_tf, np.transpose(out_th, (0, 2, 3, 1)), atol=1e-05) <add> <add> <ide> def test_maxpooling_2d(): <ide> nb_samples = 9 <ide> stack_size = 7 <ide> def test_maxpooling_2d(): <ide> layer.get_config() <ide> <ide> <add>def test_maxpooling_2d_dim_ordering(): <add> stack_size = 3 <add> <add> input = np.random.random((1, stack_size, 10, 10)) <add> <add> layer = convolutional.MaxPooling2D( <add> (2, 2), <add> input_shape=input.shape[1:], <add> dim_ordering='th') <add> layer.input = K.variable(input) <add> out_th = K.eval(layer.get_output(False)) <add> <add> input = np.transpose(input, (0, 2, 3, 1)) <add> layer = convolutional.MaxPooling2D( <add> (2, 2), <add> input_shape=input.shape[1:], <add> dim_ordering='tf') <add> layer.input = K.variable(input) <add> out_tf = K.eval(layer.get_output(False)) <add> <add> assert_allclose(out_tf, np.transpose(out_th, (0, 2, 3, 1)), atol=1e-05) <add> <add> <ide> def test_averagepooling_2d(): <ide> nb_samples = 9 <ide> stack_size = 7 <ide><path>tests/test_shape_inference.py <ide> def test_Convolution1D(): <ide> <ide> def test_Convolution2D(): <ide> for border_mode in ['same', 'valid']: <del> for nb_row, nb_col in [(3, 3), (4, 4)]: <add> for nb_row, nb_col in [(3, 3), (4, 4), (3, 4)]: <ide> for subsample in [(1, 1), (2, 2), (3, 3)]: <ide> if (subsample[0] > nb_row or subsample[1] > nb_col) and border_mode == 'same': <ide> continue
2
Go
Go
add test for builder cache with root source path
86faf1e165b8ffa0cb2394b1f5504caa1fa8f718
<ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) { <ide> c.Assert(out, checker.Matches, "bar") <ide> <ide> } <add> <add>// #17827 <add>func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> name := "testbuildrootsource" <add> ctx, err := fakeContext(` <add> FROM busybox <add> COPY / /data`, <add> map[string]string{ <add> "foo": "bar", <add> }) <add> c.Assert(err, checker.IsNil) <add> defer ctx.Close() <add> <add> // warm up cache <add> _, err = buildImageFromContext(name, ctx, true) <add> c.Assert(err, checker.IsNil) <add> <add> // change file, should invalidate cache <add> err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644) <add> c.Assert(err, checker.IsNil) <add> <add> _, out, err := buildImageFromContextWithOut(name, ctx, true) <add> c.Assert(err, checker.IsNil) <add> <add> c.Assert(out, checker.Not(checker.Contains), "Using cache") <add>}
1
Ruby
Ruby
use file checksum rather than file diffing
64c83f3286a40cbe8871124f208fb3eaaaffd97a
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> require "cmd/style" <ide> require "date" <ide> require "blacklist" <add>require "digest" <ide> <ide> module Homebrew <ide> module_function <ide> def audit_urls <ide> <ide> return unless @online <ide> urls.each do |url| <del> next unless url.start_with? "http:" <del> # Check for insecure mirrors <del> details = get_content_details(url, 1) <del> secure_url = url.sub "http", "https" <del> secure_details = get_content_details(secure_url, 2) <del> <del> next unless details[:status].start_with?("2") && secure_details[:status].start_with?("2") <del> <del> if (details[:etag] && details[:etag] == secure_details[:etag]) \ <del> || (details[:content_length] && details[:content_length] == secure_details[:content_length]) \ <del> || are_same_file(details[:filename], secure_details[:filename]) <del> problem "The URL #{url} could use HTTPS rather than HTTP" <del> end <add> check_insecure_mirror(url) if url.start_with? "http:" <add> end <add> end <add> <add> def check_insecure_mirror(url) <add> details = get_content_details(url) <add> secure_url = url.sub "http", "https" <add> secure_details = get_content_details(secure_url) <add> <add> return if !details[:status].start_with?("2") || !secure_details[:status].start_with?("2") <ide> <del> remove_files details[:filename], secure_details[:filename] <add> etag_match = details[:etag] && details[:etag] == secure_details[:etag] <add> content_length_match = details[:content_length] && details[:content_length] == secure_details[:content_length] <add> file_match = details[:file_hash] == secure_details[:file_hash] <add> <add> if etag_match || content_length_match || file_match <add> problem "The URL #{url} could use HTTPS rather than HTTP" <ide> end <ide> end <ide> <ide> def problem(text) <ide> @problems << text <ide> end <ide> <del> def get_content_details(url, id) <add> def get_content_details(url) <ide> out = {} <del> out_file = "/tmp/_c#{id}" <del> headers, = curl_output "--connect-timeout", "15", "--output", out_file, "--dump-header", "/dev/stdout", url <add> output, = curl_output "--connect-timeout", "15", "--include", url <add> split = output.partition("\r\n\r\n") <add> headers = split.first <ide> out[:status] = headers[%r{HTTP\/.* (\d+)}, 1] <ide> out[:etag] = headers[%r{ETag: ([wW]\/)?"(([^"]|\\")*)"}, 2] <ide> out[:content_length] = headers[/Content-Length: (\d+)/, 1] <del> out[:filename] = out_file <add> out[:file_hash] = Digest::SHA256.digest split.last <ide> out <ide> end <del> <del> def are_same_file(one, two) <del> quiet_system "diff", "--report-identical-files", "--binary", "--speed-large-files", one, two <del> end <del> <del> def remove_files(*files) <del> quiet_system "rm", "-f", *files <del> end <ide> end
1
Javascript
Javascript
add hascrypto check to test-cli-node-options
427cd293d593511f3f592f3bcf99b0f4b4900fda
<ide><path>test/parallel/test-cli-node-options.js <ide> expect('--track-heap-objects', 'B\n'); <ide> expect('--throw-deprecation', 'B\n'); <ide> expect('--zero-fill-buffers', 'B\n'); <ide> expect('--v8-pool-size=10', 'B\n'); <del>expect('--use-openssl-ca', 'B\n'); <del>expect('--use-bundled-ca', 'B\n'); <del>expect('--openssl-config=_ossl_cfg', 'B\n'); <add>if (common.hasCrypto) { <add> expect('--use-openssl-ca', 'B\n'); <add> expect('--use-bundled-ca', 'B\n'); <add> expect('--openssl-config=_ossl_cfg', 'B\n'); <add>} <ide> expect('--icu-data-dir=_d', 'B\n'); <ide> <ide> // V8 options
1
PHP
PHP
improve test for first in collection
2a0bb9c7061bf4b577121a878412d96642d94e32
<ide><path>tests/Support/SupportCollectionTest.php <ide> public function testFirstWithDefaultAndWithoutCallback($collection) <ide> $data = new $collection; <ide> $result = $data->first(null, 'default'); <ide> $this->assertSame('default', $result); <add> <add> $data = new $collection(['foo', 'bar']); <add> $result = $data->first(null, 'default'); <add> $this->assertSame('foo', $result); <ide> } <ide> <ide> /**
1
PHP
PHP
allow extra conditions using http basic auth
b55592a57eeac8d76c27f343c159e63ebc65c5d2
<ide><path>src/Illuminate/Auth/SessionGuard.php <ide> public function validate(array $credentials = []) <ide> * Attempt to authenticate using HTTP Basic Auth. <ide> * <ide> * @param string $field <add> * @param array $extraConditions <ide> * @return \Symfony\Component\HttpFoundation\Response|null <ide> */ <del> public function basic($field = 'email') <add> public function basic($field = 'email', $extraConditions = []) <ide> { <ide> if ($this->check()) { <ide> return; <ide> public function basic($field = 'email') <ide> // If a username is set on the HTTP basic request, we will return out without <ide> // interrupting the request lifecycle. Otherwise, we'll need to generate a <ide> // request indicating that the given credentials were invalid for login. <del> if ($this->attemptBasic($this->getRequest(), $field)) { <add> if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) { <ide> return; <ide> } <ide> <ide> public function basic($field = 'email') <ide> * Perform a stateless HTTP Basic login attempt. <ide> * <ide> * @param string $field <add> * @param array $extraConditions <ide> * @return \Symfony\Component\HttpFoundation\Response|null <ide> */ <del> public function onceBasic($field = 'email') <add> public function onceBasic($field = 'email', $extraConditions = []) <ide> { <del> if (! $this->once($this->getBasicCredentials($this->getRequest(), $field))) { <add> $credentials = $this->getBasicCredentials($this->getRequest(), $field); <add> <add> if (! $this->once(array_merge($credentials, $extraConditions))) { <ide> return $this->getBasicResponse(); <ide> } <ide> } <ide> public function onceBasic($field = 'email') <ide> * <ide> * @param \Symfony\Component\HttpFoundation\Request $request <ide> * @param string $field <add> * @param array $extraConditions <ide> * @return bool <ide> */ <del> protected function attemptBasic(Request $request, $field) <add> protected function attemptBasic(Request $request, $field, $extraConditions = []) <ide> { <ide> if (! $request->getUser()) { <ide> return false; <ide> } <ide> <del> return $this->attempt($this->getBasicCredentials($request, $field)); <add> $credentials = $this->getBasicCredentials($request, $field); <add> <add> return $this->attempt(array_merge($credentials, $extraConditions)); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Contracts/Auth/SupportsBasicAuth.php <ide> interface SupportsBasicAuth <ide> * Attempt to authenticate using HTTP Basic Auth. <ide> * <ide> * @param string $field <add> * @param array $extraConditions <ide> * @return \Symfony\Component\HttpFoundation\Response|null <ide> */ <del> public function basic($field = 'email'); <add> public function basic($field = 'email', $extraConditions = []); <ide> <ide> /** <ide> * Perform a stateless HTTP Basic login attempt. <ide> * <ide> * @param string $field <add> * @param array $extraConditions <ide> * @return \Symfony\Component\HttpFoundation\Response|null <ide> */ <del> public function onceBasic($field = 'email'); <add> public function onceBasic($field = 'email', $extraConditions = []); <ide> } <ide><path>tests/Auth/AuthGuardTest.php <ide> public function testBasicReturnsResponseOnFailure() <ide> $this->assertEquals(401, $response->getStatusCode()); <ide> } <ide> <add> public function testBasicWithExtraConditions() <add> { <add> list($session, $provider, $request, $cookie) = $this->getMocks(); <add> $guard = m::mock('Illuminate\Auth\SessionGuard[check,attempt]', ['default', $provider, $session]); <add> $guard->shouldReceive('check')->once()->andReturn(false); <add> $guard->shouldReceive('attempt')->once()->with(['email' => '[email protected]', 'password' => 'secret', 'active' => 1])->andReturn(true); <add> $request = Symfony\Component\HttpFoundation\Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => '[email protected]', 'PHP_AUTH_PW' => 'secret']); <add> $guard->setRequest($request); <add> <add> $guard->basic('email', ['active' => 1]); <add> } <add> <ide> public function testAttemptCallsRetrieveByCredentials() <ide> { <ide> $guard = $this->getGuard();
3
Javascript
Javascript
remove scatological terminology
2244f7d9923e4037bb10b8f8f41ebc8c19e783cb
<ide><path>lib/net.js <ide> function afterShutdown(status, handle, req) { <ide> // if the writable side has ended already, then clean everything <ide> // up. <ide> function onSocketEnd() { <del> // XXX Should not have to do as much crap in this function. <add> // XXX Should not have to do as much in this function. <ide> // ended should already be true, since this is called *after* <ide> // the EOF errno and onread has eof'ed <ide> debug('onSocketEnd', this._readableState); <ide><path>test/parallel/test-async-wrap-uncaughtexception.js <ide> process.on('uncaughtException', common.mustCall(() => { <ide> require('crypto').randomBytes(1, common.mustCall(() => { <ide> assert.strictEqual(call_id, async_hooks.executionAsyncId()); <ide> call_log[1]++; <del> throw new Error('ah crap'); <add> throw new Error(); <ide> }));
2
Javascript
Javascript
implement consistent braces
5b63d48e9ea93e5fe1265e9e0d43574b6b0d807a
<ide><path>benchmark/child_process/child-process-read-ipc.js <ide> 'use strict'; <del>if (process.argv[2] === 'child') <del>{ <add>if (process.argv[2] === 'child') { <ide> const len = +process.argv[3]; <ide> const msg = `"${'.'.repeat(len)}"`; <ide> while (true) { <ide><path>lib/_stream_readable.js <ide> Readable.prototype.wrap = function(stream) { <ide> // important when wrapping filters and duplexes. <ide> for (var i in stream) { <ide> if (this[i] === undefined && typeof stream[i] === 'function') { <del> this[i] = function(method) { return function() { <del> return stream[method].apply(stream, arguments); <del> }; }(i); <add> this[i] = function(method) { <add> return function() { <add> return stream[method].apply(stream, arguments); <add> }; <add> }(i); <ide> } <ide> } <ide> <ide><path>lib/module.js <ide> Module._preloadModules = function(requests) { <ide> var parent = new Module('internal/preload', null); <ide> try { <ide> parent.paths = Module._nodeModulePaths(process.cwd()); <del> } <del> catch (e) { <add> } catch (e) { <ide> if (e.code !== 'ENOENT') { <ide> throw e; <ide> } <ide><path>lib/net.js <ide> function createServerHandle(address, port, addressType, fd) { <ide> if (typeof fd === 'number' && fd >= 0) { <ide> try { <ide> handle = createHandle(fd); <del> } <del> catch (e) { <add> } catch (e) { <ide> // Not a fd we can listen on. This will trigger an error. <ide> debug('listen invalid fd=' + fd + ': ' + e.message); <ide> return uv.UV_EINVAL; <ide><path>test/internet/test-dgram-broadcast-multi-process.js <ide> if (process.argv[2] !== 'child') { <ide> //all child process are listening, so start sending <ide> sendSocket.sendNext(); <ide> } <del> } <del> else if (msg.message) { <add> } else if (msg.message) { <ide> worker.messagesReceived.push(msg.message); <ide> <ide> if (worker.messagesReceived.length === messages.length) { <ide><path>test/parallel/test-child-process-fork-exec-path.js <ide> if (process.env.FORK) { <ide> assert.equal(process.argv[0], copyPath); <ide> process.send(msg); <ide> process.exit(); <del>} <del>else { <add>} else { <ide> common.refreshTmpDir(); <ide> try { <ide> fs.unlinkSync(copyPath); <del> } <del> catch (e) { <add> } catch (e) { <ide> if (e.code !== 'ENOENT') throw e; <ide> } <ide> fs.writeFileSync(copyPath, fs.readFileSync(nodePath)); <ide><path>test/parallel/test-child-process-recv-handle.js <ide> function worker() { <ide> if (n === 1) { <ide> assert.equal(msg, 'one'); <ide> assert.equal(handle, undefined); <del> } <del> else if (n === 2) { <add> } else if (n === 2) { <ide> assert.equal(msg, 'two'); <ide> assert.equal(typeof handle, 'object'); // Also matches null, therefore... <ide> assert.ok(handle); // also check that it's truthy. <ide> handle.close(); <del> } <del> else if (n === 3) { <add> } else if (n === 3) { <ide> assert.equal(msg, 'three'); <ide> assert.equal(handle, undefined); <ide> process.exit(); <ide><path>test/parallel/test-cluster-basic.js <ide> if (cluster.isWorker) { <ide> http.Server(function() { <ide> <ide> }).listen(common.PORT, '127.0.0.1'); <del>} <del> <del>else if (cluster.isMaster) { <add>} else if (cluster.isMaster) { <ide> <ide> var checks = { <ide> cluster: { <ide><path>test/parallel/test-cluster-bind-privileged-port.js <ide> if (cluster.isMaster) { <ide> cluster.fork().on('exit', common.mustCall(function(exitCode) { <ide> assert.equal(exitCode, 0); <ide> })); <del>} <del>else { <add>} else { <ide> var s = net.createServer(common.fail); <ide> s.listen(42, common.fail.bind(null, 'listen should have failed')); <ide> s.on('error', common.mustCall(function(err) { <ide><path>test/parallel/test-cluster-bind-twice.js <ide> if (!id) { <ide> process.on('exit', function() { <ide> assert(ok); <ide> }); <del>} <del>else if (id === 'one') { <add>} else if (id === 'one') { <ide> if (cluster.isMaster) return startWorker(); <ide> <ide> http.createServer(common.fail).listen(common.PORT, function() { <ide> else if (id === 'one') { <ide> process.on('message', function(m) { <ide> if (m === 'QUIT') process.exit(); <ide> }); <del>} <del>else if (id === 'two') { <add>} else if (id === 'two') { <ide> if (cluster.isMaster) return startWorker(); <ide> <ide> let ok = false; <ide> else if (id === 'two') { <ide> ok = true; <ide> }); <ide> }); <del>} <del>else { <add>} else { <ide> assert(0); // bad command line argument <ide> } <ide> <ide><path>test/parallel/test-cluster-eaddrinuse.js <ide> if (id === 'undefined') { <ide> }); <ide> }); <ide> }); <del>} <del>else if (id === 'worker') { <add>} else if (id === 'worker') { <ide> let server = net.createServer(common.fail); <ide> server.listen(common.PORT, common.fail); <ide> server.on('error', common.mustCall(function(e) { <ide> else if (id === 'worker') { <ide> })); <ide> }); <ide> })); <del>} <del>else { <add>} else { <ide> assert(0); // Bad argument. <ide> } <ide><path>test/parallel/test-cluster-listening-port.js <ide> if (cluster.isMaster) { <ide> // ensure that the 'listening' handler has been called <ide> assert(port); <ide> }); <del>} <del>else { <add>} else { <ide> net.createServer(common.fail).listen(0); <ide> } <ide><path>test/parallel/test-cluster-message.js <ide> if (cluster.isWorker) { <ide> }); <ide> <ide> server.listen(common.PORT, '127.0.0.1'); <del>} <del> <del>else if (cluster.isMaster) { <add>} else if (cluster.isMaster) { <ide> <ide> var checks = { <ide> global: { <ide><path>test/parallel/test-cluster-net-listen.js <ide> if (cluster.isMaster) { <ide> process.on('exit', function() { <ide> assert.equal(worker, null); <ide> }); <del>} <del>else { <add>} else { <ide> // listen() without port should not trigger a libuv assert <ide> net.createServer(common.fail).listen(process.exit); <ide> } <ide><path>test/parallel/test-cluster-shared-handle-bind-error.js <ide> if (cluster.isMaster) { <ide> server.close(); <ide> })); <ide> }); <del>} <del>else { <add>} else { <ide> var s = net.createServer(common.fail); <ide> s.listen(common.PORT, common.fail.bind(null, 'listen should have failed')); <ide> s.on('error', common.mustCall(function(err) { <ide><path>test/parallel/test-cluster-shared-handle-bind-privileged-port.js <ide> if (cluster.isMaster) { <ide> cluster.fork().on('exit', common.mustCall(function(exitCode) { <ide> assert.equal(exitCode, 0); <ide> })); <del>} <del>else { <add>} else { <ide> var s = net.createServer(common.fail); <ide> s.listen(42, common.fail.bind(null, 'listen should have failed')); <ide> s.on('error', common.mustCall(function(err) { <ide><path>test/parallel/test-cluster-uncaught-exception.js <ide> if (isTestRunner) { <ide> master.on('exit', function(code) { <ide> exitCode = code; <ide> }); <del>} <del>else if (cluster.isMaster) { <add>} else if (cluster.isMaster) { <ide> process.on('uncaughtException', function() { <ide> process.nextTick(function() { <ide> process.exit(MAGIC_EXIT_CODE); <ide> else if (cluster.isMaster) { <ide> <ide> cluster.fork(); <ide> throw new Error('kill master'); <del>} <del>else { // worker <add>} else { // worker <ide> process.exit(); <ide> } <ide><path>test/parallel/test-cluster-worker-death.js <ide> var cluster = require('cluster'); <ide> <ide> if (!cluster.isMaster) { <ide> process.exit(42); <del>} <del>else { <add>} else { <ide> var seenExit = 0; <ide> var seenDeath = 0; <ide> var worker = cluster.fork(); <ide><path>test/parallel/test-crypto-authenticated.js <ide> for (var i in TEST_CASES) { <ide> (function() { <ide> if (!test.password) return; <ide> if (common.hasFipsCrypto) { <del> assert.throws(function() <del> { crypto.createCipher(test.algo, test.password); }, <add> assert.throws(() => { crypto.createCipher(test.algo, test.password); }, <ide> /not supported in FIPS mode/); <ide> } else { <ide> var encrypt = crypto.createCipher(test.algo, test.password); <ide> for (var i in TEST_CASES) { <ide> (function() { <ide> if (!test.password) return; <ide> if (common.hasFipsCrypto) { <del> assert.throws(function() <del> { crypto.createDecipher(test.algo, test.password); }, <add> assert.throws(() => { crypto.createDecipher(test.algo, test.password); }, <ide> /not supported in FIPS mode/); <ide> } else { <ide> var decrypt = crypto.createDecipher(test.algo, test.password); <ide> for (var i in TEST_CASES) { <ide> 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); <ide> encrypt.update('blah', 'ascii'); <ide> encrypt.final(); <del> assert.throws(function() { encrypt.getAuthTag(); }, / state/); <del> assert.throws(function() { <del> encrypt.setAAD(Buffer.from('123', 'ascii')); }, / state/); <add> assert.throws(() => { encrypt.getAuthTag(); }, / state/); <add> assert.throws(() => { encrypt.setAAD(Buffer.from('123', 'ascii')); }, <add> / state/); <ide> })(); <ide> <ide> (function() { <ide> for (var i in TEST_CASES) { <ide> // trying to set tag on encryption object: <ide> var encrypt = crypto.createCipheriv(test.algo, <ide> Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); <del> assert.throws(function() { <del> encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); <add> assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, <add> / state/); <ide> })(); <ide> <ide> (function() { <ide><path>test/parallel/test-debugger-util-regression.js <ide> proc.stdout.on('data', (data) => { <ide> stdout.includes('> 4') && nextCount < 4) { <ide> nextCount++; <ide> proc.stdin.write('n\n'); <del> } <del> else if (stdout.includes('{ a: \'b\' }')) { <add> } else if (stdout.includes('{ a: \'b\' }')) { <ide> clearTimeout(timer); <ide> proc.stdin.write('.exit\n'); <del> } <del> else if (stdout.includes('program terminated')) { <add> } else if (stdout.includes('program terminated')) { <ide> // Catch edge case present in v4.x <ide> // process will terminate after call to util.inspect <ide> common.fail('the program should not terminate'); <ide><path>test/parallel/test-fs-open.js <ide> try { <ide> // should throw ENOENT, not EBADF <ide> // see https://github.com/joyent/node/pull/1228 <ide> fs.openSync('/path/to/file/that/does/not/exist', 'r'); <del>} <del>catch (e) { <add>} catch (e) { <ide> assert.equal(e.code, 'ENOENT'); <ide> caughtException = true; <ide> } <ide><path>test/parallel/test-fs-realpath.js <ide> function asynctest(testBlock, args, callback, assertBlock) { <ide> if (assertBlock) { <ide> try { <ide> ignoreError = assertBlock.apply(assertBlock, arguments); <del> } <del> catch (e) { <add> } catch (e) { <ide> err = e; <ide> } <ide> } <ide><path>test/parallel/test-http-server-stale-close.js <ide> if (process.env.NODE_TEST_FORK_PORT) { <ide> }, process.exit); <ide> req.write('BAM'); <ide> req.end(); <del>} <del>else { <add>} else { <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Length': '42'}); <ide> req.pipe(res); <ide><path>test/parallel/test-next-tick-errors.js <ide> process.on('uncaughtException', function() { <ide> if (!exceptionHandled) { <ide> exceptionHandled = true; <ide> order.push('B'); <del> } <del> else { <add> } else { <ide> // If we get here then the first process.nextTick got called twice <ide> order.push('OOPS!'); <ide> } <ide><path>test/parallel/test-process-argv-0.js <ide> if (process.argv[2] !== 'child') { <ide> process.on('exit', function() { <ide> assert.equal(childArgv0, process.execPath); <ide> }); <del>} <del>else { <add>} else { <ide> process.stdout.write(process.argv[0]); <ide> } <ide><path>test/parallel/test-process-cpuUsage.js <ide> assert.throws(function() { process.cpuUsage({ user: null, system: 'c' }); }); <ide> assert.throws(function() { process.cpuUsage({ user: 'd', system: null }); }); <ide> assert.throws(function() { process.cpuUsage({ user: -1, system: 2 }); }); <ide> assert.throws(function() { process.cpuUsage({ user: 3, system: -2 }); }); <del>assert.throws(function() { process.cpuUsage({ <del> user: Number.POSITIVE_INFINITY, <del> system: 4 <del>});}); <del>assert.throws(function() { process.cpuUsage({ <del> user: 5, <del> system: Number.NEGATIVE_INFINITY <del>});}); <add>assert.throws(function() { <add> process.cpuUsage({ <add> user: Number.POSITIVE_INFINITY, <add> system: 4 <add> }); <add>}); <add>assert.throws(function() { <add> process.cpuUsage({ <add> user: 5, <add> system: Number.NEGATIVE_INFINITY <add> }); <add>}); <ide> <ide> // Ensure that the return value is the expected shape. <ide> function validateResult(result) { <ide><path>test/parallel/test-repl-domain.js <ide> putIn.write = function(data) { <ide> // give a false negative. Don't throw, just print and exit. <ide> if (data === 'OK\n') { <ide> console.log('ok'); <del> } <del> else { <add> } else { <ide> console.error(data); <ide> process.exit(1); <ide> } <ide><path>test/parallel/test-vm-context.js <ide> console.error('test runInContext signature'); <ide> var gh1140Exception; <ide> try { <ide> vm.runInContext('throw new Error()', context, 'expected-filename.js'); <del>} <del>catch (e) { <add>} catch (e) { <ide> gh1140Exception = e; <ide> assert.ok(/expected-filename/.test(e.stack), <ide> 'expected appearance of filename in Error stack'); <ide><path>test/pummel/test-fs-watch-file-slow.js <ide> var nevents = 0; <ide> <ide> try { <ide> fs.unlinkSync(FILENAME); <del>} <del>catch (e) { <add>} catch (e) { <ide> // swallow <ide> } <ide> <ide><path>test/pummel/test-regress-GH-814.js <ide> var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. <ide> if (bufPool.push(nuBuf) > 100) { <ide> bufPool.length = 0; <ide> } <del> } <del> else { <add> } else { <ide> throw new Error("Buffer GC'ed test -> FAIL"); <ide> } <ide> <ide> if (Date.now() < timeToQuit) { <ide> process.nextTick(main); <del> } <del> else { <add> } else { <ide> tail.kill(); <ide> console.log("Buffer GC'ed test -> PASS (OK)"); <ide> }
30