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
PHP
PHP
allow broadcast on demand notifications
d2b14466c27a3d62219256cea27088e6ecd9d32f
<ide><path>src/Illuminate/Notifications/Events/BroadcastNotificationCreated.php <ide> use Illuminate\Broadcasting\PrivateChannel; <ide> use Illuminate\Bus\Queueable; <ide> use Illuminate\Contracts\Broadcasting\ShouldBroadcast; <add>use Illuminate\Notifications\AnonymousNotifiable; <ide> use Illuminate\Queue\SerializesModels; <add>use Illuminate\Support\Arr; <ide> <ide> class BroadcastNotificationCreated implements ShouldBroadcast <ide> { <ide> public function __construct($notifiable, $notification, $data) <ide> */ <ide> public function broadcastOn() <ide> { <del> $channels = $this->notification->broadcastOn(); <add> if ($this->notifiable instanceof AnonymousNotifiable && <add> $this->notifiable->routeNotificationFor('broadcast')) { <add> $channels = Arr::wrap($this->notifiable->routeNotificationFor('broadcast')); <add> } else { <add> $channels = $this->notification->broadcastOn(); <add> } <ide> <ide> if (! empty($channels)) { <ide> return $channels;
1
Javascript
Javascript
explain all 3 ways how to use ngclass
21dac2a3daae528471d5e767072b10e1491f2106
<ide><path>src/ng/directive/ngClass.js <ide> function classDirective(name, selector) { <ide> * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding <ide> * an expression that represents all classes to be added. <ide> * <add> * The directive operates in three different ways, depending on which of three types the expression <add> * evaluates to: <add> * <add> * 1. If the expression evaluates to a string, the string should be one or more space-delimited class <add> * names. <add> * <add> * 2. If the expression evaluates to an array, each element of the array should be a string that is <add> * one or more space-delimited class names. <add> * <add> * 3. If the expression evaluates to an object, then for each key-value pair of the <add> * object with a truthy value the corresponding key is used as a class name. <add> * <ide> * The directive won't add duplicate classes if a particular class was already set. <ide> * <ide> * When the expression changes, the previously added classes are removed and only then the
1
Python
Python
fix override func style and regular usage
cad1b082602ce1367cae6a3a3668a64436fb4bde
<ide><path>rest_framework/relations.py <ide> class Hyperlink(str): <ide> in some contexts, or render as a plain URL in others. <ide> """ <ide> def __new__(cls, url, obj): <del> ret = str.__new__(cls, url) <add> ret = super().__new__(cls, url) <ide> ret.obj = obj <ide> return ret <ide> <ide> def __getnewargs__(self): <del> return(str(self), self.name,) <add> return (str(self), self.name) <ide> <ide> @property <ide> def name(self):
1
Ruby
Ruby
use dir.mktmpdir in doctor
75642e6271205d8c3ac9436e67cb4d6ffc0f32de
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_multiple_volumes <ide> # Find the volumes for the TMP folder & HOMEBREW_CELLAR <ide> real_cellar = HOMEBREW_CELLAR.realpath <ide> <del> tmp = Pathname.new with_system_path { `mktemp -d #{HOMEBREW_TEMP}/homebrew-brew-doctor-XXXXXX` }.strip <add> tmp = Pathname.new(Dir.mktmpdir("doctor", HOMEBREW_TEMP)) <ide> real_temp = tmp.realpath.parent <ide> <ide> where_cellar = volumes.which real_cellar
1
Javascript
Javascript
fix saveasset scales filtering
b6e0f4a12d817af6968cd1461e4f92f1bf996544
<ide><path>local-cli/bundle/saveAssets.js <ide> function saveAssets( <ide> <ide> const filesToCopy = Object.create(null); // Map src -> dest <ide> assets <del> .forEach(asset => <del> filterPlatformAssetScales(platform, asset.scales).forEach((scale, idx) => { <add> .forEach(asset => { <add> const validScales = new Set(filterPlatformAssetScales(platform, asset.scales)); <add> asset.scales.forEach((scale, idx) => { <add> if (!validScales.has(scale)) { <add> return; <add> } <ide> const src = asset.files[idx]; <ide> const dest = path.join(assetsDest, getAssetDestPath(asset, scale)); <ide> filesToCopy[src] = dest; <ide> }) <del> ); <add> }); <ide> <ide> return copyAll(filesToCopy); <ide> }
1
Python
Python
acquire lock on db for the time of migration
5d96eb0e00b831daf398f14919cbd7dadc95d254
<ide><path>airflow/migrations/env.py <ide> def run_migrations_online(): <ide> ) <ide> <ide> with context.begin_transaction(): <add> if connection.dialect.name == 'mysql' and connection.dialect.server_version_info >= (5, 6): <add> connection.execute("select GET_LOCK('alembic',1800);") <add> if connection.dialect.name == 'postgresql': <add> context.get_context()._ensure_version_table() # pylint: disable=protected-access <add> connection.execute("LOCK TABLE alembic_version IN ACCESS EXCLUSIVE MODE") <ide> context.run_migrations() <add> if connection.dialect.name == 'mysql' and connection.dialect.server_version_info >= (5, 6): <add> connection.execute("select RELEASE_LOCK('alembic');") <add> # for Postgres lock is released when transaction ends <ide> <ide> <ide> if context.is_offline_mode():
1
Python
Python
deduplicate euclidean_length method in vector
a64c9f1e7cc9616c54296ca3983123e15ec486f1
<ide><path>linear_algebra/src/lib.py <ide> class Vector: <ide> component(i): gets the i-th component (0-indexed) <ide> change_component(pos: int, value: float): changes specified component <ide> euclidean_length(): returns the euclidean length of the vector <del> magnitude(): returns the magnitude of the vector <ide> angle(other: Vector, deg: bool): returns the angle between two vectors <ide> TODO: compare-operator <ide> """ <ide> def change_component(self, pos: int, value: float) -> None: <ide> def euclidean_length(self) -> float: <ide> """ <ide> returns the euclidean length of the vector <del> """ <del> squares = [c ** 2 for c in self.__components] <del> return math.sqrt(sum(squares)) <del> <del> def magnitude(self) -> float: <del> """ <del> Magnitude of a Vector <ide> <del> >>> Vector([2, 3, 4]).magnitude() <add> >>> Vector([2, 3, 4]).euclidean_length() <ide> 5.385164807134504 <del> <add> >>> Vector([1]).euclidean_length() <add> 1.0 <add> >>> Vector([0, -1, -2, -3, 4, 5, 6]).euclidean_length() <add> 9.539392014169456 <add> >>> Vector([]).euclidean_length() <add> Traceback (most recent call last): <add> ... <add> Exception: Vector is empty <ide> """ <add> if len(self.__components) == 0: <add> raise Exception("Vector is empty") <ide> squares = [c ** 2 for c in self.__components] <ide> return math.sqrt(sum(squares)) <ide> <ide> def angle(self, other: Vector, deg: bool = False) -> float: <ide> Exception: invalid operand! <ide> """ <ide> num = self * other <del> den = self.magnitude() * other.magnitude() <add> den = self.euclidean_length() * other.euclidean_length() <ide> if deg: <ide> return math.degrees(math.acos(num / den)) <ide> else: <ide> class Matrix: <ide> <ide> def __init__(self, matrix: list[list[float]], w: int, h: int) -> None: <ide> """ <del> simple constructor for initializing <del> the matrix with components. <add> simple constructor for initializing the matrix with components. <ide> """ <ide> self.__matrix = matrix <ide> self.__width = w <ide> self.__height = h <ide> <ide> def __str__(self) -> str: <ide> """ <del> returns a string representation of this <del> matrix. <add> returns a string representation of this matrix. <ide> """ <ide> ans = "" <ide> for i in range(self.__height): <ide> def __str__(self) -> str: <ide> <ide> def __add__(self, other: Matrix) -> Matrix: <ide> """ <del> implements the matrix-addition. <add> implements matrix addition. <ide> """ <ide> if self.__width == other.width() and self.__height == other.height(): <ide> matrix = [] <ide> def __add__(self, other: Matrix) -> Matrix: <ide> <ide> def __sub__(self, other: Matrix) -> Matrix: <ide> """ <del> implements the matrix-subtraction. <add> implements matrix subtraction. <ide> """ <ide> if self.__width == other.width() and self.__height == other.height(): <ide> matrix = [] <ide><path>linear_algebra/src/test_linear_algebra.py <ide> def test_size(self) -> None: <ide> x = Vector([1, 2, 3, 4]) <ide> self.assertEqual(len(x), 4) <ide> <del> def test_euclidLength(self) -> None: <add> def test_euclidean_length(self) -> None: <ide> """ <ide> test for method euclidean_length() <ide> """ <ide> x = Vector([1, 2]) <add> y = Vector([1, 2, 3, 4, 5]) <add> z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) <add> w = Vector([1, -1, 1, -1, 2, -3, 4, -5]) <ide> self.assertAlmostEqual(x.euclidean_length(), 2.236, 3) <add> self.assertAlmostEqual(y.euclidean_length(), 7.416, 3) <add> self.assertEqual(z.euclidean_length(), 0) <add> self.assertAlmostEqual(w.euclidean_length(), 7.616, 3) <ide> <ide> def test_add(self) -> None: <ide> """
2
Text
Text
add missing deprecation number
37321a9e11f2198d03a525cddca20827636b786c
<ide><path>doc/api/deprecations.md <ide> Type: Runtime <ide> Passing a callback to [`worker.terminate()`][] is deprecated. Use the returned <ide> `Promise` instead, or a listener to the worker’s `'exit'` event. <ide> <del><a id="DEP0XXX"></a> <del>### DEP0XXX: http connection <add><a id="DEP0133"></a> <add>### DEP0133: http connection <ide> <!-- YAML <ide> changes: <ide> - version: REPLACEME
1
Python
Python
add __version__ to __init__.py
0d7d50fe22d0b574f64e9d534b36cd7d30d10caa
<ide><path>spacy/__init__.py <ide> from .cli.info import info as cli_info <ide> from .glossary import explain <ide> from .deprecated import resolve_load_name <add>from .about import __version__ <ide> from . import util <ide> <del> <ide> def load(name, **overrides): <ide> name = resolve_load_name(name, **overrides) <ide> return util.load_model(name, **overrides)
1
Ruby
Ruby
fix bugs when running with use_codegen_discovery
bfb8f63c18c12204b20ba6a3d64a7e551ebcead1
<ide><path>scripts/react_native_pods.rb <ide> def get_react_codegen_spec(options={}) <ide> end <ide> <ide> def get_codegen_config_from_file(config_path, config_key) <del> empty = {'libraries': []} <add> empty = {'libraries' => []} <ide> if !File.exist?(config_path) <ide> return empty <ide> end <ide> def get_react_codegen_script_phases(options={}) <ide> <ide> config_file_dir = options[:config_file_dir] ||= '' <ide> relative_config_file_dir = '' <del> if config_file_dir <add> if config_file_dir != '' <ide> relative_config_file_dir = Pathname.new(config_file_dir).relative_path_from(Pod::Config.instance.installation_root) <ide> end <ide>
1
Go
Go
use router.cancellable for pull and push
c6ad1980a2eb2994940bdf7f79835ffdbed2b44d
<ide><path>api/server/router/image/image.go <ide> func (r *imageRouter) initRoutes() { <ide> router.NewGetRoute("/images/{name:.*}/json", r.getImagesByName), <ide> // POST <ide> router.NewPostRoute("/commit", r.postCommit), <del> router.NewPostRoute("/images/create", r.postImagesCreate), <ide> router.NewPostRoute("/images/load", r.postImagesLoad), <del> router.NewPostRoute("/images/{name:.*}/push", r.postImagesPush), <add> router.Cancellable(router.NewPostRoute("/images/create", r.postImagesCreate)), <add> router.Cancellable(router.NewPostRoute("/images/{name:.*}/push", r.postImagesPush)), <ide> router.NewPostRoute("/images/{name:.*}/tag", r.postImagesTag), <ide> // DELETE <ide> router.NewDeleteRoute("/images/{name:.*}", r.deleteImages),
1
Text
Text
fix english grammar in computer vision
3aef85bceca826fb8151ecb553a2e4d272c77953
<ide><path>computer_vision/README.md <ide> Computer vision is a field of computer science that works on enabling computers to see, <ide> identify and process images in the same way that human vision does, and then provide appropriate output. <ide> It is like imparting human intelligence and instincts to a computer. <del>Image processing and computer vision and little different from each other.Image processing means applying some algorithms for transforming image from one form to other like smoothing,contrasting, stretching etc <del>While in computer vision comes from modelling image processing using the techniques of machine learning.Computer vision applies machine learning to recognize patterns for interpretation of images. <del>Much like the process of visual reasoning of human vision <add>Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc. <add>While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
1
Ruby
Ruby
fix m2 detection
449b872916c29a7b9d4155b176f7aca85b8c2c84
<ide><path>Library/Homebrew/extend/os/mac/hardware/cpu.rb <ide> def sysctl_bool(key) <ide> end <ide> <ide> def sysctl_int(key) <del> sysctl_n(key).to_i <add> if (x = sysctl_n(key).to_i) >= 0 <add> x <add> else <add> x & 0xffffffff <add> end <ide> end <ide> <ide> def sysctl_n(*keys)
1
PHP
PHP
apply fixes from styleci
cfc3433880a6cea6bcb93251e63ff101979456c3
<ide><path>src/Illuminate/Queue/Events/WorkerStopping.php <ide> <ide> namespace Illuminate\Queue\Events; <ide> <del>use Illuminate\Queue\WorkerOptions; <del> <ide> class WorkerStopping <ide> { <ide> /**
1
Java
Java
add stomp broker relay to configure "host" header
7c3749769a8d136eee5e3b01e156b9a5eac3ec49
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> <ide> <ide> /** <del> * A {@link MessageHandler} that handles messages by forwarding them to a STOMP broker and <del> * reversely sends any returned messages from the broker to the provided <del> * {@link MessageChannel}. <add> * A {@link MessageHandler} that handles messages by forwarding them to a STOMP broker. <add> * For each new {@link SimpMessageType#CONNECT CONNECT} message, an independent TCP <add> * connection to the broker is opened and used exclusively for all messages from the <add> * client that originated the CONNECT message. Messages from the same client are <add> * identified through the session id message header. Reversely, when the STOMP broker <add> * sends messages back on the TCP connection, those messages are enriched with the session <add> * id of the client and sent back downstream through the {@link MessageChannel} provided <add> * to the constructor. <add> * <p> <add> * This class also automatically opens a default "system" TCP connection to the message <add> * broker that is used for sending messages that originate from the server application (as <add> * opposed to from a client). Such messages are recognized because they are not associated <add> * with any client and therefore do not have a session id header. The "system" connection <add> * is effectively shared and cannot be used to receive messages. Several properties are <add> * provided to configure the "system" session including the the <add> * {@link #setSystemLogin(String) login} {@link #setSystemPasscode(String) passcode}, <add> * heartbeat {@link #setSystemHeartbeatSendInterval(long) send} and <add> * {@link #setSystemHeartbeatReceiveInterval(long) receive} intervals. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Andy Wilkinson <ide> public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler <ide> <ide> private long systemHeartbeatReceiveInterval = 10000; <ide> <add> private String virtualHost; <add> <ide> private Environment environment; <ide> <ide> private TcpClient<Message<byte[]>, Message<byte[]>> tcpClient; <ide> public int getRelayPort() { <ide> } <ide> <ide> /** <del> * Set the interval, in milliseconds, at which the "system" relay session will, <del> * in the absence of any other data being sent, send a heartbeat to the STOMP broker. <del> * A value of zero will prevent heartbeats from being sent to the broker. <add> * Set the interval, in milliseconds, at which the "system" relay session will, in the <add> * absence of any other data being sent, send a heartbeat to the STOMP broker. A value <add> * of zero will prevent heartbeats from being sent to the broker. <ide> * <p> <ide> * The default value is 10000. <add> * <p> <add> * See class-level documentation for more information on the "system" session. <ide> */ <ide> public void setSystemHeartbeatSendInterval(long systemHeartbeatSendInterval) { <ide> this.systemHeartbeatSendInterval = systemHeartbeatSendInterval; <ide> public long getSystemHeartbeatSendInterval() { <ide> * heartbeats from the broker. <ide> * <p> <ide> * The default value is 10000. <add> * <p> <add> * See class-level documentation for more information on the "system" session. <ide> */ <ide> public void setSystemHeartbeatReceiveInterval(long heartbeatReceiveInterval) { <ide> this.systemHeartbeatReceiveInterval = heartbeatReceiveInterval; <ide> public long getSystemHeartbeatReceiveInterval() { <ide> /** <ide> * Set the login for the "system" relay session used to send messages to the STOMP <ide> * broker without having a client session (e.g. REST/HTTP request handling method). <add> * <p> <add> * See class-level documentation for more information on the "system" session. <ide> */ <ide> public void setSystemLogin(String systemLogin) { <ide> Assert.hasText(systemLogin, "systemLogin must not be empty"); <ide> public String getSystemLogin() { <ide> /** <ide> * Set the passcode for the "system" relay session used to send messages to the STOMP <ide> * broker without having a client session (e.g. REST/HTTP request handling method). <add> * <p> <add> * See class-level documentation for more information on the "system" session. <ide> */ <ide> public void setSystemPasscode(String systemPasscode) { <ide> this.systemPasscode = systemPasscode; <ide> public String getSystemPasscode() { <ide> return this.systemPasscode; <ide> } <ide> <add> /** <add> * Set the value of the "host" header to use in STOMP CONNECT frames. When this <add> * property is configured, a "host" header will be added to every STOMP frame sent to <add> * the STOMP broker. This may be useful for example in a cloud environment where the <add> * actual host to which the TCP connection is established is different from the host <add> * providing the cloud-based STOMP service. <add> * <p> <add> * By default this property is not set. <add> */ <add> public void setVirtualHost(String virtualHost) { <add> this.virtualHost = virtualHost; <add> } <add> <add> /** <add> * @return the configured virtual host value. <add> */ <add> public String getVirtualHost() { <add> return this.virtualHost; <add> } <add> <ide> <ide> @Override <ide> protected void startInternal() { <ide> protected void handleMessageInternal(Message<?> message) { <ide> } <ide> <ide> if (SimpMessageType.CONNECT.equals(messageType)) { <del> message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build(); <add> if (getVirtualHost() != null) { <add> headers.setHost(getVirtualHost()); <add> message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build(); <add> } <ide> StompRelaySession session = new StompRelaySession(sessionId); <ide> this.relaySessions.put(sessionId, session); <ide> session.connect(message); <ide> public void connect() { <ide> headers.setLogin(systemLogin); <ide> headers.setPasscode(systemPasscode); <ide> headers.setHeartbeat(systemHeartbeatSendInterval, systemHeartbeatReceiveInterval); <add> if (getVirtualHost() != null) { <add> headers.setHost(getVirtualHost()); <add> } <ide> Message<?> connectMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); <ide> super.connect(connectMessage); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java <ide> public void tearDown() throws Exception { <ide> } <ide> } <ide> <add> // test "host" header (virtualHost property) when TCP client is behind interface and configurable <add> <ide> @Test <ide> public void publishSubscribe() throws Exception { <ide>
2
Javascript
Javascript
fix flaky cluster test on windows 10
25f8a0d2dc7be14dcdd28c69ed542c8d699a65ce
<ide><path>test/parallel/test-cluster-shared-leak.js <ide> if (cluster.isMaster) { <ide> worker2 = cluster.fork(); <ide> worker2.on('online', function() { <ide> conn = net.connect(common.PORT, common.mustCall(function() { <del> worker1.send('die'); <del> worker2.send('die'); <add> worker1.disconnect(); <add> worker2.disconnect(); <ide> })); <ide> conn.on('error', function(e) { <ide> // ECONNRESET is OK <ide> if (cluster.isMaster) { <ide> return; <ide> } <ide> <del>var server = net.createServer(function(c) { <add>const server = net.createServer(function(c) { <ide> c.end('bye'); <ide> }); <ide> <ide> server.listen(common.PORT, function() { <ide> process.send('listening'); <ide> }); <del> <del>process.on('message', function(msg) { <del> if (msg !== 'die') return; <del> server.close(function() { <del> setImmediate(() => process.disconnect()); <del> }); <del>});
1
Javascript
Javascript
add /external/update-my-current-challenge endpoint
8380c8a1811e87c7748ce0e5ccb05a1e0bca3f1b
<ide><path>server/boot/settings.js <ide> export default function settingsController(app) { <ide> createValidatorErrorHandler(alertTypes.danger), <ide> updateMyCurrentChallenge <ide> ); <add> api.post( <add> '/external/update-my-current-challenge', <add> ifNoUser401, <add> updateMyCurrentChallengeValidators, <add> createValidatorErrorHandler(alertTypes.danger), <add> updateMyCurrentChallenge <add> ); <ide> api.post( <ide> '/update-my-portfolio', <ide> ifNoUser401,
1
Javascript
Javascript
fix auto transparency
0d1e85694731632281bdc351ae33d4d2b55c89ac
<ide><path>examples/js/nodes/NodeMaterial.js <ide> THREE.NodeMaterial.prototype.build = function() { <ide> } <ide> <ide> this.lights = this.requestAttribs.light; <del> this.transparent = this.requestAttribs.transparent || this.blendMode > THREE.NormalBlending; <add> this.transparent = this.requestAttribs.transparent || this.blending > THREE.NormalBlending; <ide> <ide> this.vertexShader = [ <ide> this.prefixCode,
1
Python
Python
add setup back
cca97db0e2cda358dd52d1f6b3a7822c1b8a4374
<ide><path>research/setup.py <add>"""Setup script for object_detection.""" <add> <add>from setuptools import find_packages <add>from setuptools import setup <add> <add> <add>REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1'] <add> <add>setup( <add> name='object_detection', <add> version='0.1', <add> install_requires=REQUIRED_PACKAGES, <add> include_package_data=True, <add> packages=[p for p in find_packages() if p.startswith('object_detection')], <add> description='Tensorflow Object Detection Library', <add>)
1
Javascript
Javascript
remove unused uncaughtexception handler
573ec5b0229da2fb6263987f1456595b7bac8b09
<ide><path>test/pseudo-tty/test-tty-stdout-end.js <ide> 'use strict'; <del>const common = require('../common'); <del> <del>process.on('uncaughtException', common.expectsError({ <del> code: 'ERR_STDOUT_CLOSE', <del> type: Error, <del> message: 'process.stdout cannot be closed' <del>})); <add>require('../common'); <ide> <ide> process.stdout.end();
1
Javascript
Javascript
covert the `objectloader` to a "normal" class
6a935682fd6f81795e5fa8d855d5bde49d8ccb5c
<ide><path>src/core/object_loader.js <ide> import { Dict, isStream, Ref, RefSet } from "./primitives.js"; <ide> import { MissingDataException } from "./core_utils.js"; <ide> import { warn } from "../shared/util.js"; <ide> <add>function mayHaveChildren(value) { <add> return ( <add> value instanceof Ref || <add> value instanceof Dict || <add> Array.isArray(value) || <add> isStream(value) <add> ); <add>} <add> <add>function addChildren(node, nodesToVisit) { <add> if (node instanceof Dict) { <add> node = node.getRawValues(); <add> } else if (isStream(node)) { <add> node = node.dict.getRawValues(); <add> } else if (!Array.isArray(node)) { <add> return; <add> } <add> for (const rawValue of node) { <add> if (mayHaveChildren(rawValue)) { <add> nodesToVisit.push(rawValue); <add> } <add> } <add>} <add> <ide> /** <ide> * A helper for loading missing data in `Dict` graphs. It traverses the graph <ide> * depth first and queues up any objects that have missing data. Once it has <ide> import { warn } from "../shared/util.js"; <ide> * that have references to the catalog or other pages since that will cause the <ide> * entire PDF document object graph to be traversed. <ide> */ <del>const ObjectLoader = (function () { <del> function mayHaveChildren(value) { <del> return ( <del> value instanceof Ref || <del> value instanceof Dict || <del> Array.isArray(value) || <del> isStream(value) <del> ); <del> } <del> <del> function addChildren(node, nodesToVisit) { <del> if (node instanceof Dict) { <del> node = node.getRawValues(); <del> } else if (isStream(node)) { <del> node = node.dict.getRawValues(); <del> } else if (!Array.isArray(node)) { <del> return; <del> } <del> for (const rawValue of node) { <del> if (mayHaveChildren(rawValue)) { <del> nodesToVisit.push(rawValue); <del> } <del> } <del> } <del> <del> // eslint-disable-next-line no-shadow <del> function ObjectLoader(dict, keys, xref) { <add>class ObjectLoader { <add> constructor(dict, keys, xref) { <ide> this.dict = dict; <ide> this.keys = keys; <ide> this.xref = xref; <ide> this.refSet = null; <ide> } <ide> <del> ObjectLoader.prototype = { <del> async load() { <del> // Don't walk the graph if all the data is already loaded; note that only <del> // `ChunkedStream` instances have a `allChunksLoaded` method. <del> if ( <del> !this.xref.stream.allChunksLoaded || <del> this.xref.stream.allChunksLoaded() <del> ) { <del> return undefined; <del> } <add> async load() { <add> // Don't walk the graph if all the data is already loaded; note that only <add> // `ChunkedStream` instances have a `allChunksLoaded` method. <add> if ( <add> !this.xref.stream.allChunksLoaded || <add> this.xref.stream.allChunksLoaded() <add> ) { <add> return undefined; <add> } <ide> <del> const { keys, dict } = this; <del> this.refSet = new RefSet(); <del> // Setup the initial nodes to visit. <del> const nodesToVisit = []; <del> for (let i = 0, ii = keys.length; i < ii; i++) { <del> const rawValue = dict.getRaw(keys[i]); <del> // Skip nodes that are guaranteed to be empty. <del> if (rawValue !== undefined) { <del> nodesToVisit.push(rawValue); <del> } <add> const { keys, dict } = this; <add> this.refSet = new RefSet(); <add> // Setup the initial nodes to visit. <add> const nodesToVisit = []; <add> for (let i = 0, ii = keys.length; i < ii; i++) { <add> const rawValue = dict.getRaw(keys[i]); <add> // Skip nodes that are guaranteed to be empty. <add> if (rawValue !== undefined) { <add> nodesToVisit.push(rawValue); <ide> } <del> return this._walk(nodesToVisit); <del> }, <add> } <add> return this._walk(nodesToVisit); <add> } <ide> <del> async _walk(nodesToVisit) { <del> const nodesToRevisit = []; <del> const pendingRequests = []; <del> // DFS walk of the object graph. <del> while (nodesToVisit.length) { <del> let currentNode = nodesToVisit.pop(); <add> async _walk(nodesToVisit) { <add> const nodesToRevisit = []; <add> const pendingRequests = []; <add> // DFS walk of the object graph. <add> while (nodesToVisit.length) { <add> let currentNode = nodesToVisit.pop(); <ide> <del> // Only references or chunked streams can cause missing data exceptions. <del> if (currentNode instanceof Ref) { <del> // Skip nodes that have already been visited. <del> if (this.refSet.has(currentNode)) { <del> continue; <del> } <del> try { <del> this.refSet.put(currentNode); <del> currentNode = this.xref.fetch(currentNode); <del> } catch (ex) { <del> if (!(ex instanceof MissingDataException)) { <del> warn(`ObjectLoader._walk - requesting all data: "${ex}".`); <del> this.refSet = null; <add> // Only references or chunked streams can cause missing data exceptions. <add> if (currentNode instanceof Ref) { <add> // Skip nodes that have already been visited. <add> if (this.refSet.has(currentNode)) { <add> continue; <add> } <add> try { <add> this.refSet.put(currentNode); <add> currentNode = this.xref.fetch(currentNode); <add> } catch (ex) { <add> if (!(ex instanceof MissingDataException)) { <add> warn(`ObjectLoader._walk - requesting all data: "${ex}".`); <add> this.refSet = null; <ide> <del> const { manager } = this.xref.stream; <del> return manager.requestAllChunks(); <del> } <del> nodesToRevisit.push(currentNode); <del> pendingRequests.push({ begin: ex.begin, end: ex.end }); <add> const { manager } = this.xref.stream; <add> return manager.requestAllChunks(); <ide> } <add> nodesToRevisit.push(currentNode); <add> pendingRequests.push({ begin: ex.begin, end: ex.end }); <ide> } <del> if (currentNode && currentNode.getBaseStreams) { <del> const baseStreams = currentNode.getBaseStreams(); <del> let foundMissingData = false; <del> for (let i = 0, ii = baseStreams.length; i < ii; i++) { <del> const stream = baseStreams[i]; <del> if (stream.allChunksLoaded && !stream.allChunksLoaded()) { <del> foundMissingData = true; <del> pendingRequests.push({ begin: stream.start, end: stream.end }); <del> } <del> } <del> if (foundMissingData) { <del> nodesToRevisit.push(currentNode); <add> } <add> if (currentNode && currentNode.getBaseStreams) { <add> const baseStreams = currentNode.getBaseStreams(); <add> let foundMissingData = false; <add> for (let i = 0, ii = baseStreams.length; i < ii; i++) { <add> const stream = baseStreams[i]; <add> if (stream.allChunksLoaded && !stream.allChunksLoaded()) { <add> foundMissingData = true; <add> pendingRequests.push({ begin: stream.start, end: stream.end }); <ide> } <ide> } <del> <del> addChildren(currentNode, nodesToVisit); <add> if (foundMissingData) { <add> nodesToRevisit.push(currentNode); <add> } <ide> } <ide> <del> if (pendingRequests.length) { <del> await this.xref.stream.manager.requestRanges(pendingRequests); <add> addChildren(currentNode, nodesToVisit); <add> } <ide> <del> for (let i = 0, ii = nodesToRevisit.length; i < ii; i++) { <del> const node = nodesToRevisit[i]; <del> // Remove any reference nodes from the current `RefSet` so they <del> // aren't skipped when we revist them. <del> if (node instanceof Ref) { <del> this.refSet.remove(node); <del> } <add> if (pendingRequests.length) { <add> await this.xref.stream.manager.requestRanges(pendingRequests); <add> <add> for (let i = 0, ii = nodesToRevisit.length; i < ii; i++) { <add> const node = nodesToRevisit[i]; <add> // Remove any reference nodes from the current `RefSet` so they <add> // aren't skipped when we revist them. <add> if (node instanceof Ref) { <add> this.refSet.remove(node); <ide> } <del> return this._walk(nodesToRevisit); <ide> } <del> // Everything is loaded. <del> this.refSet = null; <del> return undefined; <del> }, <del> }; <del> <del> return ObjectLoader; <del>})(); <add> return this._walk(nodesToRevisit); <add> } <add> // Everything is loaded. <add> this.refSet = null; <add> return undefined; <add> } <add>} <ide> <ide> export { ObjectLoader };
1
Text
Text
add support details for storage driver
feab8b179e20833dd0a65e58934cf24938da6d84
<ide><path>docs/userguide/storagedriver/selectadriver.md <ide> For example, the `btrfs` storage driver on a Btrfs backing filesystem. The <ide> following table lists each storage driver and whether it must match the host's <ide> backing file system: <ide> <del> |Storage driver |Must match backing filesystem | <del> |---------------|------------------------------| <del> |overlay |No | <del> |aufs |No | <del> |btrfs |Yes | <del> |devicemapper |No | <del> |vfs* |No | <del> |zfs |Yes | <del> <add>|Storage driver |Must match backing filesystem |Incompatible with | <add>|---------------|------------------------------|--------------------| <add>|`overlay` |No |`btrfs` `aufs` `zfs`| <add>|`aufs` |No |`btrfs` `aufs` | <add>|`btrfs` |Yes | N/A | <add>|`devicemapper` |No | N/A | <add>|`vfs` |No | N/A | <add>|`zfs` |Yes | N/A | <add> <add> <add>> **Note** <add>> Incompatible with means some storage drivers can not run over certain backing <add>> filesystem. <ide> <ide> You can set the storage driver by passing the `--storage-driver=<name>` option <ide> to the `docker daemon` command line, or by setting the option on the
1
Ruby
Ruby
fix index method for ruby 1.8
ea167399a293ac0a14d09150e0479ae849f9b2b8
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit <ide> class FormulaText <ide> def initialize path <ide> @text = path.open("rb", &:read) <del> @lines = @text.lines <add> @lines = @text.lines.to_a <ide> end <ide> <ide> def without_patch
1
Ruby
Ruby
raise errors when index creation fails
55d0d57bfc72c0bdbc81ae5d95c99729f16899af
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def add_index(table_name, column_name, options = {}) <ide> end <ide> <ide> if index_name.length > index_name_length <del> @logger.warn("Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters. Skipping.") <del> return <add> raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters" <ide> end <ide> if index_name_exists?(table_name, index_name, false) <del> @logger.warn("Index name '#{index_name}' on table '#{table_name}' already exists. Skipping.") <del> return <add> raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists" <ide> end <ide> quoted_column_names = quoted_columns_for_index(column_names, options).join(", ") <ide>
1
Mixed
Javascript
change default autoskippadding to 3
a026b6065324fe8967de7789b091996a30557ed6
<ide><path>docs/docs/axes/cartesian/_common_ticks.md <ide> Namespace: `options.scales[scaleId].ticks` <ide> | `crossAlign` | `string` | `'near'` | The tick alignment perpendicular to the axis. Can be `'near'`, `'center'`, or `'far'`. See [Tick Alignment](./index#tick-alignment) <ide> | `sampleSize` | `number` | `ticks.length` | The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length. <ide> | `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what. <del>| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. <add>| `autoSkipPadding` | `number` | `3` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. <ide> | `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x-direction for the x-axis, and the y-direction for the y-axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas* <ide> | `maxRotation` | `number` | `50` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.* <ide> | `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.* <ide><path>src/core/core.scale.js <ide> defaults.set('scale', { <ide> padding: 0, <ide> display: true, <ide> autoSkip: true, <del> autoSkipPadding: 0, <add> autoSkipPadding: 3, <ide> labelOffset: 0, <ide> // We pass through arrays to be rendered as multiline labels, we convert Others to strings here. <ide> callback: Ticks.formatters.values, <ide><path>test/specs/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> ticks: { <ide> source: 'data', <ide> autoSkip: true, <add> autoSkipPadding: 0, <ide> maxRotation: 0 <ide> } <ide> },
3
Javascript
Javascript
add react map
6c276338267434406efc812cffb31160b2b964c5
<ide><path>index.js <ide> Observable.combineLatest( <ide> var isComingSoon = !!challengeSpec.isComingSoon; <ide> var fileName = challengeSpec.fileName; <ide> var helpRoom = challengeSpec.helpRoom || 'Help'; <add> var time = challengeSpec.time || 'N/A'; <ide> <ide> console.log('parsed %s successfully', blockName); <ide> <ide> Observable.combineLatest( <ide> dashedName: dasherize(blockName), <ide> superOrder: superOrder, <ide> superBlock: superBlock, <del> order: order <add> order: order, <add> time: time <ide> }; <ide> <ide> return createBlocks(block)
1
PHP
PHP
fix consoleoutput styles() api
20952468597f99746bd39fbdac14df60a75d20fa
<ide><path>src/Console/ConsoleIo.php <ide> public function setOutputAs(int $mode): void <ide> } <ide> <ide> /** <add> * Gets defined styles. <add> * <ide> * @return array <ide> * @see \Cake\Console\ConsoleOutput::styles() <ide> */ <ide> public function styles(): array <ide> } <ide> <ide> /** <del> * Get defined styles. <add> * Get defined style. <ide> * <ide> * @param string $style <ide> * @return array <ide> public function getStyle(string $style): array <ide> } <ide> <ide> /** <del> * Add a new output style or <add> * Adds a new output style. <ide> * <del> * @param string|null $style The style to get or create. <del> * @param array|false|null $definition The array definition of the style to change or create a style <del> * or false to remove a style. <add> * @param string $style The style to set. <add> * @param array $definition The array definition of the style to change or create. <ide> * @return void <ide> * @see \Cake\Console\ConsoleOutput::setStyle() <ide> */ <ide><path>src/Console/ConsoleOutput.php <ide> public function getStyle(string $style): array <ide> * $this->output->setStyle('annoy', []); <ide> * ``` <ide> * <del> * @param string $style The style to get or create. <add> * @param string $style The style to set. <ide> * @param array $definition The array definition of the style to change or create.. <ide> * @return void <ide> */
2
Javascript
Javascript
replace common.fixtiresdir with fixtures.readkey()
fa8aee8c598aa3dcc0cc35a11231502d31af5b38
<ide><path>test/parallel/test-tls-js-stream.js <ide> 'use strict'; <ide> const common = require('../common'); <add> <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <add>const fixtures = require('../common/fixtures'); <add> <ide> const assert = require('assert'); <del>const tls = require('tls'); <del>const stream = require('stream'); <del>const fs = require('fs'); <ide> const net = require('net'); <add>const stream = require('stream'); <add>const tls = require('tls'); <ide> <ide> const connected = { <ide> client: 0, <ide> server: 0 <ide> }; <ide> <ide> const server = tls.createServer({ <del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`) <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem') <ide> }, function(c) { <ide> console.log('new client'); <ide> connected.server++;
1
PHP
PHP
fix failing test
81208d1fa71f10865a7742d5d3bf46badb298f13
<ide><path>lib/Cake/Test/Case/View/HelperTest.php <ide> class HelperTest extends CakeTestCase { <ide> * @return void <ide> */ <ide> public function setUp() { <add> parent::setUp(); <add> <ide> ClassRegistry::flush(); <ide> Router::reload(); <ide> $null = null; <ide> public function setUp() { <ide> * @return void <ide> */ <ide> public function tearDown() { <add> parent::tearDown(); <add> Configure::delete('Asset'); <add> <ide> CakePlugin::unload(); <ide> unset($this->Helper, $this->View); <del> ClassRegistry::flush(); <ide> } <ide> <ide> /** <ide> public function testUrlConversion() { <ide> * @return void <ide> */ <ide> public function testAssetTimestamp() { <del> $_timestamp = Configure::read('Asset.timestamp'); <del> $_debug = Configure::read('debug'); <del> <add> Configure::write('Foo.bar', 'test'); <ide> Configure::write('Asset.timestamp', false); <ide> $result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css'); <ide> $this->assertEquals(CSS_URL . 'cake.generic.css', $result); <ide> public function testAssetTimestamp() { <ide> $this->Helper->request->webroot = '/some/dir/'; <ide> $result = $this->Helper->assetTimestamp('/some/dir/' . CSS_URL . 'cake.generic.css'); <ide> $this->assertRegExp('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result); <del> <del> Configure::write('debug', $_debug); <del> Configure::write('Asset.timestamp', $_timestamp); <ide> } <ide> <ide> /** <ide> public function testAssetTimestamp() { <ide> */ <ide> public function testAssetUrl() { <ide> $this->Helper->webroot = ''; <del> $_timestamp = Configure::read('Asset.timestamp'); <del> <ide> $result = $this->Helper->assetUrl(array( <ide> 'controller' => 'js', <ide> 'action' => 'post', <ide> public function testAssetUrlTimestampForce() { <ide> * @return void <ide> */ <ide> public function testAssetTimestampPluginsAndThemes() { <del> $timestamp = Configure::read('Asset.timestamp'); <ide> Configure::write('Asset.timestamp', 'force'); <ide> App::build(array( <ide> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), <ide> public function testAssetTimestampPluginsAndThemes() { <ide> <ide> $result = $this->Helper->assetTimestamp('/theme/test_theme/js/non_existant.js'); <ide> $this->assertRegExp('#/theme/test_theme/js/non_existant.js\?$#', $result, 'No error on missing file'); <del> <del> App::build(); <del> Configure::write('Asset.timestamp', $timestamp); <ide> } <ide> <ide> /**
1
Go
Go
fix fd leak on attach
0f5147701775a6c5d4980a7b7c0ed2e830688034
<ide><path>container/stream/attach.go <ide> package stream // import "github.com/docker/docker/container/stream" <ide> import ( <ide> "context" <ide> "io" <del> "sync" <ide> <ide> "github.com/docker/docker/pkg/pools" <ide> "github.com/docker/docker/pkg/term" <add> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <add> "golang.org/x/sync/errgroup" <ide> ) <ide> <ide> var defaultEscapeSequence = []byte{16, 17} // ctrl-p, ctrl-q <ide> func (c *Config) AttachStreams(cfg *AttachConfig) { <ide> <ide> // CopyStreams starts goroutines to copy data in and out to/from the container <ide> func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) <-chan error { <del> var ( <del> wg sync.WaitGroup <del> errors = make(chan error, 3) <del> ) <add> var group errgroup.Group <ide> <add> // Connect stdin of container to the attach stdin stream. <ide> if cfg.Stdin != nil { <del> wg.Add(1) <del> } <del> <del> if cfg.Stdout != nil { <del> wg.Add(1) <del> } <del> <del> if cfg.Stderr != nil { <del> wg.Add(1) <del> } <add> group.Go(func() error { <add> logrus.Debug("attach: stdin: begin") <add> defer logrus.Debug("attach: stdin: end") <ide> <del> // Connect stdin of container to the attach stdin stream. <del> go func() { <del> if cfg.Stdin == nil { <del> return <del> } <del> logrus.Debug("attach: stdin: begin") <add> defer func() { <add> if cfg.CloseStdin && !cfg.TTY { <add> cfg.CStdin.Close() <add> } else { <add> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <add> if cfg.CStdout != nil { <add> cfg.CStdout.Close() <add> } <add> if cfg.CStderr != nil { <add> cfg.CStderr.Close() <add> } <add> } <add> }() <ide> <del> var err error <del> if cfg.TTY { <del> _, err = copyEscapable(cfg.CStdin, cfg.Stdin, cfg.DetachKeys) <del> } else { <del> _, err = pools.Copy(cfg.CStdin, cfg.Stdin) <del> } <del> if err == io.ErrClosedPipe { <del> err = nil <del> } <del> if err != nil { <del> logrus.Errorf("attach: stdin: %s", err) <del> errors <- err <del> } <del> if cfg.CloseStdin && !cfg.TTY { <del> cfg.CStdin.Close() <del> } else { <del> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <del> if cfg.CStdout != nil { <del> cfg.CStdout.Close() <add> var err error <add> if cfg.TTY { <add> _, err = copyEscapable(cfg.CStdin, cfg.Stdin, cfg.DetachKeys) <add> } else { <add> _, err = pools.Copy(cfg.CStdin, cfg.Stdin) <ide> } <del> if cfg.CStderr != nil { <del> cfg.CStderr.Close() <add> if err == io.ErrClosedPipe { <add> err = nil <ide> } <del> } <del> logrus.Debug("attach: stdin: end") <del> wg.Done() <del> }() <del> <del> attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) { <del> if stream == nil { <del> return <del> } <add> if err != nil { <add> logrus.WithError(err).Debug("error on attach stdin") <add> return errors.Wrap(err, "error on attach stdin") <add> } <add> return nil <add> }) <add> } <ide> <add> attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) error { <ide> logrus.Debugf("attach: %s: begin", name) <add> defer logrus.Debugf("attach: %s: end", name) <add> defer func() { <add> // Make sure stdin gets closed <add> if cfg.Stdin != nil { <add> cfg.Stdin.Close() <add> } <add> streamPipe.Close() <add> }() <add> <ide> _, err := pools.Copy(stream, streamPipe) <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> } <ide> if err != nil { <del> logrus.Errorf("attach: %s: %v", name, err) <del> errors <- err <del> } <del> // Make sure stdin gets closed <del> if cfg.Stdin != nil { <del> cfg.Stdin.Close() <add> logrus.WithError(err).Debugf("attach: %s", name) <add> return errors.Wrapf(err, "error attaching %s stream", name) <ide> } <del> streamPipe.Close() <del> logrus.Debugf("attach: %s: end", name) <del> wg.Done() <add> return nil <ide> } <ide> <del> go attachStream("stdout", cfg.Stdout, cfg.CStdout) <del> go attachStream("stderr", cfg.Stderr, cfg.CStderr) <add> if cfg.Stdout != nil { <add> group.Go(func() error { <add> return attachStream("stdout", cfg.Stdout, cfg.CStdout) <add> }) <add> } <add> if cfg.Stderr != nil { <add> group.Go(func() error { <add> return attachStream("stderr", cfg.Stderr, cfg.CStderr) <add> }) <add> } <ide> <ide> errs := make(chan error, 1) <del> <ide> go func() { <del> defer close(errs) <del> errs <- func() error { <del> done := make(chan struct{}) <del> go func() { <del> wg.Wait() <del> close(done) <del> }() <del> select { <del> case <-done: <del> case <-ctx.Done(): <del> // close all pipes <del> if cfg.CStdin != nil { <del> cfg.CStdin.Close() <del> } <del> if cfg.CStdout != nil { <del> cfg.CStdout.Close() <del> } <del> if cfg.CStderr != nil { <del> cfg.CStderr.Close() <del> } <del> <-done <add> defer logrus.Debug("attach done") <add> groupErr := make(chan error, 1) <add> go func() { <add> groupErr <- group.Wait() <add> }() <add> select { <add> case <-ctx.Done(): <add> // close all pipes <add> if cfg.CStdin != nil { <add> cfg.CStdin.Close() <ide> } <del> close(errors) <del> for err := range errors { <del> if err != nil { <del> return err <del> } <add> if cfg.CStdout != nil { <add> cfg.CStdout.Close() <ide> } <del> return nil <del> }() <add> if cfg.CStderr != nil { <add> cfg.CStderr.Close() <add> } <add> <add> // Now with these closed, wait should return. <add> if err := group.Wait(); err != nil { <add> errs <- err <add> return <add> } <add> errs <- ctx.Err() <add> case err := <-groupErr: <add> errs <- err <add> } <ide> }() <ide> <ide> return errs <ide><path>daemon/attach.go <ide> func (daemon *Daemon) containerAttach(c *container.Container, cfg *stream.Attach <ide> ctx := c.InitAttachContext() <ide> err := <-c.StreamConfig.CopyStreams(ctx, cfg) <ide> if err != nil { <del> if _, ok := err.(term.EscapeError); ok { <add> if _, ok := errors.Cause(err).(term.EscapeError); ok || err == context.Canceled { <ide> daemon.LogContainerEvent(c, "detach") <ide> } else { <ide> logrus.Errorf("attach failed with error: %v", err)
2
Ruby
Ruby
use `def before_setup` instead of `setup do`
76836ef7db8d0b1e40492c9a62f7c637718d813d
<ide><path>railties/lib/rails/test_help.rb <ide> def create_fixtures(*fixture_set_names, &block) <ide> end <ide> <ide> class ActionController::TestCase <del> setup do <add> def before_setup <ide> @routes = Rails.application.routes <add> super <ide> end <ide> end <ide> <ide> class ActionDispatch::IntegrationTest <del> setup do <add> def before_setup <ide> @routes = Rails.application.routes <add> super <ide> end <ide> end
1
Ruby
Ruby
avoid unnecessary downloads in `audit`
e5d656bcce8b68bb11d4bd7a6f2160e6b7ba2bc7
<ide><path>Library/Homebrew/utils/curl.rb <ide> def url_protected_by_incapsula?(details) <ide> def curl_check_http_content(url, user_agents: [:default], check_content: false, strict: false) <ide> return unless url.start_with? "http" <ide> <add> secure_url = url.sub(/\Ahttp:/, "https:") <add> secure_details = nil <add> hash_needed = false <add> if url != secure_url <add> user_agents.each do |user_agent| <add> secure_details = <add> curl_http_content_headers_and_checksum(secure_url, hash_needed: true, user_agent: user_agent) <add> <add> next unless http_status_ok?(secure_details[:status]) <add> <add> hash_needed = true <add> user_agents = [user_agent] <add> break <add> end <add> end <add> <ide> details = nil <del> user_agent = nil <del> hash_needed = url.start_with?("http:") <del> user_agents.each do |ua| <del> details = curl_http_content_headers_and_checksum(url, hash_needed: hash_needed, user_agent: ua) <del> user_agent = ua <add> user_agents.each do |user_agent| <add> details = curl_http_content_headers_and_checksum(url, hash_needed: hash_needed, user_agent: user_agent) <ide> break if http_status_ok?(details[:status]) <ide> end <ide> <ide> def curl_check_http_content(url, user_agents: [:default], check_content: false, <ide> return "The URL #{url} redirects back to HTTP" <ide> end <ide> <del> return unless hash_needed <del> <del> secure_url = url.sub "http", "https" <del> secure_details = <del> curl_http_content_headers_and_checksum(secure_url, hash_needed: true, user_agent: user_agent) <add> return unless secure_details <ide> <del> if !http_status_ok?(details[:status]) || <del> !http_status_ok?(secure_details[:status]) <del> return <del> end <add> return if !http_status_ok?(details[:status]) || !http_status_ok?(secure_details[:status]) <ide> <ide> etag_match = details[:etag] && <ide> details[:etag] == secure_details[:etag] <ide> def curl_check_http_content(url, user_agents: [:default], check_content: false, <ide> return unless check_content <ide> <ide> no_protocol_file_contents = %r{https?:\\?/\\?/} <del> details[:file] = details[:file].gsub(no_protocol_file_contents, "/") <del> secure_details[:file] = secure_details[:file].gsub(no_protocol_file_contents, "/") <add> http_content = details[:file]&.gsub(no_protocol_file_contents, "/") <add> https_content = secure_details[:file]&.gsub(no_protocol_file_contents, "/") <ide> <ide> # Check for the same content after removing all protocols <del> if (details[:file] == secure_details[:file]) && <del> secure_details[:final_url].start_with?("https://") && <del> url.start_with?("http://") <add> if (http_content && https_content) && (http_content == https_content) && <add> url.start_with?("http://") && secure_details[:final_url].start_with?("https://") <ide> return "The URL #{url} should use HTTPS rather than HTTP" <ide> end <ide> <ide> return unless strict <ide> <ide> # Same size, different content after normalization <ide> # (typical causes: Generated ID, Timestamp, Unix time) <del> if details[:file].length == secure_details[:file].length <add> if http_content.length == https_content.length <ide> return "The URL #{url} may be able to use HTTPS rather than HTTP. Please verify it in a browser." <ide> end <ide> <del> lenratio = (100 * secure_details[:file].length / details[:file].length).to_i <add> lenratio = (100 * https_content.length / http_content.length).to_i <ide> return unless (90..110).cover?(lenratio) <ide> <ide> "The URL #{url} may be able to use HTTPS rather than HTTP. Please verify it in a browser." <ide> def curl_http_content_headers_and_checksum(url, hash_needed: false, user_agent: <ide> file = Tempfile.new.tap(&:close) <ide> <ide> max_time = hash_needed ? "600" : "25" <del> output, = curl_output( <add> output, _, status = curl_output( <ide> "--dump-header", "-", "--output", file.path, "--location", <del> "--connect-timeout", "15", "--max-time", max_time, url, <add> "--connect-timeout", "15", "--max-time", max_time, "--retry-max-time", max_time, url, <ide> user_agent: user_agent <ide> ) <ide> <ide> def curl_http_content_headers_and_checksum(url, hash_needed: false, user_agent: <ide> final_url = location.chomp if location <ide> end <ide> <del> file_hash = Digest::SHA256.file(file.path) if hash_needed <add> if status.success? <add> file_contents = File.read(file.path) <add> file_hash = Digest::SHA2.hexdigest(file_contents) if hash_needed <add> end <ide> <ide> final_url ||= url <ide> <ide> def curl_http_content_headers_and_checksum(url, hash_needed: false, user_agent: <ide> content_length: headers[/Content-Length: (\d+)/, 1], <ide> headers: headers, <ide> file_hash: file_hash, <del> file: File.read(file.path), <add> file: file_contents, <ide> } <ide> ensure <ide> file.unlink
1
Ruby
Ruby
use assignment instead of call
6720efb8e33bb45d502cafc4d84da1ff9a5b5eeb
<ide><path>activerecord/lib/active_record/observer.rb <ide> module ClassMethods <ide> # # Same as above, just using explicit class references <ide> # ActiveRecord::Base.observers = Cacher, GarbageCollector <ide> def observers=(*observers) <del> observers = [ observers ].flatten.collect do |observer| <add> observers = [ observers ].flatten.each do |observer| <ide> observer.is_a?(Symbol) ? <ide> observer.to_s.camelize.constantize.instance : <ide> observer.instance <ide> end <del> <del> observers.size > 1 ? observers : observers.first <ide> end <ide> end <ide> end
1
Ruby
Ruby
add test for hash visitor
12ff6e13498a1990af58d5bff30dbf44095348e6
<ide><path>spec/arel/visitors/to_sql_spec.rb <ide> module Visitors <ide> @visitor.accept 2.14 <ide> end <ide> <add> it "should visit_Hash" do <add> @visitor.accept({:a => 1}) <add> end <add> <ide> it "should visit_BigDecimal" do <ide> @visitor.accept BigDecimal.new('2.14') <ide> end
1
Python
Python
accept doc input in pipelines
2f0bb7792081f9f0ab8caddaddf305244d7775d5
<ide><path>spacy/errors.py <ide> class Errors: <ide> E202 = ("Unsupported alignment mode '{mode}'. Supported modes: {modes}.") <ide> <ide> # New errors added in v3.x <add> E866 = ("Expected a string or 'Doc' as input, but got: {type}.") <ide> E867 = ("The 'textcat' component requires at least two labels because it " <ide> "uses mutually exclusive classes where exactly one label is True " <ide> "for each doc. For binary classification tasks, you can use two " <ide><path>spacy/language.py <ide> def enable_pipe(self, name: str) -> None: <ide> <ide> def __call__( <ide> self, <del> text: str, <add> text: Union[str, Doc], <ide> *, <ide> disable: Iterable[str] = SimpleFrozenList(), <ide> component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, <ide> def __call__( <ide> and can contain arbitrary whitespace. Alignment into the original string <ide> is preserved. <ide> <del> text (str): The text to be processed. <add> text (Union[str, Doc]): If `str`, the text to be processed. If `Doc`, <add> the doc will be passed directly to the pipeline, skipping <add> `Language.make_doc`. <ide> disable (list): Names of the pipeline components to disable. <ide> component_cfg (Dict[str, dict]): An optional dictionary with extra <ide> keyword arguments for specific components. <ide> RETURNS (Doc): A container for accessing the annotations. <ide> <ide> DOCS: https://spacy.io/api/language#call <ide> """ <del> doc = self.make_doc(text) <add> doc = self._ensure_doc(text) <ide> if component_cfg is None: <ide> component_cfg = {} <ide> for name, proc in self.pipeline: <ide> def make_doc(self, text: str) -> Doc: <ide> ) <ide> return self.tokenizer(text) <ide> <add> def _ensure_doc(self, doc_like: Union[str, Doc]) -> Doc: <add> """Create a Doc if need be, or raise an error if the input is not a Doc or a string.""" <add> if isinstance(doc_like, Doc): <add> return doc_like <add> if isinstance(doc_like, str): <add> return self.make_doc(doc_like) <add> raise ValueError(Errors.E866.format(type=type(doc_like))) <add> <ide> def update( <ide> self, <ide> examples: Iterable[Example], <ide> def use_params(self, params: Optional[dict]): <ide> @overload <ide> def pipe( <ide> self, <del> texts: Iterable[Tuple[str, _AnyContext]], <add> texts: Iterable[Tuple[Union[str, Doc], _AnyContext]], <ide> *, <ide> as_tuples: bool = ..., <ide> batch_size: Optional[int] = ..., <ide> def pipe( <ide> <ide> def pipe( # noqa: F811 <ide> self, <del> texts: Iterable[str], <add> texts: Iterable[Union[str, Doc]], <ide> *, <ide> as_tuples: bool = False, <ide> batch_size: Optional[int] = None, <ide> def pipe( # noqa: F811 <ide> ) -> Iterator[Doc]: <ide> """Process texts as a stream, and yield `Doc` objects in order. <ide> <del> texts (Iterable[str]): A sequence of texts to process. <add> texts (Iterable[Union[str, Doc]]): A sequence of texts or docs to <add> process. <ide> as_tuples (bool): If set to True, inputs should be a sequence of <ide> (text, context) tuples. Output will then be a sequence of <ide> (doc, context) tuples. Defaults to False. <ide> def pipe( # noqa: F811 <ide> docs = self._multiprocessing_pipe(texts, pipes, n_process, batch_size) <ide> else: <ide> # if n_process == 1, no processes are forked. <del> docs = (self.make_doc(text) for text in texts) <add> docs = (self._ensure_doc(text) for text in texts) <ide> for pipe in pipes: <ide> docs = pipe(docs) <ide> for doc in docs: <ide> def _multiprocessing_pipe( <ide> procs = [ <ide> mp.Process( <ide> target=_apply_pipes, <del> args=(self.make_doc, pipes, rch, sch, Underscore.get_state()), <add> args=(self._ensure_doc, pipes, rch, sch, Underscore.get_state()), <ide> ) <ide> for rch, sch in zip(texts_q, bytedocs_send_ch) <ide> ] <ide> def _copy_examples(examples: Iterable[Example]) -> List[Example]: <ide> <ide> <ide> def _apply_pipes( <del> make_doc: Callable[[str], Doc], <add> ensure_doc: Callable[[Union[str, Doc]], Doc], <ide> pipes: Iterable[Callable[[Doc], Doc]], <ide> receiver, <ide> sender, <ide> underscore_state: Tuple[dict, dict, dict], <ide> ) -> None: <ide> """Worker for Language.pipe <ide> <del> make_doc (Callable[[str,] Doc]): Function to create Doc from text. <add> ensure_doc (Callable[[Union[str, Doc]], Doc]): Function to create Doc from text <add> or raise an error if the input is neither a Doc nor a string. <ide> pipes (Iterable[Callable[[Doc], Doc]]): The components to apply. <ide> receiver (multiprocessing.Connection): Pipe to receive text. Usually <ide> created by `multiprocessing.Pipe()` <ide> def _apply_pipes( <ide> while True: <ide> try: <ide> texts = receiver.get() <del> docs = (make_doc(text) for text in texts) <add> docs = (ensure_doc(text) for text in texts) <ide> for pipe in pipes: <ide> docs = pipe(docs) <ide> # Connection does not accept unpickable objects, so send list. <ide><path>spacy/tests/test_language.py <ide> def test_language_source_and_vectors(nlp2): <ide> assert long_string in nlp2.vocab.strings <ide> # vectors should remain unmodified <ide> assert nlp.vocab.vectors.to_bytes() == vectors_bytes <add> <add> <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_pass_doc_to_pipeline(nlp, n_process): <add> texts = ["cats", "dogs", "guinea pigs"] <add> docs = [nlp.make_doc(text) for text in texts] <add> assert not any(len(doc.cats) for doc in docs) <add> doc = nlp(docs[0]) <add> assert doc.text == texts[0] <add> assert len(doc.cats) > 0 <add> if isinstance(get_current_ops(), NumpyOps) or n_process < 2: <add> docs = nlp.pipe(docs, n_process=n_process) <add> assert [doc.text for doc in docs] == texts <add> assert all(len(doc.cats) for doc in docs) <add> <add> <add>def test_invalid_arg_to_pipeline(nlp): <add> str_list = ["This is a text.", "This is another."] <add> with pytest.raises(ValueError): <add> nlp(str_list) # type: ignore <add> assert len(list(nlp.pipe(str_list))) == 2 <add> int_list = [1, 2, 3] <add> with pytest.raises(ValueError): <add> list(nlp.pipe(int_list)) # type: ignore <add> with pytest.raises(ValueError): <add> nlp(int_list) # type: ignore
3
Go
Go
remove outdated "experimental" annotation
90f19fc375562eeb8c8db9a453559dbcfe353cb6
<ide><path>cmd/dockerd/config_unix.go <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "Default address pools for node specific local networks") <ide> // rootless needs to be explicitly specified for running "rootful" dockerd in rootless dockerd (#38702) <ide> // Note that defaultUserlandProxyPath and honorXDG are configured according to the value of rootless.RunningWithRootlessKit, not the value of --rootless. <del> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithRootlessKit(), "Enable rootless mode; typically used with RootlessKit (experimental)") <add> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithRootlessKit(), "Enable rootless mode; typically used with RootlessKit") <ide> defaultCgroupNamespaceMode := "host" <ide> if cgroups.IsCgroup2UnifiedMode() { <ide> defaultCgroupNamespaceMode = "private"
1
Go
Go
fix timeout issue of `inspectnetwork` on aarch64
8f5c1841a8bffb4a7e33f51174177b7ad0182969
<ide><path>integration/network/inspect_test.go <ide> func TestInspectNetwork(t *testing.T) { <ide> require.NoError(t, err) <ide> <ide> pollSettings := func(config *poll.Settings) { <del> if runtime.GOARCH == "arm" { <add> if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" { <ide> config.Timeout = 30 * time.Second <ide> config.Delay = 100 * time.Millisecond <ide> }
1
PHP
PHP
fix failing code in paginatorcomponent
20e9fd2c9729df350a516bc5995877707b01e173
<ide><path>Cake/Controller/Component/PaginatorComponent.php <ide> public function paginate($object, array $settings = []) { <ide> $parameters = compact('conditions', 'fields', 'order', 'limit', 'page'); <ide> $query = $object->find($type, array_merge($parameters, $extra)); <ide> <del> $results = $query->execute(); <add> $results = $query->all(); <ide> $numResults = count($results); <ide> <ide> $defaults = $this->getDefaults($alias, $settings); <ide><path>Cake/Test/TestCase/Controller/Component/PaginatorComponentTest.php <ide> protected function _getMockPosts($methods = []) { <ide> * @return Query <ide> */ <ide> protected function _getMockFindQuery() { <del> $query = $this->getMock('Cake\ORM\Query', ['total', 'execute'], [], '', false); <add> $query = $this->getMock('Cake\ORM\Query', ['total', 'all'], [], '', false); <ide> <ide> $results = $this->getMock('Cake\ORM\ResultSet', [], [], '', false); <ide> $results->expects($this->any()) <ide> ->method('count') <ide> ->will($this->returnValue(2)); <ide> <ide> $query->expects($this->any()) <del> ->method('execute') <add> ->method('all') <ide> ->will($this->returnValue($results)); <ide> <ide> $query->expects($this->any())
2
Ruby
Ruby
make debug an installer mode
ce5e2aa65ccd8ef129fb879d8bdcdacf78122c0b
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install_formula f <ide> fi.interactive &&= :git if ARGV.flag? "--git" <ide> fi.verbose = ARGV.verbose? <ide> fi.verbose &&= :quieter if ARGV.quieter? <add> fi.debug = ARGV.debug? <ide> fi.prelude <ide> fi.install <ide> fi.caveats <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade_formula f <ide> installer.build_from_source = ARGV.build_from_source? <ide> installer.verbose = ARGV.verbose? <ide> installer.verbose &&= :quieter if ARGV.quieter? <add> installer.debug = ARGV.debug? <ide> installer.prelude <ide> <ide> oh1 "Upgrading #{f.name}" <ide><path>Library/Homebrew/extend/ARGV.rb <ide> def filter_for_dependencies <ide> old_args = clone <ide> <ide> flags_to_clear = %w[ <del> --debug -d <ide> --devel <ide> --HEAD <ide> ] <ide><path>Library/Homebrew/formula_installer.rb <ide> def self.mode_attr_accessor(*names) <ide> mode_attr_accessor :show_summary_heading, :show_header <ide> mode_attr_accessor :build_from_source, :build_bottle, :force_bottle <ide> mode_attr_accessor :ignore_deps, :only_deps, :interactive <del> mode_attr_accessor :verbose <add> mode_attr_accessor :verbose, :debug <ide> <ide> def initialize ff <ide> @f = ff <ide> def initialize ff <ide> @force_bottle = false <ide> @interactive = false <ide> @verbose = false <add> @debug = false <ide> @options = Options.new <ide> <ide> @@attempted ||= Set.new <ide> def install <ide> # HACK: If readline is present in the dependency tree, it will clash <ide> # with the stdlib's Readline module when the debugger is loaded <ide> def perform_readline_hack <del> if f.recursive_dependencies.any? { |d| d.name == "readline" } && ARGV.debug? <add> if f.recursive_dependencies.any? { |d| d.name == "readline" } && debug? <ide> ENV['HOMEBREW_NO_READLINE'] = '1' <ide> end <ide> end <ide> def install_dependency(dep, inherited_options) <ide> fi.ignore_deps = true <ide> fi.build_from_source = build_from_source? <ide> fi.verbose = verbose? unless verbose == :quieter <add> fi.debug = debug? <ide> fi.prelude <ide> oh1 "Installing #{f} dependency: #{Tty.green}#{dep.name}#{Tty.reset}" <ide> outdated_keg.unlink if outdated_keg <ide> def sanitized_ARGV_options <ide> end <ide> <ide> args << "--verbose" if verbose? <del> args << "--debug" if ARGV.debug? <add> args << "--debug" if debug? <ide> args << "--cc=#{ARGV.cc}" if ARGV.cc <ide> args << "--env=#{ARGV.env}" if ARGV.env <ide> args << "--HEAD" if ARGV.build_head? <ide> def link <ide> puts "Possible conflicting files are:" <ide> mode = OpenStruct.new(:dry_run => true, :overwrite => true) <ide> keg.link(mode) <del> ohai e, e.backtrace if ARGV.debug? <add> ohai e, e.backtrace if debug? <ide> @show_summary_heading = true <ide> ignore_interrupts{ keg.unlink } <ide> raise unless e.kind_of? RuntimeError <ide> def fix_install_names <ide> onoe "Failed to fix install names" <ide> puts "The formula built, but you may encounter issues using it or linking other" <ide> puts "formula against it." <del> ohai e, e.backtrace if ARGV.debug? <add> ohai e, e.backtrace if debug? <ide> @show_summary_heading = true <ide> end <ide> <ide> def clean <ide> rescue Exception => e <ide> opoo "The cleaning step did not complete successfully" <ide> puts "Still, the installation was successful, so we will link it into your prefix" <del> ohai e, e.backtrace if ARGV.debug? <add> ohai e, e.backtrace if debug? <ide> @show_summary_heading = true <ide> end <ide> <ide> def post_install <ide> rescue Exception => e <ide> opoo "The post-install step did not complete successfully" <ide> puts "You can try again using `brew postinstall #{f.name}`" <del> ohai e, e.backtrace if ARGV.debug? <add> ohai e, e.backtrace if debug? <ide> @show_summary_heading = true <ide> end <ide> <ide><path>Library/Homebrew/test/test_ARGV.rb <ide> def test_flag? <ide> end <ide> <ide> def test_filter_for_dependencies_clears_flags <del> @argv << "--debug" <add> @argv << "--HEAD" << "--devel" <ide> @argv.filter_for_dependencies { assert @argv.empty? } <ide> end <ide>
5
PHP
PHP
apply fixes from styleci
64f11a3412d37b00f2bdbc2d3dda1d35cb9fccb5
<ide><path>src/Illuminate/Validation/Rules/In.php <ide> class In <ide> { <ide> /** <ide> * The name of the rule. <del> * <add> * <ide> * @var string <ide> */ <ide> protected $rule = 'in';
1
Go
Go
fix flakey logssincefuturefollow
acaef7caaf6078719d8e838efad0fb1b7ce153d8
<ide><path>integration-cli/docker_cli_logs_test.go <ide> func (s *DockerSuite) TestLogsSince(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) { <add> // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now. <add> testRequires(c, DaemonIsLinux) <ide> name := "testlogssincefuturefollow" <ide> out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`) <ide>
1
PHP
PHP
fix bus fake
e72027960fd4d8ff281938edb4632e13e391b8fd
<ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php <ide> public function assertChained(array $expectedChain) <ide> if ($command instanceof Closure) { <ide> [$command, $callback] = [$this->firstClosureParameterType($command), $command]; <ide> } elseif (! is_string($command)) { <del> $command = get_class($command); <add> $instance = $command; <add> <add> $command = get_class($instance); <add> <add> $callback = function ($job) use ($instance) { <add> return serialize($this->resetChainPropertiesToDefaults($job)) === serialize($instance); <add> }; <ide> } <ide> <ide> PHPUnit::assertTrue( <ide> public function assertChained(array $expectedChain) <ide> : $this->assertDispatchedWithChainOfClasses($command, $expectedChain, $callback); <ide> } <ide> <add> /** <add> * Reset the chain properties to their default values on the job. <add> * <add> * @param mixed $job <add> * @return mixed <add> */ <add> protected function resetChainPropertiesToDefaults($job) <add> { <add> return tap(clone $job, function ($job) { <add> $job->chainConnection = null; <add> $job->chainQueue = null; <add> $job->chainCatchCallbacks = null; <add> $job->chained = []; <add> }); <add> } <add> <ide> /** <ide> * Assert if a job was dispatched with an empty chain based on a truth-test callback. <ide> *
1
Text
Text
add attribute selector to the list of selectors
a78b7b4ac2ff54998137abc7eb13c8008cd9cd55
<ide><path>guide/english/jquery/jquery-selectors/index.md <ide> As with the class selector, this can also be used in combination with a tag name <ide> $("h1#headline").css("font-size", "2em"); <ide> ``` <ide> <add>### Selecting by attribute value <add>If you want to select elements with a certain attribute, use ([attributeName="value"]). <add>```html <add><input name="myInput" /> <add>``` <add>```javascript <add>$("[name='myInput']").value("Test"); // sets input value to "Test" <add>``` <add> <add>You can also use the attribute selector in combination with a tag name to be more specific. <add>```html <add><input name="myElement" />`<br> <add><button name="myElement">Button</button> <add>``` <add>```javascript <add>$("input[name='myElement']").remove(); // removes the input field not the button <add>``` <add> <ide> ### Selectors that act as filters <ide> There are also selectors that act as filters - they will usually start with colons. For example, the `:first` selector selects the element that is the first child of its parent. Here's an example of an unordered list with some list items. The jQuery selector below the list selects the first `<li>` element in the list--the "One" list item--and then uses the `.css` method to turn the text green. <ide>
1
Java
Java
fix typos in responseentity javadoc
6bc7e12bcd317cabdc5ec818976da6d98cddeacc
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseEntity.java <ide> <ide> /** <ide> * Extension of {@link HttpEntity} that adds a {@link HttpStatus} status code. <del> * Used in {@code RestTemplate} as well {@code @Controller} methods. <add> * Used in {@code RestTemplate} as well as {@code @Controller} methods. <ide> * <ide> * <p>In {@code RestTemplate}, this class is returned by <ide> * {@link org.springframework.web.client.RestTemplate#getForEntity getForEntity()} and <ide> * HttpStatus statusCode = entity.getStatusCode(); <ide> * </pre> <ide> * <del> * <p>Can also be used in Spring MVC, as the return value from a @Controller method: <add> * <p>This can also be used in Spring MVC as the return value from a @Controller method: <ide> * <pre class="code"> <ide> * &#64;RequestMapping("/handle") <ide> * public ResponseEntity&lt;String&gt; handle() { <ide> <ide> <ide> /** <del> * Create a new {@code ResponseEntity} with the given status code, and no body nor headers. <add> * Create a new {@code ResponseEntity} with the given status code, but no body or headers. <ide> * @param status the status code <ide> */ <ide> public ResponseEntity(HttpStatus status) { <ide> this(null, null, status); <ide> } <ide> <ide> /** <del> * Create a new {@code ResponseEntity} with the given body and status code, and no headers. <add> * Create a new {@code ResponseEntity} with the given body and status code, but no headers. <ide> * @param body the entity body <ide> * @param status the status code <ide> */ <ide> public ResponseEntity(@Nullable T body, HttpStatus status) { <ide> } <ide> <ide> /** <del> * Create a new {@code HttpEntity} with the given headers and status code, and no body. <add> * Create a new {@code HttpEntity} with the given headers and status code, but no body. <ide> * @param headers the entity headers <ide> * @param status the status code <ide> */
1
Ruby
Ruby
remove outdated docs
c9317a2325d3592673daa72e2c52109fdf1d90b1
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> module Base <ide> # <ide> # For options, see +match+, as +root+ uses it internally. <ide> # <del> # You can also pass a string which will expand <del> # <del> # root 'pages#main' <del> # <ide> # You should put the root route at the top of <tt>config/routes.rb</tt>, <ide> # because this means it will be matched first. As this is the most popular route <ide> # of most Rails applications, this is beneficial.
1
Ruby
Ruby
use our own popen implementation in formula.system
22afc5e1c7c1d2141232f85eeb1436061ddfd835
<ide><path>Library/Homebrew/formula.rb <ide> def deps <ide> # Pretty titles the command and buffers stdout/stderr <ide> # Throws if there's an error <ide> def system cmd, *args <del> full="#{cmd} #{args*' '}".strip <del> ohai full <add> ohai "#{cmd} #{args*' '}".strip <add> <ide> if ARGV.verbose? <ide> safe_system cmd, *args <ide> else <del> out='' <del> # TODO write a ruby extension that does a good popen :P <del> IO.popen "#{full} 2>&1" do |f| <del> until f.eof? <del> out+=f.gets <del> end <add> rd, wr = IO.pipe <add> fork do <add> rd.close <add> $stdout.reopen wr <add> $stderr.reopen wr <add> exec cmd, *args <add> end <add> out = '' <add> ignore_interrupts do <add> wr.close <add> out << rd.read until rd.eof? <ide> end <del> unless $? == 0 <del> puts "Exit code: #{$?}" <add> unless $?.success? <ide> puts out <ide> raise <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> require 'formula' <ide> require 'set' <ide> <del>def ignore_interrupts <del> std_trap = trap("INT") {} <del> yield <del>ensure <del> trap("INT", std_trap) <del>end <del> <ide> class FormulaInstaller <ide> @@attempted = Set.new <ide> <ide><path>Library/Homebrew/utils.rb <ide> def inreplace path, before, after <ide> f.reopen(path, 'w').write(o) <ide> f.close <ide> end <add> <add>def ignore_interrupts <add> std_trap = trap("INT") {} <add> yield <add>ensure <add> trap("INT", std_trap) <add>end
3
Javascript
Javascript
fix filename to relativefilename in parseimage()
37ab2c2420f40d233756e4249a4fdf66b44c2258
<ide><path>examples/js/loaders/FBXLoader.js <ide> <ide> var id = parseInt( nodeID ); <ide> <del> images[ id ] = videoNode.Filename; <add> images[ id ] = videoNode.RelativeFilename || videoNode.Filename; <ide> <ide> // raw image data is in videoNode.Content <ide> if ( 'Content' in videoNode ) {
1
Python
Python
use six.text_type instead of str everywhere
381771731f48c75e7d5951e353049cceec386512
<ide><path>rest_framework/compat.py <ide> <ide> # flake8: noqa <ide> from __future__ import unicode_literals <del>import django <del>import inspect <add> <ide> from django.core.exceptions import ImproperlyConfigured <ide> from django.conf import settings <ide> from django.utils import six <add>import django <add>import inspect <ide> <ide> <ide> # Handle django.utils.encoding rename in 1.5 onwards. <ide> def generic(self, method, path, <ide> r = { <ide> 'PATH_INFO': self._get_path(parsed), <ide> 'QUERY_STRING': force_text(parsed[4]), <del> 'REQUEST_METHOD': str(method), <add> 'REQUEST_METHOD': six.text_type(method), <ide> } <ide> if data: <ide> r.update({ <ide> 'CONTENT_LENGTH': len(data), <del> 'CONTENT_TYPE': str(content_type), <add> 'CONTENT_TYPE': six.text_type(content_type), <ide> 'wsgi.input': FakePayload(data), <ide> }) <ide> elif django.VERSION <= (1, 4): <ide><path>rest_framework/fields.py <ide> from django.conf import settings <ide> from django.core import validators <ide> from django.core.exceptions import ValidationError <del>from django.utils import timezone <add>from django.utils import six, timezone <ide> from django.utils.datastructures import SortedDict <ide> from django.utils.dateparse import parse_date, parse_datetime, parse_time <ide> from django.utils.encoding import is_protected_type <ide> def run_validation(self, data=empty): <ide> return super(CharField, self).run_validation(data) <ide> <ide> def to_internal_value(self, data): <del> return str(data) <add> return six.text_type(data) <ide> <ide> def to_representation(self, value): <del> return str(value) <add> return six.text_type(value) <ide> <ide> <ide> class EmailField(CharField): <ide> def __init__(self, **kwargs): <ide> self.validators.append(validator) <ide> <ide> def to_internal_value(self, data): <del> return str(data).strip() <add> return six.text_type(data).strip() <ide> <ide> def to_representation(self, value): <del> return str(value).strip() <add> return six.text_type(value).strip() <ide> <ide> <ide> class RegexField(CharField): <ide> def __init__(self, **kwargs): <ide> <ide> def to_internal_value(self, data): <ide> try: <del> data = int(str(data)) <add> data = int(six.text_type(data)) <ide> except (ValueError, TypeError): <ide> self.fail('invalid') <ide> return data <ide> def to_internal_value(self, value): <ide> <ide> def to_representation(self, value): <ide> if not isinstance(value, decimal.Decimal): <del> value = decimal.Decimal(str(value).strip()) <add> value = decimal.Decimal(six.text_type(value).strip()) <ide> <ide> context = decimal.getcontext().copy() <ide> context.prec = self.max_digits <ide> def __init__(self, choices, **kwargs): <ide> # Allows us to deal with eg. integer choices while supporting either <ide> # integer or string input, but still get the correct datatype out. <ide> self.choice_strings_to_values = dict([ <del> (str(key), key) for key in self.choices.keys() <add> (six.text_type(key), key) for key in self.choices.keys() <ide> ]) <ide> <ide> super(ChoiceField, self).__init__(**kwargs) <ide> <ide> def to_internal_value(self, data): <ide> try: <del> return self.choice_strings_to_values[str(data)] <add> return self.choice_strings_to_values[six.text_type(data)] <ide> except KeyError: <ide> self.fail('invalid_choice', input=data) <ide> <ide> def to_representation(self, value): <del> return self.choice_strings_to_values[str(value)] <add> return self.choice_strings_to_values[six.text_type(value)] <ide> <ide> <ide> class MultipleChoiceField(ChoiceField): <ide> def to_internal_value(self, data): <ide> <ide> def to_representation(self, value): <ide> return set([ <del> self.choice_strings_to_values[str(item)] for item in value <add> self.choice_strings_to_values[six.text_type(item)] for item in value <ide> ]) <ide> <ide> <ide><path>rest_framework/filters.py <ide> returned by list views. <ide> """ <ide> from __future__ import unicode_literals <add> <ide> from django.core.exceptions import ImproperlyConfigured <ide> from django.db import models <ide> from django.utils import six <ide> def filter_queryset(self, request, queryset, view): <ide> if not search_fields: <ide> return queryset <ide> <del> orm_lookups = [self.construct_search(str(search_field)) <add> orm_lookups = [self.construct_search(six.text_type(search_field)) <ide> for search_field in search_fields] <ide> <ide> for search_term in self.get_search_terms(request): <ide><path>rest_framework/generics.py <ide> """ <ide> from __future__ import unicode_literals <ide> <del>from django.db.models.query import QuerySet <ide> from django.core.paginator import Paginator, InvalidPage <add>from django.db.models.query import QuerySet <ide> from django.http import Http404 <ide> from django.shortcuts import get_object_or_404 as _get_object_or_404 <add>from django.utils import six <ide> from django.utils.translation import ugettext as _ <ide> from rest_framework import views, mixins <ide> from rest_framework.settings import api_settings <ide> def paginate_queryset(self, queryset): <ide> error_format = _('Invalid page (%(page_number)s): %(message)s') <ide> raise Http404(error_format % { <ide> 'page_number': page_number, <del> 'message': str(exc) <add> 'message': six.text_type(exc) <ide> }) <ide> <ide> return page <ide><path>rest_framework/parsers.py <ide> on the request, such as form content or json encoded data. <ide> """ <ide> from __future__ import unicode_literals <add> <ide> from django.conf import settings <ide> from django.core.files.uploadhandler import StopFutureHandlers <ide> from django.http import QueryDict <ide> def parse(self, stream, media_type=None, parser_context=None): <ide> data, files = parser.parse() <ide> return DataAndFiles(data, files) <ide> except MultiPartParserError as exc: <del> raise ParseError('Multipart form parse error - %s' % str(exc)) <add> raise ParseError('Multipart form parse error - %s' % six.text_type(exc)) <ide> <ide> <ide> class XMLParser(BaseParser): <ide><path>rest_framework/relations.py <ide> from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured <ide> from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 <ide> from django.db.models.query import QuerySet <add>from django.utils import six <ide> from django.utils.translation import ugettext_lazy as _ <ide> <ide> <ide> def __init__(self, **kwargs): <ide> super(StringRelatedField, self).__init__(**kwargs) <ide> <ide> def to_representation(self, value): <del> return str(value) <add> return six.text_type(value) <ide> <ide> <ide> class PrimaryKeyRelatedField(RelatedField): <ide><path>rest_framework/reverse.py <ide> """ <ide> from __future__ import unicode_literals <ide> from django.core.urlresolvers import reverse as django_reverse <add>from django.utils import six <ide> from django.utils.functional import lazy <ide> <ide> <ide> def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra <ide> return url <ide> <ide> <del>reverse_lazy = lazy(reverse, str) <add>reverse_lazy = lazy(reverse, six.text_type) <ide><path>rest_framework/utils/encoders.py <ide> Helper classes for parsers. <ide> """ <ide> from __future__ import unicode_literals <del>from django.utils import timezone <ide> from django.db.models.query import QuerySet <add>from django.utils import six, timezone <ide> from django.utils.datastructures import SortedDict <ide> from django.utils.functional import Promise <ide> from rest_framework.compat import force_text <ide> def default(self, obj): <ide> representation = representation[:12] <ide> return representation <ide> elif isinstance(obj, datetime.timedelta): <del> return str(obj.total_seconds()) <add> return six.text_type(obj.total_seconds()) <ide> elif isinstance(obj, decimal.Decimal): <ide> # Serializers will coerce decimals to strings by default. <ide> return float(obj) <ide> class SafeDumper(yaml.SafeDumper): <ide> than the usual behaviour of sorting the keys. <ide> """ <ide> def represent_decimal(self, data): <del> return self.represent_scalar('tag:yaml.org,2002:str', str(data)) <add> return self.represent_scalar('tag:yaml.org,2002:str', six.text_type(data)) <ide> <ide> def represent_mapping(self, tag, mapping, flow_style=None): <ide> value = []
8
Javascript
Javascript
add innerviewref prop to scrollview
10254a900a2332fc87063d9287da2403abbdf5c3
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> const invariant = require('invariant'); <ide> const processDecelerationRate = require('./processDecelerationRate'); <ide> const resolveAssetSource = require('../../Image/resolveAssetSource'); <ide> const splitLayoutProps = require('../../StyleSheet/splitLayoutProps'); <add>const setAndForwardRef = require('../../Utilities/setAndForwardRef'); <ide> <ide> import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType'; <ide> import type {PointProp} from '../../StyleSheet/PointPropType'; <ide> export type Props = $ReadOnly<{| <ide> // $FlowFixMe - how to handle generic type without existential operator? <ide> refreshControl?: ?React.Element<any>, <ide> children?: React.Node, <add> /** <add> * A ref to the inner View element of the ScrollView. This should be used <add> * instead of calling `getInnerViewRef`. <add> */ <add> innerViewRef?: React.Ref<typeof View>, <ide> |}>; <ide> <ide> type State = {| <ide> class ScrollView extends React.Component<Props, State> { <ide> } <ide> <ide> getInnerViewNode(): ?number { <add> console.warn( <add> '`getInnerViewNode()` is deprecated. This will be removed in a future release. ' + <add> 'Use <ScrollView innerViewRef={myRef} /> instead.', <add> ); <ide> return ReactNative.findNodeHandle(this._innerViewRef); <ide> } <ide> <del> getInnerViewRef(): ?React.ElementRef<HostComponent<mixed>> { <add> getInnerViewRef(): ?React.ElementRef<typeof View> { <add> console.warn( <add> '`getInnerViewRef()` is deprecated. This will be removed in a future release. ' + <add> 'Use <ScrollView innerViewRef={myRef} /> instead.', <add> ); <ide> return this._innerViewRef; <ide> } <ide> <ide> class ScrollView extends React.Component<Props, State> { <ide> this._scrollViewRef = ref; <ide> }; <ide> <del> _innerViewRef: ?React.ElementRef<HostComponent<mixed>> = null; <del> _setInnerViewRef = (ref: ?React.ElementRef<HostComponent<mixed>>) => { <del> this._innerViewRef = ref; <del> }; <add> _innerViewRef: ?React.ElementRef<typeof View> = null; <add> _setInnerViewRef = setAndForwardRef({ <add> getForwardedRef: () => this.props.innerViewRef, <add> setLocalRef: ref => { <add> this._innerViewRef = ref; <add> }, <add> }); <ide> <ide> render(): React.Node | React.Element<string> { <ide> let ScrollViewClass;
1
Javascript
Javascript
fix listener cleanup on unmount
9965b6b9dda2716e3618e4cb1acbf83ce29e3c2f
<ide><path>src/core/ReactNativeComponent.js <ide> ReactNativeComponent.Mixin = { <ide> * @internal <ide> */ <ide> unmountComponent: function() { <add> ReactEvent.deleteAllListeners(this._rootNodeID); <ide> ReactComponent.Mixin.unmountComponent.call(this); <ide> this.unmountMultiChild(); <del> ReactEvent.deleteAllListeners(this._rootNodeID); <ide> } <ide> <ide> }; <ide><path>src/core/__tests__/ReactNativeComponent-test.js <ide> describe('ReactNativeComponent', function() { <ide> }); <ide> }); <ide> <add> describe('unmountComponent', function() { <add> it("should clean up listeners", function() { <add> var React = require('React'); <add> var ReactEvent = require('ReactEvent'); <add> <add> var container = document.createElement('div'); <add> document.documentElement.appendChild(container); <add> <add> var callback = function() {}; <add> var instance = <div onClick={callback} />; <add> React.renderComponent(instance, container); <add> <add> var rootNode = instance.getDOMNode(); <add> var rootNodeID = rootNode.id; <add> expect(ReactEvent.getListener(rootNodeID, 'onClick')).toBe(callback); <add> <add> React.unmountAndReleaseReactRootNode(container); <add> <add> expect(ReactEvent.getListener(rootNodeID, 'onClick')).toBe(undefined); <add> }); <add> }); <add> <ide> });
2
PHP
PHP
use getkey
1e1b4c5b0681141f0219dbf938d117d7239acd88
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function setKeysForSaveQuery(Builder $query) <ide> protected function getKeyForSaveQuery() <ide> { <ide> return $this->original[$this->getKeyName()] <del> ?? $this->getAttribute($this->getKeyName()); <add> ?? $this->getKey(); <ide> } <ide> <ide> /**
1
Text
Text
introduce categories to cpp style guide
fff4272fa7ce5044a800195be7c40664f9aa04ec
<ide><path>CPP_STYLE_GUIDE.md <ide> <ide> ## Table of Contents <ide> <del>* [Left-leaning (C++ style) asterisks for pointer declarations](#left-leaning-c-style-asterisks-for-pointer-declarations) <del>* [2 spaces of indentation for blocks or bodies of conditionals](#2-spaces-of-indentation-for-blocks-or-bodies-of-conditionals) <del>* [4 spaces of indentation for statement continuations](#4-spaces-of-indentation-for-statement-continuations) <del>* [Align function arguments vertically](#align-function-arguments-vertically) <del>* [Initialization lists](#initialization-lists) <del>* [CamelCase for methods, functions, and classes](#camelcase-for-methods-functions-and-classes) <del>* [snake\_case for local variables and parameters](#snake_case-for-local-variables-and-parameters) <del>* [snake\_case\_ for private class fields](#snake_case_-for-private-class-fields) <del>* [Space after `template`](#space-after-template) <del>* [Type casting](#type-casting) <del>* [Memory allocation](#memory-allocation) <del>* [`nullptr` instead of `NULL` or `0`](#nullptr-instead-of-null-or-0) <del>* [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included) <del>* [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) <del>* [Ownership and Smart Pointers](#ownership-and-smart-pointers) <add>* [Formatting](#formatting) <add> * [Left-leaning (C++ style) asterisks for pointer declarations](#left-leaning-c-style-asterisks-for-pointer-declarations) <add> * [2 spaces of indentation for blocks or bodies of conditionals](#2-spaces-of-indentation-for-blocks-or-bodies-of-conditionals) <add> * [4 spaces of indentation for statement continuations](#4-spaces-of-indentation-for-statement-continuations) <add> * [Align function arguments vertically](#align-function-arguments-vertically) <add> * [Initialization lists](#initialization-lists) <add> * [CamelCase for methods, functions and classes](#camelcase-for-methods-functions-and-classes) <add> * [snake\_case for local variables and parameters](#snake_case-for-local-variables-and-parameters) <add> * [snake\_case\_ for private class fields](#snake_case_-for-private-class-fields) <add> * [Space after `template`](#space-after-template) <add>* [Memory Management](#memory-management) <add> * [Memory allocation](#memory-allocation) <add> * [Use `nullptr` instead of `NULL` or `0`](#use-nullptr-instead-of-null-or-0) <add> * [Ownership and Smart Pointers](#ownership-and-smart-pointers) <add>* [Others](#others) <add> * [Type casting](#type-casting) <add> * [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included) <add> * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) <ide> <ide> Unfortunately, the C++ linter (based on <ide> [Google’s `cpplint`](https://github.com/google/styleguide)), which can be run <ide> explicitly via `make lint-cpp`, does not currently catch a lot of rules that are <ide> specific to the Node.js C++ code base. This document explains the most common of <ide> these rules: <ide> <add>## Formatting <add> <ide> ## Left-leaning (C++ style) asterisks for pointer declarations <ide> <ide> `char* buffer;` instead of `char *buffer;` <ide> class FancyContainer { <ide> ... <ide> } <ide> ``` <del> <del>## Type casting <del> <del>- Always avoid C-style casts (`(type)value`) <del>- `dynamic_cast` does not work because RTTI is not enabled <del>- Use `static_cast` for casting whenever it works <del>- `reinterpret_cast` is okay if `static_cast` is not appropriate <add>## Memory Management <ide> <ide> ## Memory allocation <ide> <ide> - `Malloc()`, `Calloc()`, etc. from `util.h` abort in Out-of-Memory situations <ide> - `UncheckedMalloc()`, etc. return `nullptr` in OOM situations <ide> <del>## `nullptr` instead of `NULL` or `0` <add>## Use `nullptr` instead of `NULL` or `0` <ide> <ide> What it says in the title. <ide> <add>## Ownership and Smart Pointers <add> <add>"Smart" pointers are classes that act like pointers, e.g. <add>by overloading the `*` and `->` operators. Some smart pointer types can be <add>used to automate ownership bookkeeping, to ensure these responsibilities are <add>met. `std::unique_ptr` is a smart pointer type introduced in C++11, which <add>expresses exclusive ownership of a dynamically allocated object; the object <add>is deleted when the `std::unique_ptr` goes out of scope. It cannot be <add>copied, but can be moved to represent ownership transfer. <add>`std::shared_ptr` is a smart pointer type that expresses shared ownership of a <add>dynamically allocated object. `std::shared_ptr`s can be copied; ownership <add>of the object is shared among all copies, and the object <add>is deleted when the last `std::shared_ptr` is destroyed. <add> <add>Prefer to use `std::unique_ptr` to make ownership <add>transfer explicit. For example: <add> <add>```cpp <add>std::unique_ptr<Foo> FooFactory(); <add>void FooConsumer(std::unique_ptr<Foo> ptr); <add>``` <add> <add>Never use `std::auto_ptr`. Instead, use `std::unique_ptr`. <add> <add>## Others <add> <add>## Type casting <add> <add>- Always avoid C-style casts (`(type)value`) <add>- `dynamic_cast` does not work because RTTI is not enabled <add>- Use `static_cast` for casting whenever it works <add>- `reinterpret_cast` is okay if `static_cast` is not appropriate <add> <ide> ## Do not include `*.h` if `*-inl.h` has already been included <ide> <ide> Do <ide> A lot of code inside Node.js is written so that typechecking etc. is performed <ide> in JavaScript. <ide> <ide> Using C++ `throw` is not allowed. <del> <del>## Ownership and Smart Pointers <del> <del>"Smart" pointers are classes that act like pointers, e.g. <del>by overloading the `*` and `->` operators. Some smart pointer types can be <del>used to automate ownership bookkeeping, to ensure these responsibilities are <del>met. `std::unique_ptr` is a smart pointer type introduced in C++11, which <del>expresses exclusive ownership of a dynamically allocated object; the object <del>is deleted when the `std::unique_ptr` goes out of scope. It cannot be <del>copied, but can be moved to represent ownership transfer. <del>`std::shared_ptr` is a smart pointer type that expresses shared ownership of a <del>dynamically allocated object. `std::shared_ptr`s can be copied; ownership <del>of the object is shared among all copies, and the object <del>is deleted when the last `std::shared_ptr` is destroyed. <del> <del>Prefer to use `std::unique_ptr` to make ownership <del>transfer explicit. For example: <del> <del>```cpp <del>std::unique_ptr<Foo> FooFactory(); <del>void FooConsumer(std::unique_ptr<Foo> ptr); <del>``` <del> <del>Never use `std::auto_ptr`. Instead, use `std::unique_ptr`.
1
Ruby
Ruby
remove rackmount const usage
a28d0ea33e04cd7bf785c26a95e74f78dff82ce0
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def call(env) <ide> <ide> @constraints.each { |constraint| <ide> if constraint.respond_to?(:matches?) && !constraint.matches?(req) <del> return Rack::Mount::Const::EXPECTATION_FAILED_RESPONSE <add> return [417, {}, []] <ide> elsif constraint.respond_to?(:call) && !constraint.call(req) <del> return Rack::Mount::Const::EXPECTATION_FAILED_RESPONSE <add> return [417, {}, []] <ide> end <ide> } <ide> <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> module ActionDispatch <ide> module Routing <ide> class RouteSet #:nodoc: <ide> NotFound = lambda { |env| <del> raise ActionController::RoutingError, "No route matches #{env[::Rack::Mount::Const::PATH_INFO].inspect} with #{env.inspect}" <add> raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect} with #{env.inspect}" <ide> } <ide> <ide> PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
2
Ruby
Ruby
use didyoumean for associationnotfounderror
3bc7756036332dac7037de0061d9afc15f4f6e1a
<ide><path>activerecord/lib/active_record/associations.rb <ide> <ide> module ActiveRecord <ide> class AssociationNotFoundError < ConfigurationError #:nodoc: <add> attr_reader :record, :association_name <ide> def initialize(record = nil, association_name = nil) <add> @record = record <add> @association_name = association_name <ide> if record && association_name <ide> super("Association named '#{association_name}' was not found on #{record.class.name}; perhaps you misspelled it?") <ide> else <ide> super("Association was not found.") <ide> end <ide> end <add> <add> class Correction <add> def initialize(error) <add> @error = error <add> end <add> <add> def corrections <add> if @error.association_name <add> maybe_these = @error.record.class.reflections.keys <add> <add> maybe_these.sort_by { |n| <add> DidYouMean::Jaro.distance(@error.association_name.to_s, n) <add> }.reverse.first(4) <add> else <add> [] <add> end <add> end <add> end <add> <add> # We may not have DYM, and DYM might not let us register error handlers <add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <add> DidYouMean.correct_error(self, Correction) <add> end <ide> end <ide> <ide> class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc: <ide><path>activerecord/test/cases/associations/eager_test.rb <ide> def test_eager_with_invalid_association_reference <ide> e = assert_raise(ActiveRecord::AssociationNotFoundError) { <ide> Post.all.merge!(includes: :monkeys).find(6) <ide> } <del> assert_equal("Association named 'monkeys' was not found on Post; perhaps you misspelled it?", e.message) <add> assert_match(/Association named 'monkeys' was not found on Post; perhaps you misspelled it\?/, e.message) <ide> <ide> e = assert_raise(ActiveRecord::AssociationNotFoundError) { <ide> Post.all.merge!(includes: [ :monkeys ]).find(6) <ide> } <del> assert_equal("Association named 'monkeys' was not found on Post; perhaps you misspelled it?", e.message) <add> assert_match(/Association named 'monkeys' was not found on Post; perhaps you misspelled it\?/, e.message) <ide> <ide> e = assert_raise(ActiveRecord::AssociationNotFoundError) { <ide> Post.all.merge!(includes: [ "monkeys" ]).find(6) <ide> } <del> assert_equal("Association named 'monkeys' was not found on Post; perhaps you misspelled it?", e.message) <add> assert_match(/Association named 'monkeys' was not found on Post; perhaps you misspelled it\?/, e.message) <ide> <ide> e = assert_raise(ActiveRecord::AssociationNotFoundError) { <ide> Post.all.merge!(includes: [ :monkeys, :elephants ]).find(6) <ide> } <del> assert_equal("Association named 'monkeys' was not found on Post; perhaps you misspelled it?", e.message) <add> assert_match(/Association named 'monkeys' was not found on Post; perhaps you misspelled it\?/, e.message) <add> end <add> <add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <add> test "exceptions have suggestions for fix" do <add> error = assert_raise(ActiveRecord::AssociationNotFoundError) { <add> Post.all.merge!(includes: :monkeys).find(6) <add> } <add> assert_match "Did you mean?", error.message <add> end <ide> end <ide> <ide> def test_eager_has_many_through_with_order
2
PHP
PHP
update typehints for collection classes
47bd1b8bd79333d588c89e42f10823689eb4bd60
<ide><path>src/Collection/CollectionInterface.php <ide> interface CollectionInterface extends Iterator, JsonSerializable <ide> * in this collection <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function each(callable $c): CollectionInterface; <add> public function each(callable $c); <ide> <ide> /** <ide> * Looks through each value in the collection, and returns another collection with <ide> public function reduce(callable $c, $zero = null); <ide> * inside the hierarchy of each value so that the column can be extracted. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function extract($matcher): CollectionInterface; <add> public function extract(string $matcher): CollectionInterface; <ide> <ide> /** <ide> * Returns the top element in this collection after being sorted by a property. <ide> public function combine($keyPath, $valuePath, $groupPath = null): CollectionInte <ide> * @param string $nestingKey The key name under which children are nested <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function nest($idPath, $parentPath, $nestingKey = 'children'): CollectionInterface; <add> public function nest($idPath, $parentPath, string $nestingKey = 'children'): CollectionInterface; <ide> <ide> /** <ide> * Returns a new collection containing each of the elements found in `$values` as <ide> public function listNested($dir = 'desc', $nestingKey = 'children'): CollectionI <ide> * $comments = (new Collection($comments))->stopWhen(['is_approved' => false]); <ide> * ``` <ide> * <del> * @param callable $condition the method that will receive each of the elements and <add> * @param callable|array $condition the method that will receive each of the elements and <ide> * returns true when the iteration should be stopped. <ide> * If an array, it will be interpreted as a key-value list of conditions where <ide> * the key is a property path as accepted by `Collection::extract`, <ide><path>src/Collection/CollectionTrait.php <ide> trait CollectionTrait <ide> /** <ide> * @inheritDoc <ide> */ <del> public function each(callable $c): CollectionInterface <add> public function each(callable $c) <ide> { <ide> foreach ($this->optimizeUnwrap() as $k => $v) { <ide> $c($v, $k); <ide> public function reduce(callable $c, $zero = null) <ide> /** <ide> * @inheritDoc <ide> */ <del> public function extract($matcher): CollectionInterface <add> public function extract(string $matcher): CollectionInterface <ide> { <ide> $extractor = new ExtractIterator($this->unwrap(), $matcher); <ide> if (is_string($matcher) && strpos($matcher, '{*}') !== false) { <ide> public function combine($keyPath, $valuePath, $groupPath = null): CollectionInte <ide> /** <ide> * @inheritDoc <ide> */ <del> public function nest($idPath, $parentPath, $nestingKey = 'children'): CollectionInterface <add> public function nest($idPath, $parentPath, string $nestingKey = 'children'): CollectionInterface <ide> { <ide> $parents = []; <ide> $idPath = $this->_propertyExtractor($idPath); <ide><path>src/Collection/Iterator/InsertIterator.php <ide> class InsertIterator extends Collection <ide> * @param iterable $values The source collection from which the values will <ide> * be inserted at the specified path. <ide> */ <del> public function __construct(iterable $into, $path, iterable $values) <add> public function __construct(iterable $into, string $path, iterable $values) <ide> { <ide> parent::__construct($into); <ide> <ide> public function __construct(iterable $into, $path, iterable $values) <ide> * <ide> * @return void <ide> */ <del> public function next() <add> public function next(): void <ide> { <ide> parent::next(); <ide> if ($this->_validValues) { <ide> public function current() <ide> * <ide> * @return void <ide> */ <del> public function rewind() <add> public function rewind(): void <ide> { <ide> parent::rewind(); <ide> $this->_values->rewind(); <ide><path>src/Collection/Iterator/MapReduce.php <ide> public function emit($val, $key = null): void <ide> * @throws \LogicException if emitIntermediate was called but no reducer function <ide> * was provided <ide> */ <del> protected function _execute() <add> protected function _execute(): void <ide> { <ide> $mapper = $this->_mapper; <ide> foreach ($this->_data as $key => $val) { <ide><path>src/Collection/Iterator/SortIterator.php <ide> class SortIterator extends Collection <ide> * @param int $type the type of comparison to perform, either SORT_STRING <ide> * SORT_NUMERIC or SORT_NATURAL <ide> */ <del> public function __construct(iterable $items, $callback, $dir = \SORT_DESC, $type = \SORT_NUMERIC) <add> public function __construct(iterable $items, $callback, int $dir = \SORT_DESC, int $type = \SORT_NUMERIC) <ide> { <ide> if (!is_array($items)) { <ide> $items = iterator_to_array((new Collection($items))->unwrap(), false); <ide><path>src/Collection/Iterator/TreeIterator.php <ide> class TreeIterator extends RecursiveIteratorIterator implements CollectionInterf <ide> * @param int $mode Iterator mode. <ide> * @param int $flags Iterator flags. <ide> */ <del> public function __construct(RecursiveIterator $items, $mode = RecursiveIteratorIterator::SELF_FIRST, $flags = 0) <del> { <add> public function __construct( <add> RecursiveIterator $items, <add> int $mode = RecursiveIteratorIterator::SELF_FIRST, <add> int $flags = 0 <add> ) { <ide> parent::__construct($items, $mode, $flags); <ide> $this->_mode = $mode; <ide> } <ide><path>src/Collection/Iterator/TreePrinter.php <ide> namespace Cake\Collection\Iterator; <ide> <ide> use Cake\Collection\CollectionTrait; <add>use RecursiveIterator; <ide> use RecursiveIteratorIterator; <ide> <ide> /** <ide> class TreePrinter extends RecursiveIteratorIterator <ide> * their depth in the tree. <ide> * @param int $mode Iterator mode. <ide> */ <del> public function __construct($items, $valuePath, $keyPath, $spacer, $mode = RecursiveIteratorIterator::SELF_FIRST) <del> { <add> public function __construct( <add> RecursiveIterator $items, <add> $valuePath, <add> $keyPath, <add> string $spacer, <add> int $mode = RecursiveIteratorIterator::SELF_FIRST <add> ) { <ide> parent::__construct($items, $mode); <ide> $this->_value = $this->_propertyExtractor($valuePath); <ide> $this->_key = $this->_propertyExtractor($keyPath); <ide><path>src/Collection/Iterator/ZipIterator.php <ide> class ZipIterator extends MultipleIterator implements CollectionInterface, Seria <ide> * @param array $sets The list of array or iterators to be zipped. <ide> * @param callable|null $callable The function to use for zipping the elements of each iterator. <ide> */ <del> public function __construct(array $sets, $callable = null) <add> public function __construct(array $sets, ?callable $callable = null) <ide> { <ide> $sets = array_map(function ($items) { <ide> return (new Collection($items))->unwrap();
8
Text
Text
fix fragment identifier
d4075e111612a7bfb5a1fbeabc219ae81c4eb099
<ide><path>docs/basics/UsageWithReact.md <ide> React bindings for Redux separate _presentational_ components from _container_ c <ide> </tbody> <ide> </table> <ide> <del>Most of the components we'll write will be presentational, but we'll need to generate a few container components to connect them to the Redux store. This and the design brief below do not imply container components must be near the top of the component tree. If a container component becomes too complex (i.e. it has heavily nested presentational components with countless callbacks being passed down), introduce another container within the component tree as noted in the [FAQ](../faq/ReactRedux.md#react-multiple-components). <add>Most of the components we'll write will be presentational, but we'll need to generate a few container components to connect them to the Redux store. This and the design brief below do not imply container components must be near the top of the component tree. If a container component becomes too complex (i.e. it has heavily nested presentational components with countless callbacks being passed down), introduce another container within the component tree as noted in the [FAQ](../faq/ReactRedux.md#should-i-only-connect-my-top-component-or-can-i-connect-multiple-components-in-my-tree). <ide> <ide> Technically you could write the container components by hand using [`store.subscribe()`](../api/Store.md#subscribe). We don't advise you to do this because React Redux makes many performance optimizations that are hard to do by hand. For this reason, rather than write container components, we will generate them using the [`connect()`](https://react-redux.js.org/api/connect#connect) function provided by React Redux, as you will see below. <ide>
1
Javascript
Javascript
remove useless clearlines, updated test
39fec6003e2cd52dfcd4e25f6da7f6e54617630d
<ide><path>lib/_debugger.js <ide> function Interface(stdin, stdout, args) { <ide> this.breakpoints = []; <ide> <ide> // Run script automatically <del> this.clearline(); <ide> this.pause(); <ide> <ide> // XXX Need to figure out why we need this delay <ide> Interface.prototype.clearline = function() { <ide> if (this.stdout.isTTY) { <ide> this.stdout.cursorTo(0); <ide> this.stdout.clearLine(1); <add> } else { <add> this.stdout.write('\b'); <ide> } <ide> }; <ide> <ide> Interface.prototype.handleBreak = function(r) { <ide> // And list source <ide> this.list(2); <ide> <del> this.resume(); <add> this.resume(true); <ide> }; <ide> <ide> <ide><path>test/simple/test-debugger-repl.js <ide> var expected = []; <ide> child.on('line', function(line) { <ide> assert.ok(expected.length > 0, 'Got unexpected line: ' + line); <ide> <del> console.log(JSON.stringify(line) + ','); <del> <ide> var expectedLine = expected[0].lines.shift(); <ide> assert.equal(line, expectedLine); <ide> <ide> function addTest(input, output) { <ide> <ide> // Initial lines <ide> addTest(null, [ <del> "debug> < debugger listening on port 5858", <del> "debug> connecting... ok", <del> "debug> break in [unnamed]:3", <del> " 1 ", <del> " 2 debugger;", <del> " 3 debugger;", <del> " 4 function a(x) {", <del> " 5 var i = 10;" <add> "debug> \b< debugger listening on port 5858", <add> "debug> \bconnecting... ok", <add> "debug> \bbreak in [unnamed]:3", <add> "\b 1 ", <add> "\b 2 debugger;", <add> "\b 3 debugger;", <add> "\b 4 function a(x) {", <add> "\b 5 var i = 10;" <ide> ]); <ide> <ide> // Next <ide> addTest('n', [ <del> "debug> debug> debug> break in [unnamed]:13", <del> " 11 return [\"hello\", \"world\"].join(\" \");", <del> " 12 };", <del> " 13 a();", <del> " 14 a(1);", <del> " 15 b();" <add> "debug> debug> debug> \bbreak in [unnamed]:13", <add> "\b 11 return ['hello', 'world'].join(' ');", <add> "\b 12 };", <add> "\b 13 a();", <add> "\b 14 a(1);", <add> "\b 15 b();" <ide> ]); <ide> <ide> // Continue <ide> addTest('c', [ <del> "debug> debug> debug> break in [unnamed]:7", <del> " 5 var i = 10;", <del> " 6 while (--i != 0);", <del> " 7 debugger;", <del> " 8 return i;", <del> " 9 };" <add> "debug> debug> debug> \bbreak in [unnamed]:7", <add> "\b 5 var i = 10;", <add> "\b 6 while (--i != 0);", <add> "\b 7 debugger;", <add> "\b 8 return i;", <add> "\b 9 };" <ide> ]); <ide> <del> <ide> // Step out <ide> addTest('o', [ <del> "debug> debug> debug> break in [unnamed]:14", <del> " 12 };", <del> " 13 a();", <del> " 14 a(1);", <del> " 15 b();", <del> " 16 b();" <add> "debug> debug> debug> \bbreak in [unnamed]:14", <add> "\b 12 };", <add> "\b 13 a();", <add> "\b 14 a(1);", <add> "\b 15 b();", <add> "\b 16 b();" <ide> ]); <ide> <ide> <ide> setTimeout(function() { <ide> <ide> process.once('uncaughtException', function(e) { <ide> quit(); <del> throw e; <add> console.error(e.toString()); <add> process.exit(1); <ide> }); <ide> <del>process.on('exit', function() { <add>process.on('exit', function(code) { <ide> quit(); <add> if (code === 0) { <add> assert.equal(expected.length, 0); <add> } <ide> });
2
Javascript
Javascript
fix round option for time scales
7423c48eb7af78fb05008f49964d9520c0db83a4
<ide><path>src/scales/scale.time.js <ide> module.exports = function(Chart) { <ide> if (timeOpts.min) { <ide> var minMoment = timeHelpers.parseTime(me, timeOpts.min); <ide> if (timeOpts.round) { <del> minMoment.round(timeOpts.round); <add> minMoment.startOf(timeOpts.round); <ide> } <ide> minTimestamp = minMoment.valueOf(); <ide> }
1
Javascript
Javascript
reap children when cluster-bind-twice fails
a90dc41df2a10858e7135cab55af335da9bc4b05
<ide><path>test/simple/test-cluster-bind-twice.js <ide> if (!id) { <ide> var b = fork(__filename, ['two']); <ide> <ide> a.on('exit', function(c) { <del> if (c) <add> if (c) { <add> b.send('QUIT'); <ide> throw new Error('A exited with ' + c); <add> } <ide> }); <ide> <ide> b.on('exit', function(c) { <del> if (c) <add> if (c) { <add> a.send('QUIT'); <ide> throw new Error('B exited with ' + c); <add> } <ide> }); <ide> <ide>
1
Text
Text
fix napi_default_property name
11430a6de36b6511134b33d8a2dc23a7fd750b70
<ide><path>doc/api/n-api.md <ide> typedef enum { <ide> napi_default_method = napi_writable | napi_configurable, <ide> <ide> // Default for object properties, like in JS obj[prop]. <del> napi_default_property = napi_writable | <add> napi_default_jsproperty = napi_writable | <ide> napi_enumerable | <ide> napi_configurable, <ide> } napi_property_attributes; <ide> They can be one or more of the following bitflags: <ide> [`napi_define_class`][]. It is ignored by `napi_define_properties`. <ide> * `napi_default_method`: Like a method in a JS class, the property is <ide> configurable and writeable, but not enumerable. <del>* `napi_default_property`: Like a property set via assignment in JavaScript, the <del> property is writable, enumerable, and configurable. <add>* `napi_default_jsproperty`: Like a property set via assignment in JavaScript, <add> the property is writable, enumerable, and configurable. <ide> <ide> #### napi_property_descriptor <ide>
1
Text
Text
linkify remaining references to fs.stats object
51e7bc8f79eb99d402d5633dcfd8b147318c4b40
<ide><path>doc/api/fs.md <ide> Synchronous fdatasync(2). Returns `undefined`. <ide> * `callback` {Function} <ide> <ide> Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where <del>`stats` is a `fs.Stats` object. `fstat()` is identical to [`stat()`][], except that <del>the file to be stat-ed is specified by the file descriptor `fd`. <add>`stats` is a [`fs.Stats`][] object. `fstat()` is identical to [`stat()`][], <add>except that the file to be stat-ed is specified by the file descriptor `fd`. <ide> <ide> ## fs.fstatSync(fd) <ide> <ide> Synchronous link(2). Returns `undefined`. <ide> * `callback` {Function} <ide> <ide> Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where <del>`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if <del>`path` is a symbolic link, then the link itself is stat-ed, not the file that it <del>refers to. <add>`stats` is a [`fs.Stats`][] object. `lstat()` is identical to `stat()`, <add>except that if `path` is a symbolic link, then the link itself is stat-ed, <add>not the file that it refers to. <ide> <ide> ## fs.lstatSync(path) <ide>
1
Ruby
Ruby
improve blocks usage
d05fa0cc8da0ffa01333f8956acd4a24c9fd46be
<ide><path>lib/arel/algebra/relations/operations/having.rb <ide> class Having < Compound <ide> deriving :== <ide> requires :restricting <ide> <del> def initialize(relation, *predicates, &block) <add> def initialize(relation, *predicates) <ide> predicates = [yield(relation)] + predicates if block_given? <ide> @predicates = predicates.map { |p| p.bind(relation) } <ide> @relation = relation <ide><path>lib/arel/algebra/relations/operations/lock.rb <ide> class Lock < Compound <ide> attributes :relation, :locked <ide> deriving :initialize, :== <ide> <del> def initialize(relation, locked, &block) <add> def initialize(relation, locked) <ide> @relation = relation <ide> @locked = locked.blank? ? " FOR UPDATE" : locked <ide> end <ide><path>lib/arel/algebra/relations/operations/where.rb <ide> class Where < Compound <ide> deriving :== <ide> requires :restricting <ide> <del> def initialize(relation, *predicates, &block) <add> def initialize(relation, *predicates) <ide> predicates = [yield(relation)] + predicates if block_given? <ide> @predicates = predicates.map { |p| p.bind(relation) } <ide> @relation = relation <ide><path>lib/arel/algebra/relations/relation.rb <ide> def bind(relation) <ide> module Enumerable <ide> include ::Enumerable <ide> <del> def each(&block) <del> session.read(self).each(&block) <add> def each <add> session.read(self).each { |e| yield e } <ide> end <ide> <ide> def first <ide><path>lib/arel/algebra/relations/utilities/compound.rb <ide> def engine <ide> <ide> private <ide> <del> def arguments_from_block(relation, &block) <add> def arguments_from_block(relation) <ide> block_given?? [yield(relation)] : [] <ide> end <ide> end
5
Javascript
Javascript
replace assert.throws w/ common.expectserror
20a8e83e44a6555a40c9d5f367a9a7be8fed0374
<ide><path>test/parallel/test-dgram-createSocket-type.js <ide> const errMessage = /^Bad socket type specified\. Valid types are: udp4, udp6$/; <ide> <ide> // Error must be thrown with invalid types <ide> invalidTypes.forEach((invalidType) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> dgram.createSocket(invalidType); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_SOCKET_BAD_TYPE', <ide> type: TypeError, <ide> message: errMessage <del> })); <add> }); <ide> }); <ide> <ide> // Error must not be thrown with valid types <ide><path>test/parallel/test-dgram-custom-lookup.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> const dns = require('dns'); <ide> <ide> const dns = require('dns'); <ide> { <ide> // Verify that non-functions throw. <ide> [null, true, false, 0, 1, NaN, '', 'foo', {}, Symbol()].forEach((value) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> dgram.createSocket({ type: 'udp4', lookup: value }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "lookup" argument must be of type Function' <del> })); <add> }); <ide> }); <ide> } <ide><path>test/parallel/test-dgram-membership.js <ide> const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true }); <ide> { <ide> const socket = setup(); <ide> socket.close(common.mustCall(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.addMembership(multicastAddress); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_SOCKET_DGRAM_NOT_RUNNING', <ide> type: Error, <ide> message: /^Not running$/ <del> })); <add> }); <ide> })); <ide> } <ide> <ide> // dropMembership() on closed socket should throw <ide> { <ide> const socket = setup(); <ide> socket.close(common.mustCall(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.dropMembership(multicastAddress); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_SOCKET_DGRAM_NOT_RUNNING', <ide> type: Error, <ide> message: /^Not running$/ <del> })); <add> }); <ide> })); <ide> } <ide> <ide> // addMembership() with no argument should throw <ide> { <ide> const socket = setup(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.addMembership(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: /^The "multicastAddress" argument must be specified$/ <del> })); <add> }); <ide> socket.close(); <ide> } <ide> <ide> // dropMembership() with no argument should throw <ide> { <ide> const socket = setup(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.dropMembership(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: /^The "multicastAddress" argument must be specified$/ <del> })); <add> }); <ide> socket.close(); <ide> } <ide> <ide><path>test/parallel/test-dgram-multicast-setTTL.js <ide> socket.on('listening', common.mustCall(() => { <ide> socket.setMulticastTTL(1000); <ide> }, /^Error: setMulticastTTL EINVAL$/); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setMulticastTTL('foo'); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "ttl" argument must be of type number. Received type string' <del> })); <add> }); <ide> <ide> //close the socket <ide> socket.close(); <ide><path>test/parallel/test-dgram-send-address-types.js <ide> const client = dgram.createSocket('udp4').bind(0, () => { <ide> client.send(buf, port, onMessage); <ide> <ide> // invalid address: object <del> assert.throws(() => { <add> common.expectsError(() => { <ide> client.send(buf, port, []); <del> }, common.expectsError(expectedError)); <add> }, expectedError); <ide> <ide> // invalid address: nonzero number <del> assert.throws(() => { <add> common.expectsError(() => { <ide> client.send(buf, port, 1); <del> }, common.expectsError(expectedError)); <add> }, expectedError); <ide> <ide> // invalid address: true <del> assert.throws(() => { <add> common.expectsError(() => { <ide> client.send(buf, port, true); <del> }, common.expectsError(expectedError)); <add> }, expectedError); <ide> }); <ide> <ide> client.unref(); <ide><path>test/parallel/test-dgram-sendto.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> const socket = dgram.createSocket('udp4'); <ide> <ide> const errorMessageOffset = <ide> /^The "offset" argument must be of type number$/; <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> socket.sendto(); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: errorMessageOffset <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> socket.sendto('buffer', 1, 'offset', 'port', 'address', 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "length" argument must be of type number$/ <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> socket.sendto('buffer', 'offset', 1, 'port', 'address', 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: errorMessageOffset <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> socket.sendto('buffer', 1, 1, 10, false, 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "address" argument must be of type string$/ <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> socket.sendto('buffer', 1, 1, false, 'address', 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "port" argument must be of type number$/ <del>})); <add>}); <ide><path>test/parallel/test-dgram-setTTL.js <ide> socket.on('listening', common.mustCall(() => { <ide> const result = socket.setTTL(16); <ide> assert.strictEqual(result, 16); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setTTL('foo'); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "ttl" argument must be of type number. Received type string' <del> })); <add> }); <ide> <ide> // TTL must be a number from > 0 to < 256 <ide> assert.throws(() => { <ide><path>test/parallel/test-dgram-socket-buffer-size.js <ide> const dgram = require('dgram'); <ide> <ide> const socket = dgram.createSocket('udp4'); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setRecvBufferSize(8192); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setSendBufferSize(8192); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.getRecvBufferSize(); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.getSendBufferSize(); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> } <ide> <ide> { <ide> const dgram = require('dgram'); <ide> <ide> socket.bind(common.mustCall(() => { <ide> badBufferSizes.forEach((badBufferSize) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setRecvBufferSize(badBufferSize); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket.setSendBufferSize(badBufferSize); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> }); <ide> socket.close(); <ide> })); <ide> function checkBufferSizeError(type, size) { <ide> 'BufferSize'; <ide> const socket = dgram.createSocket('udp4'); <ide> socket.bind(common.mustCall(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> socket[functionName](size); <del> }, common.expectsError(errorObj)); <add> }, errorObj); <ide> socket.close(); <ide> })); <ide> } <ide><path>test/parallel/test-dns-lookup.js <ide> const dns = require('dns'); <ide> // Stub `getaddrinfo` to *always* error. <ide> cares.getaddrinfo = () => process.binding('uv').UV_ENOENT; <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup(1, {}); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "hostname" argument must be one of type string or falsy/ <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup(false, 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_CALLBACK', <ide> type: TypeError <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup(false, 'options', 'cb'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_CALLBACK', <ide> type: TypeError <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup(false, { <ide> hints: 100, <ide> family: 0, <ide> all: false <ide> }, common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> type: TypeError, <ide> message: 'The value "100" is invalid for option "hints"' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup(false, { <ide> hints: 0, <ide> family: 20, <ide> all: false <ide> }, common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> type: TypeError, <ide> message: 'The value "20" is invalid for option "family"' <del>})); <add>}); <ide> <ide> assert.doesNotThrow(() => { <ide> dns.lookup(false, { <ide><path>test/parallel/test-dns-regress-7070.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const dns = require('dns'); <ide> <ide> // Should not raise assertion error. Issue #7070 <del>assert.throws(() => dns.resolveNs([]), // bad name <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: /^The "name" argument must be of type string/ <del> })); <del>assert.throws(() => dns.resolveNs(''), // bad callback <del> common.expectsError({ <del> code: 'ERR_INVALID_CALLBACK', <del> type: TypeError <del> })); <add>common.expectsError(() => dns.resolveNs([]), // bad name <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: /^The "name" argument must be of type string/ <add> }); <add>common.expectsError(() => dns.resolveNs(''), // bad callback <add> { <add> code: 'ERR_INVALID_CALLBACK', <add> type: TypeError <add> });
10
Python
Python
use the new logging.nullhandler in python 2.7
b784c7912afcab34632bf60b935b929f218c9180
<ide><path>celery/app/log.py <ide> <ide> from logging.handlers import WatchedFileHandler <ide> <del>from kombu.log import NullHandler <ide> from kombu.utils.encoding import set_default_encoding_file <ide> <ide> from celery import signals <ide> def _detect_handler(self, logfile=None): <ide> return WatchedFileHandler(logfile) <ide> <ide> def _has_handler(self, logger): <del> if logger.handlers: <del> return any(not isinstance(h, NullHandler) for h in logger.handlers) <add> return any( <add> not isinstance(h, logging.NullHandler) <add> for h in logger.handlers or [] <add> ) <ide> <ide> def _is_configured(self, logger): <ide> return self._has_handler(logger) and not getattr( <ide><path>celery/tests/case.py <ide> import mock # noqa <ide> from nose import SkipTest <ide> from kombu import Queue <del>from kombu.log import NullHandler <ide> from kombu.utils import symbol_by_name <ide> <ide> from celery import Celery <ide> def teardown(self): <ide> <ide> <ide> def get_handlers(logger): <del> return [h for h in logger.handlers if not isinstance(h, NullHandler)] <add> return [ <add> h for h in logger.handlers <add> if not isinstance(h, logging.NullHandler) <add> ] <ide> <ide> <ide> @contextmanager
2
PHP
PHP
apply fixes from styleci
f185be865a02d147cb2793b419b61786e913a8b4
<ide><path>src/Illuminate/Queue/Queue.php <ide> use Closure; <ide> use DateTimeInterface; <ide> use Illuminate\Container\Container; <del>use Illuminate\Database\DatabaseTransactionManager; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\InteractsWithTime; <ide> use Illuminate\Support\Str;
1
Javascript
Javascript
improve assertion message in dgram test
75d41cf531c19496c854acf65d48d9c8421907bc
<ide><path>test/parallel/test-dgram-send-callback-recursive.js <ide> function onsend() { <ide> if (sent++ < limit) { <ide> client.send(chunk, 0, chunk.length, port, common.localhostIPv4, onsend); <ide> } else { <del> assert.strictEqual(async, true, 'Send should be asynchronous.'); <add> assert.strictEqual(async, true); <ide> } <ide> } <ide>
1
Text
Text
add line break
cd89f6b60268cdf041a06f5120660b80396993cc
<ide><path>.github/ISSUE_TEMPLATE.md <ide> If you're looking for help with your code, consider posting a question on StackO <ide> http://stackoverflow.com/questions/tagged/spacy --> <ide> <ide> <add> <ide> ## Your Environment <ide> <!-- Include details of your environment --> <ide> * **Operating System:**
1
Python
Python
add test for french tokenizer
c09a8ce5bb47db4ea4381925ec07199415ae5c39
<ide><path>spacy/tests/integration/test_load_languages.py <ide> def test_load_french(): <ide> nlp = French() <ide> doc = nlp(u'Parlez-vous français?') <add> assert doc[0].text == u'Parlez' <add> assert doc[1].text == u'-' <add> assert doc[2].text == u'vouz' <add> assert doc[3].text == u'français' <add> assert doc[4].text == u'?'
1
Mixed
Go
move resources from config to hostconfig
837eec064d2d40a4d86acbc6f47fada8263e0d4c
<ide><path>daemon/container.go <ide> func populateCommand(c *Container, env []string) error { <ide> } <ide> <ide> resources := &execdriver.Resources{ <del> Memory: c.Config.Memory, <del> MemorySwap: c.Config.MemorySwap, <del> CpuShares: c.Config.CpuShares, <del> Cpuset: c.Config.Cpuset, <add> Memory: c.hostConfig.Memory, <add> MemorySwap: c.hostConfig.MemorySwap, <add> CpuShares: c.hostConfig.CpuShares, <add> CpusetCpus: c.hostConfig.CpusetCpus, <ide> Rlimits: rlimits, <ide> } <ide> <ide><path>daemon/create.go <ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status { <ide> } else if len(job.Args) > 1 { <ide> return job.Errorf("Usage: %s", job.Name) <ide> } <add> <ide> config := runconfig.ContainerConfigFromJob(job) <del> if config.Memory != 0 && config.Memory < 4194304 { <add> hostConfig := runconfig.ContainerHostConfigFromJob(job) <add> <add> if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 { <ide> return job.Errorf("Minimum memory limit allowed is 4MB") <ide> } <del> if config.Memory > 0 && !daemon.SystemConfig().MemoryLimit { <add> if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit { <ide> job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n") <del> config.Memory = 0 <add> hostConfig.Memory = 0 <ide> } <del> if config.Memory > 0 && !daemon.SystemConfig().SwapLimit { <add> if hostConfig.Memory > 0 && !daemon.SystemConfig().SwapLimit { <ide> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n") <del> config.MemorySwap = -1 <add> hostConfig.MemorySwap = -1 <ide> } <del> if config.Memory > 0 && config.MemorySwap > 0 && config.MemorySwap < config.Memory { <add> if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory { <ide> return job.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.\n") <ide> } <del> if config.Memory == 0 && config.MemorySwap > 0 { <add> if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 { <ide> return job.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.\n") <ide> } <ide> <del> var hostConfig *runconfig.HostConfig <del> if job.EnvExists("HostConfig") { <del> hostConfig = runconfig.ContainerHostConfigFromJob(job) <del> } else { <del> // Older versions of the API don't provide a HostConfig. <del> hostConfig = nil <del> } <del> <ide> container, buildWarnings, err := daemon.Create(config, hostConfig, name) <ide> if err != nil { <ide> if daemon.Graph().IsNotExist(err) { <ide><path>daemon/execdriver/driver.go <ide> type Resources struct { <ide> Memory int64 `json:"memory"` <ide> MemorySwap int64 `json:"memory_swap"` <ide> CpuShares int64 `json:"cpu_shares"` <del> Cpuset string `json:"cpuset"` <add> CpusetCpus string `json:"cpuset_cpus"` <ide> Rlimits []*ulimit.Rlimit `json:"rlimits"` <ide> } <ide> <ide> func SetupCgroups(container *configs.Config, c *Command) error { <ide> container.Cgroups.Memory = c.Resources.Memory <ide> container.Cgroups.MemoryReservation = c.Resources.Memory <ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap <del> container.Cgroups.CpusetCpus = c.Resources.Cpuset <add> container.Cgroups.CpusetCpus = c.Resources.CpusetCpus <ide> } <ide> <ide> return nil <ide><path>daemon/execdriver/lxc/lxc_template.go <ide> lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}} <ide> {{if .Resources.CpuShares}} <ide> lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} <ide> {{end}} <del>{{if .Resources.Cpuset}} <del>lxc.cgroup.cpuset.cpus = {{.Resources.Cpuset}} <add>{{if .Resources.CpusetCpus}} <add>lxc.cgroup.cpuset.cpus = {{.Resources.CpusetCpus}} <ide> {{end}} <ide> {{end}} <ide> <ide><path>docs/man/docker-create.1.md <ide> docker-create - Create a new container <ide> [**--cap-add**[=*[]*]] <ide> [**--cap-drop**[=*[]*]] <ide> [**--cidfile**[=*CIDFILE*]] <del>[**--cpuset**[=*CPUSET*]] <add>[**--cpuset-cpus**[=*CPUSET-CPUS*]] <ide> [**--device**[=*[]*]] <ide> [**--dns-search**[=*[]*]] <ide> [**--dns**[=*[]*]] <ide> IMAGE [COMMAND] [ARG...] <ide> **--cidfile**="" <ide> Write the container ID to the file <ide> <del>**--cpuset**="" <add>**--cpuset-cpus**="" <ide> CPUs in which to allow execution (0-3, 0,1) <ide> <ide> **--device**=[] <ide><path>docs/man/docker-run.1.md <ide> docker-run - Run a command in a new container <ide> [**--cap-add**[=*[]*]] <ide> [**--cap-drop**[=*[]*]] <ide> [**--cidfile**[=*CIDFILE*]] <del>[**--cpuset**[=*CPUSET*]] <add>[**--cpuset-cpus**[=*CPUSET-CPUS*]] <ide> [**-d**|**--detach**[=*false*]] <ide> [**--device**[=*[]*]] <ide> [**--dns-search**[=*[]*]] <ide> division of CPU shares: <ide> **--cidfile**="" <ide> Write the container ID to the file <ide> <del>**--cpuset**="" <add>**--cpuset-cpus**="" <ide> CPUs in which to allow execution (0-3, 0,1) <ide> <ide> **-d**, **--detach**=*true*|*false* <ide><path>docs/sources/reference/api/docker_remote_api_v1.18.md <ide> Create a container <ide> "Hostname": "", <ide> "Domainname": "", <ide> "User": "", <del> "Memory": 0, <del> "MemorySwap": 0, <del> "CpuShares": 512, <del> "Cpuset": "0,1", <ide> "AttachStdin": false, <ide> "AttachStdout": true, <ide> "AttachStderr": true, <ide> Create a container <ide> "Binds": ["/tmp:/tmp"], <ide> "Links": ["redis3:redis"], <ide> "LxcConf": {"lxc.utsname":"docker"}, <add> "Memory": 0, <add> "MemorySwap": 0, <add> "CpuShares": 512, <add> "CpusetCpus": "0,1", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> always use this with `memory`, and make the value larger than `memory`. <ide> - **CpuShares** - An integer value containing the CPU Shares for container <ide> (ie. the relative weight vs othercontainers). <del> **CpuSet** - String value containg the cgroups Cpuset to use. <add>- **Cpuset** - The same as CpusetCpus, but deprecated, please don't use. <add>- **CpusetCpus** - String value containg the cgroups CpusetCpus to use. <ide> - **AttachStdin** - Boolean value, attaches to stdin. <ide> - **AttachStdout** - Boolean value, attaches to stdout. <ide> - **AttachStderr** - Boolean value, attaches to stderr. <ide> Json Parameters: <ide> of strings <ide> - **Image** - String value containing the image name to use for the container <ide> - **Volumes** – An object mapping mountpoint paths (strings) inside the <del> container to empty objects. <add> container to empty objects. <ide> - **WorkingDir** - A string value containing the working dir for commands to <ide> run in. <ide> - **NetworkDisabled** - Boolean value, when true disables neworking for the <ide> Return low-level information on the container `id` <ide> "-c", <ide> "exit 9" <ide> ], <del> "CpuShares": 0, <del> "Cpuset": "", <ide> "Domainname": "", <ide> "Entrypoint": null, <ide> "Env": [ <ide> Return low-level information on the container `id` <ide> "Hostname": "ba033ac44011", <ide> "Image": "ubuntu", <ide> "MacAddress": "", <del> "Memory": 0, <del> "MemorySwap": 0, <ide> "NetworkDisabled": false, <ide> "OnBuild": null, <ide> "OpenStdin": false, <ide> Return low-level information on the container `id` <ide> "CapAdd": null, <ide> "CapDrop": null, <ide> "ContainerIDFile": "", <add> "CpusetCpus": "", <add> "CpuShares": 0, <ide> "Devices": [], <ide> "Dns": null, <ide> "DnsSearch": null, <ide> "ExtraHosts": null, <ide> "IpcMode": "", <ide> "Links": null, <ide> "LxcConf": [], <add> "Memory": 0, <add> "MemorySwap": 0, <ide> "NetworkMode": "bridge", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> Return low-level information on the image `name` <ide> { <ide> "Hostname": "", <ide> "User": "", <del> "Memory": 0, <del> "MemorySwap": 0, <ide> "AttachStdin": false, <ide> "AttachStdout": false, <ide> "AttachStderr": false, <ide> Create a new image from a container's changes <ide> "Hostname": "", <ide> "Domainname": "", <ide> "User": "", <del> "Memory": 0, <del> "MemorySwap": 0, <del> "CpuShares": 512, <del> "Cpuset": "0,1", <ide> "AttachStdin": false, <ide> "AttachStdout": true, <ide> "AttachStderr": true, <ide> Return low-level information about the exec command `id`. <ide> "Hostname" : "8f177a186b97", <ide> "Domainname" : "", <ide> "User" : "", <del> "Memory" : 0, <del> "MemorySwap" : 0, <del> "CpuShares" : 0, <del> "Cpuset" : "", <ide> "AttachStdin" : false, <ide> "AttachStdout" : false, <ide> "AttachStderr" : false, <ide><path>docs/sources/reference/commandline/cli.md <ide> Creates a new container. <ide> --cap-add=[] Add Linux capabilities <ide> --cap-drop=[] Drop Linux capabilities <ide> --cidfile="" Write the container ID to the file <del> --cpuset="" CPUs in which to allow execution (0-3, 0,1) <add> --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) <ide> --device=[] Add a host device to the container <ide> --dns=[] Set custom DNS servers <ide> --dns-search=[] Set custom DNS search domains <ide> removed before the image is removed. <ide> --cap-add=[] Add Linux capabilities <ide> --cap-drop=[] Drop Linux capabilities <ide> --cidfile="" Write the container ID to the file <del> --cpuset="" CPUs in which to allow execution (0-3, 0,1) <add> --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) <ide> -d, --detach=false Run container in background and print container ID <ide> --device=[] Add a host device to the container <ide> --dns=[] Set custom DNS servers <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunWithCpuset(t *testing.T) { <ide> logDone("run - cpuset 0") <ide> } <ide> <add>func TestRunWithCpusetCpus(t *testing.T) { <add> defer deleteAllContainers() <add> <add> cmd := exec.Command(dockerBinary, "run", "--cpuset-cpus", "0", "busybox", "true") <add> if code, err := runCommand(cmd); err != nil || code != 0 { <add> t.Fatalf("container should run successfuly with cpuset-cpus of 0: %s", err) <add> } <add> <add> logDone("run - cpuset-cpus 0") <add>} <add> <ide> func TestRunDeviceNumbers(t *testing.T) { <ide> defer deleteAllContainers() <ide> <ide><path>runconfig/config.go <ide> type Config struct { <ide> Hostname string <ide> Domainname string <ide> User string <del> Memory int64 // Memory limit (in bytes) <del> MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap <del> CpuShares int64 // CPU shares (relative weight vs. other containers) <del> Cpuset string // Cpuset 0-2, 0,1 <add> Memory int64 // FIXME: we keep it for backward compatibility, it has been moved to hostConfig. <add> MemorySwap int64 // FIXME: it has been moved to hostConfig. <add> CpuShares int64 // FIXME: it has been moved to hostConfig. <add> Cpuset string // FIXME: it has been moved to hostConfig and renamed to CpusetCpus. <ide> AttachStdin bool <ide> AttachStdout bool <ide> AttachStderr bool <ide><path>runconfig/hostconfig.go <ide> type HostConfig struct { <ide> Binds []string <ide> ContainerIDFile string <ide> LxcConf []utils.KeyValuePair <add> Memory int64 // Memory limit (in bytes) <add> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap <add> CpuShares int64 // CPU shares (relative weight vs. other containers) <add> CpusetCpus string // CpusetCpus 0-2, 0,1 <ide> Privileged bool <ide> PortBindings nat.PortMap <ide> Links []string <ide> func ContainerHostConfigFromJob(job *engine.Job) *HostConfig { <ide> if job.EnvExists("HostConfig") { <ide> hostConfig := HostConfig{} <ide> job.GetenvJson("HostConfig", &hostConfig) <add> <add> // FIXME: These are for backward compatibility, if people use these <add> // options with `HostConfig`, we should still make them workable. <add> if job.EnvExists("Memory") && hostConfig.Memory == 0 { <add> hostConfig.Memory = job.GetenvInt64("Memory") <add> } <add> if job.EnvExists("MemorySwap") && hostConfig.MemorySwap == 0 { <add> hostConfig.MemorySwap = job.GetenvInt64("MemorySwap") <add> } <add> if job.EnvExists("CpuShares") && hostConfig.CpuShares == 0 { <add> hostConfig.CpuShares = job.GetenvInt64("CpuShares") <add> } <add> if job.EnvExists("Cpuset") && hostConfig.CpusetCpus == "" { <add> hostConfig.CpusetCpus = job.Getenv("Cpuset") <add> } <add> <ide> return &hostConfig <ide> } <ide> <ide> hostConfig := &HostConfig{ <ide> ContainerIDFile: job.Getenv("ContainerIDFile"), <add> Memory: job.GetenvInt64("Memory"), <add> MemorySwap: job.GetenvInt64("MemorySwap"), <add> CpuShares: job.GetenvInt64("CpuShares"), <add> CpusetCpus: job.Getenv("CpusetCpus"), <ide> Privileged: job.GetenvBool("Privileged"), <ide> PublishAllPorts: job.GetenvBool("PublishAllPorts"), <ide> NetworkMode: NetworkMode(job.Getenv("NetworkMode")), <ide> func ContainerHostConfigFromJob(job *engine.Job) *HostConfig { <ide> ReadonlyRootfs: job.GetenvBool("ReadonlyRootfs"), <ide> } <ide> <add> // FIXME: This is for backward compatibility, if people use `Cpuset` <add> // in json, make it workable, we will only pass hostConfig.CpusetCpus <add> // to execDriver. <add> if job.EnvExists("Cpuset") && hostConfig.CpusetCpus == "" { <add> hostConfig.CpusetCpus = job.Getenv("Cpuset") <add> } <add> <ide> job.GetenvJson("LxcConf", &hostConfig.LxcConf) <ide> job.GetenvJson("PortBindings", &hostConfig.PortBindings) <ide> job.GetenvJson("Devices", &hostConfig.Devices) <ide><path>runconfig/parse.go <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: <name|uid>[:<group|gid>])") <ide> flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") <ide> flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") <del> flCpuset = cmd.String([]string{"-cpuset"}, "", "CPUs in which to allow execution (0-3, 0,1)") <add> flCpusetCpus = cmd.String([]string{"#-cpuset", "-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") <ide> flNetMode = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container") <ide> flMacAddress = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)") <ide> flIpcMode = cmd.String([]string{"-ipc"}, "", "IPC namespace to use") <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> Tty: *flTty, <ide> NetworkDisabled: !*flNetwork, <ide> OpenStdin: *flStdin, <del> Memory: flMemory, <del> MemorySwap: MemorySwap, <del> CpuShares: *flCpuShares, <del> Cpuset: *flCpuset, <add> Memory: flMemory, // FIXME: for backward compatibility <add> MemorySwap: MemorySwap, // FIXME: for backward compatibility <add> CpuShares: *flCpuShares, // FIXME: for backward compatibility <add> Cpuset: *flCpusetCpus, // FIXME: for backward compatibility <ide> AttachStdin: attachStdin, <ide> AttachStdout: attachStdout, <ide> AttachStderr: attachStderr, <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> Binds: binds, <ide> ContainerIDFile: *flContainerIDFile, <ide> LxcConf: lxcConf, <add> Memory: flMemory, <add> MemorySwap: MemorySwap, <add> CpuShares: *flCpuShares, <add> CpusetCpus: *flCpusetCpus, <ide> Privileged: *flPrivileged, <ide> PortBindings: portBindings, <ide> Links: flLinks.GetAll(),
12
Text
Text
use consistent capitalization for addons
3e9caaf5051961f640664a138297de11bb5c5c26
<ide><path>doc/api/addons.md <ide> <!--introduced_in=v0.10.0--> <ide> <!-- type=misc --> <ide> <del>Addons are dynamically-linked shared objects written in C++. The <del>[`require()`][require] function can load Addons as ordinary Node.js modules. <add>_Addons_ are dynamically-linked shared objects written in C++. The <add>[`require()`][require] function can load addons as ordinary Node.js modules. <ide> Addons provide an interface between JavaScript and C/C++ libraries. <ide> <del>There are three options for implementing Addons: N-API, nan, or direct <add>There are three options for implementing addons: N-API, nan, or direct <ide> use of internal V8, libuv and Node.js libraries. Unless there is a need for <ide> direct access to functionality which is not exposed by N-API, use N-API. <del>Refer to [C/C++ Addons with N-API](n-api.html) for more information on N-API. <add>Refer to [C/C++ addons with N-API](n-api.html) for more information on N-API. <ide> <del>When not using N-API, implementing Addons is complicated, <add>When not using N-API, implementing addons is complicated, <ide> involving knowledge of several components and APIs: <ide> <ide> * V8: the C++ library Node.js uses to provide the <ide> involving knowledge of several components and APIs: <ide> access across all major operating systems to many common system tasks, such <ide> as interacting with the filesystem, sockets, timers, and system events. libuv <ide> also provides a pthreads-like threading abstraction that may be used to <del> power more sophisticated asynchronous Addons that need to move beyond the <add> power more sophisticated asynchronous addons that need to move beyond the <ide> standard event loop. Addon authors are encouraged to think about how to <ide> avoid blocking the event loop with I/O or other time-intensive tasks by <ide> off-loading work via libuv to non-blocking system operations, worker threads <ide> or a custom use of libuv's threads. <ide> <del>* Internal Node.js libraries. Node.js itself exports C++ APIs that Addons can <add>* Internal Node.js libraries. Node.js itself exports C++ APIs that addons can <ide> use, the most important of which is the `node::ObjectWrap` class. <ide> <ide> * Node.js includes other statically linked libraries including OpenSSL. These <ide> other libraries are located in the `deps/` directory in the Node.js source <ide> tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully <del> re-exported by Node.js and may be used to various extents by Addons. See <add> re-exported by Node.js and may be used to various extents by addons. See <ide> [Linking to libraries included with Node.js][] for additional information. <ide> <ide> All of the following examples are available for [download][] and may <del>be used as the starting-point for an Addon. <add>be used as the starting-point for an addon. <ide> <ide> ## Hello world <ide> <del>This "Hello world" example is a simple Addon, written in C++, that is the <add>This "Hello world" example is a simple addon, written in C++, that is the <ide> equivalent of the following JavaScript code: <ide> <ide> ```js <ide> NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) <ide> } // namespace demo <ide> ``` <ide> <del>All Node.js Addons must export an initialization function following <add>All Node.js addons must export an initialization function following <ide> the pattern: <ide> <ide> ```cpp <ide> Once the source code has been written, it must be compiled into the binary <ide> `addon.node` file. To do so, create a file called `binding.gyp` in the <ide> top-level of the project describing the build configuration of the module <ide> using a JSON-like format. This file is used by [node-gyp][], a tool written <del>specifically to compile Node.js Addons. <add>specifically to compile Node.js addons. <ide> <ide> ```json <ide> { <ide> specifically to compile Node.js Addons. <ide> A version of the `node-gyp` utility is bundled and distributed with <ide> Node.js as part of `npm`. This version is not made directly available for <ide> developers to use and is intended only to support the ability to use the <del>`npm install` command to compile and install Addons. Developers who wish to <add>`npm install` command to compile and install addons. Developers who wish to <ide> use `node-gyp` directly can install it using the command <ide> `npm install -g node-gyp`. See the `node-gyp` [installation instructions][] for <ide> more information, including platform-specific requirements. <ide> will generate either a `Makefile` (on Unix platforms) or a `vcxproj` file <ide> Next, invoke the `node-gyp build` command to generate the compiled `addon.node` <ide> file. This will be put into the `build/Release/` directory. <ide> <del>When using `npm install` to install a Node.js Addon, npm uses its own bundled <add>When using `npm install` to install a Node.js addon, npm uses its own bundled <ide> version of `node-gyp` to perform this same set of actions, generating a <del>compiled version of the Addon for the user's platform on demand. <add>compiled version of the addon for the user's platform on demand. <ide> <del>Once built, the binary Addon can be used from within Node.js by pointing <add>Once built, the binary addon can be used from within Node.js by pointing <ide> [`require()`][require] to the built `addon.node` module: <ide> <ide> ```js <ide> console.log(addon.hello()); <ide> // Prints: 'world' <ide> ``` <ide> <del>Because the exact path to the compiled Addon binary can vary depending on how <del>it is compiled (i.e. sometimes it may be in `./build/Debug/`), Addons can use <add>Because the exact path to the compiled addon binary can vary depending on how <add>it is compiled (i.e. sometimes it may be in `./build/Debug/`), addons can use <ide> the [bindings][] package to load the compiled module. <ide> <ide> While the `bindings` package implementation is more sophisticated in how it <del>locates Addon modules, it is essentially using a `try…catch` pattern similar to: <add>locates addon modules, it is essentially using a `try…catch` pattern similar to: <ide> <ide> ```js <ide> try { <ide> try { <ide> ### Linking to libraries included with Node.js <ide> <ide> Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All <del>Addons are required to link to V8 and may link to any of the other dependencies <add>addons are required to link to V8 and may link to any of the other dependencies <ide> as well. Typically, this is as simple as including the appropriate <ide> `#include <...>` statements (e.g. `#include <v8.h>`) and `node-gyp` will locate <ide> the appropriate headers automatically. However, there are a few caveats to be <ide> aware of: <ide> <ide> * When `node-gyp` runs, it will detect the specific release version of Node.js <ide> and download either the full source tarball or just the headers. If the full <del>source is downloaded, Addons will have complete access to the full set of <add>source is downloaded, addons will have complete access to the full set of <ide> Node.js dependencies. However, if only the Node.js headers are downloaded, then <ide> only the symbols exported by Node.js will be available. <ide> <ide> * `node-gyp` can be run using the `--nodedir` flag pointing at a local Node.js <del>source image. Using this option, the Addon will have access to the full set of <add>source image. Using this option, the addon will have access to the full set of <ide> dependencies. <ide> <ide> ### Loading addons using `require()` <ide> <del>The filename extension of the compiled Addon binary is `.node` (as opposed <add>The filename extension of the compiled addon binary is `.node` (as opposed <ide> to `.dll` or `.so`). The [`require()`][require] function is written to look for <ide> files with the `.node` file extension and initialize those as dynamically-linked <ide> libraries. <ide> <ide> When calling [`require()`][require], the `.node` extension can usually be <del>omitted and Node.js will still find and initialize the Addon. One caveat, <add>omitted and Node.js will still find and initialize the addon. One caveat, <ide> however, is that Node.js will first attempt to locate and load modules or <ide> JavaScript files that happen to share the same base name. For instance, if <ide> there is a file `addon.js` in the same directory as the binary `addon.node`, <ide> and load it instead. <ide> ## Native abstractions for Node.js <ide> <ide> Each of the examples illustrated in this document make direct use of the <del>Node.js and V8 APIs for implementing Addons. The V8 API can, and has, changed <add>Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed <ide> dramatically from one V8 release to the next (and one major Node.js release to <del>the next). With each change, Addons may need to be updated and recompiled in <add>the next). With each change, addons may need to be updated and recompiled in <ide> order to continue functioning. The Node.js release schedule is designed to <ide> minimize the frequency and impact of such changes but there is little that <ide> Node.js can do to ensure stability of the V8 APIs. <ide> <ide> The [Native Abstractions for Node.js][] (or `nan`) provide a set of tools that <del>Addon developers are recommended to use to keep compatibility between past and <add>addon developers are recommended to use to keep compatibility between past and <ide> future releases of V8 and Node.js. See the `nan` [examples][] for an <ide> illustration of how it can be used. <ide> <ide> ## N-API <ide> <ide> > Stability: 2 - Stable <ide> <del>N-API is an API for building native Addons. It is independent from <add>N-API is an API for building native addons. It is independent from <ide> the underlying JavaScript runtime (e.g. V8) and is maintained as part of <ide> Node.js itself. This API will be Application Binary Interface (ABI) stable <del>across versions of Node.js. It is intended to insulate Addons from <add>across versions of Node.js. It is intended to insulate addons from <ide> changes in the underlying JavaScript engine and allow modules <ide> compiled for one version to run on later versions of Node.js without <ide> recompilation. Addons are built/packaged with the same approach/tools <ide> NAPI_MODULE(NODE_GYP_MODULE_NAME, init) <ide> ``` <ide> <ide> The functions available and how to use them are documented in <del>[C/C++ Addons with N-API](n-api.html). <add>[C/C++ addons with N-API](n-api.html). <ide> <ide> ## Addon examples <ide> <del>Following are some example Addons intended to help developers get started. The <add>Following are some example addons intended to help developers get started. The <ide> examples make use of the V8 APIs. Refer to the online [V8 reference][v8-docs] <ide> for help with the various V8 calls, and V8's [Embedder's Guide][] for an <ide> explanation of several concepts used such as handles, scopes, function <ide> filename to the `sources` array: <ide> "sources": ["addon.cc", "myexample.cc"] <ide> ``` <ide> <del>Once the `binding.gyp` file is ready, the example Addons can be configured and <add>Once the `binding.gyp` file is ready, the example addons can be configured and <ide> built using `node-gyp`: <ide> <ide> ```console <ide> NODE_MODULE(NODE_GYP_MODULE_NAME, Init) <ide> } // namespace demo <ide> ``` <ide> <del>Once compiled, the example Addon can be required and used from within Node.js: <add>Once compiled, the example addon can be required and used from within Node.js: <ide> <ide> ```js <ide> // test.js <ide> console.log('This should be eight:', addon.add(3, 5)); <ide> <ide> ### Callbacks <ide> <del>It is common practice within Addons to pass JavaScript functions to a C++ <add>It is common practice within addons to pass JavaScript functions to a C++ <ide> function and execute them from there. The following example illustrates how <ide> to invoke such callbacks: <ide> <ide> NODE_MODULE(NODE_GYP_MODULE_NAME, Init) <ide> ``` <ide> <ide> This example uses a two-argument form of `Init()` that receives the full <del>`module` object as the second argument. This allows the Addon to completely <add>`module` object as the second argument. This allows the addon to completely <ide> overwrite `exports` with a single function instead of adding the function as a <ide> property of `exports`. <ide>
1
Ruby
Ruby
improve documentation comments
c936a9420eed710d955346cbfb76140a24d1b551
<ide><path>Library/Homebrew/livecheck/strategy.rb <ide> module Strategy <ide> <ide> module_function <ide> <del> # Strategy priorities informally range from 1 to 10, where 10 is the <add> # {Strategy} priorities informally range from 1 to 10, where 10 is the <ide> # highest priority. 5 is the default priority because it's roughly in <ide> # the middle of this range. Strategies with a priority of 0 (or lower) <ide> # are ignored. <ide> module Strategy <ide> # The `curl` process will sometimes hang indefinitely (despite setting <ide> # the `--max-time` argument) and it needs to be quit for livecheck to <ide> # continue. This value is used to set the `timeout` argument on <del> # `Utils::Curl` method calls in `Strategy`. <add> # `Utils::Curl` method calls in {Strategy}. <ide> CURL_PROCESS_TIMEOUT = CURL_MAX_TIME + 5 <ide> <del> # Baseline `curl` arguments used in `Strategy` methods. <add> # Baseline `curl` arguments used in {Strategy} methods. <ide> DEFAULT_CURL_ARGS = [ <ide> # Follow redirections to handle mirrors, relocations, etc. <ide> "--location", <ide> module Strategy <ide> "--include", <ide> ] + DEFAULT_CURL_ARGS).freeze <ide> <del> # Baseline `curl` options used in `Strategy` methods. <add> # Baseline `curl` options used in {Strategy} methods. <ide> DEFAULT_CURL_OPTIONS = { <ide> print_stdout: false, <ide> print_stderr: false, <ide> module Strategy <ide> <ide> # Creates and/or returns a `@strategies` `Hash`, which maps a snake <ide> # case strategy name symbol (e.g. `:page_match`) to the associated <del> # {Strategy}. <add> # strategy. <ide> # <ide> # At present, this should only be called after tap strategies have been <ide> # loaded, otherwise livecheck won't be able to use them. <ide> def strategies <ide> end <ide> private_class_method :strategies <ide> <del> # Returns the {Strategy} that corresponds to the provided `Symbol` (or <del> # `nil` if there is no matching {Strategy}). <add> # Returns the strategy that corresponds to the provided `Symbol` (or <add> # `nil` if there is no matching strategy). <ide> # <del> # @param symbol [Symbol] the strategy name in snake case as a `Symbol` <del> # (e.g. `:page_match`) <del> # @return [Strategy, nil] <add> # @param symbol [Symbol, nil] the strategy name in snake case as a <add> # `Symbol` (e.g. `:page_match`) <add> # @return [Class, nil] <ide> sig { params(symbol: T.nilable(Symbol)).returns(T.nilable(T.untyped)) } <ide> def from_symbol(symbol) <ide> strategies[symbol] if symbol.present? <ide> def from_symbol(symbol) <ide> # Returns an array of strategies that apply to the provided URL. <ide> # <ide> # @param url [String] the URL to check for matching strategies <del> # @param livecheck_strategy [Symbol] a {Strategy} symbol from the <add> # @param livecheck_strategy [Symbol] a strategy symbol from the <add> # `livecheck` block <add> # @param url_provided [Boolean] whether a url is provided in the <ide> # `livecheck` block <ide> # @param regex_provided [Boolean] whether a regex is provided in the <ide> # `livecheck` block <add> # @param block_provided [Boolean] whether a `strategy` block is provided <add> # in the `livecheck` block <ide> # @return [Array] <ide> sig { <ide> params( <ide> def from_url(url, livecheck_strategy: nil, url_provided: false, regex_provided: <ide> end <ide> end <ide> <add> # Collects HTTP response headers, starting with the provided URL. <add> # Redirections will be followed and all the response headers are <add> # collected into an array of hashes. <add> # <add> # @param url [String] the URL to fetch <add> # @return [Array] <ide> sig { params(url: String).returns(T::Array[T::Hash[String, String]]) } <ide> def self.page_headers(url) <ide> headers = [] <ide><path>Library/Homebrew/livecheck/strategy/electron_builder.rb <ide> module Strategy <ide> # The {ElectronBuilder} strategy fetches content at a URL and parses <ide> # it as an electron-builder appcast in YAML format. <ide> # <add> # This strategy is not applied automatically and it's necessary to use <add> # `strategy :electron_builder` in a `livecheck` block to apply it. <add> # <ide> # @api private <ide> class ElectronBuilder <ide> extend T::Sig <ide> <ide> NICE_NAME = "electron-builder" <ide> <ide> # A priority of zero causes livecheck to skip the strategy. We do this <del> # for {ElectronBuilder} so we can selectively apply the strategy using <del> # `strategy :electron_builder` in a `livecheck` block. <add> # for {ElectronBuilder} so we can selectively apply it when appropriate. <ide> PRIORITY = 0 <ide> <ide> # The `Regexp` used to determine if the strategy applies to the URL. <ide> def self.versions_from_content(content, &block) <ide> version.present? ? [version] : [] <ide> end <ide> <del> # Checks the content at the URL for new versions. <add> # Checks the YAML content at the URL for new versions. <ide> # <ide> # @param url [String] the URL of the content to check <del> # @param regex [Regexp] a regex used for matching versions in content <add> # @param regex [Regexp, nil] a regex used for matching versions <ide> # @return [Hash] <ide> sig { <ide> params( <ide><path>Library/Homebrew/livecheck/strategy/extract_plist.rb <ide> module Homebrew <ide> module Livecheck <ide> module Strategy <del> # The {ExtractPlist} strategy downloads the file at a URL and <del> # extracts versions from contained `.plist` files. <add> # The {ExtractPlist} strategy downloads the file at a URL and extracts <add> # versions from contained `.plist` files using {UnversionedCaskChecker}. <add> # <add> # In practice, this strategy operates by downloading very large files, <add> # so it's both slow and data-intensive. As such, the {ExtractPlist} <add> # strategy should only be used as an absolute last resort. <add> # <add> # This strategy is not applied automatically and it's necessary to use <add> # `strategy :extract_plist` in a `livecheck` block to apply it. <ide> # <ide> # @api private <ide> class ExtractPlist <ide> extend T::Sig <ide> <del> # A priority of zero causes livecheck to skip the strategy. We only <del> # apply {ExtractPlist} using `strategy :extract_plist` in a `livecheck` block, <del> # as we can't automatically determine when this can be successfully <del> # applied to a URL without fetching the content. <add> # A priority of zero causes livecheck to skip the strategy. We do this <add> # for {ExtractPlist} so we can selectively apply it when appropriate. <ide> PRIORITY = 0 <ide> <ide> # The `Regexp` used to determine if the strategy applies to the URL. <ide> URL_MATCH_REGEX = %r{^https?://}i.freeze <ide> <ide> # Whether the strategy can be applied to the provided URL. <del> # The strategy will technically match any HTTP URL but is <del> # only usable with a `livecheck` block containing a regex <del> # or block. <add> # <add> # @param url [String] the URL to match against <add> # @return [Boolean] <ide> sig { params(url: String).returns(T::Boolean) } <ide> def self.match?(url) <ide> URL_MATCH_REGEX.match?(url) <ide><path>Library/Homebrew/livecheck/strategy/git.rb <ide> def self.versions_from_tags(tags, regex = nil, &block) <ide> # strings and parses the remaining text as a {Version}. <ide> # <ide> # @param url [String] the URL of the Git repository to check <del> # @param regex [Regexp] the regex to use for matching versions <add> # @param regex [Regexp, nil] a regex used for matching versions <ide> # @return [Hash] <ide> sig { <ide> params( <ide><path>Library/Homebrew/livecheck/strategy/header_match.rb <ide> module Strategy <ide> # The {HeaderMatch} strategy follows all URL redirections and scans <ide> # the resulting headers for matching text using the provided regex. <ide> # <add> # This strategy is not applied automatically and it's necessary to use <add> # `strategy :header_match` in a `livecheck` block to apply it. <add> # <ide> # @api private <ide> class HeaderMatch <ide> extend T::Sig <ide> <ide> NICE_NAME = "Header match" <ide> <del> # A priority of zero causes livecheck to skip the strategy. We only <del> # apply {HeaderMatch} using `strategy :header_match` in a `livecheck` <del> # block, as we can't automatically determine when this can be <del> # successfully applied to a URL. <add> # A priority of zero causes livecheck to skip the strategy. We do this <add> # for {HeaderMatch} so we can selectively apply it when appropriate. <ide> PRIORITY = 0 <ide> <ide> # The `Regexp` used to determine if the strategy applies to the URL. <ide> class HeaderMatch <ide> DEFAULT_HEADERS_TO_CHECK = ["content-disposition", "location"].freeze <ide> <ide> # Whether the strategy can be applied to the provided URL. <del> # The strategy will technically match any HTTP URL but is <del> # only usable with a `livecheck` block containing a regex <del> # or block. <add> # <add> # @param url [String] the URL to match against <add> # @return [Boolean] <ide> sig { params(url: String).returns(T::Boolean) } <ide> def self.match?(url) <ide> URL_MATCH_REGEX.match?(url) <ide> def self.match?(url) <ide> # Identify versions from HTTP headers. <ide> # <ide> # @param headers [Hash] a hash of HTTP headers to check for versions <del> # @param regex [Regexp, nil] a regex to use to identify versions <add> # @param regex [Regexp, nil] a regex for matching versions <ide> # @return [Array] <ide> sig { <ide> params( <ide> def self.versions_from_headers(headers, regex = nil, &block) <ide> <ide> # Checks the final URL for new versions after following all redirections, <ide> # using the provided regex for matching. <add> # <add> # @param url [String] the URL to fetch <add> # @param regex [Regexp, nil] a regex used for matching versions <add> # @return [Hash] <ide> sig { <ide> params( <ide> url: String, <ide><path>Library/Homebrew/livecheck/strategy/page_match.rb <ide> module Strategy <ide> # strategies apply to a given URL. Though {PageMatch} will technically <ide> # match any HTTP URL, the strategy also requires a regex to function. <ide> # <del> # The {find_versions} method is also used within other <del> # strategies, to handle the process of identifying version text in <del> # content. <add> # The {find_versions} method is also used within other strategies, <add> # to handle the process of identifying version text in content. <ide> # <ide> # @api public <ide> class PageMatch <ide> class PageMatch <ide> NICE_NAME = "Page match" <ide> <ide> # A priority of zero causes livecheck to skip the strategy. We do this <del> # for PageMatch so we can selectively apply the strategy only when a <del> # regex is provided in a `livecheck` block. <add> # for {PageMatch} so we can selectively apply it only when a regex is <add> # provided in a `livecheck` block. <ide> PRIORITY = 0 <ide> <ide> # The `Regexp` used to determine if the strategy applies to the URL. <ide> URL_MATCH_REGEX = %r{^https?://}i.freeze <ide> <ide> # Whether the strategy can be applied to the provided URL. <del> # PageMatch will technically match any HTTP URL but is only <add> # {PageMatch} will technically match any HTTP URL but is only <ide> # usable with a `livecheck` block containing a regex. <add> # <add> # @param url [String] the URL to match against <add> # @return [Boolean] <ide> sig { params(url: String).returns(T::Boolean) } <ide> def self.match?(url) <ide> URL_MATCH_REGEX.match?(url) <ide> def self.versions_from_content(content, regex, &block) <ide> # regex for matching. <ide> # <ide> # @param url [String] the URL of the content to check <del> # @param regex [Regexp] a regex used for matching versions in content <del> # @param provided_content [String] page content to use in place of <add> # @param regex [Regexp] a regex used for matching versions <add> # @param provided_content [String, nil] page content to use in place of <ide> # fetching via Strategy#page_content <ide> # @return [Hash] <ide> sig { <ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> module Strategy <ide> # The {Sparkle} strategy fetches content at a URL and parses <ide> # it as a Sparkle appcast in XML format. <ide> # <add> # This strategy is not applied automatically and it's necessary to use <add> # `strategy :sparkle` in a `livecheck` block to apply it. <add> # <ide> # @api private <ide> class Sparkle <ide> extend T::Sig <ide> <del> # A priority of zero causes livecheck to skip the strategy. We only <del> # apply {Sparkle} using `strategy :sparkle` in a `livecheck` block, <del> # as we can't automatically determine when this can be successfully <del> # applied to a URL without fetching the content. <add> # A priority of zero causes livecheck to skip the strategy. We do this <add> # for {Sparkle} so we can selectively apply it when appropriate. <ide> PRIORITY = 0 <ide> <ide> # The `Regexp` used to determine if the strategy applies to the URL. <ide> URL_MATCH_REGEX = %r{^https?://}i.freeze <ide> <ide> # Whether the strategy can be applied to the provided URL. <del> # The strategy will technically match any HTTP URL but is <del> # only usable with a `livecheck` block containing a regex <del> # or block. <add> # <add> # @param url [String] the URL to match against <add> # @return [Boolean] <ide> sig { params(url: String).returns(T::Boolean) } <ide> def self.match?(url) <ide> URL_MATCH_REGEX.match?(url) <ide> def self.match?(url) <ide> delegate short_version: :bundle_version <ide> end <ide> <add> # Identify version information from a Sparkle appcast. <add> # <add> # @param content [String] the text of the Sparkle appcast <add> # @return [Item, nil] <ide> sig { params(content: String).returns(T.nilable(Item)) } <ide> def self.item_from_content(content) <ide> require "rexml/document"
7
Javascript
Javascript
add bigint to globals
bf1238498844645cef022b13989176d975ecfefd
<ide><path>.eslintrc.js <ide> module.exports = { <ide> 'node-core/no-unescaped-regexp-dot': 'error', <ide> }, <ide> globals: { <add> BigInt: false, <ide> COUNTER_HTTP_CLIENT_REQUEST: false, <ide> COUNTER_HTTP_CLIENT_RESPONSE: false, <ide> COUNTER_HTTP_SERVER_REQUEST: false, <ide><path>lib/internal/fs/utils.js <ide> Stats.prototype._checkModeProperty = function(property) { <ide> return false; // Some types are not available on Windows <ide> } <ide> if (typeof this.mode === 'bigint') { // eslint-disable-line valid-typeof <del> // eslint-disable-next-line no-undef <ide> return (this.mode & BigInt(S_IFMT)) === BigInt(property); <ide> } <ide> return (this.mode & S_IFMT) === property; <ide><path>test/parallel/test-fs-stat-bigint.js <ide> function verifyStats(bigintStats, numStats) { <ide> `difference of ${key}.getTime() should < 2.\n` + <ide> `Number version ${time}, BigInt version ${time2}n`); <ide> } else if (key === 'mode') { <del> // eslint-disable-next-line no-undef <ide> assert.strictEqual(bigintStats[key], BigInt(val)); <ide> assert.strictEqual( <ide> bigintStats.isBlockDevice(), <ide> function verifyStats(bigintStats, numStats) { <ide> assert.strictEqual(bigintStats[key], undefined); <ide> assert.strictEqual(numStats[key], undefined); <ide> } else if (Number.isSafeInteger(val)) { <del> // eslint-disable-next-line no-undef <ide> assert.strictEqual(bigintStats[key], BigInt(val)); <ide> } else { <ide> assert(
3
Text
Text
adjust colour description to images
4906a6726b6a234f13af0dcf59869beb69b979c5
<ide><path>client/src/pages/guide/english/css/css3-gradients/index.md <ide> To create a linear gradient you must define at least two color stops. Color stop <ide> background: linear-gradient(direction, color-stop1, color-stop2, ...); <ide> <ide> ##### Linear Gradient - Top to Bottom (this is default) <del>The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow: <add>The following example shows a linear gradient that starts at the top. It starts red, transitioning to green: <ide> ![default-linear-gradient](https://i.imgur.com/2uGfleD.jpg) <ide> <ide> #### Example <ide> The following example shows a linear gradient that starts at the top. It starts <ide> <body> <ide> <ide> <h3>Linear Gradient - Top to Bottom</h3> <del><p>This linear gradient starts at the top. It starts red, transitioning to yellow:</p> <add><p>This linear gradient starts at the top. It starts red, transitioning to green:</p> <ide> <ide> <div id="grad1"></div> <ide> <ide> The following example shows a linear gradient that starts at the top. It starts <ide> ![default-linear-gradient](https://i.imgur.com/CvtXCMd.jpg) <ide> <ide> ##### Linear Gradient - Left to Right <del>The following example shows a linear gradient that starts from the left. It starts red, transitioning to yellow: <add>The following example shows a linear gradient that starts from the left. It starts red, transitioning to green: <ide> ![left-to-right](https://i.imgur.com/e4dRvZR.jpg) <ide> <ide> #### Example <ide> The following example shows a linear gradient that starts from the left. It star <ide> <body> <ide> <ide> <h3>Linear Gradient - Left to Right</h3> <del><p>This linear gradient starts at the left. It starts red, transitioning to yellow:</p> <add><p>This linear gradient starts at the left. It starts red, transitioning to green:</p> <ide> <ide> <div id="grad1"></div> <ide> <ide> The following example shows a linear gradient that starts from the left. It star <ide> <ide> You can make a gradient diagonally by specifying both the horizontal and vertical starting positions. <ide> <del>The following example shows a linear gradient that starts at top left (and goes to bottom right). It starts red, transitioning to yellow: <add>The following example shows a linear gradient that starts at top left (and goes to bottom right). It starts red, transitioning to green: <ide> <ide> ![diagonal](https://i.imgur.com/YvtbUBH.jpg) <ide> <ide> The following example shows a linear gradient that starts at top left (and goes <ide> <body> <ide> <ide> <h3>Linear Gradient - Diagonal</h3> <del><p>This linear gradient starts at top left. It starts red, transitioning to yellow:</p> <add><p>This linear gradient starts at top left. It starts red, transitioning to green:</p> <ide> <ide> <div id="grad1"></div> <ide> <ide> The following example shows a linear gradient that starts at top left (and goes <ide> <ide> #### More Information: <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <del>[MDN Documentatiion](https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient) || [w3schools](https://www.w3schools.com/css/css3_gradients.asp) <ide>\ No newline at end of file <add>- [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient) <add>- [W3Schools](https://www.w3schools.com/css/css3_gradients.asp) <add>- [CSS Tricks](https://css-tricks.com/snippets/css/css-linear-gradient/)
1
Javascript
Javascript
add backslash to path test for windows paths
83c6de01444b046095aaf4ac9fdeee6dc031acb0
<ide><path>curriculum/getChallenges.js <ide> Trying to parse ${fullPath}`); <ide> exports.createChallenge = createChallenge; <ide> <ide> function getEnglishPath(fullPath) { <del> const posix = path.posix.normalize(fullPath); <add> const posix = path <add> .normalize(fullPath) <add> .split(path.sep) <add> .join(path.posix.sep); <ide> const match = posix.match(/(.*curriculum\/challenges\/)([^/]*)(.*)(\2)(.*)/); <ide> const lang = getChallengeLang(fullPath); <ide> if (!isAcceptedLanguage(lang))
1
Ruby
Ruby
remove unused block parameters
1e784cb386d921127ad67ee5fe4bf6768567ccaf
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def setup_subscriptions <ide> @_layouts = Hash.new(0) <ide> @_files = Hash.new(0) <ide> <del> ActiveSupport::Notifications.subscribe("render_template.action_view") do |name, start, finish, id, payload| <add> ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload| <ide> path = payload[:layout] <ide> if path <ide> @_layouts[path] += 1 <ide> def setup_subscriptions <ide> end <ide> end <ide> <del> ActiveSupport::Notifications.subscribe("!render_template.action_view") do |name, start, finish, id, payload| <add> ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload| <ide> path = payload[:virtual_path] <ide> next unless path <ide> partial = path =~ /^.*\/_[^\/]*$/ <ide> def setup_subscriptions <ide> @_templates[path] += 1 <ide> end <ide> <del> ActiveSupport::Notifications.subscribe("!render_template.action_view") do |name, start, finish, id, payload| <add> ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload| <ide> next if payload[:virtual_path] # files don't have virtual path <ide> <ide> path = payload[:identifier]
1
Javascript
Javascript
remove validateopts for server class
446995306a9f6fe7628aa9d39c0ad148cddb6c5e
<ide><path>packager/react-packager/react-packager.js <ide> exports.createServer = createServer; <ide> exports.Logger = Logger; <ide> <ide> type Options = { <add> nonPersistent: boolean, <add> projectRoots: Array<string>, <ide> reporter?: Reporter, <ide> watch?: boolean, <del> nonPersistent: boolean, <ide> }; <ide> <ide> exports.buildBundle = function(options: Options, bundleOptions: {}) { <ide><path>packager/react-packager/src/Bundler/index.js <ide> type Options = { <ide> allowBundleUpdates: boolean, <ide> assetExts: Array<string>, <ide> assetServer: AssetServer, <del> blacklistRE: RegExp, <add> blacklistRE?: RegExp, <ide> cacheVersion: string, <ide> extraNodeModules: {}, <ide> getTransformOptions?: GetTransformOptions<*>, <ide> type Options = { <ide> projectRoots: Array<string>, <ide> reporter: Reporter, <ide> resetCache: boolean, <del> transformModulePath: string, <add> transformModulePath?: string, <ide> transformTimeoutInterval: ?number, <ide> watch: boolean, <ide> }; <ide><path>packager/react-packager/src/Server/index.js <ide> import type {IncomingMessage, ServerResponse} from 'http'; <ide> import type ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse'; <ide> import type Bundle from '../Bundler/Bundle'; <ide> import type {Reporter} from '../lib/reporting'; <add>import type {GetTransformOptions} from '../Bundler'; <ide> <ide> const { <ide> createActionStartEntry, <ide> function debounceAndBatch(fn, delay) { <ide> }; <ide> } <ide> <del>const validateOpts = declareOpts({ <del> projectRoots: { <del> type: 'array', <del> required: true, <del> }, <del> blacklistRE: { <del> type: 'object', // typeof regex is object <del> }, <del> moduleFormat: { <del> type: 'string', <del> default: 'haste', <del> }, <del> polyfillModuleNames: { <del> type: 'array', <del> default: [], <del> }, <del> cacheVersion: { <del> type: 'string', <del> default: '1.0', <del> }, <del> resetCache: { <del> type: 'boolean', <del> default: false, <del> }, <del> transformModulePath: { <del> type: 'string', <del> required: false, <del> }, <del> extraNodeModules: { <del> type: 'object', <del> required: false, <del> }, <del> watch: { <del> type: 'boolean', <del> default: false, <del> }, <del> assetExts: { <del> type: 'array', <del> default: defaults.assetExts, <del> }, <del> platforms: { <del> type: 'array', <del> default: defaults.platforms, <del> }, <del> transformTimeoutInterval: { <del> type: 'number', <del> required: false, <del> }, <del> getTransformOptions: { <del> type: 'function', <del> required: false, <del> }, <del> silent: { <del> type: 'boolean', <del> default: false, <del> }, <del> reporter: { <del> type: 'object', <del> }, <del>}); <add>type Options = { <add> assetExts?: Array<string>, <add> blacklistRE?: RegExp, <add> cacheVersion?: string, <add> extraNodeModules?: {}, <add> getTransformOptions?: GetTransformOptions<*>, <add> moduleFormat?: string, <add> platforms?: Array<string>, <add> polyfillModuleNames?: Array<string>, <add> projectRoots: Array<string>, <add> reporter: Reporter, <add> resetCache?: boolean, <add> silent?: boolean, <add> transformModulePath?: string, <add> transformTimeoutInterval?: number, <add> watch?: boolean, <add>}; <ide> <ide> const bundleOpts = declareOpts({ <ide> sourceMapUrl: { <ide> const NODE_MODULES = `${path.sep}node_modules${path.sep}`; <ide> class Server { <ide> <ide> _opts: { <add> assetExts: Array<string>, <add> blacklistRE: ?RegExp, <add> cacheVersion: string, <add> extraNodeModules: {}, <add> getTransformOptions?: GetTransformOptions<*>, <add> moduleFormat: string, <add> platforms: Array<string>, <add> polyfillModuleNames: Array<string>, <ide> projectRoots: Array<string>, <add> reporter: Reporter, <add> resetCache: boolean, <add> silent: boolean, <add> transformModulePath: ?string, <add> transformTimeoutInterval: ?number, <ide> watch: boolean, <ide> }; <ide> _projectRoots: Array<string>; <ide> class Server { <ide> _hmrFileChangeListener: (type: string, filePath: string) => mixed; <ide> _reporter: Reporter; <ide> <del> constructor(options: { <del> reporter: Reporter, <del> watch?: boolean, <del> }) { <del> const opts = this._opts = validateOpts(options); <add> constructor(options: Options) { <add> this._opts = { <add> assetExts: options.assetExts || defaults.assetExts, <add> blacklistRE: options.blacklistRE, <add> cacheVersion: options.cacheVersion || '1.0', <add> extraNodeModules: options.extraNodeModules || {}, <add> getTransformOptions: options.getTransformOptions, <add> moduleFormat: options.moduleFormat != null ? options.moduleFormat : 'haste', <add> platforms: options.platforms || defaults.platforms, <add> polyfillModuleNames: options.polyfillModuleNames || [], <add> projectRoots: options.projectRoots, <add> reporter: options.reporter, <add> resetCache: options.resetCache || false, <add> silent: options.silent || false, <add> transformModulePath: options.transformModulePath, <add> transformTimeoutInterval: options.transformTimeoutInterval, <add> watch: options.watch || false, <add> }; <ide> const processFileChange = <ide> ({type, filePath, stat}) => this.onFileChange(type, filePath, stat); <ide> <ide> this._reporter = options.reporter; <del> this._projectRoots = opts.projectRoots; <add> this._projectRoots = this._opts.projectRoots; <ide> this._bundles = Object.create(null); <ide> this._changeWatchers = []; <ide> this._fileChangeListeners = []; <ide> <ide> this._assetServer = new AssetServer({ <del> assetExts: opts.assetExts, <del> projectRoots: opts.projectRoots, <add> assetExts: this._opts.assetExts, <add> projectRoots: this._opts.projectRoots, <ide> }); <ide> <del> const bundlerOpts = Object.create(opts); <add> const bundlerOpts = Object.create(this._opts); <ide> bundlerOpts.assetServer = this._assetServer; <del> bundlerOpts.allowBundleUpdates = options.watch; <del> bundlerOpts.watch = options.watch; <add> bundlerOpts.allowBundleUpdates = this._opts.watch; <add> bundlerOpts.watch = this._opts.watch; <ide> bundlerOpts.reporter = options.reporter; <ide> this._bundler = new Bundler(bundlerOpts); <ide>
3
PHP
PHP
change method names and vars
ea9b2832d557805cafeecc879a5192b3d5997b04
<ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php <ide> protected function getConfigurationFiles(Application $app) <ide> $configPath = realpath($app->configPath()); <ide> <ide> foreach (Finder::create()->files()->name('*.php')->in($configPath) as $file) { <del> $nesting = $this->getConfigurationNesting($file, $configPath); <add> $directory = $this->getNestedDirectory($file, $configPath); <ide> <del> $files[$nesting.basename($file->getRealPath(), '.php')] = $file->getRealPath(); <add> $files[$directory.basename($file->getRealPath(), '.php')] = $file->getRealPath(); <ide> } <ide> <ide> return $files; <ide> protected function getConfigurationFiles(Application $app) <ide> * @param string $configPath <ide> * @return string <ide> */ <del> protected function getConfigurationNesting(SplFileInfo $file, $configPath) <add> protected function getNestedDirectory(SplFileInfo $file, $configPath) <ide> { <ide> $directory = $file->getPath(); <ide> <del> if ($tree = trim(str_replace($configPath, '', $directory), DIRECTORY_SEPARATOR)) { <del> $tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree).'.'; <add> if ($nested = trim(str_replace($configPath, '', $directory), DIRECTORY_SEPARATOR)) { <add> $nested = str_replace(DIRECTORY_SEPARATOR, '.', $nested).'.'; <ide> } <ide> <del> return $tree; <add> return $nested; <ide> } <ide> }
1
Text
Text
fix syntax highlighting [ci-skip]
f3f36e7ef74d169caf7fa1d1f1e14422758901e1
<ide><path>guides/source/2_3_release_notes.md <ide> grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], <ide> <ide> returns <ide> <del>```ruby <add>```html <ide> <option value="">Choose a product...</option> <ide> <optgroup label="Hats"> <ide> <option value="Baseball Cap">Baseball Cap</option> <ide><path>guides/source/5_1_release_notes.md <ide> Secrets will be decrypted in production, using a key stored either in the <ide> Allows specifying common parameters used for all methods in a mailer class in <ide> order to share instance variables, headers, and other common setup. <ide> <del>``` ruby <add>```ruby <ide> class InvitationsMailer < ApplicationMailer <ide> before_action { @inviter, @invitee = params[:inviter], params[:invitee] } <ide> before_action { @account = params[:inviter].account } <ide> InvitationsMailer.with(inviter: person_a, invitee: person_b) <ide> Rails 5.1 adds two new methods, `resolve` and `direct`, to the routing <ide> DSL. The `resolve` method allows customizing polymorphic mapping of models. <ide> <del>``` ruby <add>```ruby <ide> resource :basket <ide> <ide> resolve("Basket") { [:basket] } <ide> ``` <ide> <del>``` erb <add>```erb <ide> <%= form_for @basket do |form| %> <ide> <!-- basket form --> <ide> <% end %> <ide> This will generate the singular URL `/basket` instead of the usual `/baskets/:id <ide> <ide> The `direct` method allows creation of custom URL helpers. <ide> <del>``` ruby <add>```ruby <ide> direct(:homepage) { "http://www.rubyonrails.org" } <ide> <ide> homepage_url # => "http://www.rubyonrails.org" <ide> The return value of the block must be a valid argument for the `url_for` <ide> method. So, you can pass a valid string URL, Hash, Array, an <ide> Active Model instance, or an Active Model class. <ide> <del>``` ruby <add>```ruby <ide> direct :commentable do |model| <ide> [ model, anchor: model.dom_id ] <ide> end <ide> can generate form tags based on URLs, scopes, or models. <ide> <ide> Using just a URL: <ide> <del>``` erb <add>```erb <ide> <%= form_with url: posts_path do |form| %> <ide> <%= form.text_field :title %> <ide> <% end %> <ide> Using just a URL: <ide> <ide> Adding a scope prefixes the input field names: <ide> <del>``` erb <add>```erb <ide> <%= form_with scope: :post, url: posts_path do |form| %> <ide> <%= form.text_field :title %> <ide> <% end %> <ide> Adding a scope prefixes the input field names: <ide> <ide> Using a model infers both the URL and scope: <ide> <del>``` erb <add>```erb <ide> <%= form_with model: Post.new do |form| %> <ide> <%= form.text_field :title %> <ide> <% end %> <ide> Using a model infers both the URL and scope: <ide> <ide> An existing model makes an update form and fills out field values: <ide> <del>``` erb <add>```erb <ide> <%= form_with model: Post.first do |form| %> <ide> <%= form.text_field :title %> <ide> <% end %> <ide><path>guides/source/6_1_release_notes.md <ide> Please refer to the [Changelog][active-record] for detailed changes. <ide> <ide> Before: <ide> <del> User.where(name: "John").create do |john| <del> User.find_by(name: "David") # => nil <del> end <add> ```ruby <add> User.where(name: "John").create do |john| <add> User.find_by(name: "David") # => nil <add> end <add> ``` <ide> <ide> After: <ide> <del> User.where(name: "John").create do |john| <del> User.find_by(name: "David") # => #<User name: "David", ...> <del> end <add> ```ruby <add> User.where(name: "John").create do |john| <add> User.find_by(name: "David") # => #<User name: "David", ...> <add> end <add> ``` <ide> <ide> * Named scope chain does no longer leak scope to class level querying methods. <ide> <del> class User < ActiveRecord::Base <del> scope :david, -> { User.where(name: "David") } <del> end <add> ```ruby <add> class User < ActiveRecord::Base <add> scope :david, -> { User.where(name: "David") } <add> end <add> ``` <ide> <ide> Before: <ide> <del> User.where(name: "John").david <del> # SELECT * FROM users WHERE name = 'John' AND name = 'David' <add> ```ruby <add> User.where(name: "John").david <add> # SELECT * FROM users WHERE name = 'John' AND name = 'David' <add> ``` <ide> <ide> After: <ide> <del> User.where(name: "John").david <del> # SELECT * FROM users WHERE name = 'David' <add> ```ruby <add> User.where(name: "John").david <add> # SELECT * FROM users WHERE name = 'David' <add> ``` <ide> <ide> * `where.not` now generates NAND predicates instead of NOR. <ide> <ide> Before: <ide> <del> User.where.not(name: "Jon", role: "admin") <del> # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin' <add> ```ruby <add> User.where.not(name: "Jon", role: "admin") <add> # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin' <add> ``` <ide> <ide> After: <ide> <del> User.where.not(name: "Jon", role: "admin") <del> # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin') <add> ```ruby <add> User.where.not(name: "Jon", role: "admin") <add> # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin') <add> ``` <ide> <ide> * To use the new per-database connection handling applications must change <ide> `legacy_connection_handling` to false and remove deprecated accessors on <ide><path>guides/source/action_mailer_basics.md <ide> config.asset_host = 'http://example.com' <ide> <ide> Now you can display an image inside your email. <ide> <del>```ruby <add>```html+erb <ide> <%= image_tag 'image.jpg' %> <ide> ``` <ide> <ide><path>guides/source/active_record_validations.md <ide> class Person < ApplicationRecord <ide> end <ide> ``` <ide> <del>```irb> <add>```irb <ide> irb> person = Person.new(name: "John Doe") <ide> irb> person.valid? <ide> => true <ide> it generates that displays the full list of errors on that model. <ide> Assuming we have a model that's been saved in an instance variable named <ide> `@article`, it looks like this: <ide> <del>```ruby <add>```html+erb <ide> <% if @article.errors.any? %> <ide> <div id="error_explanation"> <ide> <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2> <ide><path>guides/source/association_basics.md <ide> The [`collection.clear`][] method removes every object from the collection by de <ide> <ide> The [`collection.empty?`][] method returns `true` if the collection does not contain any associated objects. <ide> <del>```ruby <add>```html+erb <ide> <% if @part.assemblies.empty? %> <ide> This part is not used in any assemblies <ide> <% end %> <ide><path>guides/source/engines.md <ide> not your engine's application controller. Ruby is able to resolve the `Applicati <ide> The best way to prevent this from happening is to use `require_dependency` to ensure that the engine's application <ide> controller is loaded. For example: <ide> <del>``` ruby <add>```ruby <ide> # app/controllers/blorgh/articles_controller.rb: <ide> require_dependency "blorgh/application_controller" <ide> <ide><path>guides/source/generators.md <ide> escaped so that the generated output is valid ERB code. <ide> For example, the following escaped ERB tag would be needed in the template <ide> (note the extra `%`)... <ide> <del>```ruby <add>```erb <ide> <%%= stylesheet_include_tag :application %> <ide> ``` <ide> <ide> ...to generate the following output: <ide> <del>```ruby <add>```erb <ide> <%= stylesheet_include_tag :application %> <ide> ``` <ide> <ide><path>guides/source/layouts_and_rendering.md <ide> Partial templates - usually just called "partials" - are another device for brea <ide> <ide> To render a partial as part of a view, you use the [`render`][view.render] method within the view: <ide> <del>```ruby <add>```html+erb <ide> <%= render "menu" %> <ide> ``` <ide> <ide> This will render a file named `_menu.html.erb` at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder: <ide> <del>```ruby <add>```html+erb <ide> <%= render "shared/menu" %> <ide> ``` <ide> <ide><path>guides/source/routing.md <ide> Both the `matches?` method and the lambda gets the `request` object as an argume <ide> <ide> You can specify constraints in a block form. This is useful for when you need to apply the same rule to several routes. For example <ide> <del>``` <add>```ruby <ide> class RestrictedListConstraint <ide> # ...Same as the example above <ide> end <ide> end <ide> <ide> You also use a `lambda`: <ide> <del>``` <add>```ruby <ide> Rails.application.routes.draw do <ide> constraints(lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) }) do <ide> get '*path', to: 'restricted_list#index', <ide> end <ide> <ide> The [`resolve`][] method allows customizing polymorphic mapping of models. For example: <ide> <del>``` ruby <add>```ruby <ide> resource :basket <ide> <ide> resolve("Basket") { [:basket] } <ide> ``` <ide> <del>``` erb <add>```erb <ide> <%= form_with model: @basket do |form| %> <ide> <!-- basket form --> <ide> <% end %> <ide><path>guides/source/upgrading_ruby_on_rails.md <ide> warning about this upcoming change. <ide> When you are ready, you can opt into the new behavior and remove the deprecation <ide> warning by adding the following configuration to your `config/application.rb`: <ide> <del> ActiveSupport.halt_callback_chains_on_return_false = false <add>```ruby <add>ActiveSupport.halt_callback_chains_on_return_false = false <add>``` <ide> <ide> Note that this option will not affect Active Support callbacks since they never <ide> halted the chain when any value was returned. <ide> parameters are already permitted, then you will not need to make any changes. If <ide> and other methods that depend on being able to read the hash regardless of `permitted?` you will <ide> need to upgrade your application to first permit and then convert to a hash. <ide> <del> params.permit([:proceed_to, :return_to]).to_h <add>```ruby <add>params.permit([:proceed_to, :return_to]).to_h <add>``` <ide> <ide> ### `protect_from_forgery` Now Defaults to `prepend: false` <ide> <ide> This can be turned off per-association with `optional: true`. <ide> This default will be automatically configured in new applications. If an existing application <ide> wants to add this feature it will need to be turned on in an initializer: <ide> <del> config.active_record.belongs_to_required_by_default = true <add>```ruby <add>config.active_record.belongs_to_required_by_default = true <add>``` <ide> <ide> The configuration is by default global for all your models, but you can <ide> override it on a per model basis. This should help you migrate all your models to have their <ide> Rails 5 now supports per-form CSRF tokens to mitigate against code-injection att <ide> created by JavaScript. With this option turned on, forms in your application will each have their <ide> own CSRF token that is specific to the action and method for that form. <ide> <del> config.action_controller.per_form_csrf_tokens = true <add>```ruby <add>config.action_controller.per_form_csrf_tokens = true <add>``` <ide> <ide> #### Forgery Protection with Origin Check <ide> <ide> You can now configure your application to check if the HTTP `Origin` header should be checked <ide> against the site's origin as an additional CSRF defense. Set the following in your config to <ide> true: <ide> <del> config.action_controller.forgery_protection_origin_check = true <add>```ruby <add>config.action_controller.forgery_protection_origin_check = true <add>``` <ide> <ide> #### Allow Configuration of Action Mailer Queue Name <ide> <ide> The default mailer queue name is `mailers`. This configuration option allows you to globally change <ide> the queue name. Set the following in your config: <ide> <del> config.action_mailer.deliver_later_queue_name = :new_queue_name <add>```ruby <add>config.action_mailer.deliver_later_queue_name = :new_queue_name <add>``` <ide> <ide> #### Support Fragment Caching in Action Mailer Views <ide> <ide> Set `config.action_mailer.perform_caching` in your config to determine whether your Action Mailer views <ide> should support caching. <ide> <del> config.action_mailer.perform_caching = true <add>```ruby <add>config.action_mailer.perform_caching = true <add>``` <ide> <ide> #### Configure the Output of `db:structure:dump` <ide> <ide> If you're using `schema_search_path` or other PostgreSQL extensions, you can control how the schema is <ide> dumped. Set to `:all` to generate all dumps, or to `:schema_search_path` to generate from schema search path. <ide> <del> config.active_record.dump_schemas = :all <add>```ruby <add>config.active_record.dump_schemas = :all <add>``` <ide> <ide> #### Configure SSL Options to Enable HSTS with Subdomains <ide> <ide> Set the following in your config to enable HSTS when using subdomains: <ide> <del> config.ssl_options = { hsts: { subdomains: true } } <add>```ruby <add>config.ssl_options = { hsts: { subdomains: true } } <add>``` <ide> <ide> #### Preserve Timezone of the Receiver <ide> <ide> When using Ruby 2.4, you can preserve the timezone of the receiver when calling `to_time`. <ide> <del> ActiveSupport.to_time_preserves_timezone = false <add>```ruby <add>ActiveSupport.to_time_preserves_timezone = false <add>``` <ide> <ide> ### Changes with JSON/JSONB serialization <ide> <ide> you are ready, you can opt into the new behavior and remove the <ide> deprecation warning by adding following configuration to your <ide> `config/application.rb`: <ide> <del> config.active_record.raise_in_transactional_callbacks = true <add>```ruby <add>config.active_record.raise_in_transactional_callbacks = true <add>``` <ide> <ide> See [#14488](https://github.com/rails/rails/pull/14488) and <ide> [#16537](https://github.com/rails/rails/pull/16537) for more details.
11
Text
Text
install release for android
ce82428b1595526108bd90acf0c24ba2940569c6
<ide><path>docs/SignedAPKAndroid.md <ide> The generated APK can be found under `android/app/build/outputs/apk/app-release. <ide> Before uploading the release build to the Play Store, make sure you test it thoroughly. Install it on the device using: <ide> <ide> ```sh <del>$ cd android && ./gradlew installRelease <add>$ react-native run-android --variant=release <ide> ``` <ide> <del>Note that `installRelease` is only available if you've set up signing as described above. <add>Note that `--variant=release` is only available if you've set up signing as described above. <ide> <ide> You can kill any running packager instances, all your and framework JavaScript code is bundled in the APK's assets. <ide>
1
Javascript
Javascript
fix jshint errors with long lines
269bc7e51f0ae4e4230308e43db934a9fff48756
<ide><path>src/ngResource/resource.js <ide> var $resourceMinErr = angular.$$minErr('$resource'); <ide> * <ide> * # ngResource <ide> * <del> * The `ngResource` module provides interaction support with RESTful services via the $resource service. <add> * The `ngResource` module provides interaction support with RESTful services <add> * via the $resource service. <ide> * <ide> * {@installModule resource} <ide> * <ide><path>src/ngTouch/touch.js <ide> * # ngTouch <ide> * <ide> * The `ngTouch` module provides touch events and other helpers for touch-enabled devices. <del> * The implementation is based on jQuery Mobile touch event handling ([jquerymobile.com](http://jquerymobile.com/)). <add> * The implementation is based on jQuery Mobile touch event handling <add> * ([jquerymobile.com](http://jquerymobile.com/)). <ide> * <ide> * {@installModule touch} <ide> *
2
Javascript
Javascript
update translation of monday and saturday
0dcaaa689d02dde824029b09ab6aa64ff351ee2e
<ide><path>src/locale/tr.js <ide> export default moment.defineLocale('tr', { <ide> weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split( <ide> '_' <ide> ), <del> weekdaysShort: 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), <add> weekdaysShort: 'Paz_Pzt_Sal_Çar_Per_Cum_Cmt'.split('_'), <ide> weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), <ide> meridiem: function (hours, minutes, isLower) { <ide> if (hours < 12) { <ide><path>src/test/locale/tr.js <ide> test('format month', function (assert) { <ide> }); <ide> <ide> test('format week', function (assert) { <del> var expected = 'Pazar Paz Pz_Pazartesi Pts Pt_Salı Sal Sa_Çarşamba Çar Ça_Perşembe Per Pe_Cuma Cum Cu_Cumartesi Cts Ct'.split( <add> var expected = 'Pazar Paz Pz_Pazartesi Pzt Pt_Salı Sal Sa_Çarşamba Çar Ça_Perşembe Per Pe_Cuma Cum Cu_Cumartesi Cmt Ct'.split( <ide> '_' <ide> ), <ide> i;
2
Python
Python
remove debug statements
eddef438696729d40092e3f8dfaf939b38ec8d5d
<ide><path>numpy/lib/function_base.py <ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False, <ide> <ide> else: <ide> # weight the points above and below the indices <del> #import pdb; pdb.set_trace() <ide> <ide> indices_below = not_scalar(floor(indices)).astype(intp) <ide> indices_above = not_scalar(indices_below + 1)
1
Javascript
Javascript
set textcontent rather than using element.text()
074a146d8b1ee7c93bf6d5892448a5c2a0143a28
<ide><path>src/ng/directive/ngBind.js <ide> var ngBindDirective = ['$compile', function($compile) { <ide> $compile.$$addBindingClass(templateElement); <ide> return function ngBindLink(scope, element, attr) { <ide> $compile.$$addBindingInfo(element, attr.ngBind); <add> element = element[0]; <ide> scope.$watch(attr.ngBind, function ngBindWatchAction(value) { <del> // We are purposefully using == here rather than === because we want to <del> // catch when value is "null or undefined" <del> // jshint -W041 <del> element.text(value == undefined ? '' : value); <add> element.textContent = value === undefined ? '' : value; <ide> }); <ide> }; <ide> } <ide> var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate <ide> return function ngBindTemplateLink(scope, element, attr) { <ide> var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); <ide> $compile.$$addBindingInfo(element, interpolateFn.expressions); <add> element = element[0]; <ide> attr.$observe('ngBindTemplate', function(value) { <del> element.text(value); <add> element.textContent = value === undefined ? '' : value; <ide> }); <ide> }; <ide> }
1
Python
Python
fix metrics support in theano
d9fae78e554db4bb4d4590564ce49b3d70e64d0e
<ide><path>keras/backend/theano_backend.py <ide> def __init__(self, inputs, outputs, updates=[], name=None, **kwargs): <ide> if v not in unique_variables_to_update: <ide> unique_variables_to_update[v] = nv <ide> updates = unique_variables_to_update.items() <add> self.outputs = outputs <ide> self.function = theano.function(inputs, outputs, updates=updates, <ide> allow_input_downcast=True, <ide> on_unused_input='ignore', <ide> name=name, <ide> **kwargs) <add> self._metrics = [x for x in outputs if hasattr(x, '_is_metric')] <add> self._metrics_function = theano.function( <add> [], self._metrics, <add> name=name + '_metrics' if name else None) <ide> self.name = name <ide> <ide> def __call__(self, inputs): <ide> assert isinstance(inputs, (list, tuple)) <del> return self.function(*inputs) <add> outputs = self.function(*inputs) <add> if self._metrics: <add> metrics = self._metrics_function() <add> i = 0 <add> j = 0 <add> for x in self.outputs: <add> if hasattr(x, '_is_metric'): <add> v = metrics[j] <add> outputs[i] = v <add> j += 1 <add> i += 1 <add> return outputs <ide> <ide> <ide> def _raise_invalid_arg(key): <ide><path>keras/metrics.py <ide> def __new__(cls, *args, **kwargs): <ide> @K.symbolic <ide> def __call__(self, *args, **kwargs): <ide> """Accumulates statistics and then computes metric result value.""" <del> if K.backend() != 'tensorflow': <del> raise RuntimeError( <del> 'Metric calling only supported with TensorFlow backend.') <ide> update_op = self.update_state(*args, **kwargs) <ide> with K.control_dependencies(update_op): # For TF <ide> result_t = self.result() <ide><path>keras/utils/metrics_utils.py <ide> def result_wrapper(result_fn): <ide> def decorated(metric_obj, *args, **kwargs): <ide> result_t = K.identity(result_fn(*args, **kwargs)) <ide> metric_obj._call_result = result_t <add> result_t._is_metric = True <ide> return result_t <ide> <ide> return decorated <ide><path>tests/integration_tests/test_image_data_tasks.py <ide> def test_image_classification(): <ide> optimizer='rmsprop', <ide> metrics=['accuracy']) <ide> model.summary() <del> history = model.fit(x_train, y_train, epochs=10, batch_size=16, <add> history = model.fit(x_train, y_train, epochs=12, batch_size=16, <ide> validation_data=(x_test, y_test), <ide> verbose=0) <ide> assert history.history['val_accuracy'][-1] > 0.75 <ide> def test_image_data_generator_training(): <ide> optimizer='rmsprop', <ide> metrics=['accuracy']) <ide> history = model.fit_generator(img_gen.flow(x_train, y_train, batch_size=16), <del> epochs=12, <add> epochs=15, <ide> validation_data=img_gen.flow(x_test, y_test, <ide> batch_size=16), <ide> verbose=0) <ide><path>tests/integration_tests/test_temporal_data_tasks.py <ide> def test_temporal_classification(): <ide> optimizer='rmsprop', <ide> metrics=['accuracy']) <ide> model.summary() <del> history = model.fit(x_train, y_train, epochs=4, batch_size=10, <add> history = model.fit(x_train, y_train, epochs=5, batch_size=10, <ide> validation_data=(x_test, y_test), <ide> verbose=0) <ide> assert(history.history['accuracy'][-1] >= 0.8) <ide> def test_temporal_classification_functional(): <ide> model.compile(loss='categorical_crossentropy', <ide> optimizer='rmsprop', <ide> metrics=['accuracy']) <del> history = model.fit(x_train, y_train, epochs=4, batch_size=10, <add> history = model.fit(x_train, y_train, epochs=5, batch_size=10, <ide> validation_data=(x_test, y_test), <ide> verbose=0) <del> assert(history.history['accuracy'][-1] >= 0.8) <add> assert(history.history['accuracy'][-1] >= 0.75) <ide> <ide> <ide> def test_temporal_regression():
5
Javascript
Javascript
fix small typo in comment
6aa4200a8cefa87bb4ec100c0b0369517e35ed6b
<ide><path>src/selector.js <ide> jQuery.extend({ <ide> // Match: :contains('foo') <ide> /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/, <ide> <del> // Match: :even, :last-chlid, #id, .class <add> // Match: :even, :last-child, #id, .class <ide> new RegExp("^([:.#]*)(" + chars + "+)") <ide> ], <ide>
1
Javascript
Javascript
ensure validation works during watch
d233cb35a3bf1d7275bca98a8a7ac57020a11d63
<ide><path>client/gatsby-config.js <ide> module.exports = { <ide> options: { <ide> name: 'challenges', <ide> source: buildChallenges, <del> onSourceChange: replaceChallengeNode, <add> onSourceChange: replaceChallengeNode(config.locale), <ide> curriculumPath: localeChallengesRootDir <ide> } <ide> }, <ide><path>client/utils/buildChallenges.js <ide> const arrToString = arr => <ide> <ide> exports.localeChallengesRootDir = getChallengesDirForLang(locale); <ide> <del>exports.replaceChallengeNode = async function replaceChallengeNode( <del> fullFilePath <del>) { <del> return prepareChallenge(await createChallenge(fullFilePath)); <add>exports.replaceChallengeNode = locale => { <add> return async function replaceChallengeNode(fullFilePath) { <add> return prepareChallenge(await createChallenge(fullFilePath, null, locale)); <add> }; <ide> }; <ide> <ide> exports.buildChallenges = async function buildChallenges() { <ide><path>curriculum/getChallenges.js <ide> exports.getMetaForBlock = getMetaForBlock; <ide> <ide> exports.getChallengesForLang = function getChallengesForLang(lang) { <ide> let curriculum = {}; <del> const validate = challengeSchemaValidator(lang); <ide> return new Promise(resolve => { <ide> let running = 1; <ide> function done() { <ide> exports.getChallengesForLang = function getChallengesForLang(lang) { <ide> readDirP({ root: getChallengesDirForLang(lang) }) <ide> .on('data', file => { <ide> running++; <del> buildCurriculum(file, curriculum, validate).then(done); <add> buildCurriculum(file, curriculum, lang).then(done); <ide> }) <ide> .on('end', done); <ide> }); <ide> }; <ide> <del>async function buildCurriculum(file, curriculum, validate) { <add>async function buildCurriculum(file, curriculum, lang) { <ide> const { name, depth, path: filePath, fullPath, stat } = file; <ide> if (depth === 1 && stat.isDirectory()) { <ide> // extract the superBlock info <ide> async function buildCurriculum(file, curriculum, validate) { <ide> } <ide> const { meta } = challengeBlock; <ide> <del> const challenge = await createChallenge(fullPath, meta, validate); <add> const challenge = await createChallenge(fullPath, meta, lang); <ide> <ide> challengeBlock.challenges = [...challengeBlock.challenges, challenge]; <ide> } <ide> <del>async function createChallenge(fullPath, maybeMeta, validate) { <add>async function createChallenge(fullPath, maybeMeta, lang) { <ide> let meta; <ide> if (maybeMeta) { <ide> meta = maybeMeta; <ide> async function createChallenge(fullPath, maybeMeta, validate) { <ide> } <ide> const { name: superBlock } = superBlockInfoFromFullPath(fullPath); <ide> const challenge = await parseMarkdown(fullPath); <del> const result = validate(challenge); <add> const result = challengeSchemaValidator(lang)(challenge); <ide> if (result.error) { <ide> console.log(result.value); <ide> throw new Error(result.error);
3
Javascript
Javascript
reduce need for runtime template compilation
9fce04129121884c522a887dc57fe0c6d5bbb2c2
<ide><path>packages/ember-handlebars/lib/controls/checkbox.js <ide> Ember.Checkbox = Ember.View.extend({ <ide> _updateElementValue: function() { <ide> var input = get(this, 'title') ? this.$('input:checkbox') : this.$(); <ide> set(this, 'checked', input.prop('checked')); <del> }, <del> <del> init: function() { <del> if (get(this, 'title') || get(this, 'titleBinding')) { <del> Ember.deprecate("Automatically surrounding Ember.Checkbox inputs with a label by providing a 'title' property is deprecated"); <del> this.tagName = undefined; <del> this.attributeBindings = []; <del> this.defaultTemplate = Ember.Handlebars.compile('<label><input type="checkbox" {{bindAttr checked="checked" disabled="disabled"}}>{{title}}</label>'); <del> } <del> <del> this._super(); <ide> } <ide> }); <ide><path>packages/ember-handlebars/lib/controls/select.js <ide> Ember.Select = Ember.View.extend( <ide> <ide> Ember.SelectOption = Ember.View.extend({ <ide> tagName: 'option', <del> defaultTemplate: Ember.Handlebars.compile("{{view.label}}"), <ide> attributeBindings: ['value', 'selected'], <ide> <add> defaultTemplate: function(context, options) { <add> options = { data: options.data, hash: {} }; <add> Ember.Handlebars.helpers.bind.call(context, "view.label", options); <add> }, <add> <ide> init: function() { <ide> this.labelPathDidChange(); <ide> this.valuePathDidChange(); <ide><path>packages/ember-handlebars/tests/controls/checkbox_test.js <ide> test("checking the checkbox updates the value", function() { <ide> equal(get(checkboxView, 'checked'), false, "changing the checkbox causes the view's value to get updated"); <ide> }); <ide> <del>// deprecated behaviors <del>test("wraps the checkbox in a label if a title attribute is provided", function(){ <del> Ember.TESTING_DEPRECATION = true; <del> <del> try { <del> checkboxView = Ember.Checkbox.create({ title: "I have a title" }); <del> append(); <del> equal(checkboxView.$('label').length, 1); <del> } finally { <del> Ember.TESTING_DEPRECATION = false; <del> } <del>}); <del> <ide> test("proxies the checked attribute to value for backwards compatibility", function(){ <ide> Ember.TESTING_DEPRECATION = true; <ide>
3
Python
Python
replace getters/setters with properties - round 2
c5a2c25b35467e61cc1cc45bcd4c4e843c2a4266
<ide><path>glances/core/glances_logs.py <ide> def set_process_sort(self, item_type): <ide> else: <ide> # Default sort is... <ide> process_auto_by = 'cpu_percent' <del> glances_processes.setautosortkey(process_auto_by) <add> glances_processes.auto_sort = True <add> glances_processes.sort_key = process_auto_by <ide> <ide> def reset_process_sort(self): <del> """Reset the process_auto_by variable.""" <add> """Reset the process auto sort key.""" <ide> # Default sort is... <del> process_auto_by = 'cpu_percent' <del> glances_processes.setautosortkey(process_auto_by) <del> glances_processes.setmanualsortkey(None) <add> glances_processes.auto_sort = True <add> glances_processes.sort_key = 'cpu_percent' <ide> <ide> def add(self, item_state, item_type, item_value, <ide> proc_list=None, proc_desc="", peak_time=3): <ide><path>glances/core/glances_processes.py <ide> def __init__(self, cache_timeout=60): <ide> self.process_tree = None <ide> <ide> # Init stats <del> self.resetsort() <add> self.auto_sort = True <add> self._sort_key = 'cpu_percent' <ide> self.allprocesslist = [] <ide> self.processlist = [] <del> self.processcount = { <del> 'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0} <add> self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0} <ide> <ide> # Tag to enable/disable the processes stats (to reduce the Glances CPU consumption) <ide> # Default is to enable the processes stats <ide> def __init__(self, cache_timeout=60): <ide> # Extended stats for top process is enable by default <ide> self.disable_extended_tag = False <ide> <del> # Maximum number of processes showed in the UI interface <del> # None if no limit <del> self.max_processes = None <add> # Maximum number of processes showed in the UI (None if no limit) <add> self._max_processes = None <ide> <ide> # Process filter is a regular expression <del> self.process_filter = None <del> self.process_filter_re = None <add> self._process_filter = None <add> self._process_filter_re = None <ide> <ide> # Whether or not to hide kernel threads <ide> self.no_kernel_threads = False <ide> def disable_extended(self): <ide> """Disable extended process stats.""" <ide> self.disable_extended_tag = True <ide> <del> def set_max_processes(self, value): <del> """Set the maximum number of processes showed in the UI interfaces""" <del> self.max_processes = value <add> @property <add> def max_processes(self): <add> """Get the maximum number of processes showed in the UI.""" <add> return self._max_processes <ide> <del> def get_max_processes(self): <del> """Get the maximum number of processes showed in the UI interfaces""" <del> return self.max_processes <add> @max_processes.setter <add> def max_processes(self, value): <add> """Set the maximum number of processes showed in the UI.""" <add> self._max_processes = value <ide> <del> def set_process_filter(self, value): <del> """Set the process filter""" <add> @property <add> def process_filter(self): <add> """Get the process filter.""" <add> return self._process_filter <add> <add> @process_filter.setter <add> def process_filter(self, value): <add> """Set the process filter.""" <ide> logger.info("Set process filter to {0}".format(value)) <del> self.process_filter = value <add> self._process_filter = value <ide> if value is not None: <ide> try: <del> self.process_filter_re = re.compile(value) <del> logger.debug( <del> "Process filter regex compilation OK: {0}".format(self.get_process_filter())) <add> self._process_filter_re = re.compile(value) <add> logger.debug("Process filter regex compilation OK: {0}".format(self.process_filter)) <ide> except Exception: <del> logger.error( <del> "Cannot compile process filter regex: {0}".format(value)) <del> self.process_filter_re = None <add> logger.error("Cannot compile process filter regex: {0}".format(value)) <add> self._process_filter_re = None <ide> else: <del> self.process_filter_re = None <del> <del> def get_process_filter(self): <del> """Get the process filter""" <del> return self.process_filter <add> self._process_filter_re = None <ide> <del> def get_process_filter_re(self): <del> """Get the process regular expression compiled""" <del> return self.process_filter_re <add> @property <add> def process_filter_re(self): <add> """Get the process regular expression compiled.""" <add> return self._process_filter_re <ide> <ide> def is_filtered(self, value): <ide> """Return True if the value should be filtered""" <del> if self.get_process_filter() is None: <add> if self.process_filter is None: <ide> # No filter => Not filtered <ide> return False <ide> else: <del> # logger.debug(self.get_process_filter() + " <> " + value + " => " + str(self.get_process_filter_re().match(value) is None)) <del> return self.get_process_filter_re().match(value) is None <add> # logger.debug(self.process_filter + " <> " + value + " => " + str(self.process_filter_re.match(value) is None)) <add> return self.process_filter_re.match(value) is None <ide> <ide> def disable_kernel_threads(self): <ide> """ Ignore kernel threads in process list. """ <ide> def update(self): <ide> """ <ide> # Reset the stats <ide> self.processlist = [] <del> self.processcount = { <del> 'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0} <add> self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0} <ide> <ide> # Do not process if disable tag is set <ide> if self.disable_tag: <ide> def update(self): <ide> if self.no_kernel_threads and not is_windows and is_kernel_thread(proc): <ide> continue <ide> <del> # If self.get_max_processes() is None: Only retreive mandatory stats <add> # If self.max_processes is None: Only retreive mandatory stats <ide> # Else: retreive mandatory and standard stats <ide> s = self.__get_process_stats(proc, <ide> mandatory_stats=True, <del> standard_stats=self.get_max_processes() is None) <add> standard_stats=self.max_processes is None) <ide> # Continue to the next process if it has to be filtered <ide> if s is None or (self.is_filtered(s['cmdline']) and self.is_filtered(s['name'])): <ide> continue <ide> def update(self): <ide> <ide> if self._enable_tree: <ide> self.process_tree = ProcessTreeNode.build_tree(processdict, <del> self.getsortkey(), <add> self.sort_key, <ide> self.no_kernel_threads) <ide> <ide> for i, node in enumerate(self.process_tree): <del> # Only retreive stats for visible processes (get_max_processes) <del> if self.get_max_processes() is not None and i >= self.get_max_processes(): <add> # Only retreive stats for visible processes (max_processes) <add> if self.max_processes is not None and i >= self.max_processes: <ide> break <ide> <ide> # add standard stats <ide> def update(self): <ide> <ide> else: <ide> # Process optimization <del> # Only retreive stats for visible processes (get_max_processes) <del> if self.get_max_processes() is not None: <add> # Only retreive stats for visible processes (max_processes) <add> if self.max_processes is not None: <ide> # Sort the internal dict and cut the top N (Return a list of tuple) <ide> # tuple=key (proc), dict (returned by __get_process_stats) <ide> try: <ide> processiter = sorted( <del> processdict.items(), key=lambda x: x[1][self.getsortkey()], reverse=True) <add> processdict.items(), key=lambda x: x[1][self.sort_key], reverse=True) <ide> except (KeyError, TypeError) as e: <del> logger.error( <del> "Cannot sort process list by %s (%s)" % (self.getsortkey(), e)) <add> logger.error("Cannot sort process list by {0}: {1}".format(self.sort_key, e)) <ide> logger.error("%s" % str(processdict.items()[0])) <ide> # Fallback to all process (issue #423) <ide> processloop = processdict.items() <ide> first = False <ide> else: <del> processloop = processiter[0:self.get_max_processes()] <add> processloop = processiter[0:self.max_processes] <ide> first = True <ide> else: <ide> # Get all processes stats <ide> def update(self): <ide> for i in processloop: <ide> # Already existing mandatory stats <ide> procstat = i[1] <del> if self.get_max_processes() is not None: <add> if self.max_processes is not None: <ide> # Update with standard stats <ide> # and extended stats but only for TOP (first) process <ide> s = self.__get_process_stats(i[0], <ide> def gettree(self): <ide> """Get the process tree.""" <ide> return self.process_tree <ide> <del> def getsortkey(self): <del> """Get the current sort key""" <del> if self.getmanualsortkey() is not None: <del> return self.getmanualsortkey() <del> else: <del> return self.getautosortkey() <del> <del> def getmanualsortkey(self): <del> """Get the current sort key for manual sort.""" <del> return self.processmanualsort <del> <del> def getautosortkey(self): <del> """Get the current sort key for automatic sort.""" <del> return self.processautosort <del> <del> def setmanualsortkey(self, sortedby): <del> """Set the current sort key for manual sort.""" <del> self.processmanualsort = sortedby <del> if self._enable_tree and (self.process_tree is not None): <del> self.process_tree.set_sorting(sortedby, sortedby != "name") <del> <del> def setautosortkey(self, sortedby): <del> """Set the current sort key for automatic sort.""" <del> self.processautosort = sortedby <del> <del> def resetsort(self): <del> """Set the default sort: Auto""" <del> self.setmanualsortkey(None) <del> self.setautosortkey('cpu_percent') <add> @property <add> def sort_key(self): <add> """Get the current sort key.""" <add> return self._sort_key <add> <add> @sort_key.setter <add> def sort_key(self, key): <add> """Set the current sort key.""" <add> self._sort_key = key <add> if not self.auto_sort and self._enable_tree and self.process_tree is not None: <add> self.process_tree.set_sorting(key, key != "name") <ide> <ide> def getsortlist(self, sortedby=None): <ide> """Get the sorted processlist.""" <ide><path>glances/core/glances_standalone.py <ide> def __init__(self, config=None, args=None): <ide> self.stats = GlancesStats(config=config, args=args) <ide> <ide> # Default number of processes to displayed is set to 50 <del> glances_processes.set_max_processes(50) <add> glances_processes.max_processes = 50 <ide> <ide> # If process extended stats is disabled by user <ide> if not args.enable_process_extended: <ide> def __init__(self, config=None, args=None): <ide> <ide> # Manage optionnal process filter <ide> if args.process_filter is not None: <del> glances_processes.set_process_filter(args.process_filter) <add> glances_processes.process_filter = args.process_filter <ide> <ide> if (not is_windows) and args.no_kernel_threads: <ide> # Ignore kernel threads in process list <ide><path>glances/outputs/glances_curses.py <ide> def __init__(self, args=None): <ide> # Init refresh time <ide> self.__refresh_time = args.time <ide> <del> # Init process sort method <del> self.args.process_sorted_by = 'auto' <del> <ide> # Init edit filter tag <ide> self.edit_filter = False <ide> <ide> def __catch_key(self, return_to_browser=False): <ide> # '/' > Switch between short/long name for processes <ide> self.args.process_short_name = not self.args.process_short_name <ide> elif self.pressedkey == ord('a'): <del> # 'a' > Sort processes automatically <del> self.args.process_sorted_by = 'auto' <del> glances_processes.resetsort() <add> # 'a' > Sort processes automatically and reset to 'cpu_percent' <add> glances_processes.auto_sort = True <add> glances_processes.sort_key = 'cpu_percent' <ide> elif self.pressedkey == ord('b'): <ide> # 'b' > Switch between bit/s and Byte/s for network IO <ide> # self.net_byteps_tag = not self.net_byteps_tag <ide> self.args.byte = not self.args.byte <ide> elif self.pressedkey == ord('c'): <ide> # 'c' > Sort processes by CPU usage <del> self.args.process_sorted_by = 'cpu_percent' <del> glances_processes.setmanualsortkey(self.args.process_sorted_by) <add> glances_processes.auto_sort = False <add> glances_processes.sort_key = 'cpu_percent' <ide> elif self.pressedkey == ord('d'): <ide> # 'd' > Show/hide disk I/O stats <ide> self.args.disable_diskio = not self.args.disable_diskio <ide> def __catch_key(self, return_to_browser=False): <ide> self.args.help_tag = not self.args.help_tag <ide> elif self.pressedkey == ord('i'): <ide> # 'i' > Sort processes by IO rate (not available on OS X) <del> self.args.process_sorted_by = 'io_counters' <del> glances_processes.setmanualsortkey(self.args.process_sorted_by) <add> glances_processes.auto_sort = False <add> glances_processes.sort_key = 'io_counters' <ide> elif self.pressedkey == ord('I'): <ide> # 'I' > Show/hide IP module <ide> self.args.disable_ip = not self.args.disable_ip <ide> def __catch_key(self, return_to_browser=False): <ide> self.args.disable_log = not self.args.disable_log <ide> elif self.pressedkey == ord('m'): <ide> # 'm' > Sort processes by MEM usage <del> self.args.process_sorted_by = 'memory_percent' <del> glances_processes.setmanualsortkey(self.args.process_sorted_by) <add> glances_processes.auto_sort = False <add> glances_processes.sort_key = 'memory_percent' <ide> elif self.pressedkey == ord('n'): <ide> # 'n' > Show/hide network stats <ide> self.args.disable_network = not self.args.disable_network <ide> elif self.pressedkey == ord('p'): <ide> # 'p' > Sort processes by name <del> self.args.process_sorted_by = 'name' <del> glances_processes.setmanualsortkey(self.args.process_sorted_by) <add> glances_processes.auto_sort = False <add> glances_processes.sort_key = 'name' <ide> elif self.pressedkey == ord('r'): <ide> # 'r' > Reset history <ide> self.reset_history_tag = not self.reset_history_tag <ide> def __catch_key(self, return_to_browser=False): <ide> self.args.disable_sensors = not self.args.disable_sensors <ide> elif self.pressedkey == ord('t'): <ide> # 't' > Sort processes by TIME usage <del> self.args.process_sorted_by = 'cpu_times' <del> glances_processes.setmanualsortkey(self.args.process_sorted_by) <add> glances_processes.auto_sort = False <add> glances_processes.sort_key = 'cpu_times' <ide> elif self.pressedkey == ord('T'): <ide> # 'T' > View network traffic as sum Rx+Tx <ide> self.args.network_sum = not self.args.network_sum <ide> def new_column(self): <ide> """New column in the curses interface""" <ide> self.column = self.next_column <ide> <del> def display(self, stats, cs_status="None"): <add> def display(self, stats, cs_status=None): <ide> """Display stats on the screen. <ide> <ide> stats: Stats database to display <ide> def display(self, stats, cs_status="None"): <ide> max_processes_displayed -= 4 <ide> if max_processes_displayed < 0: <ide> max_processes_displayed = 0 <del> if glances_processes.get_max_processes() is None or \ <del> glances_processes.get_max_processes() != max_processes_displayed: <del> logger.debug("Set number of displayed processes to %s" % <del> max_processes_displayed) <del> glances_processes.set_max_processes(max_processes_displayed) <add> if (glances_processes.max_processes is None or <add> glances_processes.max_processes != max_processes_displayed): <add> logger.debug("Set number of displayed processes to {0}".format(max_processes_displayed)) <add> glances_processes.max_processes = max_processes_displayed <ide> <ide> stats_processlist = stats.get_plugin( <ide> 'processlist').get_stats_display(args=self.args) <ide> def display(self, stats, cs_status="None"): <ide> self.display_plugin(stats_docker) <ide> self.new_line() <ide> self.display_plugin(stats_processcount) <del> if glances_processes.get_process_filter() is None and cs_status == 'None': <add> if glances_processes.process_filter is None and cs_status is None: <ide> # Do not display stats monitor list if a filter exist <ide> self.new_line() <ide> self.display_plugin(stats_monitor) <ide> def display(self, stats, cs_status="None"): <ide> self.reset_history_tag = False <ide> <ide> # Display edit filter popup <del> # Only in standalone mode (cs_status == 'None') <del> if self.edit_filter and cs_status == 'None': <add> # Only in standalone mode (cs_status is None) <add> if self.edit_filter and cs_status is None: <ide> new_filter = self.display_popup(_("Process filter pattern: "), <ide> is_input=True, <del> input_value=glances_processes.get_process_filter()) <del> glances_processes.set_process_filter(new_filter) <add> input_value=glances_processes.process_filter) <add> glances_processes.process_filter = new_filter <ide> elif self.edit_filter and cs_status != 'None': <ide> self.display_popup( <ide> _("Process filter only available in standalone mode")) <ide> def erase(self): <ide> """Erase the content of the screen.""" <ide> self.term_window.erase() <ide> <del> def flush(self, stats, cs_status="None"): <add> def flush(self, stats, cs_status=None): <ide> """Clear and update the screen. <ide> <ide> stats: Stats database to display <ide> def flush(self, stats, cs_status="None"): <ide> self.erase() <ide> self.display(stats, cs_status=cs_status) <ide> <del> def update(self, stats, cs_status="None", return_to_browser=False): <add> def update(self, stats, cs_status=None, return_to_browser=False): <ide> """Update the screen. <ide> <ide> Wait for __refresh_time sec / catch key every 100 ms. <ide><path>glances/plugins/glances_processcount.py <ide> def msg_curse(self, args=None): <ide> return ret <ide> <ide> # Display the filter (if it exists) <del> if glances_processes.get_process_filter() is not None: <add> if glances_processes.process_filter is not None: <ide> msg = _("Processes filter:") <ide> ret.append(self.curse_add_line(msg, "TITLE")) <del> msg = _(" {0} ").format(glances_processes.get_process_filter()) <add> msg = _(" {0} ").format(glances_processes.process_filter) <ide> ret.append(self.curse_add_line(msg, "FILTER")) <ide> msg = _("(press ENTER to edit)") <ide> ret.append(self.curse_add_line(msg)) <ide> def msg_curse(self, args=None): <ide> ret.append(self.curse_add_line(msg)) <ide> <ide> # Display sort information <del> if glances_processes.getmanualsortkey() is None: <add> if glances_processes.auto_sort: <ide> msg = _("sorted automatically") <ide> ret.append(self.curse_add_line(msg)) <del> msg = _(" by {0}").format(glances_processes.getautosortkey()) <add> msg = _(" by {0}").format(glances_processes.sort_key) <ide> ret.append(self.curse_add_line(msg)) <ide> else: <del> msg = _("sorted by {0}").format(glances_processes.getmanualsortkey()) <add> msg = _("sorted by {0}").format(glances_processes.sort_key) <ide> ret.append(self.curse_add_line(msg)) <ide> ret[-1]["msg"] += ", %s view" % ("tree" if glances_processes.is_tree_enabled() else "flat") <ide> <ide><path>glances/plugins/glances_processlist.py <ide> def msg_curse(self, args=None): <ide> return ret <ide> <ide> # Compute the sort key <del> process_sort_key = glances_processes.getsortkey() <add> process_sort_key = glances_processes.sort_key <ide> sort_style = 'SORT' <ide> <ide> # Header <ide> def msg_curse(self, args=None): <ide> ret.extend(self.get_process_tree_curses_data(self.sortstats(process_sort_key), <ide> args, <ide> first_level=True, <del> max_node_count=glances_processes.get_max_processes())) <add> max_node_count=glances_processes.max_processes)) <ide> else: <ide> # Loop over processes (sorted by the sort key previously compute) <ide> first = True
6
Ruby
Ruby
suggest homepage in usage
5144ac9e6af6b7b40e646056298e58e0ff45e520
<ide><path>Library/Homebrew/ARGV+yeast.rb <ide> def usage <ide> info [formula] [--github] <ide> make url <ide> prune <add> <add>To visit the Homebrew homepage type: <add> brew home <ide> EOS <ide> end <ide>
1
Ruby
Ruby
break each polymorphic type to it's own method
4b8ab797b4653d8764c687e73cb630c32ae8bb4b
<ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb <ide> def polymorphic_url(record_or_hash_or_array, options = {}) <ide> <ide> opts = options.except(:action, :routing_type) <ide> <add> if options[:action] == 'new' <add> inflection = SINGULAR_ROUTE_KEY <add> else <add> inflection = ROUTE_KEY <add> end <add> <add> prefix = action_prefix options <add> suffix = routing_type options <add> <ide> case record_or_hash_or_array <ide> when Array <ide> if record_or_hash_or_array.empty? || record_or_hash_or_array.any?(&:nil?) <ide> def polymorphic_url(record_or_hash_or_array, options = {}) <ide> recipient = record_or_hash_or_array.shift <ide> end <ide> <del> record_list = record_or_hash_or_array.dup <del> record = record_list.pop <add> method, args = handle_list record_or_hash_or_array, <add> prefix, <add> suffix, <add> inflection <ide> when Hash <ide> unless record_or_hash_or_array[:id] <ide> raise ArgumentError, "Nil location provided. Can't build URI." <ide> end <ide> <ide> opts = record_or_hash_or_array.dup.merge!(opts) <del> record_list = [] <ide> record = opts.delete(:id) <add> <add> method, args = handle_model record, <add> prefix, <add> suffix, <add> inflection <add> when String, Symbol <add> args = [] <add> method = prefix + "#{record_or_hash_or_array}_#{suffix}" <add> when Class <add> method, args = handle_class record_or_hash_or_array, <add> prefix, <add> suffix, <add> inflection <add> <ide> when nil <ide> raise ArgumentError, "Nil location provided. Can't build URI." <ide> else <del> <del> record_list = [] <del> record = record_or_hash_or_array <add> method, args = handle_model record_or_hash_or_array, <add> prefix, <add> suffix, <add> inflection <ide> end <ide> <del> if options[:action] == 'new' <del> inflection = lambda { |name| name.singular_route_key } <add> <add> if opts.empty? <add> recipient.send(method, *args) <ide> else <del> inflection = lambda { |name| name.route_key } <add> recipient.send(method, *args, opts) <ide> end <add> end <add> <add> # Returns the path component of a URL for the given record. It uses <add> # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>. <add> def polymorphic_path(record_or_hash_or_array, options) <add> polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path)) <add> end <add> <add> def handle_list(list, prefix, suffix, inflection) <add> record_list = list.dup <add> record = record_list.pop <ide> <ide> args = [] <ide> <ide> def polymorphic_url(record_or_hash_or_array, options = {}) <ide> end <ide> end <ide> <del> route << routing_type(options) <del> <del> named_route = action_prefix(options) + route.join("_") <del> <del> if opts.empty? <del> recipient.send(named_route, *args) <del> else <del> recipient.send(named_route, *args, opts) <del> end <del> end <add> route << suffix <ide> <del> # Returns the path component of a URL for the given record. It uses <del> # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>. <del> def polymorphic_path(record_or_hash_or_array, options = {}) <del> polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path)) <add> named_route = prefix + route.join("_") <add> [named_route, args] <ide> end <ide> <ide> %w(edit new).each do |action| <ide> def #{action}_polymorphic_path(record_or_hash, options = {}) # def edit_p <ide> end <ide> <ide> private <add> ROUTE_KEY = lambda { |name| name.route_key } <add> SINGULAR_ROUTE_KEY = lambda { |name| name.singular_route_key } <add> <add> def handle_model(record, prefix, suffix, inflection) <add> args = [] <add> <add> model = record.to_model <add> name = if record.persisted? <add> args << model <add> model.class.model_name.singular_route_key <add> else <add> inflection.call model.class.model_name <add> end <add> <add> named_route = prefix + "#{name}_#{suffix}" <add> <add> [named_route, args] <add> end <add> <add> def handle_class(klass, prefix, suffix, inflection) <add> name = inflection.call klass.model_name <add> [prefix + "#{name}_#{suffix}", []] <add> end <add> <add> def model_path_helper_call(record) <add> handle_model record, ''.freeze, "path".freeze, ROUTE_KEY <add> end <add> <add> def class_path_helper_call(klass) <add> handle_class klass, ''.freeze, "path".freeze, ROUTE_KEY <add> end <add> <ide> def action_prefix(options) <ide> options[:action] ? "#{options[:action]}_" : '' <ide> end <ide> def routing_type(options) <ide> end <ide> end <ide> end <del> <ide><path>actionview/lib/action_view/routing_url_for.rb <ide> def url_for(options = nil) <ide> _back_url <ide> when Array <ide> polymorphic_path(options, options.extract_options!) <add> when Class <add> method = class_path_helper_call options <add> send method <ide> else <del> polymorphic_path(options) <add> method, args = model_path_helper_call options <add> send(method, *args) <ide> end <ide> end <ide>
2
Python
Python
use py3k compatible raise syntax
18d6b8f4246ea1b3f5718283b57f41de6211c4e7
<ide><path>numpy/testing/decorators.py <ide> def knownfail_decorator(f): <ide> from noseclasses import KnownFailureTest <ide> def knownfailer(*args, **kwargs): <ide> if fail_val(): <del> raise KnownFailureTest, msg <add> raise KnownFailureTest(msg) <ide> else: <ide> return f(*args, **kwargs) <ide> return nose.tools.make_decorator(f)(knownfailer)
1
Javascript
Javascript
replace date.now function by primordial datenow
0da6983cdad80dad8c1d4155b1bc887ce37d9c40
<ide><path>lib/internal/fs/utils.js <ide> <ide> const { <ide> ArrayIsArray, <add> DateNow, <ide> ObjectSetPrototypeOf, <ide> ReflectOwnKeys, <ide> } = primordials; <ide> function toUnixTimestamp(time, name = 'time') { <ide> } <ide> if (Number.isFinite(time)) { <ide> if (time < 0) { <del> return Date.now() / 1000; <add> return DateNow() / 1000; <ide> } <ide> return time; <ide> } <ide><path>lib/readline.js <ide> 'use strict'; <ide> <ide> const { <add> DateNow, <ide> MathCeil, <ide> MathFloor, <ide> MathMax, <ide> Interface.prototype._normalWrite = function(b) { <ide> } <ide> let string = this._decoder.write(b); <ide> if (this._sawReturnAt && <del> Date.now() - this._sawReturnAt <= this.crlfDelay) { <add> DateNow() - this._sawReturnAt <= this.crlfDelay) { <ide> string = string.replace(/^\n/, ''); <ide> this._sawReturnAt = 0; <ide> } <ide> Interface.prototype._normalWrite = function(b) { <ide> this._line_buffer = null; <ide> } <ide> if (newPartContainsEnding) { <del> this._sawReturnAt = string.endsWith('\r') ? Date.now() : 0; <add> this._sawReturnAt = string.endsWith('\r') ? DateNow() : 0; <ide> <ide> // Got one or more newlines; process into "line" events <ide> const lines = string.split(lineEnding); <ide> function _ttyWriteDumb(s, key) { <ide> <ide> switch (key.name) { <ide> case 'return': // Carriage return, i.e. \r <del> this._sawReturnAt = Date.now(); <add> this._sawReturnAt = DateNow(); <ide> this._line(); <ide> break; <ide> <ide> case 'enter': <ide> // When key interval > crlfDelay <ide> if (this._sawReturnAt === 0 || <del> Date.now() - this._sawReturnAt > this.crlfDelay) { <add> DateNow() - this._sawReturnAt > this.crlfDelay) { <ide> this._line(); <ide> } <ide> this._sawReturnAt = 0; <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> <ide> switch (key.name) { <ide> case 'return': // Carriage return, i.e. \r <del> this._sawReturnAt = Date.now(); <add> this._sawReturnAt = DateNow(); <ide> this._line(); <ide> break; <ide> <ide> case 'enter': <ide> // When key interval > crlfDelay <ide> if (this._sawReturnAt === 0 || <del> Date.now() - this._sawReturnAt > this.crlfDelay) { <add> DateNow() - this._sawReturnAt > this.crlfDelay) { <ide> this._line(); <ide> } <ide> this._sawReturnAt = 0;
2
Python
Python
add type hints for fnet pytorch
0dcdfe8630808bf284eebb370ed4c3cf77fa19f4
<ide><path>src/transformers/models/fnet/modeling_fnet.py <ide> import warnings <ide> from dataclasses import dataclass <ide> from functools import partial <del>from typing import Optional, Tuple <add>from typing import Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> def set_output_embeddings(self, new_embeddings): <ide> @replace_return_docstrings(output_type=FNetForPreTrainingOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> next_sentence_label=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> next_sentence_label: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, FNetForPreTrainingOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def set_output_embeddings(self, new_embeddings): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MaskedLMOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> output_hidden_states=None, <del> return_dict=None, <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, NextSentencePredictorOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, SequenceClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MultipleChoiceModelOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> labels=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, TokenClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> token_type_ids=None, <del> position_ids=None, <del> inputs_embeds=None, <del> start_positions=None, <del> end_positions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> start_positions: Optional[torch.Tensor] = None, <add> end_positions: Optional[torch.Tensor] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, QuestionAnsweringModelOutput]: <ide> r""" <ide> start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss.
1
Javascript
Javascript
remove unused variable e from try catch
f0c5c962ce971213c0c055b91bb747860defd492
<ide><path>lib/repl.js <ide> function defineDefaultCommands(repl) { <ide> this.outputStream.write('Failed to load: ' + file + <ide> ' is not a valid file\n'); <ide> } <del> } catch (e) { <add> } catch { <ide> this.outputStream.write('Failed to load: ' + file + '\n'); <ide> } <ide> this.displayPrompt();
1
PHP
PHP
convert another long test to use a dataprovider
1487357ba631bc34d19cabc08d93017294268401
<ide><path>lib/Cake/Test/Case/Routing/DispatcherTest.php <ide> public function testAssetFilterForThemeAndPlugins() { <ide> <ide> $this->assertFalse($Dispatcher->asset('js/cjs/debug_kit.js', $response)); <ide> } <add> <ide> /** <del> * testFullPageCachingDispatch method <add> * Data provider for cached actions. <ide> * <del> * @return void <add> * - Test simple views <add> * - Test views with nocache tags <add> * - Test requests with named + passed params. <add> * - Test themed views. <add> * <add> * @return array <ide> */ <del> public function testFullPageCachingDispatch() { <del> Configure::write('Cache.disable', false); <del> Configure::write('Cache.check', true); <del> Configure::write('debug', 2); <del> <del> <del> Router::reload(); <del> Router::connect('/', array('controller' => 'test_cached_pages', 'action' => 'index')); <del> Router::connect('/:controller/:action/*'); <del> <del> App::build(array( <del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), <del> ), true); <del> <del> $dispatcher = new TestDispatcher(); <del> $request = new CakeRequest('/'); <del> $response = new CakeResponse(); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> <del> $filename = $this->__cachePath($request->here); <del> unlink($filename); <del> <del> $request = new CakeRequest('test_cached_pages/index'); <del> $_POST = array( <del> 'slasher' => "Up in your's grill \ '" <add> public static function cacheActionProvider() { <add> return array( <add> array('/'), <add> array('test_cached_pages/index'), <add> array('TestCachedPages/index'), <add> array('test_cached_pages/test_nocache_tags'), <add> array('TestCachedPages/test_nocache_tags'), <add> array('test_cached_pages/view/param/param'), <add> array('test_cached_pages/view/foo:bar/value:goo'), <add> array('test_cached_pages/themed'), <ide> ); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> $filename = $this->__cachePath($request->here); <del> unlink($filename); <del> <del> $request = new CakeRequest('TestCachedPages/index'); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> $filename = $this->__cachePath($request->here); <del> unlink($filename); <del> <del> $request = new CakeRequest('TestCachedPages/test_nocache_tags'); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> $filename = $this->__cachePath($request->here); <del> unlink($filename); <del> <del> $request = new CakeRequest('test_cached_pages/view/param/param'); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> $filename = $this->__cachePath($request->here); <del> unlink($filename); <del> <del> $request = new CakeRequest('test_cached_pages/view/foo:bar/value:goo'); <del> <del> ob_start(); <del> $dispatcher->dispatch($request, $response); <del> $out = ob_get_clean(); <del> <del> ob_start(); <del> $dispatcher->cached($request->here); <del> $cached = ob_get_clean(); <del> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <del> <del> $this->assertEqual($expected, $result); <del> $filename = $this->__cachePath($request->here); <del> $this->assertTrue(file_exists($filename)); <del> <del> unlink($filename); <ide> } <del> <add> <ide> /** <del> * Test full page caching with themes. <add> * testFullPageCachingDispatch method <ide> * <add> * @dataProvider cacheActionProvider <ide> * @return void <ide> */ <del> public function testFullPageCachingWithThemes() { <add> public function testFullPageCachingDispatch($url) { <ide> Configure::write('Cache.disable', false); <ide> Configure::write('Cache.check', true); <ide> Configure::write('debug', 2); <ide> <ide> Router::reload(); <add> Router::connect('/', array('controller' => 'test_cached_pages', 'action' => 'index')); <ide> Router::connect('/:controller/:action/*'); <ide> <ide> App::build(array( <ide> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), <ide> ), true); <ide> <ide> $dispatcher = new TestDispatcher(); <del> $request = new CakeRequest('/test_cached_pages/themed'); <add> $request = new CakeRequest($url); <ide> $response = new CakeResponse(); <ide> <ide> ob_start();
1
Go
Go
fix typo in names-generator
6cf137860102b8df5db75dd68924375a7b74c1c3
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // http://en.wikipedia.org/wiki/John_Bardeen <ide> // http://en.wikipedia.org/wiki/Walter_Houser_Brattain <ide> // http://en.wikipedia.org/wiki/William_Shockley <del> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclid", "newton", "fermat", "archimedes", "poincare", "heisenberg", "feynman", "hawking", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley", "goldstine", "hoover", "hopper", "bartik", "sammet", "jones", "perlman", "wilson", "kowalevski", "hypatia", "goodall", "mayer", "elion", "blackwell", "lalande", "kirch", "ardinghelli", "colden", "almeida", "leakey", "meitner", "mestorf", "rosalind", "sinoussi", "carson", "mcmclintock", "yonath"} <add> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclid", "newton", "fermat", "archimedes", "poincare", "heisenberg", "feynman", "hawking", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley", "goldstine", "hoover", "hopper", "bartik", "sammet", "jones", "perlman", "wilson", "kowalevski", "hypatia", "goodall", "mayer", "elion", "blackwell", "lalande", "kirch", "ardinghelli", "colden", "almeida", "leakey", "meitner", "mestorf", "rosalind", "sinoussi", "carson", "mcclintock", "yonath"} <ide> ) <ide> <ide> func GenerateRandomName(checker NameChecker) (string, error) {
1
Text
Text
clarify use of #update_all
71db79938dfabe03e330fa1ef4f70d3364dac3f9
<ide><path>guides/source/active_record_basics.md <ide> user = User.find_by(name: 'David') <ide> user.update(name: 'Dave') <ide> ``` <ide> <del>This is most useful when updating several attributes at once. If, on the other <del>hand, you'd like to update several records in bulk, you may find the <del>`update_all` class method useful: <add>This is most useful when updating several attributes at once. <ide> <del>```ruby <del>User.update_all "max_login_attempts = 3, must_change_password = 'true'" <del>``` <del> <del>This is the same as if you wrote: <add>If you'd like to update several records in bulk without callbacks or <add>validations, you can update the database directly using `update_all`: <ide> <ide> ```ruby <del>User.update(:all, max_login_attempts: 3, must_change_password: true) <add>User.update_all max_login_attempts: 3, must_change_password: true <ide> ``` <ide> <ide> ### Delete
1
Go
Go
fix docker --init with /dev bind mount
bcacbf523b35b6cf22bd84ac33e4425784c5a0a2
<ide><path>daemon/oci_linux.go <ide> import ( <ide> "golang.org/x/sys/unix" <ide> ) <ide> <add>const ( <add> inContainerInitPath = "/sbin/" + daemonconfig.DefaultInitBinary <add>) <add> <ide> func setResources(s *specs.Spec, r containertypes.Resources) error { <ide> weightDevices, err := getBlkioWeightDevices(r) <ide> if err != nil { <ide> func (daemon *Daemon) populateCommonSpec(s *specs.Spec, c *container.Container) <ide> if c.HostConfig.PidMode.IsPrivate() { <ide> if (c.HostConfig.Init != nil && *c.HostConfig.Init) || <ide> (c.HostConfig.Init == nil && daemon.configStore.Init) { <del> s.Process.Args = append([]string{"/dev/init", "--", c.Path}, c.Args...) <del> var path string <del> if daemon.configStore.InitPath == "" { <add> s.Process.Args = append([]string{inContainerInitPath, "--", c.Path}, c.Args...) <add> path := daemon.configStore.InitPath <add> if path == "" { <ide> path, err = exec.LookPath(daemonconfig.DefaultInitBinary) <ide> if err != nil { <ide> return err <ide> } <ide> } <del> if daemon.configStore.InitPath != "" { <del> path = daemon.configStore.InitPath <del> } <ide> s.Mounts = append(s.Mounts, specs.Mount{ <del> Destination: "/dev/init", <add> Destination: inContainerInitPath, <ide> Type: "bind", <ide> Source: path, <ide> Options: []string{"bind", "ro"},
1
Text
Text
give package styling recommendations
492d7bc69a07f94f85df3f6182f691258219a994
<ide><path>docs/creating-a-package.md <ide> Any stylesheets in this directory will be loaded and attached to the DOM when <ide> your package is activated. Stylesheets can be written as CSS or [LESS] (but LESS <ide> is recommended). <ide> <add>Ideally you will not need much in the way of styling. We've provided a standard <add>set of components. You can view all components by using the command palette <add>(`cmd-p`) and searching for "styleguide" or just `cmd+ctrl+D`. <add> <add>If you do need styling, we try to keep only structural styles in the package <add>stylesheets. Colors and sizing should be taken from the active theme's <add>[ui-variables.less][ui-variables]. If you follow this guideline, your package <add>will look good out of the box with any theme! <add> <ide> An optional `stylesheets` array in your _package.json_ can list the stylesheets <ide> by name to specify a loading order; otherwise, stylesheets are loaded <ide> alphabetically. <ide> Additional libraries can be found by browsing Atom's _node_modules_ folder. <ide> [jasmine]: https://github.com/pivotal/jasmine <ide> [cson]: https://github.com/atom/season <ide> [less]: http://lesscss.org <add>[ui-variables]: https://github.com/atom/atom-dark-ui/blob/master/stylesheets/ui-variables.less
1
Text
Text
update changelog for
25ada9b5411808c4ae8dc72ba99cc09fe10ff884
<ide><path>activerecord/CHANGELOG.md <add>* Callbacks on has_many should access the in memory parent if a inverse_of is set. <add> <add> *arthurnn* <add> <ide> * `ActiveRecord::ConnectionAdapters.string_to_time` respects <ide> string with timezone (e.g. Wed, 04 Sep 2013 20:30:00 JST). <del> <add> <ide> Fixes: #12278 <ide> <ide> *kennyj*
1