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
|
---|---|---|---|---|---|
Go | Go | add closewriters back and do an interface cast | 8e2284aaa2364a8e47a8058e65d60813f9cd5089 | <ide><path>container.go
<ide> func (container *Container) cleanup() {
<ide> utils.Errorf("%s: Error close stdin: %s", container.ID, err)
<ide> }
<ide> }
<del> if err := container.stdout.Close(); err != nil {
<add> if err := container.stdout.CloseWriters(); err != nil {
<ide> utils.Errorf("%s: Error close stdout: %s", container.ID, err)
<ide> }
<del> if err := container.stderr.Close(); err != nil {
<add> if err := container.stderr.CloseWriters(); err != nil {
<ide> utils.Errorf("%s: Error close stderr: %s", container.ID, err)
<ide> }
<ide> if container.command.Terminal != nil {
<ide><path>execdriver/term.go
<ide> type Term interface {
<ide>
<ide> type Pipes struct {
<ide> Stdin io.ReadCloser
<del> Stdout, Stderr io.WriteCloser
<add> Stdout, Stderr io.Writer
<ide> }
<ide>
<del>func NewPipes(stdin io.ReadCloser, stdout, stderr io.WriteCloser, useStdin bool) *Pipes {
<add>func NewPipes(stdin io.ReadCloser, stdout, stderr io.Writer, useStdin bool) *Pipes {
<ide> p := &Pipes{
<ide> Stdout: stdout,
<ide> Stderr: stderr,
<ide> func (t *TtyConsole) attach(command *Command, pipes *Pipes) error {
<ide> command.Console = t.Slave.Name()
<ide>
<ide> go func() {
<del> defer pipes.Stdout.Close()
<add> if wb, ok := pipes.Stdout.(interface {
<add> CloseWriters() error
<add> }); ok {
<add> defer wb.CloseWriters()
<add> }
<ide> io.Copy(pipes.Stdout, t.Master)
<ide> }()
<ide>
<ide><path>utils/utils.go
<ide> func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
<ide> return len(p), nil
<ide> }
<ide>
<del>func (w *WriteBroadcaster) Close() error {
<add>func (w *WriteBroadcaster) CloseWriters() error {
<ide> w.Lock()
<ide> defer w.Unlock()
<ide> for sw := range w.writers {
<ide><path>utils/utils_test.go
<ide> func TestWriteBroadcaster(t *testing.T) {
<ide> t.Errorf("Buffer contains %v", bufferC.String())
<ide> }
<ide>
<del> writer.Close()
<add> writer.CloseWriters()
<ide> }
<ide>
<ide> type devNullCloser int | 4 |
Go | Go | fix a typo in hostconfig.shmsize validation | fee7e7c7a31023be9f0c26608e6cbd4e8a97d25b | <ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.
<ide> warnings = append(warnings, w...)
<ide>
<ide> if hostConfig.ShmSize < 0 {
<del> return warnings, fmt.Errorf("SHM size must be greater then 0")
<add> return warnings, fmt.Errorf("SHM size must be greater than 0")
<ide> }
<ide>
<ide> if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
<ide> status, body, err := sockRequest("POST", "/containers/create", config)
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<del> c.Assert(string(body), checker.Contains, "SHM size must be greater then 0")
<add> c.Assert(string(body), checker.Contains, "SHM size must be greater than 0")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) { | 2 |
Text | Text | add v3.17.3 to changelog.md | ad82c1b182d401f5c9107a00c2ca995f0ab3659c | <ide><path>CHANGELOG.md
<ide> - [#18774](https://github.com/emberjs/ember.js/pull/18774) [BUGFIX] Suspend observer deactivation during property changes
<ide> - [#18785](https://github.com/emberjs/ember.js/pull/18785) Drop Node 8 support.
<ide>
<add>### v3.17.3 (April 2, 2020)
<add>
<add>- [#18857](https://github.com/emberjs/ember.js/pull/18857) Pass value through to `PROPERTY_DID_CHANGE` to avoid calling `get` when setting values for computed props
<add>
<ide> ### v3.17.2 (March 26, 2020)
<ide>
<ide> - [#18837](https://github.com/emberjs/ember.js/pull/18837) [BUGFIX] Fix `willDestroy` on class based helpers. | 1 |
Javascript | Javascript | remove underlines on button text | f03a731c362995346d91d983b8bbc22a5ce2ea45 | <ide><path>client/src/components/helpers/CurrentChallengeLink.js
<ide> const createClickHandler = hardGoTo => e => {
<ide>
<ide> function CurrentChallengeLink({ children, hardGoTo }) {
<ide> return (
<del> <a href={currentChallengeApi} onClick={createClickHandler(hardGoTo)}>
<add> <a
<add> className='btn-cta-big btn btn-primary btn-block'
<add> href={currentChallengeApi}
<add> onClick={createClickHandler(hardGoTo)}
<add> >
<ide> {children}
<ide> </a>
<ide> );
<ide><path>client/src/components/profile/Profile.js
<ide> import React, { Fragment } from 'react';
<ide> import PropTypes from 'prop-types';
<del>import { Alert, Button, Grid, Row, Col } from '@freecodecamp/react-bootstrap';
<add>import { Alert, Grid, Row, Col } from '@freecodecamp/react-bootstrap';
<ide> import Helmet from 'react-helmet';
<ide> import { Link } from 'gatsby';
<ide>
<ide> const propTypes = {
<ide> };
<ide>
<ide> function TakeMeToTheChallenges() {
<del> return (
<del> <CurrentChallengeLink>
<del> <Button block={true} bsSize='lg' bsStyle='primary' className='btn-invert'>
<del> Take me to the Challenges
<del> </Button>
<del> </CurrentChallengeLink>
<del> );
<add> return <CurrentChallengeLink>Take me to the Challenges</CurrentChallengeLink>;
<ide> }
<ide>
<ide> function renderIsLocked(username) {
<ide> function renderSettingsButton() {
<ide> <Fragment>
<ide> <Row>
<ide> <Col sm={4} smOffset={4}>
<del> <Link to='/settings'>
<del> <Button
<del> block={true}
<del> bsSize='lg'
<del> bsStyle='primary'
<del> className='btn-invert'
<del> >
<del> Update my settings
<del> </Button>
<add> <Link className='btn btn-lg btn-primary btn-block' to='/settings'>
<add> Update my settings
<ide> </Link>
<ide> </Col>
<ide> </Row>
<ide><path>client/src/components/profile/components/Certifications.js
<ide> import { Link } from 'gatsby';
<ide> import { curry } from 'lodash';
<ide> import { createSelector } from 'reselect';
<ide> import { connect } from 'react-redux';
<del>import { Button, Row, Col } from '@freecodecamp/react-bootstrap';
<add>import { Row, Col } from '@freecodecamp/react-bootstrap';
<ide>
<ide> import { userByNameSelector } from '../../../redux';
<ide> import FullWidthRow from '../../helpers/FullWidthRow';
<ide> function renderCertShow(username, cert) {
<ide> <Fragment key={cert.title}>
<ide> <Row>
<ide> <Col className='certifications' sm={10} smPush={1}>
<del> <Link to={`/certification/${username}/${cert.showURL}`}>
<del> <Button
<del> block={true}
<del> bsSize='lg'
<del> bsStyle='primary'
<del> className='btn-invert'
<del> >
<del> View {cert.title}
<del> </Button>
<add> <Link
<add> className='btn btn-lg btn-primary btn-block'
<add> to={`/certification/${username}/${cert.showURL}`}
<add> >
<add> View {cert.title}
<ide> </Link>
<ide> </Col>
<ide> </Row>
<ide><path>client/src/pages/welcome.js
<ide> import PropTypes from 'prop-types';
<ide> import { bindActionCreators } from 'redux';
<ide> import { connect } from 'react-redux';
<ide> import { createSelector } from 'reselect';
<del>import { Grid, Row, Col, Button } from '@freecodecamp/react-bootstrap';
<add>import { Grid, Row, Col } from '@freecodecamp/react-bootstrap';
<ide> import Helmet from 'react-helmet';
<ide>
<del>import { Loader, Spacer } from '../components/helpers';
<del>import CurrentChallengeLink from '../components/helpers/CurrentChallengeLink';
<add>import { CurrentChallengeLink, Loader, Spacer } from '../components/helpers';
<ide> import Supporters from '../components/Supporters';
<ide> import {
<ide> userSelector,
<ide> function Welcome({
<ide> <Row>
<ide> <Col sm={6} smOffset={3} xs={12}>
<ide> <CurrentChallengeLink>
<del> <Button block={true} bsStyle='primary' className='btn-cta-big'>
<del> Go to my next challenge
<del> </Button>
<add> Go to my next challenge
<ide> </CurrentChallengeLink>
<ide> </Col>
<ide> </Row>
<ide><path>client/src/templates/Introduction/Intro.js
<ide> import React from 'react';
<ide> import PropTypes from 'prop-types';
<ide> import { Link, graphql } from 'gatsby';
<ide> import Helmet from 'react-helmet';
<del>import {
<del> Button,
<del> ListGroup,
<del> ListGroupItem
<del>} from '@freecodecamp/react-bootstrap';
<add>import { ListGroup, ListGroupItem } from '@freecodecamp/react-bootstrap';
<ide>
<ide> import LearnLayout from '../../components/layouts/Learn';
<ide> import FullWidthRow from '../../components/helpers/FullWidthRow';
<ide> function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) {
<ide> Go to the first lesson
<ide> </Link>
<ide> <ButtonSpacer />
<del> <Link to='/learn'>
<del> <Button block={true} bsSize='lg' className='btn-invert'>
<del> View the curriculum
<del> </Button>
<add> <Link class='btn btn-lg btn-primary btn-block' to='/learn'>
<add> View the curriculum
<ide> </Link>
<ide> <ButtonSpacer />
<ide> <hr /> | 5 |
PHP | PHP | update doc blocks for addassociations() | ca27336e94efb2637b88147a1a551e866db83457 | <ide><path>src/ORM/Table.php
<ide> public function associations() {
<ide> }
<ide>
<ide> /**
<del> * Setup associations.
<add> * Setup multiple associations.
<ide> *
<ide> * It takes an array containing set of table names indexed by association type
<ide> * as argument:
<ide> *
<ide> * {{{
<ide> * $this->Posts->associations([
<del> * 'belongsTo' => [
<del> * 'Users' => ['className' => 'App\Model\Table\UsersTable']
<del> * ],
<del> * 'hasMany' => ['Comments'],
<del> * 'belongsToMany' => ['Tags']
<add> * 'belongsTo' => [
<add> * 'Users' => ['className' => 'App\Model\Table\UsersTable']
<add> * ],
<add> * 'hasMany' => ['Comments'],
<add> * 'belongsToMany' => ['Tags']
<ide> * ]);
<ide> * }}}
<ide> *
<add> * Each association type accepts multiple associations where the keys
<add> * are the aliases, and the values are association config data. If numeric
<add> * keys are used the values will be treated as association aliases.
<add> *
<ide> * @param array $params Set of associations to bind (indexed by association type)
<ide> * @return void
<ide> * @see \Cake\ORM\Table::belongsTo() | 1 |
Java | Java | remove unused imports | 3da68cfe218f4817aefe67ca67b13ccb78109cfc | <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java
<ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory;
<ide> import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
<del>import org.springframework.core.Ordered;
<ide>
<ide> /**
<ide> * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java
<ide> import org.springframework.util.SerializationTestUtils;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.Matchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/FactoryAwareOrderProviderTests.java
<ide>
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.BDDMockito.*;
<del>import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.verify;
<ide>
<ide> import java.lang.reflect.Method;
<ide> import java.util.HashMap;
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncConfigurationSelector.java
<ide>
<ide> import org.springframework.context.annotation.AdviceMode;
<ide> import org.springframework.context.annotation.AdviceModeImportSelector;
<del>import org.springframework.context.annotation.AnnotationConfigUtils;
<ide>
<ide> /**
<ide> * Selects which implementation of {@link AbstractAsyncConfiguration} should be used based
<ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBean.java
<ide> import org.springframework.scheduling.support.DelegatingErrorHandlingRunnable;
<ide> import org.springframework.scheduling.support.TaskUtils;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide><path>spring-context/src/test/java/org/springframework/cache/interceptor/CacheErrorHandlerTests.java
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.BDDMockito.doReturn;
<del>import static org.mockito.BDDMockito.doThrow;
<ide> import static org.mockito.BDDMockito.*;
<del>import static org.mockito.BDDMockito.verify;
<del>import static org.mockito.Mockito.mock;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.concurrent.atomic.AtomicLong;
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java
<ide> import javax.jms.Message;
<ide> import javax.jms.MessageConsumer;
<ide> import javax.jms.Session;
<del>import javax.jms.Topic;
<ide>
<ide> import org.springframework.jms.connection.ConnectionFactoryUtils;
<ide> import org.springframework.jms.connection.JmsResourceHolder;
<ide><path>spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.BDDMockito.*;
<ide> import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.verify;
<ide>
<ide> /**
<ide> * @author Stephane Nicoll
<ide><path>spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.BDDMockito.*;
<ide> import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.verify;
<ide>
<ide> import java.io.Serializable;
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/AbstractMessagingTemplate.java
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.messaging.Message;
<del>import org.springframework.messaging.MessageHeaders;
<del>import org.springframework.messaging.converter.MessageConversionException;
<ide>
<ide> /**
<ide> * An extension of {@link AbstractMessageReceivingTemplate} that adds support for
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<del>import java.util.HashSet;
<ide> import java.util.Iterator;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.List;
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/SendToUser.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<del>import org.springframework.messaging.Message;
<del>import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
<del>
<ide> /**
<ide> * Annotation that indicates the return value of a message-handling method should
<ide> * be sent as a {@link org.springframework.messaging.Message} to the specified
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandler.java
<ide> import org.springframework.messaging.support.MessageHeaderInitializer;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ObjectUtils;
<del>import org.springframework.util.StringUtils;
<ide>
<ide> import java.lang.annotation.Annotation;
<ide> import java.security.Principal;
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/MessageBrokerRegistry.java
<ide> import org.springframework.messaging.SubscribableChannel;
<ide> import org.springframework.messaging.simp.broker.SimpleBrokerMessageHandler;
<ide> import org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler;
<del>import org.springframework.util.AntPathMatcher;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.PathMatcher;
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.mockito.Mockito;
<del>import org.springframework.beans.BeansException;
<add>
<ide> import org.springframework.beans.factory.ObjectFactory;
<ide>
<del>import java.util.Map;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide>
<ide> import static org.junit.Assert.assertThat;
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java
<ide> import org.junit.Test;
<ide>
<ide> import org.mockito.Mockito;
<del>import org.springframework.beans.DirectFieldAccessor;
<add>
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java
<ide> import org.springframework.messaging.support.MessageHeaderAccessor;
<ide> import org.springframework.util.AlternativeJdkIdGenerator;
<ide> import org.springframework.util.LinkedMultiValueMap;
<del>import org.springframework.util.MimeType;
<ide> import org.springframework.util.MimeTypeUtils;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java
<ide> import java.util.Map;
<ide> import java.util.UUID;
<ide>
<del>import org.hamcrest.CoreMatchers;
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<ide> import org.junit.rules.ExpectedException;
<ide><path>spring-test/src/test/java/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListenerTests.java
<ide> import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide><path>spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java
<ide> import java.util.GregorianCalendar;
<ide> import java.util.List;
<ide> import java.util.Locale;
<del>import java.util.Set;
<ide> import java.util.TimeZone;
<ide>
<ide> import org.hamcrest.Matchers;
<ide><path>spring-web/src/test/java/org/springframework/http/RequestEntityTests.java
<ide> import java.util.Map;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.junit.Assert.assertEquals;
<add>
<ide> import org.junit.Test;
<ide>
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java
<ide> import com.fasterxml.jackson.annotation.JsonView;
<ide> import com.fasterxml.jackson.databind.JavaType;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<del>import org.hamcrest.CoreMatchers;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide><path>spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java
<ide> import java.util.Optional;
<ide>
<ide> import javax.servlet.http.Part;
<del>import javax.swing.text.html.Option;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
<ide>
<ide> import org.w3c.dom.Element;
<ide>
<del>import org.springframework.beans.BeanMetadataElement;
<ide> import org.springframework.beans.factory.FactoryBean;
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/TilesConfigurerBeanDefinitionParser.java
<ide>
<ide> package org.springframework.web.servlet.config;
<ide>
<del>import org.springframework.beans.factory.BeanDefinitionStoreException;
<ide> import org.springframework.beans.factory.support.AbstractBeanDefinition;
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide> import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/BeanTypeNotPresentCondition.java
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.beans.factory.BeanFactoryUtils;
<ide> import org.springframework.beans.factory.ListableBeanFactory;
<del>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.context.annotation.ConditionContext;
<ide> import org.springframework.context.annotation.ConfigurationCondition;
<ide> import org.springframework.core.type.AnnotatedTypeMetadata;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java
<ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping;
<ide> import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
<ide> import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
<del>import org.springframework.web.servlet.resource.ResourceResolver;
<del>import org.springframework.web.servlet.resource.ResourceTransformer;
<ide>
<ide> /**
<ide> * Stores registrations of resource handlers for serving static resources such as images, css files and others
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMethodMappingNamingStrategy.java
<ide>
<ide> import org.springframework.web.method.HandlerMethod;
<ide>
<del>import java.lang.reflect.Method;
<del>
<ide> /**
<ide> * A strategy for assigning a name to a handler method's mapping.
<ide> *
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategy.java
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy;
<ide>
<del>import java.lang.reflect.Method;
<del>
<ide> /**
<ide> * A {@link org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy
<ide> * HandlerMethodMappingNamingStrategy} for {@code RequestMappingInfo}-based handler
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.http.HttpEntity;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpInputMessage;
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.core.io.Resource;
<ide>
<ide> /**
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceTransformer.java
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import java.io.IOException;
<del>import java.util.List;
<ide>
<ide> /**
<ide> * An abstraction for transforming the content of a resource.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceTransformerChain.java
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import java.io.IOException;
<del>import java.util.List;
<ide>
<ide> /**
<ide> * A contract for invoking a chain of {@link ResourceTransformer}s where each resolver
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
<ide> import org.springframework.format.annotation.DateTimeFormat;
<ide> import org.springframework.format.annotation.DateTimeFormat.ISO;
<ide> import org.springframework.format.support.FormattingConversionServiceFactoryBean;
<del>import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.mock.web.test.MockHttpServletRequest;
<ide> import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor;
<ide> import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter;
<ide> import org.springframework.web.context.support.GenericWebApplicationContext;
<del>import org.springframework.web.context.support.WebApplicationContextUtils;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.method.support.CompositeUriComponentsContributor;
<ide> import org.springframework.web.method.support.InvocableHandlerMethod;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketConnectionManager.java
<ide> import java.util.List;
<ide>
<ide> import org.springframework.context.Lifecycle;
<del>import org.springframework.context.SmartLifecycle;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.util.concurrent.ListenableFutureCallback;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/TransportRequest.java
<ide> package org.springframework.web.socket.sockjs.client;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.web.socket.WebSocketSession;
<ide> import org.springframework.web.socket.sockjs.frame.SockJsMessageCodec;
<del>import org.springframework.web.socket.sockjs.transport.TransportType;
<ide>
<ide> import java.net.URI;
<ide> import java.security.Principal;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/XhrTransport.java
<ide> package org.springframework.web.socket.sockjs.client;
<ide>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.ResponseEntity;
<del>import org.springframework.web.socket.CloseStatus;
<ide> import org.springframework.web.socket.TextMessage;
<ide>
<ide> import java.net.URI;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.ScheduledFuture;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/SockJsWebSocketHandler.java
<ide> package org.springframework.web.socket.sockjs.transport.handler;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/PollingSockJsSession.java
<ide>
<ide> package org.springframework.web.socket.sockjs.transport.session;
<ide>
<del>import java.util.ArrayList;
<del>import java.util.List;
<ide> import java.util.Map;
<del>import java.util.Queue;
<ide>
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.sockjs.SockJsTransportFailureException;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/StreamingSockJsSession.java
<ide>
<ide> import java.util.Map;
<ide>
<del>import org.springframework.http.server.ServerHttpRequest;
<del>import org.springframework.http.server.ServerHttpResponse;
<ide> import org.springframework.web.socket.WebSocketHandler;
<del>import org.springframework.web.socket.sockjs.SockJsException;
<ide> import org.springframework.web.socket.sockjs.SockJsTransportFailureException;
<ide> import org.springframework.web.socket.sockjs.frame.SockJsFrame;
<del>import org.springframework.web.socket.sockjs.frame.SockJsFrameFormat;
<ide> import org.springframework.web.socket.sockjs.frame.SockJsMessageCodec;
<ide> import org.springframework.web.socket.sockjs.transport.SockJsServiceConfig;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/WebSocketIntegrationTests.java
<ide> import org.springframework.web.socket.config.annotation.EnableWebSocket;
<ide> import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
<ide> import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
<del>import org.springframework.web.socket.handler.AbstractWebSocketHandler;
<ide> import org.springframework.web.socket.handler.TextWebSocketHandler;
<ide> import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/jetty/JettyWebSocketSessionTests.java
<ide> import static org.junit.Assert.assertNull;
<ide> import static org.junit.Assert.assertSame;
<ide> import static org.mockito.Mockito.reset;
<del>import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.verifyNoMoreInteractions;
<ide> import static org.mockito.Mockito.when;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/StandardWebSocketSessionTests.java
<ide> import static org.junit.Assert.assertNull;
<ide> import static org.junit.Assert.assertSame;
<ide> import static org.mockito.Mockito.reset;
<del>import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.verifyNoMoreInteractions;
<ide> import static org.mockito.Mockito.when;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java
<ide> import java.util.Map;
<ide> import java.util.concurrent.ScheduledFuture;
<ide>
<del>import org.hamcrest.Matchers;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<del>import org.springframework.beans.DirectFieldAccessor;
<ide> import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebMvcStompWebSocketEndpointRegistrationTests.java
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.HttpRequestHandler;
<ide> import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler;
<del>import org.springframework.web.socket.server.HandshakeInterceptor;
<ide> import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
<ide> import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
<ide> import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler;
<ide> import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.junit.Assert.assertArrayEquals;
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.mockito.Mockito.mock;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupportTests.java
<ide> import java.util.Set;
<ide> import java.util.concurrent.ScheduledThreadPoolExecutor;
<ide>
<del>import org.hamcrest.Description;
<del>import org.hamcrest.Matcher;
<del>import org.hamcrest.Matchers;
<del>import org.hamcrest.TypeSafeMatcher;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/JettySockJsIntegrationTests.java
<ide> package org.springframework.web.socket.sockjs.client;
<ide>
<ide> import org.eclipse.jetty.client.HttpClient;
<del>import org.eclipse.jetty.websocket.client.WebSocketClient;
<del>import org.junit.After;
<del>import org.junit.Before;
<add>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.web.socket.JettyWebSocketTestServer;
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransportTests.java
<ide> import java.util.concurrent.CountDownLatch;
<ide> import java.util.concurrent.LinkedBlockingDeque;
<ide>
<del>import static org.mockito.Matchers.eq;
<ide> import static org.mockito.Mockito.*;
<del>import static org.mockito.Mockito.verifyNoMoreInteractions;
<ide>
<ide> /**
<ide> * Unit tests for {@link RestTemplateXhrTransport}.
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java
<ide>
<ide> import org.junit.Assert;
<ide> import org.junit.Test;
<del>import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec;
<add>
<ide> import org.springframework.web.socket.sockjs.transport.TransportType;
<ide>
<ide> import java.net.URI;
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/XhrTransportTests.java
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertTrue;
<del>import static org.mockito.Matchers.notNull;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.verifyNoMoreInteractions; | 51 |
Text | Text | fix research_projects/mlm_wwm readme.md examples | 28d5700aae1bed4ec721cbeb5bc2527079113f46 | <ide><path>examples/research_projects/mlm_wwm/README.md
<ide> You could run the following:
<ide>
<ide>
<ide> ```bash
<del>export TRAIN_FILE=/path/to/dataset/wiki.train.raw
<add>export TRAIN_FILE=/path/to/train/file
<ide> export LTP_RESOURCE=/path/to/ltp/tokenizer
<ide> export BERT_RESOURCE=/path/to/bert/tokenizer
<ide> export SAVE_PATH=/path/to/data/ref.txt
<ide>
<ide> python run_chinese_ref.py \
<del> --file_name=path_to_train_or_eval_file \
<del> --ltp=path_to_ltp_tokenizer \
<del> --bert=path_to_bert_tokenizer \
<del> --save_path=path_to_reference_file
<add> --file_name=$TRAIN_FILE \
<add> --ltp=$LTP_RESOURCE \
<add> --bert=$BERT_RESOURCE \
<add> --save_path=$SAVE_PATH
<ide> ```
<ide>
<ide> Then you can run the script like this:
<ide>
<ide>
<ide> ```bash
<add>export TRAIN_FILE=/path/to/train/file
<add>export VALIDATION_FILE=/path/to/validation/file
<add>export TRAIN_REF_FILE=/path/to/train/chinese_ref/file
<add>export VALIDATION_REF_FILE=/path/to/validation/chinese_ref/file
<add>export OUTPUT_DIR=/tmp/test-mlm-wwm
<add>
<ide> python run_mlm_wwm.py \
<ide> --model_name_or_path roberta-base \
<del> --train_file path_to_train_file \
<del> --validation_file path_to_validation_file \
<del> --train_ref_file path_to_train_chinese_ref_file \
<del> --validation_ref_file path_to_validation_chinese_ref_file \
<add> --train_file $TRAIN_FILE \
<add> --validation_file $VALIDATION_FILE \
<add> --train_ref_file $TRAIN_REF_FILE \
<add> --validation_ref_file $VALIDATION_REF_FILE \
<ide> --do_train \
<ide> --do_eval \
<del> --output_dir /tmp/test-mlm-wwm
<add> --output_dir $OUTPUT_DIR
<ide> ```
<ide>
<ide> **Note1:** On TPU, you should the flag `--pad_to_max_length` to make sure all your batches have the same length.
<ide>
<del>**Note2:** And if you have any questions or something goes wrong when runing this code, don't hesitate to pin @wlhgtc.
<ide>\ No newline at end of file
<add>**Note2:** And if you have any questions or something goes wrong when runing this code, don't hesitate to pin @wlhgtc. | 1 |
Javascript | Javascript | save users into new `user` collection | 0e240ba6300d96f006737fe8a8410783bdbc76a6 | <ide><path>flattenUser.js
<ide> function createConnection(URI) {
<ide> });
<ide> }
<ide>
<del>function createQuery(db, collection, selection, options, batchSize) {
<add>function createQuery(db, collection, options, batchSize) {
<ide> return Rx.Observable.create(function (observer) {
<ide> console.log('Creating cursor...');
<del> var cursor = db.collection(collection).find(selection, options);
<add> var cursor = db.collection(collection).find({}, options);
<ide> cursor.batchSize(batchSize || 20);
<ide> // Cursor.each will yield all doc from a batch in the same tick,
<ide> // or schedule getting next batch on nextTick
<ide> function createQuery(db, collection, selection, options, batchSize) {
<ide> });
<ide> }
<ide>
<del>function saveUser(user) {
<add>function insertMany(db, collection, users, options) {
<ide> return Rx.Observable.create(function(observer) {
<del> user.save(function(err) {
<add> db.collection(collection).insertMany(users, options, function(err) {
<ide> if (err) {
<ide> return observer.onError(err);
<ide> }
<ide> function saveUser(user) {
<ide> }
<ide>
<ide> var count = 0;
<del>createConnection(secrets.db)
<add>// will supply our db object
<add>var dbObservable = createConnection(secrets.db).shareReplay();
<add>dbObservable
<ide> .flatMap(function(db) {
<add> // returns user document, n users per loop where n is the batchsize.
<ide> return createQuery(db, 'users', {});
<ide> })
<ide> .map(function(user) {
<add> // flatten user
<ide> assign(user, user.portfolio, user.profile);
<ide> return user;
<ide> })
<del> .flatMap(function(user) {
<del> return saveUser(user);
<add> // batch them into arrays of twenty documents
<add> .bufferWithCount(20)
<add> // get bd object ready for insert
<add> .withLatestFrom(dbObservable, function(users, db) {
<add> return {
<add> users: users,
<add> db: db
<add> };
<ide> })
<add> .flatMap(function(dats) {
<add> // bulk insert into new collection for loopback
<add> return insertMany(dats.db, 'user', dats.users, { w: 1 });
<add> })
<add> // count how many times insert completes
<ide> .count()
<ide> .subscribe(
<ide> function(_count) {
<del> count = _count;
<add> count = _count * 20;
<ide> },
<ide> function(err) {
<ide> console.log('an error occured', err); | 1 |
Ruby | Ruby | remove checks for encodings availability | 1e9e88fcd335c7d5a99159d592c3e1b605510a16 | <ide><path>actionmailer/test/base_test.rb
<ide> def teardown
<ide> assert_equal(1, email.attachments.length)
<ide> assert_equal('invoice.jpg', email.attachments[0].filename)
<ide> expected = "\312\213\254\232)b"
<del> expected.force_encoding(Encoding::BINARY) if '1.9'.respond_to?(:force_encoding)
<add> expected.force_encoding(Encoding::BINARY)
<ide> assert_equal expected, email.attachments['invoice.jpg'].decoded
<ide> end
<ide>
<ide> def teardown
<ide> assert_equal(1, email.attachments.length)
<ide> assert_equal('invoice.jpg', email.attachments[0].filename)
<ide> expected = "\312\213\254\232)b"
<del> expected.force_encoding(Encoding::BINARY) if '1.9'.respond_to?(:force_encoding)
<add> expected.force_encoding(Encoding::BINARY)
<ide> assert_equal expected, email.attachments['invoice.jpg'].decoded
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def raw_post
<ide> # variable is already set, wrap it in a StringIO.
<ide> def body
<ide> if raw_post = @env['RAW_POST_DATA']
<del> raw_post.force_encoding(Encoding::BINARY) if raw_post.respond_to?(:force_encoding)
<add> raw_post.force_encoding(Encoding::BINARY)
<ide> StringIO.new(raw_post)
<ide> else
<ide> @env['rack.input']
<ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
<ide> def initialize(app, options = {})
<ide>
<ide> def generate_sid
<ide> sid = SecureRandom.hex(16)
<del> sid.encode!('UTF-8') if sid.respond_to?(:encode!)
<add> sid.encode!('UTF-8')
<ide> sid
<ide> end
<ide>
<ide><path>actionpack/lib/action_view/helpers/capture_helper.rb
<ide> def content_for?(name)
<ide> def with_output_buffer(buf = nil) #:nodoc:
<ide> unless buf
<ide> buf = ActionView::OutputBuffer.new
<del> buf.force_encoding(output_buffer.encoding) if output_buffer.respond_to?(:encoding) && buf.respond_to?(:force_encoding)
<add> buf.force_encoding(output_buffer.encoding) if output_buffer
<ide> end
<ide> self.output_buffer, old_buffer = buf, output_buffer
<ide> yield
<ide><path>actionpack/test/controller/routing_test.rb
<ide> def test_route_with_text_default
<ide> assert_equal({ :controller => "content", :action => 'show_page', :id => 'foo' }, rs.recognize_path("/page/foo"))
<ide>
<ide> token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian
<del> token.force_encoding(Encoding::BINARY) if token.respond_to?(:force_encoding)
<add> token.force_encoding(Encoding::BINARY)
<ide> escaped_token = CGI::escape(token)
<ide>
<ide> assert_equal '/page/' + escaped_token, url_for(rs, { :controller => 'content', :action => 'show_page', :id => token })
<ide><path>actionpack/test/controller/send_file_test.rb
<ide> def test_file_stream
<ide> require 'stringio'
<ide> output = StringIO.new
<ide> output.binmode
<del> output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding)
<add> output.string.force_encoding(file_data.encoding)
<ide> assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } }
<ide> assert_equal file_data, output.string
<ide> end
<ide><path>actionpack/test/controller/test_test.rb
<ide> def test_test_uploaded_file
<ide> path = "#{FILES_DIR}/#{filename}"
<ide> content_type = 'image/png'
<ide> expected = File.read(path)
<del> expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding)
<add> expected.force_encoding(Encoding::BINARY)
<ide>
<ide> file = Rack::Test::UploadedFile.new(path, content_type)
<ide> assert_equal filename, file.original_filename
<ide><path>actionpack/test/dispatch/request/multipart_params_parsing_test.rb
<ide> def teardown
<ide>
<ide> # Rack doesn't handle multipart/mixed for us.
<ide> files = params['files']
<del> files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
<add> files.force_encoding('ASCII-8BIT')
<ide> assert_equal 19756, files.size
<ide> end
<ide>
<ide><path>actionpack/test/template/output_buffer_test.rb
<ide> def setup
<ide> assert_equal ['foo', 'bar'], body_parts
<ide> end
<ide>
<del> if '1.9'.respond_to?(:force_encoding)
<del> test 'flushing preserves output buffer encoding' do
<del> original_buffer = ' '.force_encoding(Encoding::EUC_JP)
<del> @vc.output_buffer = original_buffer
<del> @vc.flush_output_buffer
<del> assert_equal ['foo', original_buffer], body_parts
<del> assert_not_equal original_buffer, output_buffer
<del> assert_equal Encoding::EUC_JP, output_buffer.encoding
<del> end
<add> test 'flushing preserves output buffer encoding' do
<add> original_buffer = ' '.force_encoding(Encoding::EUC_JP)
<add> @vc.output_buffer = original_buffer
<add> @vc.flush_output_buffer
<add> assert_equal ['foo', original_buffer], body_parts
<add> assert_not_equal original_buffer, output_buffer
<add> assert_equal Encoding::EUC_JP, output_buffer.encoding
<ide> end
<ide>
<ide> protected
<ide><path>actionpack/test/template/render_test.rb
<ide> def teardown
<ide> GC.start
<ide> end
<ide>
<del> if '1.9'.respond_to?(:force_encoding)
<del> def test_render_utf8_template_with_magic_comment
<del> with_external_encoding Encoding::ASCII_8BIT do
<del> result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield")
<del> assert_equal Encoding::UTF_8, result.encoding
<del> assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result
<del> end
<add> def test_render_utf8_template_with_magic_comment
<add> with_external_encoding Encoding::ASCII_8BIT do
<add> result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield")
<add> assert_equal Encoding::UTF_8, result.encoding
<add> assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result
<ide> end
<add> end
<ide>
<del> def test_render_utf8_template_with_default_external_encoding
<del> with_external_encoding Encoding::UTF_8 do
<del> result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
<del> assert_equal Encoding::UTF_8, result.encoding
<del> assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result
<del> end
<add> def test_render_utf8_template_with_default_external_encoding
<add> with_external_encoding Encoding::UTF_8 do
<add> result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
<add> assert_equal Encoding::UTF_8, result.encoding
<add> assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result
<ide> end
<add> end
<ide>
<del> def test_render_utf8_template_with_incompatible_external_encoding
<del> with_external_encoding Encoding::SHIFT_JIS do
<del> begin
<del> @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
<del> flunk 'Should have raised incompatible encoding error'
<del> rescue ActionView::Template::Error => error
<del> assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
<del> end
<add> def test_render_utf8_template_with_incompatible_external_encoding
<add> with_external_encoding Encoding::SHIFT_JIS do
<add> begin
<add> @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
<add> flunk 'Should have raised incompatible encoding error'
<add> rescue ActionView::Template::Error => error
<add> assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
<ide> end
<ide> end
<add> end
<ide>
<del> def test_render_utf8_template_with_partial_with_incompatible_encoding
<del> with_external_encoding Encoding::SHIFT_JIS do
<del> begin
<del> @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield")
<del> flunk 'Should have raised incompatible encoding error'
<del> rescue ActionView::Template::Error => error
<del> assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
<del> end
<add> def test_render_utf8_template_with_partial_with_incompatible_encoding
<add> with_external_encoding Encoding::SHIFT_JIS do
<add> begin
<add> @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield")
<add> flunk 'Should have raised incompatible encoding error'
<add> rescue ActionView::Template::Error => error
<add> assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
<ide> end
<ide> end
<add> end
<ide>
<del> def with_external_encoding(encoding)
<del> old = Encoding.default_external
<del> silence_warnings { Encoding.default_external = encoding }
<del> yield
<del> ensure
<del> silence_warnings { Encoding.default_external = old }
<del> end
<add> def with_external_encoding(encoding)
<add> old = Encoding.default_external
<add> silence_warnings { Encoding.default_external = encoding }
<add> yield
<add> ensure
<add> silence_warnings { Encoding.default_external = old }
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def clear_cache!
<ide> @statements.clear
<ide> end
<ide>
<del> if "<3".respond_to?(:encode)
<del> # Taken from here:
<del> # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb
<del> # Author: TOMITA Masahiro <[email protected]>
<del> ENCODINGS = {
<del> "armscii8" => nil,
<del> "ascii" => Encoding::US_ASCII,
<del> "big5" => Encoding::Big5,
<del> "binary" => Encoding::ASCII_8BIT,
<del> "cp1250" => Encoding::Windows_1250,
<del> "cp1251" => Encoding::Windows_1251,
<del> "cp1256" => Encoding::Windows_1256,
<del> "cp1257" => Encoding::Windows_1257,
<del> "cp850" => Encoding::CP850,
<del> "cp852" => Encoding::CP852,
<del> "cp866" => Encoding::IBM866,
<del> "cp932" => Encoding::Windows_31J,
<del> "dec8" => nil,
<del> "eucjpms" => Encoding::EucJP_ms,
<del> "euckr" => Encoding::EUC_KR,
<del> "gb2312" => Encoding::EUC_CN,
<del> "gbk" => Encoding::GBK,
<del> "geostd8" => nil,
<del> "greek" => Encoding::ISO_8859_7,
<del> "hebrew" => Encoding::ISO_8859_8,
<del> "hp8" => nil,
<del> "keybcs2" => nil,
<del> "koi8r" => Encoding::KOI8_R,
<del> "koi8u" => Encoding::KOI8_U,
<del> "latin1" => Encoding::ISO_8859_1,
<del> "latin2" => Encoding::ISO_8859_2,
<del> "latin5" => Encoding::ISO_8859_9,
<del> "latin7" => Encoding::ISO_8859_13,
<del> "macce" => Encoding::MacCentEuro,
<del> "macroman" => Encoding::MacRoman,
<del> "sjis" => Encoding::SHIFT_JIS,
<del> "swe7" => nil,
<del> "tis620" => Encoding::TIS_620,
<del> "ucs2" => Encoding::UTF_16BE,
<del> "ujis" => Encoding::EucJP_ms,
<del> "utf8" => Encoding::UTF_8,
<del> "utf8mb4" => Encoding::UTF_8,
<del> }
<del> else
<del> ENCODINGS = Hash.new { |h,k| h[k] = k }
<del> end
<add> # Taken from here:
<add> # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb
<add> # Author: TOMITA Masahiro <[email protected]>
<add> ENCODINGS = {
<add> "armscii8" => nil,
<add> "ascii" => Encoding::US_ASCII,
<add> "big5" => Encoding::Big5,
<add> "binary" => Encoding::ASCII_8BIT,
<add> "cp1250" => Encoding::Windows_1250,
<add> "cp1251" => Encoding::Windows_1251,
<add> "cp1256" => Encoding::Windows_1256,
<add> "cp1257" => Encoding::Windows_1257,
<add> "cp850" => Encoding::CP850,
<add> "cp852" => Encoding::CP852,
<add> "cp866" => Encoding::IBM866,
<add> "cp932" => Encoding::Windows_31J,
<add> "dec8" => nil,
<add> "eucjpms" => Encoding::EucJP_ms,
<add> "euckr" => Encoding::EUC_KR,
<add> "gb2312" => Encoding::EUC_CN,
<add> "gbk" => Encoding::GBK,
<add> "geostd8" => nil,
<add> "greek" => Encoding::ISO_8859_7,
<add> "hebrew" => Encoding::ISO_8859_8,
<add> "hp8" => nil,
<add> "keybcs2" => nil,
<add> "koi8r" => Encoding::KOI8_R,
<add> "koi8u" => Encoding::KOI8_U,
<add> "latin1" => Encoding::ISO_8859_1,
<add> "latin2" => Encoding::ISO_8859_2,
<add> "latin5" => Encoding::ISO_8859_9,
<add> "latin7" => Encoding::ISO_8859_13,
<add> "macce" => Encoding::MacCentEuro,
<add> "macroman" => Encoding::MacRoman,
<add> "sjis" => Encoding::SHIFT_JIS,
<add> "swe7" => nil,
<add> "tis620" => Encoding::TIS_620,
<add> "ucs2" => Encoding::UTF_16BE,
<add> "ujis" => Encoding::EucJP_ms,
<add> "utf8" => Encoding::UTF_8,
<add> "utf8mb4" => Encoding::UTF_8,
<add> }
<ide>
<ide> # Get the client encoding for this database
<ide> def client_encoding
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
<ide> def string_to_binary(value)
<ide> end
<ide>
<ide> def binary_to_string(value)
<del> if value.respond_to?(:force_encoding) && value.encoding != Encoding::ASCII_8BIT
<add> if value.encoding != Encoding::ASCII_8BIT
<ide> value = value.force_encoding(Encoding::ASCII_8BIT)
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_client_encoding
<del> if "<3".respond_to?(:encoding)
<del> assert_equal Encoding::UTF_8, @conn.client_encoding
<del> else
<del> assert_equal 'utf8', @conn.client_encoding
<del> end
<add> assert_equal Encoding::UTF_8, @conn.client_encoding
<ide> end
<ide>
<ide> def test_exec_insert_number
<ide> def test_exec_insert_string
<ide>
<ide> value = result.rows.last.last
<ide>
<del> if "<3".respond_to?(:encoding)
<del> # FIXME: this should probably be inside the mysql AR adapter?
<del> value.force_encoding(@conn.client_encoding)
<add> # FIXME: this should probably be inside the mysql AR adapter?
<add> value.force_encoding(@conn.client_encoding)
<ide>
<del> # The strings in this file are utf-8, so transcode to utf-8
<del> value.encode!(Encoding::UTF_8)
<del> end
<add> # The strings in this file are utf-8, so transcode to utf-8
<add> value.encode!(Encoding::UTF_8)
<ide>
<ide> assert_equal str, value
<ide> end
<ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
<ide> def test_exec_query_typecasts_bind_vals
<ide> end
<ide>
<ide> def test_quote_binary_column_escapes_it
<del> return unless "<3".respond_to?(:encode)
<del>
<ide> DualEncoding.connection.execute(<<-eosql)
<ide> CREATE TABLE dual_encodings (
<ide> id integer PRIMARY KEY AUTOINCREMENT,
<ide> def test_quote_binary_column_escapes_it
<ide> assert_equal str, binary.data
<ide>
<ide> ensure
<del> if "<3".respond_to?(:encode)
<del> DualEncoding.connection.drop_table('dual_encodings')
<del> end
<add> DualEncoding.connection.drop_table('dual_encodings')
<ide> end
<ide>
<ide> def test_execute
<ide><path>activerecord/test/cases/binary_test.rb
<ide> class BinaryTest < ActiveRecord::TestCase
<ide>
<ide> def test_mixed_encoding
<ide> str = "\x80"
<del> str.force_encoding('ASCII-8BIT') if str.respond_to?(:force_encoding)
<add> str.force_encoding('ASCII-8BIT')
<ide>
<ide> binary = Binary.new :name => 'いただきます!', :data => str
<ide> binary.save!
<ide> def test_mixed_encoding
<ide>
<ide> # Mysql adapter doesn't properly encode things, so we have to do it
<ide> if current_adapter?(:MysqlAdapter)
<del> name.force_encoding('UTF-8') if name.respond_to?(:force_encoding)
<add> name.force_encoding('UTF-8')
<ide> end
<ide> assert_equal 'いただきます!', name
<ide> end
<ide> def test_load_save
<ide>
<ide> FIXTURES.each do |filename|
<ide> data = File.read(ASSETS_ROOT + "/#{filename}")
<del> data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
<add> data.force_encoding('ASCII-8BIT')
<ide> data.freeze
<ide>
<ide> bin = Binary.new(:data => data)
<ide><path>activerecord/test/cases/fixtures_test.rb
<ide> def test_subsubdir_file_with_arbitrary_name
<ide>
<ide> def test_binary_in_fixtures
<ide> data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
<del> data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
<add> data.force_encoding('ASCII-8BIT')
<ide> data.freeze
<ide> assert_equal data, @flowers.data
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/string/access.rb
<ide> require "active_support/multibyte"
<ide>
<ide> class String
<del> unless '1.9'.respond_to?(:force_encoding)
<del> # Returns the character at the +position+ treating the string as an array (where 0 is the first character).
<del> #
<del> # Examples:
<del> # "hello".at(0) # => "h"
<del> # "hello".at(4) # => "o"
<del> # "hello".at(10) # => ERROR if < 1.9, nil in 1.9
<del> def at(position)
<del> mb_chars[position, 1].to_s
<del> end
<del>
<del> # Returns the remaining of the string from the +position+ treating the string as an array (where 0 is the first character).
<del> #
<del> # Examples:
<del> # "hello".from(0) # => "hello"
<del> # "hello".from(2) # => "llo"
<del> # "hello".from(10) # => "" if < 1.9, nil in 1.9
<del> def from(position)
<del> mb_chars[position..-1].to_s
<del> end
<del>
<del> # Returns the beginning of the string up to the +position+ treating the string as an array (where 0 is the first character).
<del> #
<del> # Examples:
<del> # "hello".to(0) # => "h"
<del> # "hello".to(2) # => "hel"
<del> # "hello".to(10) # => "hello"
<del> def to(position)
<del> mb_chars[0..position].to_s
<del> end
<del>
<del> # Returns the first character of the string or the first +limit+ characters.
<del> #
<del> # Examples:
<del> # "hello".first # => "h"
<del> # "hello".first(2) # => "he"
<del> # "hello".first(10) # => "hello"
<del> def first(limit = 1)
<del> if limit == 0
<del> ''
<del> elsif limit >= size
<del> self
<del> else
<del> mb_chars[0...limit].to_s
<del> end
<del> end
<del>
<del> # Returns the last character of the string or the last +limit+ characters.
<del> #
<del> # Examples:
<del> # "hello".last # => "o"
<del> # "hello".last(2) # => "lo"
<del> # "hello".last(10) # => "hello"
<del> def last(limit = 1)
<del> if limit == 0
<del> ''
<del> elsif limit >= size
<del> self
<del> else
<del> mb_chars[(-limit)..-1].to_s
<del> end
<del> end
<del> else
<del> def at(position)
<del> self[position]
<del> end
<add> def at(position)
<add> self[position]
<add> end
<ide>
<del> def from(position)
<del> self[position..-1]
<del> end
<add> def from(position)
<add> self[position..-1]
<add> end
<ide>
<del> def to(position)
<del> self[0..position]
<del> end
<add> def to(position)
<add> self[0..position]
<add> end
<ide>
<del> def first(limit = 1)
<del> if limit == 0
<del> ''
<del> elsif limit >= size
<del> self
<del> else
<del> to(limit - 1)
<del> end
<add> def first(limit = 1)
<add> if limit == 0
<add> ''
<add> elsif limit >= size
<add> self
<add> else
<add> to(limit - 1)
<ide> end
<add> end
<ide>
<del> def last(limit = 1)
<del> if limit == 0
<del> ''
<del> elsif limit >= size
<del> self
<del> else
<del> from(-limit)
<del> end
<add> def last(limit = 1)
<add> if limit == 0
<add> ''
<add> elsif limit >= size
<add> self
<add> else
<add> from(-limit)
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/json/encoding.rb
<ide> def escape_html_entities_in_json=(value)
<ide> end
<ide>
<ide> def escape(string)
<del> if string.respond_to?(:force_encoding)
<del> string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
<del> end
<add> string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
<ide> json = string.
<ide> gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
<ide> gsub(/([\xC0-\xDF][\x80-\xBF]|
<ide> def escape(string)
<ide> s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
<ide> }
<ide> json = %("#{json}")
<del> json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
<add> json.force_encoding(::Encoding::UTF_8)
<ide> json
<ide> end
<ide> end
<ide> def as_json(options = nil) #:nodoc:
<ide> strftime('%Y/%m/%d %H:%M:%S %z')
<ide> end
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>activesupport/lib/active_support/multibyte/chars.rb
<ide> def translate_offset(byte_offset) #:nodoc:
<ide> return nil if byte_offset.nil?
<ide> return 0 if @wrapped_string == ''
<ide>
<del> if @wrapped_string.respond_to?(:force_encoding)
<del> @wrapped_string = @wrapped_string.dup.force_encoding(Encoding::ASCII_8BIT)
<del> end
<add> @wrapped_string = @wrapped_string.dup.force_encoding(Encoding::ASCII_8BIT)
<ide>
<ide> begin
<ide> @wrapped_string[0...byte_offset].unpack('U*').length
<ide><path>activesupport/lib/active_support/multibyte/utils.rb
<ide>
<ide> module ActiveSupport #:nodoc:
<ide> module Multibyte #:nodoc:
<del> if Kernel.const_defined?(:Encoding)
<del> # Returns a regular expression that matches valid characters in the current encoding
<del> def self.valid_character
<del> VALID_CHARACTER[Encoding.default_external.to_s]
<del> end
<del> else
<del> def self.valid_character
<del> case $KCODE
<del> when 'UTF8'
<del> VALID_CHARACTER['UTF-8']
<del> when 'SJIS'
<del> VALID_CHARACTER['Shift_JIS']
<del> end
<del> end
<add> # Returns a regular expression that matches valid characters in the current encoding
<add> def self.valid_character
<add> VALID_CHARACTER[Encoding.default_external.to_s]
<ide> end
<ide>
<del> if 'string'.respond_to?(:valid_encoding?)
<del> # Verifies the encoding of a string
<del> def self.verify(string)
<del> string.valid_encoding?
<del> end
<del> else
<del> def self.verify(string)
<del> if expression = valid_character
<del> # Splits the string on character boundaries, which are determined based on $KCODE.
<del> string.split(//).all? { |c| expression =~ c }
<del> else
<del> true
<del> end
<del> end
<add> # Verifies the encoding of a string
<add> def self.verify(string)
<add> string.valid_encoding?
<ide> end
<ide>
<ide> # Verifies the encoding of the string and raises an exception when it's not valid
<ide> def self.verify!(string)
<ide> raise EncodingError.new("Found characters with invalid encoding") unless verify(string)
<ide> end
<ide>
<del> if 'string'.respond_to?(:force_encoding)
<del> # Removes all invalid characters from the string.
<del> #
<del> # Note: this method is a no-op in Ruby 1.9
<del> def self.clean(string)
<del> string
<del> end
<del> else
<del> def self.clean(string)
<del> if expression = valid_character
<del> # Splits the string on character boundaries, which are determined based on $KCODE.
<del> string.split(//).grep(expression).join
<del> else
<del> string
<del> end
<del> end
<add> # Removes all invalid characters from the string.
<add> #
<add> # Note: this method is a no-op in Ruby 1.9
<add> def self.clean(string)
<add> string
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/buffered_logger_test.rb
<ide> def test_write_binary_data_to_existing_file
<ide> logger.level = Logger::DEBUG
<ide>
<ide> str = "\x80"
<del> if str.respond_to?(:force_encoding)
<del> str.force_encoding("ASCII-8BIT")
<del> end
<add> str.force_encoding("ASCII-8BIT")
<ide>
<ide> logger.add Logger::DEBUG, str
<ide> ensure
<ide> def test_write_binary_data_create_file
<ide> logger.level = Logger::DEBUG
<ide>
<ide> str = "\x80"
<del> if str.respond_to?(:force_encoding)
<del> str.force_encoding("ASCII-8BIT")
<del> end
<add> str.force_encoding("ASCII-8BIT")
<ide>
<ide> logger.add Logger::DEBUG, str
<ide> ensure
<ide> def test_buffer_multibyte
<ide> @logger.info(BYTE_STRING)
<ide> assert @output.string.include?(UNICODE_STRING)
<ide> byte_string = @output.string.dup
<del> if byte_string.respond_to?(:force_encoding)
<del> byte_string.force_encoding("ASCII-8BIT")
<del> end
<add> byte_string.force_encoding("ASCII-8BIT")
<ide> assert byte_string.include?(BYTE_STRING)
<ide> end
<ide> end
<ide><path>activesupport/test/caching_test.rb
<ide> def test_really_long_keys
<ide> # The error is caused by charcter encodings that can't be compared with ASCII-8BIT regular expressions and by special
<ide> # characters like the umlaut in UTF-8.
<ide> module EncodedKeyCacheBehavior
<del> if defined?(Encoding)
<del> Encoding.list.each do |encoding|
<del> define_method "test_#{encoding.name.underscore}_encoded_values" do
<del> key = "foo".force_encoding(encoding)
<del> assert @cache.write(key, "1", :raw => true)
<del> assert_equal "1", @cache.read(key)
<del> assert_equal "1", @cache.fetch(key)
<del> assert @cache.delete(key)
<del> assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
<del> assert_equal 3, @cache.increment(key)
<del> assert_equal 2, @cache.decrement(key)
<del> end
<del> end
<del>
<del> def test_common_utf8_values
<del> key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
<add> Encoding.list.each do |encoding|
<add> define_method "test_#{encoding.name.underscore}_encoded_values" do
<add> key = "foo".force_encoding(encoding)
<ide> assert @cache.write(key, "1", :raw => true)
<ide> assert_equal "1", @cache.read(key)
<ide> assert_equal "1", @cache.fetch(key)
<ide> def test_common_utf8_values
<ide> assert_equal 3, @cache.increment(key)
<ide> assert_equal 2, @cache.decrement(key)
<ide> end
<add> end
<ide>
<del> def test_retains_encoding
<del> key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
<del> assert @cache.write(key, "1", :raw => true)
<del> assert_equal Encoding::UTF_8, key.encoding
<del> end
<add> def test_common_utf8_values
<add> key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
<add> assert @cache.write(key, "1", :raw => true)
<add> assert_equal "1", @cache.read(key)
<add> assert_equal "1", @cache.fetch(key)
<add> assert @cache.delete(key)
<add> assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
<add> assert_equal 3, @cache.increment(key)
<add> assert_equal 2, @cache.decrement(key)
<add> end
<add>
<add> def test_retains_encoding
<add> key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
<add> assert @cache.write(key, "1", :raw => true)
<add> assert_equal Encoding::UTF_8, key.encoding
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/json/encoding_test.rb
<ide> def test_hash_encoding
<ide> def test_utf8_string_encoded_properly
<ide> result = ActiveSupport::JSON.encode('€2.99')
<ide> assert_equal '"\\u20ac2.99"', result
<del> assert_equal(Encoding::UTF_8, result.encoding) if result.respond_to?(:encoding)
<add> assert_equal(Encoding::UTF_8, result.encoding)
<ide>
<ide> result = ActiveSupport::JSON.encode('✎☺')
<ide> assert_equal '"\\u270e\\u263a"', result
<del> assert_equal(Encoding::UTF_8, result.encoding) if result.respond_to?(:encoding)
<add> assert_equal(Encoding::UTF_8, result.encoding)
<ide> end
<ide>
<ide> def test_non_utf8_string_transcodes
<ide><path>activesupport/test/multibyte_test_helpers.rb
<ide> module MultibyteTestHelpers
<ide> UNICODE_STRING = 'こにちわ'
<ide> ASCII_STRING = 'ohayo'
<del> BYTE_STRING = "\270\236\010\210\245"
<del> if BYTE_STRING.respond_to?(:force_encoding)
<del> BYTE_STRING.force_encoding("ASCII-8BIT")
<del> end
<add> BYTE_STRING = "\270\236\010\210\245".force_encoding("ASCII-8BIT")
<ide>
<ide> def chars(str)
<ide> ActiveSupport::Multibyte::Chars.new(str)
<ide><path>railties/test/application/initializers/frameworks_test.rb
<ide> def from_bar_helper
<ide> end
<ide>
<ide> test "assignment config.encoding to default_charset" do
<del> charset = "ruby".respond_to?(:force_encoding) ? 'Shift_JIS' : 'UTF8'
<add> charset = 'Shift_JIS'
<ide> add_to_config "config.encoding = '#{charset}'"
<ide> require "#{app_path}/config/environment"
<ide> assert_equal charset, ActionDispatch::Response.default_charset | 25 |
Javascript | Javascript | use _ to disambiguate local vs. global d3 | 0d7c6c55e71d43f9d8286bfdd9ffd5372c51411b | <ide><path>test/arrays/max-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.isUndefined(max([NaN, NaN]));
<ide> },
<ide> "applies the optional accessor function": function(max) {
<del> assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return d3.min(d); }), 2);
<add> assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2);
<ide> assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4);
<ide> }
<ide> }
<ide><path>test/arrays/min-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.isUndefined(min([NaN, NaN]));
<ide> },
<ide> "applies the optional accessor function": function(min) {
<del> assert.equal(min([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return d3.max(d); }), 5);
<add> assert.equal(min([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.max(d); }), 5);
<ide> assert.equal(min([1, 2, 3, 4, 5], function(d, i) { return i; }), 0);
<ide> }
<ide> }
<ide><path>test/arrays/nest-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> .key(function(d) { return d.foo; })
<ide> .entries([{foo: 1}, {foo: 1}, {foo: 2}])
<ide> .map(function(d) { return d.key; })
<del> .sort(d3.ascending);
<add> .sort(_.ascending);
<ide> assert.deepEqual(keys, ["1", "2"]);
<ide> },
<ide> "each entry is a key-values object, with values in input order": function(nest) {
<ide> suite.addBatch({
<ide> },
<ide> "keys can be sorted using an optional comparator": function(nest) {
<ide> var keys = nest()
<del> .key(function(d) { return d.foo; }).sortKeys(d3.descending)
<add> .key(function(d) { return d.foo; }).sortKeys(_.descending)
<ide> .entries([{foo: 1}, {foo: 1}, {foo: 2}])
<ide> .map(function(d) { return d.key; });
<ide> assert.deepEqual(keys, ["2", "1"]);
<ide> suite.addBatch({
<ide> "values can be aggregated using an optional rollup": function(nest) {
<ide> var entries = nest()
<ide> .key(function(d) { return d.foo; })
<del> .rollup(function(values) { return d3.sum(values, function(d) { return d.bar; }); })
<add> .rollup(function(values) { return _.sum(values, function(d) { return d.bar; }); })
<ide> .entries([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]);
<ide> assert.deepEqual(entries, [
<ide> {key: "1", values: 3},
<ide> suite.addBatch({
<ide> },
<ide> "multiple key functions can be specified": function(nest) {
<ide> var entries = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(entries, [
<ide> {key: "0", values: [
<ide> suite.addBatch({
<ide> },
<ide> "the rollup function only applies to leaf values": function(nest) {
<ide> var entries = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .rollup(function(values) { return values.length; })
<ide> .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(entries, [
<ide> suite.addBatch({
<ide> },
<ide> "the value comparator only applies to leaf values": function(nest) {
<ide> var entries = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .sortValues(function(a, b) { return a[2] - b[2]; })
<ide> .entries([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]);
<ide> assert.deepEqual(entries, [
<ide> suite.addBatch({
<ide> },
<ide> "the key comparator only applies to the last-specified key": function(nest) {
<ide> var entries = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.descending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.descending)
<ide> .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(entries, [
<ide> {key: "0", values: [
<ide> suite.addBatch({
<ide> ]}
<ide> ]);
<ide> var entries = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.descending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.descending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(entries, [
<ide> {key: "1", values: [
<ide> suite.addBatch({
<ide> "values can be aggregated using an optional rollup": function(nest) {
<ide> var map = nest()
<ide> .key(function(d) { return d.foo; })
<del> .rollup(function(values) { return d3.sum(values, function(d) { return d.bar; }); })
<add> .rollup(function(values) { return _.sum(values, function(d) { return d.bar; }); })
<ide> .map([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]);
<ide> assert.deepEqual(map, {
<ide> "1": 3,
<ide> suite.addBatch({
<ide> },
<ide> "multiple key functions can be specified": function(nest) {
<ide> var map = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .map([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(map, {
<ide> "0": {
<ide> suite.addBatch({
<ide> },
<ide> "the rollup function only applies to leaf values": function(nest) {
<ide> var map = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .rollup(function(values) { return values.length; })
<ide> .map([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]);
<ide> assert.deepEqual(map, {
<ide> suite.addBatch({
<ide> },
<ide> "the value comparator only applies to leaf values": function(nest) {
<ide> var map = nest()
<del> .key(function(d) { return d[0]; }).sortKeys(d3.ascending)
<del> .key(function(d) { return d[1]; }).sortKeys(d3.ascending)
<add> .key(function(d) { return d[0]; }).sortKeys(_.ascending)
<add> .key(function(d) { return d[1]; }).sortKeys(_.ascending)
<ide> .sortValues(function(a, b) { return a[2] - b[2]; })
<ide> .map([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]);
<ide> assert.deepEqual(map, {
<ide> suite.addBatch({
<ide> "a custom map implementation can be specified": function(nest) {
<ide> var map = nest()
<ide> .key(String)
<del> .map(["hasOwnProperty", "__proto__"], d3.map);
<add> .map(["hasOwnProperty", "__proto__"], _.map);
<ide> assert.deepEqual(map.entries(), [
<ide> {key: "hasOwnProperty", value: ["hasOwnProperty"]},
<ide> {key: "__proto__", value: ["__proto__"]}
<ide> suite.addBatch({
<ide> var map = nest()
<ide> .key(function(d) { return d.foo; })
<ide> .key(function(d) { return d.bar; })
<del> .map([{foo: 42, bar: "red"}], d3.map);
<add> .map([{foo: 42, bar: "red"}], _.map);
<ide> assert.deepEqual(map.keys(), ["42"]);
<ide> assert.deepEqual(map.get("42").keys(), ["red"]);
<ide> assert.deepEqual(map.get("42").values(), [[{foo: 42, bar: "red"}]]);
<ide><path>test/arrays/set-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("assert");
<ide>
<ide> suite.addBatch({
<ide> },
<ide> "values are returned in arbitrary order": function(set) {
<ide> var s = set(["foo", "bar"]);
<del> assert.deepEqual(s.values().sort(d3.ascending), ["bar", "foo"]);
<add> assert.deepEqual(s.values().sort(_.ascending), ["bar", "foo"]);
<ide> var s = set(["bar", "foo"]);
<del> assert.deepEqual(s.values().sort(d3.ascending), ["bar", "foo"]);
<add> assert.deepEqual(s.values().sort(_.ascending), ["bar", "foo"]);
<ide> },
<ide> "observes changes via add and remove": function(set) {
<ide> var s = set(["foo", "bar"]);
<del> assert.deepEqual(s.values().sort(d3.ascending), ["bar", "foo"]);
<add> assert.deepEqual(s.values().sort(_.ascending), ["bar", "foo"]);
<ide> s.remove("foo");
<ide> assert.deepEqual(s.values(), ["bar"]);
<ide> s.add("bar");
<ide> assert.deepEqual(s.values(), ["bar"]);
<ide> s.add("foo");
<del> assert.deepEqual(s.values().sort(d3.ascending), ["bar", "foo"]);
<add> assert.deepEqual(s.values().sort(_.ascending), ["bar", "foo"]);
<ide> s.remove("bar");
<ide> assert.deepEqual(s.values(), ["foo"]);
<ide> s.remove("foo");
<ide><path>test/color/hcl-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assertHclEqual(hcl("rgb(102, 102, 0)"), 102.85124420310271, 49.44871600399321, 41.73251953866431);
<ide> },
<ide> "can convert from RGB": function(hcl) {
<del> assertHclEqual(hcl(d3.rgb(12, 34, 56)), -89.58282792342067, 16.833655998102003, 12.65624852526134);
<add> assertHclEqual(hcl(_.rgb(12, 34, 56)), -89.58282792342067, 16.833655998102003, 12.65624852526134);
<ide> },
<ide> "can convert from HSL": function(hcl) {
<ide> assertHclEqual(hcl(hcl(20, .8, .3)), 20, 0.8, 0.3);
<ide> suite.addBatch({
<ide> assert.strictEqual(hcl(hcl(60, -4, 32)) + "", "#454c51");
<ide> },
<ide> "roundtrip to HSL is idempotent": function(hcl) {
<del> assert.hslEqual(d3.hsl(hcl("steelblue")), d3.hsl("steelblue"));
<add> assert.hslEqual(_.hsl(hcl("steelblue")), _.hsl("steelblue"));
<ide> },
<ide> "roundtrip to RGB is idempotent": function(hcl) {
<del> assert.hslEqual(d3.rgb(hcl("steelblue")), d3.rgb("steelblue"));
<add> assert.hslEqual(_.rgb(hcl("steelblue")), _.rgb("steelblue"));
<ide> },
<ide> "roundtrip to Lab is idempotent": function(hcl) {
<del> assert.hslEqual(d3.lab(hcl("steelblue")), d3.lab("steelblue"));
<add> assert.hslEqual(_.lab(hcl("steelblue")), _.lab("steelblue"));
<ide> }
<ide> }
<ide> });
<ide><path>test/color/hsl-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.hslEqual(hsl("rgb(102, 102, 0)"), 60, 1, .2);
<ide> },
<ide> "can convert from RGB": function(hsl) {
<del> assert.hslEqual(hsl(d3.rgb(12, 34, 56)), 210, .647058, .133333);
<add> assert.hslEqual(hsl(_.rgb(12, 34, 56)), 210, .647058, .133333);
<ide> },
<ide> "can convert from HSL": function(hsl) {
<ide> assert.hslEqual(hsl(hsl(20, .8, .3)), 20, .8, .3);
<ide><path>test/color/lab-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assertLabEqual(lab("rgb(102, 102, 0)"), 41.73251953866431, -10.998411255098816, 48.21006600604577);
<ide> },
<ide> "can convert from RGB": function(lab) {
<del> assertLabEqual(lab(d3.rgb(12, 34, 56)), 12.65624852526134, 0.12256520883417721, -16.833209795877284);
<add> assertLabEqual(lab(_.rgb(12, 34, 56)), 12.65624852526134, 0.12256520883417721, -16.833209795877284);
<ide> },
<ide> "can convert from HSL": function(lab) {
<ide> assertLabEqual(lab(lab(20, .8, .3)), 20, 0.8, 0.3);
<ide> suite.addBatch({
<ide> assert.strictEqual(lab(lab(60, -4, -32)) + "", "#5d95c8");
<ide> },
<ide> "roundtrip to HSL is idempotent": function(lab) {
<del> assert.hslEqual(d3.hsl(lab("steelblue")), d3.hsl("steelblue"));
<add> assert.hslEqual(_.hsl(lab("steelblue")), _.hsl("steelblue"));
<ide> },
<ide> "roundtrip to RGB is idempotent": function(lab) {
<del> assert.hslEqual(d3.rgb(lab("steelblue")), d3.rgb("steelblue"));
<add> assert.hslEqual(_.rgb(lab("steelblue")), _.rgb("steelblue"));
<ide> },
<ide> "roundtrip to HCL is idempotent": function(lab) {
<del> assert.hslEqual(d3.hcl(lab("steelblue")), d3.hcl("steelblue"));
<add> assert.hslEqual(_.hcl(lab("steelblue")), _.hcl("steelblue"));
<ide> }
<ide> }
<ide> });
<ide><path>test/color/rgb-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.rgbEqual(rgb(rgb(12, 34, 56)), 12, 34, 56);
<ide> },
<ide> "can convert from HSL": function(rgb) {
<del> assert.rgbEqual(rgb(d3.hsl(0, 1, .5)), 255, 0, 0);
<add> assert.rgbEqual(rgb(_.hsl(0, 1, .5)), 255, 0, 0);
<ide> },
<ide> "can convert to HSL": function(rgb) {
<ide> assert.hslEqual(rgb("red").hsl(), 0, 1, .5);
<ide> suite.addBatch({
<ide> assert.strictEqual(rgb("hsl(60, 100%, 20%)") + "", "#666600");
<ide> assert.strictEqual(rgb("rgb(12, 34, 56)") + "", "#0c2238");
<ide> assert.strictEqual(rgb(rgb(12, 34, 56)) + "", "#0c2238");
<del> assert.strictEqual(rgb(d3.hsl(60, 1, .2)) + "", "#666600");
<add> assert.strictEqual(rgb(_.hsl(60, 1, .2)) + "", "#666600");
<ide> }
<ide> }
<ide> });
<ide><path>test/geo/area-benchmark.js
<del>var d3 = require("../../"),
<del> formatNumber = d3.format(",.02r"),
<add>var d3 = require("../../");
<add>
<add>var formatNumber = d3.format(",.02r"),
<ide> o = d3.geo.circle().angle(30).precision(.1)(),
<ide> n = 1e3,
<ide> then = Date.now();
<ide><path>test/geo/area-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> },
<ide> "graticule outline": {
<ide> "sphere": function(area) {
<del> assert.inDelta(area(d3.geo.graticule().extent([[-180, -90], [180, 90]]).outline()), 4 * π, 1e-5);
<add> assert.inDelta(area(_.geo.graticule().extent([[-180, -90], [180, 90]]).outline()), 4 * π, 1e-5);
<ide> },
<ide> "hemisphere": function(area) {
<del> assert.inDelta(area(d3.geo.graticule().extent([[-180, 0], [180, 90]]).outline()), 2 * π, 1e-5);
<add> assert.inDelta(area(_.geo.graticule().extent([[-180, 0], [180, 90]]).outline()), 2 * π, 1e-5);
<ide> },
<ide> "semilune": function(area) {
<del> assert.inDelta(area(d3.geo.graticule().extent([[0, 0], [90, 90]]).outline()), π / 2, 1e-5);
<add> assert.inDelta(area(_.geo.graticule().extent([[0, 0], [90, 90]]).outline()), π / 2, 1e-5);
<ide> }
<ide> },
<ide> "circles": {
<ide> "hemisphere": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(90)()), 2 * π, 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(90)()), 2 * π, 1e-5);
<ide> },
<ide> "60°": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(60).precision(.1)()), π, 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(60).precision(.1)()), π, 1e-5);
<ide> },
<ide> "60° North": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(60).precision(.1).origin([0, 90])()), π, 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(60).precision(.1).origin([0, 90])()), π, 1e-5);
<ide> },
<ide> "45°": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(45).precision(.1)()), π * (2 - Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(45).precision(.1)()), π * (2 - Math.SQRT2), 1e-5);
<ide> },
<ide> "45° North": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(45).precision(.1).origin([0, 90])()), π * (2 - Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(45).precision(.1).origin([0, 90])()), π * (2 - Math.SQRT2), 1e-5);
<ide> },
<ide> "45° South": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(45).precision(.1).origin([0, -90])()), π * (2 - Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(45).precision(.1).origin([0, -90])()), π * (2 - Math.SQRT2), 1e-5);
<ide> },
<ide> "135°": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(135).precision(.1)()), π * (2 + Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(135).precision(.1)()), π * (2 + Math.SQRT2), 1e-5);
<ide> },
<ide> "135° North": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(135).precision(.1).origin([0, 90])()), π * (2 + Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(135).precision(.1).origin([0, 90])()), π * (2 + Math.SQRT2), 1e-5);
<ide> },
<ide> "135° South": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(135).precision(.1).origin([0, -90])()), π * (2 + Math.SQRT2), 1e-5);
<add> assert.inDelta(area(_.geo.circle().angle(135).precision(.1).origin([0, -90])()), π * (2 + Math.SQRT2), 1e-5);
<ide> },
<ide> "tiny": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(1e-6).precision(.1)()), 0, 1e-6);
<add> assert.inDelta(area(_.geo.circle().angle(1e-6).precision(.1)()), 0, 1e-6);
<ide> },
<ide> "huge": function(area) {
<del> assert.inDelta(area(d3.geo.circle().angle(180 - 1e-6).precision(.1)()), 4 * π, 1e-6);
<add> assert.inDelta(area(_.geo.circle().angle(180 - 1e-6).precision(.1)()), 4 * π, 1e-6);
<ide> },
<ide> "60° with 45° hole": function(area) {
<del> var circle = d3.geo.circle().precision(.1);
<add> var circle = _.geo.circle().precision(.1);
<ide> assert.inDelta(area({
<ide> type: "Polygon",
<ide> coordinates: [
<ide> suite.addBatch({
<ide> }), π * (Math.SQRT2 - 1), 1e-5);
<ide> },
<ide> "45° holes at [0°, 0°] and [0°, 90°]": function(area) {
<del> var circle = d3.geo.circle().precision(.1).angle(45);
<add> var circle = _.geo.circle().precision(.1).angle(45);
<ide> assert.inDelta(area({
<ide> type: "Polygon",
<ide> coordinates: [
<ide> suite.addBatch({
<ide> }), π * 2 * Math.SQRT2, 1e-5);
<ide> },
<ide> "45° holes at [0°, 90°] and [0°, 0°]": function(area) {
<del> var circle = d3.geo.circle().precision(.1).angle(45);
<add> var circle = _.geo.circle().precision(.1).angle(45);
<ide> assert.inDelta(area({
<ide> type: "Polygon",
<ide> coordinates: [
<ide> suite.addBatch({
<ide> },
<ide> "stripes": {
<ide> "45°, -45°": function(area) {
<del> assert.inDelta(area(stripes(d3, 45, -45)), π * 2 * Math.SQRT2, 1e-5);
<add> assert.inDelta(area(stripes(45, -45)), π * 2 * Math.SQRT2, 1e-5);
<ide> },
<ide> "-45°, 45°": function(area) {
<del> assert.inDelta(area(stripes(d3, -45, 45)), π * 2 * (2 - Math.SQRT2), 1e-5);
<add> assert.inDelta(area(stripes(-45, 45)), π * 2 * (2 - Math.SQRT2), 1e-5);
<ide> },
<ide> "45°, 30°": function(area) {
<del> assert.inDelta(area(stripes(d3, 45, 30)), π * (Math.SQRT2 - 1), 1e-5);
<add> assert.inDelta(area(stripes(45, 30)), π * (Math.SQRT2 - 1), 1e-5);
<ide> }
<ide> }
<ide> },
<ide> suite.addBatch({
<ide>
<ide> suite.export(module);
<ide>
<del>function stripes(d3, a, b) {
<add>function stripes(a, b) {
<ide> return {type: "Polygon", coordinates: [a, b].map(function(d, i) {
<del> var stripe = d3.range(-180, 180, .1).map(function(x) { return [x, d]; });
<add> var stripe = _.range(-180, 180, .1).map(function(x) { return [x, d]; });
<ide> stripe.push(stripe[0]);
<ide> return i ? stripe.reverse() : stripe;
<ide> })};
<ide><path>test/geo/centroid-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> },
<ide> "Polygon": function(centroid) {
<ide> assert.inDelta(centroid({type: "Polygon", coordinates: [[[0, -90], [0, 0], [0, 90], [1, 0], [0, -90]]]}), [.5, 0], 1e-6);
<del> //assert.inDelta(centroid(d3.geo.circle().angle(5).origin([0, 45])()), [0, 45], 1e-6);
<del> assert.equal(centroid({type: "Polygon", coordinates: [d3.range(-180, 180 + 1 / 2, 1).map(function(x) { return [x, -60]; })]})[1], -90);
<add> assert.inDelta(centroid(_.geo.circle().angle(5).origin([0, 45])()), [0, 45], 1e-6);
<add> assert.equal(centroid({type: "Polygon", coordinates: [_.range(-180, 180 + 1 / 2, 1).map(function(x) { return [x, -60]; })]})[1], -90);
<ide> assert.inDelta(centroid({type: "Polygon", coordinates: [[[0, -10], [0, 10], [10, 10], [10, -10], [0, -10]]]}), [5, 0], 1e-6);
<ide> },
<ide> "MultiPolygon": function(centroid) {
<ide><path>test/geo/circle-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> "origin([0, 90])": function(circle) {
<ide> var o = circle().origin([0, 90])();
<ide> assert.equal(o.type, "Polygon");
<del> assert.inDelta(o.coordinates, [d3.range(360, -1, -6).map(function(x) { return [x >= 180 ? x - 360 : x, 0]; })], 1e-6);
<add> assert.inDelta(o.coordinates, [_.range(360, -1, -6).map(function(x) { return [x >= 180 ? x - 360 : x, 0]; })], 1e-6);
<ide> },
<ide> "origin([45, 45])": function(circle) {
<ide> var o = circle().origin([45, 45]).angle(0)();
<ide><path>test/geo/graticule-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> .filter(function(line) { return line.coordinates[0][0] === line.coordinates[1][0]; })
<ide> .filter(function(line) { return Math.abs(line.coordinates[0][0] % 90) > ε; });
<ide> lines.forEach(function(line) {
<del> assert.deepEqual(d3.extent(line.coordinates, function(p) { return p[1]; }), [-80 - ε, +80 + ε]);
<add> assert.deepEqual(_.extent(line.coordinates, function(p) { return p[1]; }), [-80 - ε, +80 + ε]);
<ide> });
<ide> },
<ide> "default major longitude lines extend from 90°S to 90°N": function(graticule) {
<ide> var lines = graticule().lines()
<ide> .filter(function(line) { return line.coordinates[0][0] === line.coordinates[1][0]; })
<ide> .filter(function(line) { return Math.abs(line.coordinates[0][0] % 90) < ε; });
<ide> lines.forEach(function(line) {
<del> assert.deepEqual(d3.extent(line.coordinates, function(p) { return p[1]; }), [-90 + ε, +90 - ε]);
<add> assert.deepEqual(_.extent(line.coordinates, function(p) { return p[1]; }), [-90 + ε, +90 - ε]);
<ide> });
<ide> },
<ide> "default latitude lines extend from 180°W to 180°E": function(graticule) {
<ide> var lines = graticule().lines()
<ide> .filter(function(line) { return line.coordinates[0][1] === line.coordinates[1][1]; });
<ide> lines.forEach(function(line) {
<del> assert.deepEqual(d3.extent(line.coordinates, function(p) { return p[0]; }), [-180, +180]);
<add> assert.deepEqual(_.extent(line.coordinates, function(p) { return p[0]; }), [-180, +180]);
<ide> });
<ide> },
<ide> "returns an array of LineStrings": function(graticule) {
<ide><path>test/geo/path-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0));
<ide> },
<ide> suite.addBatch({
<ide> "with the default context (null) and an identity projection": {
<ide> topic: function(path) {
<ide> return path()
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0));
<ide> },
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([-180, -248])
<ide> .scale(900 / Math.PI)
<ide> .precision(0));
<ide> suite.addBatch({
<ide>
<ide> "projection": {
<ide> "returns the current projection when called with no arguments": function(path) {
<del> var p = path(), projection = d3.geo.equirectangular();
<add> var p = path(), projection = _.geo.equirectangular();
<ide> p.projection(projection);
<ide> assert.strictEqual(p.projection(), projection);
<ide> }
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> suite.addBatch({
<ide> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 1);
<ide> },
<ide> "renders a small circle of 60°": function(p) {
<del> p(d3.geo.circle().angle(60)());
<add> p(_.geo.circle().angle(60)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 276, y: 493}]);
<ide> },
<ide> "renders a small circle of 120°": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 87, y: 700}]);
<ide> }
<ide> },
<ide>
<ide> "with an equirectangular projection clipped to 90° and rotated by [-17°, -451°]": {
<ide> "renders a polygon": function(path) {
<del> var pole = d3.range(-180, 180, 10).map(function(x) { return [x, 70]; });
<add> var pole = _.range(-180, 180, 10).map(function(x) { return [x, 70]; });
<ide> pole.push(pole[0]);
<ide> path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([-17, -451])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([71.03, 42.37])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> /*
<ide> "grid component": function(path) {
<del> var yStepsBig = d3.range(-90, 90, 10);
<add> var yStepsBig = _.range(-90, 90, 10);
<ide> path({type: "LineString", coordinates: yStepsBig.map(function(y) { return [110, y]; })});
<ide> assert.inDelta(testContext.buffer(), [[
<ide> [109.538009, -90],
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([-24, -175.5])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([90, 0])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> "renders a small circle of 60°": function(p) {
<del> p(d3.geo.circle().angle(60)());
<add> p(_.geo.circle().angle(60)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 930, y: 550}]);
<ide> },
<ide> "renders a small circle of 120°": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 30, y: 550}]);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([180, 0])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> "does not render a small circle of 60°": function(p) {
<del> p(d3.geo.circle().angle(60)());
<add> p(_.geo.circle().angle(60)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), []);
<ide> },
<ide> "renders a small circle of 120° in two parts": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [
<ide> {type: "moveTo", x: 276, y: 493},
<ide> {type: "moveTo", x: 87, y: 700}
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([270, 0])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> "renders a small circle of 60°": function(p) {
<del> p(d3.geo.circle().angle(60)());
<add> p(_.geo.circle().angle(60)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 30, y: -50}]);
<ide> },
<ide> "renders a small circle of 120°": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 930, y: -50}]);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([210, 1])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> "renders a small circle of 120°": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 930, y: 250}]);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .rotate([-150, 60])
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(90));
<ide> },
<ide> "renders a small circle of 120°": function(p) {
<del> p(d3.geo.circle().angle(120)());
<add> p(_.geo.circle().angle(120)());
<ide> assert.deepEqual(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }), [{type: "moveTo", x: 30, y: -87}]);
<ide> },
<ide> "renders a sphere": function(p) {
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(170));
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .rotate([0, -90])
<ide> .precision(0)
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(30));
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .precision(0)
<ide> .clipAngle(150));
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .rotate([98, 0])
<ide> .precision(0));
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .rotate([330, 232])
<ide> .precision(0));
<ide> },
<ide> "renders degenerate points for a small circle of 30°": function(p) {
<del> p(d3.geo.circle().angle(30)());
<add> p(_.geo.circle().angle(30)());
<ide> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 2);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.equirectangular()
<add> .projection(_.geo.equirectangular()
<ide> .scale(900 / Math.PI)
<ide> .rotate([34.5, 90])
<ide> .precision(0));
<ide> },
<ide> "observes proper clip point ordering for lines": function(p) {
<del> var line = d3.range(-90, 180, 10).map(function(x) { return [x, 20]; })
<del> .concat(d3.range(170, -100, -10).map(function(x) { return [x, 0]; }))
<add> var line = _.range(-90, 180, 10).map(function(x) { return [x, 20]; })
<add> .concat(_.range(170, -100, -10).map(function(x) { return [x, 0]; }))
<ide> .concat([[-90, 20]]);
<ide> p({type: "Polygon", coordinates: [line]});
<ide> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 3);
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.stereographic()
<add> .projection(_.geo.stereographic()
<ide> .precision(1));
<ide> },
<ide> "correctly resamples points on antimeridian": function(p) {
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.albers()
<add> .projection(_.geo.albers()
<ide> .scale(140)
<ide> .rotate([0, 0])
<ide> .precision(1));
<ide> suite.addBatch({
<ide> topic: function(path) {
<ide> return path()
<ide> .context(testContext)
<del> .projection(d3.geo.albers()
<add> .projection(_.geo.albers()
<ide> .scale(140)
<ide> .rotate([11.5, 285])
<ide> .precision(1));
<ide> var testContext = {
<ide>
<ide> function stripes(a, b) {
<ide> return {type: "Polygon", coordinates: [a, b].map(function(d, i) {
<del> var stripe = d3.range(-180, 180, 1).map(function(x) { return [x, d]; });
<add> var stripe = _.range(-180, 180, 1).map(function(x) { return [x, d]; });
<ide> stripe.push(stripe[0]);
<ide> return i ? stripe.reverse() : stripe;
<ide> })};
<ide><path>test/geo/projection-test-suite.js
<ide> var assert = require("../assert"),
<del> d3 = require("../../"),
<del> format = d3.format("13.8f");
<add> _ = require("../../"),
<add> format = _.format("13.8f");
<ide>
<ide> module.exports = function(suite, mapping) {
<ide>
<ide><path>test/geom/polygon-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> "large square": {
<ide> topic: function(polygon) {
<ide> var r = 1e8,
<del> d = d3.range(0, r, r / 1e4);
<add> d = _.range(0, r, r / 1e4);
<ide> return polygon(
<ide> d.map(function(y) { return [0, y]; }).concat(
<ide> d.map(function(x) { return [x, r]; })).concat(
<ide><path>test/scale/category-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> function category(category, n) {
<ide> var y = x.copy();
<ide> assert.deepEqual(y.domain(), x.domain());
<ide> assert.deepEqual(y.range(), x.range());
<del> x.domain(d3.range(n));
<add> x.domain(_.range(n));
<ide> for (var i = 0; i < n; ++i) assert.equal(x(i + n), x(i));
<ide> assert.equal(y(1), colors[0]);
<ide> assert.equal(y(2), colors[1]);
<ide> function category(category, n) {
<ide> var x = scale[category]();
<ide> x.range().forEach(function(v) {
<ide> assert.match(v, /#[0-9a-f]{6}/);
<del> v = d3.rgb(v);
<add> v = _.rgb(v);
<ide> assert.isFalse(isNaN(v.r));
<ide> assert.isFalse(isNaN(v.g));
<ide> assert.isFalse(isNaN(v.b));
<ide> function category(category, n) {
<ide> "no range values are very dark or very light": function(scale) {
<ide> var x = scale[category]();
<ide> x.range().forEach(function(v) {
<del> var c = d3.hsl(v);
<add> var c = _.hsl(v);
<ide> assert.isTrue(c.l >= .34, "expected " + v + " to be lighter (l = " + c.l + ")");
<ide> assert.isTrue(c.l <= .89, "expected " + v + " to be darker (l = " + c.l + ")");
<ide> });
<ide><path>test/scale/quantize-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> },
<ide> "range cardinality determines the degree of quantization": function(quantize) {
<ide> var x = quantize();
<del> assert.inDelta(x.range(d3.range(0, 1.001, .001))(1/3), .333, 1e-6);
<del> assert.inDelta(x.range(d3.range(0, 1.01, .01))(1/3), .33, 1e-6);
<del> assert.inDelta(x.range(d3.range(0, 1.1, .1))(1/3), .3, 1e-6);
<del> assert.inDelta(x.range(d3.range(0, 1.2, .2))(1/3), .4, 1e-6);
<del> assert.inDelta(x.range(d3.range(0, 1.25, .25))(1/3), .25, 1e-6);
<del> assert.inDelta(x.range(d3.range(0, 1.5, .5))(1/3), .5, 1e-6);
<del> assert.inDelta(x.range(d3.range(1))(1/3), 0, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.001, .001))(1/3), .333, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.01, .01))(1/3), .33, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.1, .1))(1/3), .3, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.2, .2))(1/3), .4, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.25, .25))(1/3), .25, 1e-6);
<add> assert.inDelta(x.range(_.range(0, 1.5, .5))(1/3), .5, 1e-6);
<add> assert.inDelta(x.range(_.range(1))(1/3), 0, 1e-6);
<ide> },
<ide> "range values are arbitrary": function(quantize) {
<ide> var a = {}, b = {}, c = {}, x = quantize().range([a, b, c]);
<ide><path>test/selection/attr-test.js
<ide> var vows = require("vows"),
<del> interpolateRgb = require("../../").interpolateRgb,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.equal(div[0][1].getAttribute("bgcolor"), "coral");
<ide> },
<ide> "sets an attribute as a function of data": function(div) {
<del> div.attr("bgcolor", interpolateRgb("brown", "steelblue"));
<add> div.attr("bgcolor", _.interpolateRgb("brown", "steelblue"));
<ide> assert.equal(div[0][0].getAttribute("bgcolor"), "#a52a2a");
<ide> assert.equal(div[0][1].getAttribute("bgcolor"), "#4682b4");
<ide> },
<ide><path>test/selection/filter-test.js
<ide> var vows = require("vows"),
<del> merge = require("../../").merge,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.isTrue(some[1][0] === span[1][0]);
<ide> },
<ide> "removes non-matching elements": function(span) {
<del> var some = merge(span.filter(function(d, i) { return d & 1; }));
<add> var some = _.merge(span.filter(function(d, i) { return d & 1; }));
<ide> assert.equal(some.indexOf(span[0][0]), -1);
<ide> assert.equal(some.indexOf(span[1][0]), -1);
<ide> },
<ide><path>test/selection/property-test.js
<ide> var vows = require("vows"),
<del> interpolateRgb = require("../../").interpolateRgb,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.equal(div[0][1].opacity, "0.4");
<ide> },
<ide> "sets a property as a function": function(div) {
<del> div.property("bgcolor", interpolateRgb("brown", "steelblue"));
<add> div.property("bgcolor", _.interpolateRgb("brown", "steelblue"));
<ide> assert.equal(div[0][0].bgcolor, "#a52a2a");
<ide> assert.equal(div[0][1].bgcolor, "#4682b4");
<ide> },
<ide><path>test/selection/style-test.js
<ide> var vows = require("vows"),
<del> interpolateRgb = require("../../").interpolateRgb,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.equal(div[0][1].style.getPropertyValue("opacity"), "0.5");
<ide> },
<ide> "sets a property as a function": function(div) {
<del> div.style("background-color", interpolateRgb("orange", "yellow"));
<add> div.style("background-color", _.interpolateRgb("orange", "yellow"));
<ide> assert.equal(div[0][0].style.getPropertyValue("background-color"), "#ffa500");
<ide> assert.equal(div[0][1].style.getPropertyValue("background-color"), "#ffff00");
<ide> },
<ide><path>test/svg/area-radial-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> function testInterpolation(interpolate) {
<ide> var data = [[10, 0], [20, 1], [20, 2], [10, 3]];
<ide>
<del> var cartesian = d3.svg.area()
<add> var cartesian = _.svg.area()
<ide> .x0(function(d) { return d[0] * Math.cos(d[1] - Math.PI / 2); })
<ide> .x1(function(d) { return 2 * d[0] * Math.cos(d[1] - Math.PI / 2); })
<ide> .y0(function(d) { return d[0] * Math.sin(d[1] - Math.PI / 2); })
<ide><path>test/svg/area-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> function testInterpolation(i0, i1) {
<ide> return function(area) {
<ide> var a = area().interpolate(i0),
<ide> d = [[0, 0], [1, 1], [2, 0], [3, 1], [4, 0]],
<del> l0 = d3.svg.line().interpolate(i1).x(a.x0()).y(a.y0()),
<del> l1 = d3.svg.line().interpolate(i0).x(a.x1()).y(a.y1());
<add> l0 = _.svg.line().interpolate(i1).x(a.x0()).y(a.y0()),
<add> l1 = _.svg.line().interpolate(i0).x(a.x1()).y(a.y1());
<ide> assert.pathEqual(a(d), l1(d) + "L" + l0(d.reverse()).substring(1) + "Z");
<ide> };
<ide> }
<ide><path>test/svg/axis-test.js
<ide> var vows = require("vows"),
<del> ordinal = require("../../").scale.ordinal,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.equal(x(0.5), 0.5);
<ide> },
<ide> "can be defined as a scale object": function(d3) {
<del> var x = d3.scale.linear(), a = d3.svg.axis().scale(x);
<add> var x = _.scale.linear(), a = d3.svg.axis().scale(x);
<ide> assert.equal(a.scale(), x);
<ide> },
<ide> "can be a polylinear scale": function(d3) {
<del> var a = d3.svg.axis().scale(d3.scale.linear().domain([0, 1, 10]).range([2, 20, 200])),
<add> var a = d3.svg.axis().scale(_.scale.linear().domain([0, 1, 10]).range([2, 20, 200])),
<ide> g = d3.select("body").html("").append("svg:g").call(a),
<ide> path = g.selectAll("path");
<ide> assert.equal(path.attr("d"), "M2,6V0H200V6");
<ide> },
<ide> "can be an ordinal scale": function(d3) {
<del> var a = d3.svg.axis().scale(ordinal().domain(["A", "B", "C"]).rangeBands([10, 90])),
<add> var a = d3.svg.axis().scale(_.scale.ordinal().domain(["A", "B", "C"]).rangeBands([10, 90])),
<ide> g = d3.select("body").html("").append("svg:g").call(a),
<ide> path = g.selectAll("path");
<ide> assert.equal(path.attr("d"), "M10,6V0H90V6");
<ide> },
<ide> "can be an ordinal scale with explicit range": function(d3) {
<del> var a = d3.svg.axis().scale(ordinal().domain(["A", "B", "C"]).range([10, 50, 90])),
<add> var a = d3.svg.axis().scale(_.scale.ordinal().domain(["A", "B", "C"]).range([10, 50, 90])),
<ide> g = d3.select("body").html("").append("svg:g").call(a),
<ide> path = g.selectAll("path");
<ide> assert.equal(path.attr("d"), "M10,6V0H90V6");
<ide> suite.addBatch({
<ide> assert.equal(t.length, 2);
<ide> },
<ide> "passes any arguments to the scale's ticks function": function(d3) {
<del> var x = d3.scale.linear(), b = {}, a = d3.svg.axis().ticks(b, "%").scale(x), aa = [],
<add> var x = _.scale.linear(), b = {}, a = d3.svg.axis().ticks(b, "%").scale(x), aa = [],
<ide> g = d3.select("body").html("").append("svg:g");
<ide> x.ticks = function() { aa.push(arguments); return [42]; };
<ide> g.call(a);
<ide> suite.addBatch({
<ide> },
<ide> "passes any arguments to the scale's tickFormat function": function(d3) {
<ide> var b = {},
<del> x = d3.scale.linear(),
<add> x = _.scale.linear(),
<ide> a = d3.svg.axis().scale(x).ticks(b, "%"),
<ide> g = d3.select("body").html("").append("svg:g"),
<ide> aa = [];
<ide> suite.addBatch({
<ide> assert.equal(t.length, 2);
<ide> },
<ide> "does not change the arguments passed to the scale's tickFormat function": function(d3) {
<del> var x = d3.scale.linear(),
<add> var x = _.scale.linear(),
<ide> a = d3.svg.axis().scale(x).ticks(10).tickValues([1, 2, 3]),
<ide> g = d3.select("body").html("").append("svg:g"),
<ide> aa = [];
<ide> suite.addBatch({
<ide> assert.isTrue(a.tickFormat() == null);
<ide> },
<ide> "when null, uses the scale's tick format": function(d3) {
<del> var x = d3.scale.linear(), a = d3.svg.axis().scale(x),
<add> var x = _.scale.linear(), a = d3.svg.axis().scale(x),
<ide> g = d3.select("body").html("").append("svg:g");
<ide>
<ide> x.tickFormat = function() {
<ide> suite.addBatch({
<ide> "generates new tick marks with labels": function(d3) {
<ide> var a = d3.svg.axis(),
<ide> g = d3.select("body").html("").append("svg:g").call(a),
<del> x = d3.scale.linear(),
<add> x = _.scale.linear(),
<ide> tick = g.selectAll("g"),
<ide> ticks = x.ticks(10),
<ide> tickFormat = x.tickFormat(10);
<ide><path>test/svg/brush-test.js
<ide> var vows = require("vows"),
<del> linear = require("../../").scale.linear,
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> assert.isNull(brush().extent());
<ide> },
<ide> "returns a one-dimensional array if only x is defined": function(brush) {
<del> var b = brush().x(linear());
<add> var b = brush().x(_.scale.linear());
<ide> assert.deepEqual(b.extent(), [0, 0]);
<ide> },
<ide> "takes a one-dimensional array if only x is defined": function(brush) {
<del> var b = brush().x(linear()).extent([0.1, 0.4]);
<add> var b = brush().x(_.scale.linear()).extent([0.1, 0.4]);
<ide> assert.deepEqual(b.extent(), [0.1, 0.4]);
<ide> },
<ide> "returns a one-dimensional array if only y is defined": function(brush) {
<del> var b = brush().y(linear());
<add> var b = brush().y(_.scale.linear());
<ide> assert.deepEqual(b.extent(), [0, 0]);
<ide> },
<ide> "takes a one-dimensional array if only y is defined": function(brush) {
<del> var b = brush().y(linear()).extent([0.1, 0.4]);
<add> var b = brush().y(_.scale.linear()).extent([0.1, 0.4]);
<ide> assert.deepEqual(b.extent(), [0.1, 0.4]);
<ide> },
<ide> "returns a two-dimensional array if x and y are defined": function(brush) {
<del> var b = brush().x(linear()).y(linear());
<add> var b = brush().x(_.scale.linear()).y(_.scale.linear());
<ide> assert.deepEqual(b.extent(), [[0, 0], [0, 0]]);
<ide> },
<ide> "takes a two-dimensional array if x and y are defined": function(brush) {
<del> var b = brush().x(linear()).y(linear()).extent([[0.1, 0.2], [0.3, 0.4]]);
<add> var b = brush().x(_.scale.linear()).y(_.scale.linear()).extent([[0.1, 0.2], [0.3, 0.4]]);
<ide> assert.deepEqual(b.extent(), [[0.1, 0.2], [0.3, 0.4]]);
<ide> },
<ide> "preserves the set extent exactly": function(brush) {
<ide> var lo = new Number(0.1),
<ide> hi = new Number(0.3),
<del> b = brush().x(linear()).extent([lo, hi]),
<add> b = brush().x(_.scale.linear()).extent([lo, hi]),
<ide> extent = b.extent();
<ide> assert.strictEqual(extent[0], lo);
<ide> assert.strictEqual(extent[1], hi);
<ide><path>test/svg/line-radial-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert");
<ide>
<ide> suite.addBatch({
<ide> function testInterpolation(interpolate) {
<ide> var data = [[10, 0], [20, 1], [20, 2], [10, 3]];
<ide>
<del> var cartesian = d3.svg.line()
<add> var cartesian = _.svg.line()
<ide> .x(function(d) { return d[0] * Math.cos(d[1] - Math.PI / 2); })
<ide> .y(function(d) { return d[0] * Math.sin(d[1] - Math.PI / 2); });
<ide>
<ide><path>test/time/scale-test.js
<ide> var vows = require("vows"),
<del> d3 = require("../../"),
<add> _ = require("../../"),
<ide> load = require("../load"),
<ide> assert = require("../assert"),
<ide> time = require("./time"),
<ide> suite.addBatch({
<ide> "nice": {
<ide> "rounds using the specified time interval": function(scale) {
<ide> var x = scale().domain([local(2009, 0, 1, 0, 12), local(2009, 0, 1, 23, 48)]);
<del> assert.deepEqual(x.nice(d3.time.day).domain(), [local(2009, 0, 1), local(2009, 0, 2)]);
<del> assert.deepEqual(x.nice(d3.time.week).domain(), [local(2008, 11, 28), local(2009, 0, 4)]);
<del> assert.deepEqual(x.nice(d3.time.month).domain(), [local(2008, 11, 1), local(2009, 1, 1)]);
<del> assert.deepEqual(x.nice(d3.time.year).domain(), [local(2008, 0, 1), local(2010, 0, 1)]);
<add> assert.deepEqual(x.nice(_.time.day).domain(), [local(2009, 0, 1), local(2009, 0, 2)]);
<add> assert.deepEqual(x.nice(_.time.week).domain(), [local(2008, 11, 28), local(2009, 0, 4)]);
<add> assert.deepEqual(x.nice(_.time.month).domain(), [local(2008, 11, 1), local(2009, 1, 1)]);
<add> assert.deepEqual(x.nice(_.time.year).domain(), [local(2008, 0, 1), local(2010, 0, 1)]);
<ide> },
<ide> "works on degenerate domains": function(scale) {
<ide> var x = scale().domain([local(2009, 0, 1, 0, 12), local(2009, 0, 1, 0, 12)]);
<del> assert.deepEqual(x.nice(d3.time.day).domain(), [local(2009, 0, 1), local(2009, 0, 2)]);
<add> assert.deepEqual(x.nice(_.time.day).domain(), [local(2009, 0, 1), local(2009, 0, 2)]);
<ide> },
<ide> "nicing a polylinear domain only affects the extent": function(linear) {
<del> var x = linear().domain([local(2009, 0, 1, 0, 12), local(2009, 0, 1, 23, 48), local(2009, 0, 2, 23, 48)]).nice(d3.time.day);
<add> var x = linear().domain([local(2009, 0, 1, 0, 12), local(2009, 0, 1, 23, 48), local(2009, 0, 2, 23, 48)]).nice(_.time.day);
<ide> assert.deepEqual(x.domain(), [local(2009, 0, 1), local(2009, 0, 1, 23, 48), local(2009, 0, 3)]);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> var x = scale().domain([local(2009, 0, 1), local(2010, 0, 1)]).range(["red", "blue"]),
<ide> i = x.interpolate(),
<ide> y = x.copy();
<del> x.interpolate(d3.interpolateHsl);
<add> x.interpolate(_.interpolateHsl);
<ide> assert.equal(x(local(2009, 6, 1)), "#ff00fd");
<ide> assert.equal(y(local(2009, 6, 1)), "#81007e");
<ide> assert.equal(y.interpolate(), i);
<ide> suite.addBatch({
<ide> "ticks": {
<ide> "observes explicit tick interval": function(scale) {
<ide> var x = scale().domain([local(2011, 0, 1, 12, 1, 0), local(2011, 0, 1, 12, 4, 4)]);
<del> assert.deepEqual(x.ticks(d3.time.minutes), [
<add> assert.deepEqual(x.ticks(_.time.minutes), [
<ide> local(2011, 0, 1, 12, 1),
<ide> local(2011, 0, 1, 12, 2),
<ide> local(2011, 0, 1, 12, 3),
<ide> suite.addBatch({
<ide> },
<ide> "observes explicit tick interval and step": function(scale) {
<ide> var x = scale().domain([local(2011, 0, 1, 12, 0, 0), local(2011, 0, 1, 12, 33, 4)]);
<del> assert.deepEqual(x.ticks(d3.time.minutes, 10), [
<add> assert.deepEqual(x.ticks(_.time.minutes, 10), [
<ide> local(2011, 0, 1, 12, 0),
<ide> local(2011, 0, 1, 12, 10),
<ide> local(2011, 0, 1, 12, 20),
<ide> suite.addBatch({
<ide> "ticks": {
<ide> "observes explicit tick interval": function(scale) {
<ide> var x = scale().domain([utc(2011, 0, 1, 12, 1, 0), utc(2011, 0, 1, 12, 4, 4)]);
<del> assert.deepEqual(x.ticks(d3.time.minutes), [
<add> assert.deepEqual(x.ticks(_.time.minutes), [
<ide> utc(2011, 0, 1, 12, 1),
<ide> utc(2011, 0, 1, 12, 2),
<ide> utc(2011, 0, 1, 12, 3),
<ide> suite.addBatch({
<ide> },
<ide> "observes explicit tick interval and step": function(scale) {
<ide> var x = scale().domain([utc(2011, 0, 1, 12, 0, 0), utc(2011, 0, 1, 12, 33, 4)]);
<del> assert.deepEqual(x.ticks(d3.time.minutes, 10), [
<add> assert.deepEqual(x.ticks(_.time.minutes, 10), [
<ide> utc(2011, 0, 1, 12, 0),
<ide> utc(2011, 0, 1, 12, 10),
<ide> utc(2011, 0, 1, 12, 20),
<ide><path>test/transition/transition-test-attrTween.js
<ide> var assert = require("../assert"),
<del> interpolateHsl = require("../../").interpolateHsl;
<add> _ = require("../../");
<ide>
<ide> module.exports = {
<ide> topic: function(d3) {
<del> var cb = this.callback,
<add> var callback = this.callback,
<ide> dd = [],
<ide> ii = [],
<ide> tt = [],
<ide> module.exports = {
<ide> dd.push(d);
<ide> ii.push(i);
<ide> vv.push(v);
<del> if (tt.push(this) >= 2) cb(null, {
<add> if (tt.push(this) >= 2) callback(null, {
<ide> selection: s,
<ide> transition: t,
<ide> data: dd,
<ide> index: ii,
<ide> value: vv,
<ide> context: tt
<ide> });
<del> return i && interpolateHsl(v, "blue");
<add> return i && _.interpolateHsl(v, "blue");
<ide> }
<ide> },
<ide>
<ide> module.exports = {
<ide>
<ide> "end": {
<ide> topic: function(result) {
<del> var cb = this.callback;
<del> result.transition.each("end", function(d, i) { if (i >= 1) cb(null, result); });
<add> var callback = this.callback;
<add> result.transition.each("end", function(d, i) { if (i >= 1) callback(null, result); });
<ide> },
<ide> "uses the returned interpolator": function(result) {
<ide> assert.equal(result.selection[0][1].getAttribute("color"), "#0000ff");
<ide><path>test/transition/transition-test-filter.js
<ide> var assert = require("../assert"),
<del> merge = require("../../").merge;
<add> _ = require("../../");
<ide>
<ide> var datum = {};
<ide>
<ide> module.exports = {
<ide> assert.isTrue(some[1][0] === span[1][0]);
<ide> },
<ide> "removes non-matching elements": function(span) {
<del> var some = merge(span.filter(function(d, i) { return d & 1; }));
<add> var some = _.merge(span.filter(function(d, i) { return d & 1; }));
<ide> assert.equal(some.indexOf(span[0][0]), -1);
<ide> assert.equal(some.indexOf(span[1][0]), -1);
<ide> },
<ide><path>test/transition/transition-test-styleTween.js
<ide> var assert = require("../assert"),
<del> interpolateHsl = require("../../").interpolateHsl;
<add> _ = require("../../");
<ide>
<ide> module.exports = {
<ide> topic: function(d3) {
<ide> module.exports = {
<ide> context: tt,
<ide> fails: fails
<ide> });
<del> return i && interpolateHsl(v, "blue");
<add> return i && _.interpolateHsl(v, "blue");
<ide> }
<ide> },
<ide> | 31 |
PHP | PHP | evaluate echos within attributes | 3f537ca1c7cbf14af34dcf697801db75f2b173d3 | <ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> protected function compileComponentTags($value)
<ide> }
<ide>
<ide> return (new ComponentTagCompiler(
<del> $this->classComponentAliases
<add> $this, $this->classComponentAliases
<ide> ))->compile($value);
<ide> }
<ide>
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php
<ide> use Illuminate\Contracts\View\Factory;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\View\AnonymousComponent;
<add>use Illuminate\View\Compilers\BladeCompiler;
<ide> use InvalidArgumentException;
<ide> use ReflectionClass;
<ide>
<ide> */
<ide> class ComponentTagCompiler
<ide> {
<add> /**
<add> * The Blade compiler instance.
<add> *
<add> * @var \Illuminate\View\Compilers\BladeCompiler
<add> */
<add> protected $blade;
<add>
<ide> /**
<ide> * The component class aliases.
<ide> *
<ide> class ComponentTagCompiler
<ide> * @param array $aliases
<ide> * @return void
<ide> */
<del> public function __construct(array $aliases = [])
<add> public function __construct(BladeCompiler $blade, array $aliases = [])
<ide> {
<add> $this->blade = $blade;
<ide> $this->aliases = $aliases;
<ide> }
<ide>
<ide> protected function getAttributesFromAttributeString(string $attributeString)
<ide>
<ide> $this->boundAttributes[$attribute] = true;
<ide> } else {
<del> $value = "'".str_replace("'", "\\'", $value)."'";
<add> $value = "'".$this->compileAttributeEchos($value)."'";
<ide> }
<ide>
<ide> return [$attribute => $value];
<ide> protected function parseBindAttributes(string $attributeString)
<ide> return preg_replace($pattern, ' bind:$1=', $attributeString);
<ide> }
<ide>
<add> /**
<add> * Compile any Blade echo statements that are present in the attribute string.
<add> *
<add> * These echo statements need to be converted to string concatenation statements.
<add> *
<add> * @param string $attributeString
<add> * @return string
<add> */
<add> protected function compileAttributeEchos(string $attributeString)
<add> {
<add> $value = $this->blade->compileEchos($attributeString);
<add>
<add> $value = collect(token_get_all($value))->map(function ($token) {
<add> if (! is_array($token)) {
<add> return $token;
<add> }
<add>
<add> return $token[0] === T_INLINE_HTML
<add> ? str_replace("'", "\\'", $token[1])
<add> : $token[1];
<add> })->implode('');
<add>
<add> $value = str_replace('<?php echo ', '\'.', $value);
<add> $value = str_replace('; ?>', '.\'', $value);
<add>
<add> return $value;
<add> }
<add>
<ide> /**
<ide> * Convert an array of attributes to a string.
<ide> *
<ide><path>src/Illuminate/View/Compilers/Concerns/CompilesEchos.php
<ide> trait CompilesEchos
<ide> * @param string $value
<ide> * @return string
<ide> */
<del> protected function compileEchos($value)
<add> public function compileEchos($value)
<ide> {
<ide> foreach ($this->getEchoMethods() as $method) {
<ide> $value = $this->$method($value);
<ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Foundation\Application;
<ide> use Illuminate\Contracts\View\Factory;
<add>use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\View\Compilers\BladeCompiler;
<ide> use Illuminate\View\Compilers\ComponentTagCompiler;
<ide> use Illuminate\View\Component;
<ide> public function tearDown(): void
<ide>
<ide> public function testSlotsCanBeCompiled()
<ide> {
<del> $result = (new ComponentTagCompiler)->compileSlots('<x-slot name="foo">
<add> $result = $this->compiler()->compileSlots('<x-slot name="foo">
<ide> </x-slot>');
<ide>
<ide> $this->assertSame("@slot('foo') \n".' @endslot', trim($result));
<ide> public function testBasicComponentParsing()
<ide> {
<ide> $this->mockViewFactory();
<ide>
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<div><x-alert type="foo" limit="5" @click="foo" required /><x-alert /></div>');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<div><x-alert type="foo" limit="5" @click="foo" required /><x-alert /></div>');
<ide>
<ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testBasicComponentParsing()
<ide>
<ide> public function testBasicComponentWithEmptyAttributesParsing()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<div><x-alert type="" limit=\'\' @click="" required /></div>');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<div><x-alert type="" limit=\'\' @click="" required /></div>');
<ide>
<ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testBasicComponentWithEmptyAttributesParsing()
<ide>
<ide> public function testDataCamelCasing()
<ide> {
<del> $result = (new ComponentTagCompiler(['profile' => TestProfileComponent::class]))->compileTags('<x-profile user-id="1"></x-profile>');
<add> $result = $this->compiler(['profile' => TestProfileComponent::class])->compileTags('<x-profile user-id="1"></x-profile>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestProfileComponent', ['userId' => '1'])
<ide> <?php \$component->withName('profile'); ?>
<ide> public function testDataCamelCasing()
<ide>
<ide> public function testColonData()
<ide> {
<del> $result = (new ComponentTagCompiler(['profile' => TestProfileComponent::class]))->compileTags('<x-profile :user-id="1"></x-profile>');
<add> $result = $this->compiler(['profile' => TestProfileComponent::class])->compileTags('<x-profile :user-id="1"></x-profile>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestProfileComponent', ['userId' => 1])
<ide> <?php \$component->withName('profile'); ?>
<ide> public function testColonData()
<ide>
<ide> public function testColonAttributesIsEscapedIfStrings()
<ide> {
<del> $result = (new ComponentTagCompiler(['profile' => TestProfileComponent::class]))->compileTags('<x-profile :src="\'foo\'"></x-profile>');
<add> $result = $this->compiler(['profile' => TestProfileComponent::class])->compileTags('<x-profile :src="\'foo\'"></x-profile>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestProfileComponent', [])
<ide> <?php \$component->withName('profile'); ?>
<ide> public function testColonAttributesIsEscapedIfStrings()
<ide>
<ide> public function testColonNestedComponentParsing()
<ide> {
<del> $result = (new ComponentTagCompiler(['foo:alert' => TestAlertComponent::class]))->compileTags('<x-foo:alert></x-foo:alert>');
<add> $result = $this->compiler(['foo:alert' => TestAlertComponent::class])->compileTags('<x-foo:alert></x-foo:alert>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('foo:alert'); ?>
<ide> public function testColonNestedComponentParsing()
<ide>
<ide> public function testColonStartingNestedComponentParsing()
<ide> {
<del> $result = (new ComponentTagCompiler(['foo:alert' => TestAlertComponent::class]))->compileTags('<x:foo:alert></x-foo:alert>');
<add> $result = $this->compiler(['foo:alert' => TestAlertComponent::class])->compileTags('<x:foo:alert></x-foo:alert>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('foo:alert'); ?>
<ide> public function testColonStartingNestedComponentParsing()
<ide>
<ide> public function testSelfClosingComponentsCanBeCompiled()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<div><x-alert/></div>');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<div><x-alert/></div>');
<ide>
<ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testClassNamesCanBeGuessed()
<ide> $app->shouldReceive('getNamespace')->andReturn('App\\');
<ide> Container::setInstance($container);
<ide>
<del> $result = (new ComponentTagCompiler([]))->guessClassName('alert');
<add> $result = $this->compiler()->guessClassName('alert');
<ide>
<ide> $this->assertSame("App\View\Components\Alert", trim($result));
<ide>
<ide> public function testClassNamesCanBeGuessedWithNamespaces()
<ide> $app->shouldReceive('getNamespace')->andReturn('App\\');
<ide> Container::setInstance($container);
<ide>
<del> $result = (new ComponentTagCompiler([]))->guessClassName('base.alert');
<add> $result = $this->compiler()->guessClassName('base.alert');
<ide>
<ide> $this->assertSame("App\View\Components\Base\Alert", trim($result));
<ide>
<ide> public function testComponentsCanBeCompiledWithHyphenAttributes()
<ide> {
<ide> $this->mockViewFactory();
<ide>
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert class="bar" wire:model="foo" x-on:click="bar" @click="baz" />');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<x-alert class="bar" wire:model="foo" x-on:click="bar" @click="baz" />');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testComponentsCanBeCompiledWithHyphenAttributes()
<ide>
<ide> public function testSelfClosingComponentsCanBeCompiledWithDataAndAttributes()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert title="foo" class="bar" wire:model="foo" />');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<x-alert title="foo" class="bar" wire:model="foo" />');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', ['title' => 'foo'])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testSelfClosingComponentsCanBeCompiledWithDataAndAttributes()
<ide>
<ide> public function testComponentsCanHaveAttachedWord()
<ide> {
<del> $result = (new ComponentTagCompiler(['profile' => TestProfileComponent::class]))->compileTags('<x-profile></x-profile>Words');
<add> $result = $this->compiler(['profile' => TestProfileComponent::class])->compileTags('<x-profile></x-profile>Words');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestProfileComponent', [])
<ide> <?php \$component->withName('profile'); ?>
<ide> public function testComponentsCanHaveAttachedWord()
<ide>
<ide> public function testSelfClosingComponentsCanHaveAttachedWord()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert/>Words');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<x-alert/>Words');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testSelfClosingComponentsCanHaveAttachedWord()
<ide>
<ide> public function testSelfClosingComponentsCanBeCompiledWithBoundData()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert :title="$title" class="bar" />');
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<x-alert :title="$title" class="bar" />');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', ['title' => \$title])
<ide> <?php \$component->withName('alert'); ?>
<ide> public function testSelfClosingComponentsCanBeCompiledWithBoundData()
<ide>
<ide> public function testPairedComponentTags()
<ide> {
<del> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert>
<add> $result = $this->compiler(['alert' => TestAlertComponent::class])->compileTags('<x-alert>
<ide> </x-alert>');
<ide>
<ide> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', [])
<ide> public function testClasslessComponents()
<ide> $factory->shouldReceive('exists')->andReturn(true);
<ide> Container::setInstance($container);
<ide>
<del> $result = (new ComponentTagCompiler([]))->compileTags('<x-anonymous-component :name="\'Taylor\'" :age="31" wire:model="foo" />');
<add> $result = $this->compiler()->compileTags('<x-anonymous-component :name="\'Taylor\'" :age="31" wire:model="foo" />');
<ide>
<ide> $this->assertSame("@component('Illuminate\View\AnonymousComponent', ['view' => 'components.anonymous-component','data' => ['name' => 'Taylor','age' => 31,'wire:model' => 'foo']])
<ide> <?php \$component->withName('anonymous-component'); ?>
<ide> public function testItThrowsAnExceptionForNonExistingAliases()
<ide>
<ide> $this->expectException(InvalidArgumentException::class);
<ide>
<del> (new ComponentTagCompiler(['alert' => 'foo.bar']))->compileTags('<x-alert />');
<add> $this->compiler(['alert' => 'foo.bar'])->compileTags('<x-alert />');
<ide> }
<ide>
<ide> public function testItThrowsAnExceptionForNonExistingClass()
<ide> public function testItThrowsAnExceptionForNonExistingClass()
<ide>
<ide> $this->expectException(InvalidArgumentException::class);
<ide>
<del> (new ComponentTagCompiler)->compileTags('<x-alert />');
<add> $this->compiler()->compileTags('<x-alert />');
<ide> }
<ide>
<ide> protected function mockViewFactory($existsSucceeds = true)
<ide> protected function mockViewFactory($existsSucceeds = true)
<ide> $factory->shouldReceive('exists')->andReturn($existsSucceeds);
<ide> Container::setInstance($container);
<ide> }
<add>
<add> protected function compiler($aliases = [])
<add> {
<add> return new ComponentTagCompiler(
<add> new BladeCompiler(new Filesystem, __DIR__),
<add> $aliases
<add> );
<add> }
<ide> }
<ide>
<ide> class TestAlertComponent extends Component | 4 |
Ruby | Ruby | correct config path in error message | 3e5206f8d138492f7f2d94a279f5c42bda7d5ddb | <ide><path>test/service/shared_service_tests.rb
<ide> SERVICE_CONFIGURATIONS = begin
<ide> YAML.load_file(File.expand_path("../configurations.yml", __FILE__)).deep_symbolize_keys
<ide> rescue Errno::ENOENT
<del> puts "Missing service configuration file in test/services/configurations.yml"
<add> puts "Missing service configuration file in test/service/configurations.yml"
<ide> end
<ide>
<ide> module ActiveStorage::Service::SharedServiceTests | 1 |
Python | Python | fix the conditional, add test cases for it | 805d7181c8f2bd565d35c55884e8db9273401f97 | <ide><path>libcloud/compute/base.py
<ide> import time
<ide> import hashlib
<ide> import os
<add>import re
<ide> import socket
<ide> import random
<ide> import binascii
<ide> def deploy_node(self, **kwargs):
<ide> raise NotImplementedError(
<ide> 'deploy_node not implemented for this driver')
<ide>
<del> # NOTE 1: This is a workaround for legacy code. Sadly a lot of legacy code
<del> # uses **kwargs in "create_node()" method and simply ignores
<add> # NOTE 1: This is a workaround for legacy code. Sadly a lot of legacy
<add> # code uses **kwargs in "create_node()" method and simply ignores
<ide> # "deploy_node()" arguments which are passed to it.
<ide> # That's obviously far from idea that's why we first try to pass only
<del> # non-deploy node arguments to the "create_node()" methods and if it that
<del> # doesn't work, fall back to the old approach and simply pass in all the
<del> # arguments
<del> # NOTE 2: Some drivers which use password based SSH authentication rely on
<del> # password being stored on the "auth" argument and that's why we also
<del> # propagate that argument to "create_node()" method.
<del> create_node_kwargs = dict([(key, value) for key, value in kwargs.items() if
<del> key not in DEPLOY_NODE_KWARGS])
<add> # non-deploy node arguments to the "create_node()" methods and if it
<add> # that doesn't work, fall back to the old approach and simply pass in
<add> # all the arguments
<add> # NOTE 2: Some drivers which use password based SSH authentication
<add> # rely on password being stored on the "auth" argument and that's why
<add> # we also propagate that argument to "create_node()" method.
<add> create_node_kwargs = dict([(key, value) for key, value in kwargs.items()
<add> if key not in DEPLOY_NODE_KWARGS])
<ide>
<ide> try:
<ide> node = self.create_node(**create_node_kwargs)
<ide> except TypeError as e:
<del> if 'create_node() got an unexpected keyword argument' in str(e):
<add> msg_1_re = r'create_node\(\) missing \d+ required positional arguments.*'
<add> msg_2_re = r'create_node\(\) takes at least \d+ arguments.*'
<add> if re.match(msg_1_re, str(e)) or re.match(msg_2_re, str(e)):
<ide> node = self.create_node(**kwargs)
<del> raise e
<add> else:
<add> raise e
<ide>
<ide> max_tries = kwargs.get('max_tries', 3)
<ide>
<ide> def deploy_node(self, **kwargs):
<ide> node, ip_addresses = self.wait_until_running(
<ide> nodes=[node],
<ide> wait_period=3,
<del> timeout=kwargs.get('timeout', NODE_ONLINE_WAIT_TIMEOUT),
<add> timeout=float(kwargs.get('timeout', NODE_ONLINE_WAIT_TIMEOUT)),
<ide> ssh_interface=ssh_interface)[0]
<ide> except Exception as e:
<ide> raise DeploymentError(node=node, original_exception=e, driver=self)
<ide><path>libcloud/test/compute/test_deployment.py
<ide> from libcloud.compute.deployment import SSHKeyDeployment, ScriptDeployment
<ide> from libcloud.compute.deployment import ScriptFileDeployment, FileDeployment
<ide> from libcloud.compute.base import Node
<add>from libcloud.compute.base import DEPLOY_NODE_KWARGS
<add>from libcloud.compute.base import NodeAuthPassword
<ide> from libcloud.compute.types import NodeState, DeploymentError, LibcloudError
<ide> from libcloud.compute.ssh import BaseSSHClient
<ide> from libcloud.compute.drivers.rackspace import RackspaceFirstGenNodeDriver as Rackspace
<ide> def test_deploy_node_success(self, mock_ssh_module, _):
<ide> node = self.driver.deploy_node(deploy=deploy)
<ide> self.assertEqual(self.node.id, node.id)
<ide>
<add> @patch('libcloud.compute.base.SSHClient')
<add> @patch('libcloud.compute.ssh')
<add> def test_deploy_node_deploy_node_kwargs_except_auth_are_not_propagated_on(self, mock_ssh_module, _):
<add> # Verify that keyword arguments which are specific to deploy_node()
<add> # are not propagated to create_node()
<add> mock_ssh_module.have_paramiko = True
<add> self.driver.create_node = Mock()
<add> self.driver.create_node.return_value = self.node
<add> self.driver._connect_and_run_deployment_script = Mock()
<add> self.driver._wait_until_running = Mock()
<add>
<add> kwargs = {}
<add> for key in DEPLOY_NODE_KWARGS:
<add> kwargs[key] = key
<add>
<add> kwargs['ssh_interface'] = 'public_ips'
<add> kwargs['ssh_alternate_usernames'] = ['foo', 'bar']
<add> kwargs['timeout'] = 10
<add>
<add> auth = NodeAuthPassword('P@$$w0rd')
<add>
<add> node = self.driver.deploy_node(name='name', image='image', size='size',
<add> auth=auth, ex_foo='ex_foo', **kwargs)
<add> self.assertEqual(self.node.id, node.id)
<add> self.assertEqual(self.driver.create_node.call_count, 1)
<add>
<add> call_kwargs = self.driver.create_node.call_args_list[0][1]
<add> expected_call_kwargs = {
<add> 'name': 'name',
<add> 'image': 'image',
<add> 'size': 'size',
<add> 'auth': auth,
<add> 'ex_foo': 'ex_foo'
<add> }
<add> self.assertEqual(expected_call_kwargs, call_kwargs)
<add>
<add> # If driver throws an exception it should fall back to passing in all
<add> # the arguments
<add> global call_count
<add> call_count = 0
<add> def create_node(name, image, size, ex_custom_arg_1, ex_custom_arg_2,
<add> ex_foo=None, auth=None, **kwargs):
<add> global call_count
<add>
<add> call_count += 1
<add> if call_count == 1:
<add> msg = 'create_node() takes at least 5 arguments (7 given)'
<add> raise TypeError(msg)
<add> return self.node
<add>
<add> self.driver.create_node = create_node
<add>
<add> node = self.driver.deploy_node(name='name', image='image', size='size',
<add> auth=auth, ex_foo='ex_foo', ex_custom_arg_1='a',
<add> ex_custom_arg_2='b', **kwargs)
<add> self.assertEqual(self.node.id, node.id)
<add> self.assertEqual(call_count, 2)
<add>
<add> global call_count
<add> call_count = 0
<add> def create_node(name, image, size, ex_custom_arg_1, ex_custom_arg_2,
<add> ex_foo=None, auth=None, **kwargs):
<add> global call_count
<add>
<add> call_count += 1
<add> if call_count == 1:
<add> msg = 'create_node() missing 3 required positional arguments'
<add> raise TypeError(msg)
<add> return self.node
<add>
<add> self.driver.create_node = create_node
<add>
<add> node = self.driver.deploy_node(name='name', image='image', size='size',
<add> auth=auth, ex_foo='ex_foo', ex_custom_arg_1='a',
<add> ex_custom_arg_2='b', **kwargs)
<add> self.assertEqual(self.node.id, node.id)
<add> self.assertEqual(call_count, 2)
<add>
<add>
<ide> @patch('libcloud.compute.base.SSHClient')
<ide> @patch('libcloud.compute.ssh')
<ide> def test_deploy_node_exception_run_deployment_script(self, mock_ssh_module, | 2 |
Go | Go | remove unused types and fields | 43ea03002fd9d10f31631504be69b8b73f40a43a | <ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) {
<ide> }...)
<ide> }
<ide>
<del> type wrapper struct {
<del> containertypes.Config
<del> HostConfig containertypes.HostConfig
<del> }
<del> type createResp struct {
<del> ID string `json:"Id"`
<del> }
<del>
<ide> ctx := context.Background()
<ide> apiclient := testEnv.APIClient()
<ide> for i, x := range cases {
<ide><path>integration-cli/docker_cli_create_test.go
<ide> import (
<ide> "reflect"
<ide> "strings"
<ide> "testing"
<del> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/cli"
<ide> "github.com/docker/docker/integration-cli/cli/build"
<ide> func (s *DockerSuite) TestCreateArgs(c *testing.T) {
<ide> out, _ = dockerCmd(c, "inspect", cleanedContainerID)
<ide>
<ide> var containers []struct {
<del> ID string
<del> Created time.Time
<del> Path string
<del> Args []string
<del> Image string
<add> Path string
<add> Args []string
<ide> }
<ide>
<ide> err := json.Unmarshal([]byte(out), &containers) | 2 |
Javascript | Javascript | send suicide message on disconnect | f299d870dcfb71c0b0ab77b20d43d6a1d59d04c0 | <ide><path>lib/cluster.js
<ide> function workerInit() {
<ide>
<ide> Worker.prototype.disconnect = function() {
<ide> this.suicide = true;
<del> var waitingHandles = 0;
<add> let waitingCount = 1;
<ide>
<del> function checkRemainingHandles() {
<del> waitingHandles--;
<del> if (waitingHandles === 0) {
<add> function checkWaitingCount() {
<add> waitingCount--;
<add> if (waitingCount === 0) {
<add> send({ act: 'suicide' });
<ide> process.disconnect();
<ide> }
<ide> }
<ide>
<del> for (var key in handles) {
<del> var handle = handles[key];
<add> for (const key in handles) {
<add> const handle = handles[key];
<ide> delete handles[key];
<del> waitingHandles++;
<del> handle.owner.close(checkRemainingHandles);
<del> }
<del>
<del> if (waitingHandles === 0) {
<del> process.disconnect();
<add> waitingCount++;
<add> handle.owner.close(checkWaitingCount);
<ide> }
<ide>
<add> checkWaitingCount();
<ide> };
<ide>
<ide> Worker.prototype.destroy = function() {
<ide><path>test/parallel/test-regress-GH-3238.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>
<add>if (cluster.isMaster) {
<add> const worker = cluster.fork();
<add> let disconnected = false;
<add>
<add> worker.on('disconnect', common.mustCall(function() {
<add> assert.strictEqual(worker.suicide, true);
<add> disconnected = true;
<add> }));
<add>
<add> worker.on('exit', common.mustCall(function() {
<add> assert.strictEqual(worker.suicide, true);
<add> assert.strictEqual(disconnected, true);
<add> }));
<add>} else {
<add> cluster.worker.disconnect();
<add>} | 2 |
Text | Text | update next.js.configs line number | 1ebd6a1d9409d1e1dbf51adedf18aacccd39afc9 | <ide><path>docs/api-reference/next.config.js/introduction.md
<ide> module.exports = (phase, { defaultConfig }) => {
<ide> }
<ide> ```
<ide>
<del>The commented lines are the place where you can put the configs allowed by `next.config.js`, which are [defined in this file](https://github.com/vercel/next.js/blob/canary/packages/next/server/config-shared.ts#L137).
<add>The commented lines are the place where you can put the configs allowed by `next.config.js`, which are [defined in this file](https://github.com/vercel/next.js/blob/canary/packages/next/server/config-shared.ts#L158).
<ide>
<ide> However, none of the configs are required, and it's not necessary to understand what each config does. Instead, search for the features you need to enable or modify in this section and they will show you what to do.
<ide> | 1 |
Text | Text | update changelog for 1.6.0 | 87cf065e48ca7d2db6e51b46252adda130d67ce9 | <ide><path>CHANGELOG.md
<ide> simple ground rule: Never set a controllers content, rather always set
<ide> it's model and ember will do the right thing.
<ide>
<del>### Ember 1.6.0-beta.5 (May 27, 2014)
<add>### Ember 1.6.0 (July, 7, 2014)
<ide>
<ide> * [BUGFIX] Ensure itemController's do not leak by tying them to the parent controller lifecycle.
<ide> * [BUGFIX] Spaces in brace expansion throws an error.
<ide> * [BUGFIX] Update backburner.js to fix issue with IE8.
<ide> * [BUGFIX] `Ember.computed.alias` returns value of aliased property upon set.
<ide> * Provide better debugging information for view rendering.
<del>
<del>### Ember 1.6.0-beta.4 (May, 15, 2014)
<del>
<ide> * [BUGFIX] Don't fire redirect on parent routes during transitions from one child route to another.
<ide> * [BUGFIX] Make errors thrown by Ember use `Ember.Error` consistently.
<ide> * [BUGFIX] Ensure controllers instantiated by the `{{render}}` helper are properly torn down.
<del>
<del>### Ember 1.6.0-beta.3 (April, 29, 2014)
<del>
<ide> * [BUGFIX] sync back burner: workaround IE's issue with try/finally without Catch. Also no longer force deoptimization of the run loop queue flush.
<ide> * [BREAKING BUGFIX] An empty array are treated as falsy value in `bind-attr` to be in consistent with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty array as truthy value in `bind-attr`.
<ide> * [BUGFIX] Ember.onerror now uses Backburner's error handler.
<ide> * [BUGFIX] reduceComputed detect retain:n better. Fixes issue with `Ember.computed.filterBy` erroring when items removed from dependent array.
<ide> * [BUGFIX] Namespaces are now required to start with uppercase A-Z.
<ide> * [BUGFIX] pass context to sortFunction to avoid calling `__nextSuper` on `undefined`.
<del>
<del>### Ember 1.6.0-beta.2 (April, 8, 2014)
<del>
<ide> * [BUGFIX] Allow setting of `undefined` value to a `content` property.
<ide> * [BUGFIX] Resolve bound actionName in Handlebars context instead of direct lookup on target.
<ide> * [BUGFIX] isEqual now supports dates.
<ide> * [BUGFIX] Drop dead code for * in paths.
<ide> * [BUGFIX] Route#render name vs viewName precedence fix.
<ide> * [BUGFIX] Use parseFloat before incrementing via incrementProperty.
<del>
<del>### Ember 1.6.0-beta.1 (March 31, 2014)
<del>
<ide> * [BUGFIX] Add `which` attribute to event triggered by keyEvent test helper.
<ide> * [Performance] Improve cache lookup throughput.
<ide> * [FEATURE ember-routing-add-model-option] | 1 |
PHP | PHP | add events hook to plugins | 0cbab2a29bb6d8b8adb5411477920bf3c9db5f7a | <ide><path>src/Console/CommandRunner.php
<ide> public function run(array $argv, ConsoleIo $io = null)
<ide> * Application bootstrap wrapper.
<ide> *
<ide> * Calls `bootstrap()` and `events()` if application implements `EventApplicationInterface`.
<add> * After the application is bootstrapped and events are attached, plugins are bootstrapped
<add> * and have their events attached.
<ide> *
<ide> * @return void
<ide> */
<ide> protected function bootstrap()
<ide> }
<ide> if ($this->app instanceof PluginApplicationInterface) {
<ide> $this->app->pluginBootstrap();
<add> $this->app->pluginEvents();
<ide> }
<ide> }
<ide>
<ide><path>src/Core/PluginApp.php
<ide> class PluginApp implements PluginInterface
<ide> */
<ide> protected $bootstrapEnabled = true;
<ide>
<add> /**
<add> * Are events enabled.
<add> *
<add> * @var bool
<add> */
<add> protected $eventsEnabled = true;
<add>
<ide> /**
<ide> * Load routes or not
<ide> *
<ide> public function middleware($middleware)
<ide> {
<ide> return $middleware;
<ide> }
<add>
<add> /**
<add> * {@inheritdoc}
<add> */
<add> public function events($events)
<add> {
<add> }
<ide> }
<ide><path>src/Core/PluginApplicationInterface.php
<ide> public function pluginMiddleware($middleware);
<ide> * @return \Cake\Console\CommandCollection
<ide> */
<ide> public function pluginConsole($commands);
<add>
<add> /**
<add> * Run events hook for plugins
<add> *
<add> * @return void
<add> */
<add> public function pluginEvents();
<ide> }
<ide><path>src/Core/PluginInterface.php
<ide> interface PluginInterface
<ide> {
<ide> /**
<del> * The list of valid hooks
<add> * List of valid hooks.
<ide> */
<del> const VALID_HOOKS = ['routes', 'bootstrap', 'console', 'middleware'];
<add> const VALID_HOOKS = ['routes', 'bootstrap', 'console', 'middleware', 'events'];
<ide>
<ide> /**
<ide> * Get the name of this plugin.
<ide> public function getClassPath();
<ide> public function bootstrap();
<ide>
<ide> /**
<del> * Add a plugins console commands
<add> * Add console commands for the plugin.
<ide> *
<ide> * @param \Cake\Console\CommandCollection $commands The command collection to update
<ide> * @return \Cake\Console\CommandCollection
<ide> */
<ide> public function console($commands);
<ide>
<ide> /**
<del> * Add a plugins middleware
<add> * Add middleware for the plugin.
<ide> *
<ide> * @param \Cake\Http\MiddlewareQueue $middleware The middleware queue to update.
<ide> * @return \Cake\Http\MiddlewareQueue
<ide> */
<ide> public function middleware($middleware);
<ide>
<ide> /**
<del> * Add a routes
<add> * Add routes for the plugin.
<ide> *
<ide> * @param \Cake\Routing\RouteBuilder $routes The route builder to update.
<ide> * @return \Cake\Routing\RouteBuilder
<ide> */
<ide> public function routes($routes);
<ide>
<add> /**
<add> * Add events for the plugin.
<add> *
<add> * @param \Cake\Event\EventManager $events The application's event manager
<add> * @return void
<add> */
<add> public function events($events);
<add>
<ide> /**
<ide> * Disables the named hook
<ide> *
<ide><path>src/Http/BaseApplication.php
<ide> public function __construct($configDir, EventManagerInterface $eventManager = nu
<ide> */
<ide> abstract public function middleware($middleware);
<ide>
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public function pluginEvents()
<add> {
<add> $events = $this->getEventManager();
<add>
<add> foreach ($this->plugins->with('events') as $plugin) {
<add> $plugin->events($events);
<add> }
<add> }
<add>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Server.php
<ide> public function run(ServerRequestInterface $request = null, ResponseInterface $r
<ide> * Application bootstrap wrapper.
<ide> *
<ide> * Calls `bootstrap()` and `events()` if application implements `EventApplicationInterface`.
<add> * After the application is bootstrapped and events are attached, plugins are bootstrapped
<add> * and have their events attached.
<ide> *
<ide> * @return void
<ide> */
<ide> protected function bootstrap()
<ide> }
<ide> if ($this->app instanceof PluginApplicationInterface) {
<ide> $this->app->pluginBootstrap();
<add> $this->app->pluginEvents();
<ide> }
<ide> }
<ide>
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunTriggersBuildCommandsEvent()
<ide> public function testRunCallsPluginHookMethods()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'pluginBootstrap', 'pluginConsole'])
<add> ->setMethods(['middleware', 'bootstrap', 'pluginBootstrap', 'pluginEvents', 'pluginConsole'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<del> $app->expects($this->once())
<del> ->method('pluginBootstrap');
<add>
<add> $app->expects($this->at(0))->method('bootstrap');
<add> $app->expects($this->at(1))->method('pluginBootstrap');
<add> $app->expects($this->at(2))->method('pluginEvents');
<ide>
<ide> $commands = new CommandCollection();
<del> $app->expects($this->once())
<add> $app->expects($this->at(3))
<ide> ->method('pluginConsole')
<ide> ->with($this->isinstanceOf(CommandCollection::class))
<ide> ->will($this->returnCallback(function ($commands) {
<ide><path>tests/TestCase/Core/PluginAppTest.php
<ide> use Cake\Console\CommandCollection;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Core\PluginApp;
<add>use Cake\Event\EventManager;
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\TestSuite\TestCase;
<ide> use Company\TestPluginThree\Plugin as TestPluginThree;
<ide> public function testConsole()
<ide> $this->assertSame($commands, $plugin->console($commands));
<ide> }
<ide>
<add> public function testEvents()
<add> {
<add> $plugin = new PluginApp();
<add> $events = new EventManager();
<add> $this->assertNull($plugin->events($events));
<add> }
<add>
<ide> public function testConstructorArguments()
<ide> {
<ide> $plugin = new PluginApp([
<ide><path>tests/TestCase/Http/ServerTest.php
<ide> public function testRunCallingPluginHooks()
<ide> $request = $request->withHeader('X-pass', 'request header');
<ide>
<ide> $app = $this->getMockBuilder(MiddlewareApplication::class)
<del> ->setMethods(['pluginBootstrap', 'pluginMiddleware'])
<add> ->setMethods(['pluginBootstrap', 'pluginEvents', 'pluginMiddleware'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<del> $app->expects($this->once())
<add> $app->expects($this->at(0))
<ide> ->method('pluginBootstrap');
<del> $app->expects($this->once())
<add> $app->expects($this->at(1))
<add> ->method('pluginBootstrap');
<add> $app->expects($this->at(2))
<ide> ->method('pluginMiddleware')
<ide> ->with($this->isInstanceOf(MiddlewareQueue::class))
<ide> ->will($this->returnCallback(function ($middleware) { | 9 |
Javascript | Javascript | kill child in tls-server-verify for speed up | 4cf323d23dcefedd349fedd396a58b0ed1fa2387 | <ide><path>test/parallel/test-tls-server-verify.js
<ide> function runClient(prefix, port, options, cb) {
<ide> if (!goodbye && /_unauthed/g.test(out)) {
<ide> console.error(prefix + ' * unauthed');
<ide> goodbye = true;
<del> client.stdin.end('goodbye\n');
<add> client.kill();
<ide> authed = false;
<ide> rejected = false;
<ide> }
<ide>
<ide> if (!goodbye && /_authed/g.test(out)) {
<ide> console.error(prefix + ' * authed');
<ide> goodbye = true;
<del> client.stdin.end('goodbye\n');
<add> client.kill();
<ide> authed = true;
<ide> rejected = false;
<ide> }
<ide> function runTest(port, testIndex) {
<ide>
<ide> var renegotiated = false;
<ide> var server = tls.Server(serverOptions, function handleConnection(c) {
<add> c.on('error', function(e) {
<add> // child.kill() leads ECONNRESET errro in the TLS connection of
<add> // openssl s_client via spawn(). A Test result is already
<add> // checked by the data of client.stdout before child.kill() so
<add> // these tls errors can be ignored.
<add> });
<ide> if (tcase.renegotiate && !renegotiated) {
<ide> renegotiated = true;
<ide> setTimeout(function() { | 1 |
PHP | PHP | improve arr class documentation | b6ba0de0bd41a63e03587d13fb86a1e06f8fdb19 | <ide><path>system/arr.php
<ide> class Arr {
<ide> * Get an item from an array.
<ide> *
<ide> * If the specified key is null, the entire array will be returned. The array may
<del> * also be accessed using JavaScript "dot" style notation.
<add> * also be accessed using JavaScript "dot" style notation. Retrieving items nested
<add> * in multiple arrays is also supported.
<add> *
<add> * <code>
<add> * // Returns "taylor"
<add> * $item = Arr::get(array('name' => 'taylor'), 'name', $default);
<add> *
<add> * // Returns "taylor"
<add> * $item = Arr::get(array('name' => array('is' => 'taylor')), 'name.is');
<add> * </code>
<ide> *
<ide> * @param array $array
<ide> * @param string $key | 1 |
Text | Text | add examples to readme | 6d91b429a07ffabed2e0eb02a713dd4d68f73aa8 | <ide><path>README.md
<ide> This architecture might seem like an overkill for a counter app, but the beauty
<ide> * [Glossary](http://rackt.github.io/redux/docs/Glossary.html)
<ide> * [API Reference](http://rackt.github.io/redux/docs/api/index.html)
<ide>
<add>### Examples
<add>
<add>* [Counter](http://rackt.github.io/redux/docs/introduction/Examples.html#counter) ([source](https://github.com/rackt/redux/tree/master/examples/counter))
<add>* [TodoMVC](http://rackt.github.io/redux/docs/introduction/Examples.html#todomvc) ([source](https://github.com/rackt/redux/tree/master/examples/todomvc))
<add>* [Async](http://rackt.github.io/redux/docs/introduction/Examples.html#async) ([source](https://github.com/rackt/redux/tree/master/examples/async))
<add>* [Real World](http://rackt.github.io/redux/docs/introduction/Examples.html#real-world) ([source](https://github.com/rackt/redux/tree/master/examples/real-world))
<add>
<ide> ### Discussion
<ide>
<ide> Join the **#redux** channel of the [Reactiflux](http://reactiflux.com/) Slack community. | 1 |
Javascript | Javascript | change whitespace to tab | 7cb97cf7e3eba3da8ec668faa5841f311e83c8d4 | <ide><path>test/unit/core/Clock.js
<ide> module( "Clock" );
<ide>
<ide> function mockPerformance() {
<del> self.performance = {
<del> deltaTime: 0,
<add> self.performance = {
<add> deltaTime: 0,
<ide>
<del> next: function( delta ) {
<del> this.deltaTime += delta;
<del> },
<add> next: function( delta ) {
<add> this.deltaTime += delta;
<add> },
<ide>
<del> now: function() {
<del> return this.deltaTime;
<del> }
<del> };
<add> now: function() {
<add> return this.deltaTime;
<add> }
<add> };
<ide> }
<ide>
<ide> test( "clock with performance", function() {
<del> mockPerformance();
<add> mockPerformance();
<ide>
<del> var clock = new THREE.Clock();
<add> var clock = new THREE.Clock();
<ide>
<del> clock.start();
<add> clock.start();
<ide>
<del> self.performance.next(123);
<del> ok( clock.getElapsedTime() === 0.123 , "okay");
<add> self.performance.next(123);
<add> ok( clock.getElapsedTime() === 0.123 , "okay");
<ide>
<del> self.performance.next(100);
<del> ok( clock.getElapsedTime() === 0.223 , "okay");
<add> self.performance.next(100);
<add> ok( clock.getElapsedTime() === 0.223 , "okay");
<ide>
<del> clock.stop();
<add> clock.stop();
<ide>
<del> self.performance.next(1000);
<del> ok( clock.getElapsedTime() === 0.223 , "don't update time if the clock was stopped");
<add> self.performance.next(1000);
<add> ok( clock.getElapsedTime() === 0.223 , "don't update time if the clock was stopped");
<ide> });
<ide>
<ide> test( "clock with date", function() {
<del> // remove the performance object so that clock takes Date()
<del> self.performance = undefined;
<add> // remove the performance object so that clock takes Date()
<add> self.performance = undefined;
<ide>
<del> var clock = new THREE.Clock();
<add> var clock = new THREE.Clock();
<ide>
<del> clock.start();
<add> clock.start();
<ide>
<del> // if a value was calculated, the clock took the alternative Date() object
<del> ok( clock.getElapsedTime() >= 0 , "okay");
<add> // if a value was calculated, the clock took the alternative Date() object
<add> ok( clock.getElapsedTime() >= 0 , "okay");
<ide>
<del> clock.stop();
<add> clock.stop();
<ide> }); | 1 |
Javascript | Javascript | stop ie9 memory leak when destroying scopes | 8fe781fbe7c42c64eb895c28d9fd5479b037d020 | <ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider() {
<ide> $event.currentScope.$$destroyed = true;
<ide> }
<ide>
<add> function cleanUpScope($scope) {
<add>
<add> if (msie === 9) {
<add> // There is a memory leak in IE9 if all child scopes are not disconnected
<add> // completely when a scope is destroyed. So this code will recurse up through
<add> // all this scopes children
<add> //
<add> // See issue https://github.com/angular/angular.js/issues/10706
<add> $scope.$$childHead && cleanUpScope($scope.$$childHead);
<add> $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
<add> }
<add>
<add> // The code below works around IE9 and V8's memory leaks
<add> //
<add> // See:
<add> // - https://code.google.com/p/v8/issues/detail?id=2073#c26
<add> // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
<add> // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
<add>
<add> $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
<add> $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
<add> }
<add>
<ide> /**
<ide> * @ngdoc type
<ide> * @name $rootScope.Scope
<ide> function $RootScopeProvider() {
<ide> this.$on = this.$watch = this.$watchGroup = function() { return noop; };
<ide> this.$$listeners = {};
<ide>
<del> // All of the code below is bogus code that works around V8's memory leak via optimized code
<del> // and inline caches.
<del> //
<del> // see:
<del> // - https://code.google.com/p/v8/issues/detail?id=2073#c26
<del> // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
<del> // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
<del>
<del> this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
<del> this.$$childTail = this.$root = this.$$watchers = null;
<add> // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
<add> this.$$nextSibling = null;
<add> cleanUpScope(this);
<ide> },
<ide>
<ide> /**
<ide><path>test/ng/rootScopeSpec.js
<ide> describe('Scope', function() {
<ide> expect(child.parentModel).toBe('parent');
<ide> expect(child.childModel).toBe('child');
<ide> }));
<add>
<add>
<add> if (msie === 9) {
<add> // See issue https://github.com/angular/angular.js/issues/10706
<add> it('should completely disconnect all child scopes on IE9', inject(function($rootScope) {
<add> var parent = $rootScope.$new(),
<add> child1 = parent.$new(),
<add> child2 = parent.$new(),
<add> grandChild = child1.$new();
<add> parent.$destroy();
<add>
<add> $rootScope.$digest();
<add>
<add> expect(isDisconnected(parent)).toBe(true);
<add> expect(isDisconnected(child1)).toBe(true);
<add> expect(isDisconnected(child2)).toBe(true);
<add> expect(isDisconnected(grandChild)).toBe(true);
<add>
<add> function isDisconnected($scope) {
<add> return $scope.$$nextSibling === null &&
<add> $scope.$$prevSibling === null &&
<add> $scope.$$childHead === null &&
<add> $scope.$$childTail === null &&
<add> $scope.$root === null &&
<add> $scope.$$watchers === null;
<add> }
<add> }));
<add> }
<ide> });
<ide>
<ide> | 2 |
Javascript | Javascript | add helper for exception-safe beginpropertychanges | 817a8c840c83aa90aa084dbab1182bd7e712bb83 | <ide><path>packages/sproutcore-metal/lib/observer.js
<ide> SC.endPropertyChanges = function() {
<ide> if (suspended<=0) flushObserverQueue();
<ide> };
<ide>
<add>SC.batchPropertyChanges = function(cb){
<add> SC.beginPropertyChanges();
<add> try {
<add> cb()
<add> } finally {
<add> SC.endPropertyChanges();
<add> }
<add>}
<add>
<ide> function changeEvent(keyName) {
<ide> return keyName+AFTER_OBSERVERS;
<ide> }
<ide><path>packages/sproutcore-metal/tests/observer_test.js
<ide> testBoth('suspending property changes will defer', function(get,set) {
<ide> equals(fooCount, 1, 'foo should have fired once');
<ide> });
<ide>
<add>testBoth('suspending property changes safely despite exceptions', function(get,set) {
<add> var obj = { foo: 'foo' };
<add> var fooCount = 0;
<add> var exc = new Error("Something unexpected happened!");
<add>
<add> expect(2);
<add> SC.addObserver(obj, 'foo' ,function() { fooCount++; });
<add>
<add> try {
<add> SC.batchPropertyChanges(function(){
<add> set(obj, 'foo', 'BIFF');
<add> set(obj, 'foo', 'BAZ');
<add> throw exc;
<add> });
<add> } catch(err) {
<add> if (err != exc)
<add> throw err;
<add> }
<add>
<add> equals(fooCount, 1, 'foo should have fired once');
<add>
<add> SC.batchPropertyChanges(function(){
<add> set(obj, 'foo', 'BIFF2');
<add> set(obj, 'foo', 'BAZ2');
<add> });
<add>
<add> equals(fooCount, 2, 'foo should have fired again once');
<add>});
<add>
<ide> testBoth('suspending property changes will not defer before observers', function(get,set) {
<ide> var obj = { foo: 'foo' };
<ide> var fooCount = 0; | 2 |
Javascript | Javascript | log uncaught exceptions on the socket server | 8f5b2ccbe04a7e33da2cb4aed85386b3e0e52634 | <ide><path>packager/react-packager/src/SocketInterface/SocketServer.js
<ide> class SocketServer {
<ide> });
<ide> });
<ide>
<add> process.on('uncaughtException', (error) => {
<add> debug('uncaught error', error);
<add> setImmediate(() => process.exit(1));
<add> });
<add>
<ide> this._numConnections = 0;
<ide> this._server.on('connection', (sock) => this._handleConnection(sock));
<ide> | 1 |
Text | Text | remove beststandardssupport references | a83183c72155db3f11af287281ef3c13d56dddce | <ide><path>guides/source/command_line.md
<ide> Active Record version 4.0.0.beta
<ide> Action Pack version 4.0.0.beta
<ide> Action Mailer version 4.0.0.beta
<ide> Active Support version 4.0.0.beta
<del>Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag, ActionDispatch::BestStandardsSupport
<add>Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
<ide> Application root /home/foobar/commandsapp
<ide> Environment development
<ide> Database adapter sqlite3
<ide><path>guides/source/configuring.md
<ide> Every Rails application comes with a standard set of middleware which it uses in
<ide> * `ActionDispatch::ParamsParser` parses out parameters from the request into `params`.
<ide> * `Rack::MethodOverride` allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types.
<ide> * `ActionDispatch::Head` converts HEAD requests to GET requests and serves them as so.
<del>* `ActionDispatch::BestStandardsSupport` enables "best standards support" so that IE8 renders some elements correctly.
<ide>
<ide> Besides these usual middleware, you can add your own by using the `config.middleware.use` method:
<ide>
<ide> config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
<ide> Middlewares can also be completely swapped out and replaced with others:
<ide>
<ide> ```ruby
<del>config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
<add>config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
<ide> ```
<ide>
<ide> They can also be removed from the stack completely:
<ide>
<ide> ```ruby
<del>config.middleware.delete ActionDispatch::BestStandardsSupport
<add>config.middleware.delete "Rack::MethodOverride"
<ide> ```
<ide>
<ide> ### Configuring i18n
<ide><path>guides/source/rails_on_rack.md
<ide> use ActionDispatch::ParamsParser
<ide> use Rack::Head
<ide> use Rack::ConditionalGet
<ide> use Rack::ETag
<del>use ActionDispatch::BestStandardsSupport
<ide> run MyApp::Application.routes
<ide> ```
<ide>
<ide> And to remove browser related middleware,
<ide>
<ide> ```ruby
<ide> # config/application.rb
<del>config.middleware.delete "ActionDispatch::BestStandardsSupport"
<ide> config.middleware.delete "Rack::MethodOverride"
<ide> ```
<ide>
<ide> Much of Action Controller's functionality is implemented as Middlewares. The fol
<ide>
<ide> * Adds ETag header on all String bodies. ETags are used to validate cache.
<ide>
<del> **`ActionDispatch::BestStandardsSupport`**
<del>
<del>* Enables “best standards support” so that IE8 renders some elements correctly.
<del>
<ide> TIP: It's possible to use any of the above middlewares in your custom Rack stack.
<ide>
<ide> ### Using Rack Builder | 3 |
Ruby | Ruby | remove newlines left behind after correction | ab09d15703e897a77f4af9177a92c275973bd0a3 | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> offending_node(node)
<ide> problem "Use a single `generate_completions_from_executable` call
<ide> combining all specified shells" do |corrector|
<del> corrector.replace(@offensive_node.source_range, "")
<add> # adjust range by +1 to also include & remove trailing \n
<add> corrector.replace(@offensive_node.source_range.adjust(end_pos: 1), "")
<ide> end
<ide> end
<ide> | 1 |
Text | Text | translate 10.7 to korean | c0ac76d723e611d81886bc1cd29daec72629cc06 | <ide><path>docs/docs/10.7-pure-render-mixin.ko-KR.md
<add>---
<add>id: pure-render-mixin-ko-KR
<add>title: PureRenderMixin
<add>permalink: pure-render-mixin-ko-KR.html
<add>prev: update-ko-KR.html
<add>next: perf-ko-KR.html
<add>---
<add>
<add>React 컴포넌트의 렌더 함수가 "pure"하다면 (다른 말로, props나 state에 같은 값이 주어질 때 같은 결과를 렌더한다면) 몇몇 경우엔 이 믹스인을 사용하여 성능을 향상시킬 수 있습니다.
<add>
<add>예제:
<add>
<add>```js
<add>var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
<add>React.createClass({
<add> mixins: [PureRenderMixin],
<add>
<add> render: function() {
<add> return <div className={this.props.className}>foo</div>;
<add> }
<add>});
<add>```
<add>
<add>내부적으로 믹스인은 현재의 props와 state를 다음 값과 비교하여 같다면 `false`를 반환하도록 [shouldComponentUpdate](/react/docs/component-specs-ko-KR.html#updating-shouldcomponentupdate)를 구현합니다.
<add>
<add>> 주의:
<add>>
<add>> 여기서는 객체에 대한 얕은(shallow) 비교만 합니다. 복잡한 데이터 구조를 가진 경우에는 깊은 부분의 차이에 대해 잘못된 false를 반환 할 수도 있습니다. 간단한 props와 state를 사용하는 컴포넌트에만 적용하거나 깊은 데이터 구조가 변경 되었을때는 `forceUpdate()`를 사용하세요. 아니면 중첩 데이터의 비교를 빠르고 용이하게 하기 위해 [immutable 객체](http://facebook.github.io/immutable-js/)의 도입을 고려해보세요.
<add>>
<add>> 또, `shouldComponentUpdate`는 컴포넌트 서브트리의 업데이트를 건너뜁니다. 모든 자식 컴포넌트들도 "pure"한지 확인하세요. | 1 |
Ruby | Ruby | add missing model | 9a7e7e5fdb56dd1a805bce291acf122c7b6e3b83 | <ide><path>activerecord/test/models/boolean.rb
<add>class Boolean < ActiveRecord::Base
<add>end | 1 |
Mixed | Go | support credential specs | e85867cb68cc28208c91bb43fc5cdcff824c468e | <ide><path>api/server/router/build/build_routes.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "net/http"
<add> "runtime"
<ide> "strconv"
<ide> "strings"
<ide> "sync"
<ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
<ide> options.CPUSetMems = r.FormValue("cpusetmems")
<ide> options.CgroupParent = r.FormValue("cgroupparent")
<ide> options.Tags = r.Form["t"]
<add> options.SecurityOpt = r.Form["securityopt"]
<ide>
<ide> if r.Form.Get("shmsize") != "" {
<ide> shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
<ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
<ide> options.Isolation = i
<ide> }
<ide>
<add> if runtime.GOOS != "windows" && options.SecurityOpt != nil {
<add> return nil, fmt.Errorf("the daemon on this platform does not support --security-opt to build")
<add> }
<add>
<ide> var buildUlimits = []*units.Ulimit{}
<ide> ulimitsJSON := r.FormValue("ulimits")
<ide> if ulimitsJSON != "" {
<ide><path>api/types/client.go
<ide> type ImageBuildOptions struct {
<ide> Squash bool
<ide> // CacheFrom specifies images that are used for matching cache. Images
<ide> // specified here do not need to have a valid parent chain to match cache.
<del> CacheFrom []string
<add> CacheFrom []string
<add> SecurityOpt []string
<ide> }
<ide>
<ide> // ImageBuildResponse holds information
<ide><path>builder/dockerfile/internals.go
<ide> func (b *Builder) create() (string, error) {
<ide>
<ide> // TODO: why not embed a hostconfig in builder?
<ide> hostConfig := &container.HostConfig{
<del> Isolation: b.options.Isolation,
<del> ShmSize: b.options.ShmSize,
<del> Resources: resources,
<add> SecurityOpt: b.options.SecurityOpt,
<add> Isolation: b.options.Isolation,
<add> ShmSize: b.options.ShmSize,
<add> Resources: resources,
<ide> }
<ide>
<ide> config := *b.runConfig
<ide><path>cli/command/image/build.go
<ide> type buildOptions struct {
<ide> pull bool
<ide> cacheFrom []string
<ide> compress bool
<add> securityOpt []string
<ide> }
<ide>
<ide> // NewBuildCommand creates a new `docker build` command
<ide> func NewBuildCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> flags.BoolVar(&options.pull, "pull", false, "Always attempt to pull a newer version of the image")
<ide> flags.StringSliceVar(&options.cacheFrom, "cache-from", []string{}, "Images to consider as cache sources")
<ide> flags.BoolVar(&options.compress, "compress", false, "Compress the build context using gzip")
<add> flags.StringSliceVar(&options.securityOpt, "security-opt", []string{}, "Security options")
<ide>
<ide> command.AddTrustedFlags(flags, true)
<ide>
<ide> func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
<ide> AuthConfigs: authConfig,
<ide> Labels: runconfigopts.ConvertKVStringsToMap(options.labels.GetAll()),
<ide> CacheFrom: options.cacheFrom,
<add> SecurityOpt: options.securityOpt,
<ide> }
<ide>
<ide> response, err := dockerCli.Client().ImageBuild(ctx, body, buildOptions)
<ide><path>client/image_build.go
<ide> func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, optio
<ide>
<ide> func imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) {
<ide> query := url.Values{
<del> "t": options.Tags,
<add> "t": options.Tags,
<add> "securityopt": options.SecurityOpt,
<ide> }
<ide> if options.SuppressOutput {
<ide> query.Set("q", "1")
<ide><path>daemon/daemon.go
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide> return nil, err
<ide> }
<ide>
<add> if runtime.GOOS == "windows" {
<add> if err := idtools.MkdirAllAs(filepath.Join(config.Root, "credentialspecs"), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
<add> return nil, err
<add> }
<add> }
<add>
<ide> driverName := os.Getenv("DOCKER_DRIVER")
<ide> if driverName == "" {
<ide> driverName = config.GraphDriver
<ide><path>daemon/start_windows.go
<ide> package daemon
<ide>
<ide> import (
<ide> "fmt"
<add> "io/ioutil"
<ide> "path/filepath"
<add> "strings"
<ide>
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/libcontainerd"
<add> "golang.org/x/sys/windows/registry"
<add>)
<add>
<add>const (
<add> credentialSpecRegistryLocation = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs`
<add> credentialSpecFileLocation = "CredentialSpecs"
<ide> )
<ide>
<ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Container) (*[]libcontainerd.CreateOption, error) {
<ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain
<ide> }
<ide> }
<ide>
<del> // Now build the full set of options
<add> // Read and add credentials from the security options if a credential spec has been provided.
<add> if container.HostConfig.SecurityOpt != nil {
<add> for _, sOpt := range container.HostConfig.SecurityOpt {
<add> sOpt = strings.ToLower(sOpt)
<add> if !strings.Contains(sOpt, "=") {
<add> return nil, fmt.Errorf("invalid security option: no equals sign in supplied value %s", sOpt)
<add> }
<add> var splitsOpt []string
<add> splitsOpt = strings.SplitN(sOpt, "=", 2)
<add> if len(splitsOpt) != 2 {
<add> return nil, fmt.Errorf("invalid security option: %s", sOpt)
<add> }
<add> if splitsOpt[0] != "credentialspec" {
<add> return nil, fmt.Errorf("security option not supported: %s", splitsOpt[0])
<add> }
<add>
<add> credentialsOpts := &libcontainerd.CredentialsOption{}
<add> var (
<add> match bool
<add> csValue string
<add> err error
<add> )
<add> if match, csValue = getCredentialSpec("file://", splitsOpt[1]); match {
<add> if csValue == "" {
<add> return nil, fmt.Errorf("no value supplied for file:// credential spec security option")
<add> }
<add> if credentialsOpts.Credentials, err = readCredentialSpecFile(container.ID, daemon.root, filepath.Clean(csValue)); err != nil {
<add> return nil, err
<add> }
<add> } else if match, csValue = getCredentialSpec("registry://", splitsOpt[1]); match {
<add> if csValue == "" {
<add> return nil, fmt.Errorf("no value supplied for registry:// credential spec security option")
<add> }
<add> if credentialsOpts.Credentials, err = readCredentialSpecRegistry(container.ID, csValue); err != nil {
<add> return nil, err
<add> }
<add> } else {
<add> return nil, fmt.Errorf("invalid credential spec security option - value must be prefixed file:// or registry:// followed by a value")
<add> }
<add> createOptions = append(createOptions, credentialsOpts)
<add> }
<add> }
<add>
<add> // Now add the remaining options.
<ide> createOptions = append(createOptions, &libcontainerd.FlushOption{IgnoreFlushesDuringBoot: !container.HasBeenStartedBefore})
<ide> createOptions = append(createOptions, hvOpts)
<ide> createOptions = append(createOptions, layerOpts)
<ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain
<ide>
<ide> return &createOptions, nil
<ide> }
<add>
<add>// getCredentialSpec is a helper function to get the value of a credential spec supplied
<add>// on the CLI, stripping the prefix
<add>func getCredentialSpec(prefix, value string) (bool, string) {
<add> if strings.HasPrefix(value, prefix) {
<add> return true, strings.TrimPrefix(value, prefix)
<add> }
<add> return false, ""
<add>}
<add>
<add>// readCredentialSpecRegistry is a helper function to read a credential spec from
<add>// the registry. If not found, we return an empty string and warn in the log.
<add>// This allows for staging on machines which do not have the necessary components.
<add>func readCredentialSpecRegistry(id, name string) (string, error) {
<add> var (
<add> k registry.Key
<add> err error
<add> val string
<add> )
<add> if k, err = registry.OpenKey(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.QUERY_VALUE); err != nil {
<add> return "", fmt.Errorf("failed handling spec %q for container %s - %s could not be opened", name, id, credentialSpecRegistryLocation)
<add> }
<add> if val, _, err = k.GetStringValue(name); err != nil {
<add> if err == registry.ErrNotExist {
<add> return "", fmt.Errorf("credential spec %q for container %s as it was not found", name, id)
<add> }
<add> return "", fmt.Errorf("error %v reading credential spec %q from registry for container %s", err, name, id)
<add> }
<add> return val, nil
<add>}
<add>
<add>// readCredentialSpecFile is a helper function to read a credential spec from
<add>// a file. If not found, we return an empty string and warn in the log.
<add>// This allows for staging on machines which do not have the necessary components.
<add>func readCredentialSpecFile(id, root, location string) (string, error) {
<add> if filepath.IsAbs(location) {
<add> return "", fmt.Errorf("invalid credential spec - file:// path cannot be absolute")
<add> }
<add> base := filepath.Join(root, credentialSpecFileLocation)
<add> full := filepath.Join(base, location)
<add> if !strings.HasPrefix(full, base) {
<add> return "", fmt.Errorf("invalid credential spec - file:// path must be under %s", base)
<add> }
<add> bcontents, err := ioutil.ReadFile(full)
<add> if err != nil {
<add> return "", fmt.Errorf("credential spec '%s' for container %s as the file could not be read: %q", full, id, err)
<add> }
<add> return string(bcontents[:]), nil
<add>}
<ide><path>docs/reference/commandline/build.md
<ide> Options:
<ide> --pull Always attempt to pull a newer version of the image
<ide> -q, --quiet Suppress the build output and print image ID on success
<ide> --rm Remove intermediate containers after a successful build (default true)
<add> --security-opt value Security Options (default [])
<ide> --shm-size string Size of /dev/shm, default value is 64MB.
<ide> The format is `<number><unit>`. `number` must be greater than `0`.
<ide> Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes),
<ide> Dockerfile are echoed during the build process.
<ide> For detailed information on using `ARG` and `ENV` instructions, see the
<ide> [Dockerfile reference](../builder.md).
<ide>
<add>### Optional security options (--security-opt)
<add>
<add>This flag is only supported on a daemon running on Windows, and only supports
<add>the `credentialspec` option. The `credentialspec` must be in the format
<add>`file://spec.txt` or `registry://keyname`.
<add>
<ide> ### Specify isolation technology for container (--isolation)
<ide>
<ide> This option is useful in situations where you are running Docker containers on
<ide><path>docs/reference/commandline/run.md
<ide> The `--stop-signal` flag sets the system call signal that will be sent to the co
<ide> This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9,
<ide> or a signal name in the format SIGNAME, for instance SIGKILL.
<ide>
<add>### Optional security options (--security-opt)
<add>
<add>On Windows, this flag can be used to specify the `credentialspec` option.
<add>The `credentialspec` must be in the format `file://spec.txt` or `registry://keyname`.
<add>
<ide> ### Specify isolation technology for container (--isolation)
<ide>
<ide> This option is useful in situations where you are running Docker containers on
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *check.C) {
<ide> // NGoroutines is not updated right away, so we need to wait before failing
<ide> c.Assert(waitForGoroutines(nroutines), checker.IsNil)
<ide> }
<add>
<add>// Handles error conditions for --credentialspec. Validating E2E success cases
<add>// requires additional infrastructure (AD for example) on CI servers.
<add>func (s *DockerSuite) TestRunCredentialSpecFailures(c *check.C) {
<add> testRequires(c, DaemonIsWindows)
<add> attempts := []struct{ value, expectedError string }{
<add> {"rubbish", "invalid credential spec security option - value must be prefixed file:// or registry://"},
<add> {"rubbish://", "invalid credential spec security option - value must be prefixed file:// or registry://"},
<add> {"file://", "no value supplied for file:// credential spec security option"},
<add> {"registry://", "no value supplied for registry:// credential spec security option"},
<add> {`file://c:\blah.txt`, "path cannot be absolute"},
<add> {`file://doesnotexist.txt`, "The system cannot find the file specified"},
<add> }
<add> for _, attempt := range attempts {
<add> _, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true")
<add> c.Assert(err, checker.NotNil, check.Commentf("%s expected non-nil err", attempt.value))
<add> c.Assert(err.Error(), checker.Contains, attempt.expectedError, check.Commentf("%s expected %s got %s", attempt.value, attempt.expectedError, err))
<add> }
<add>}
<ide><path>libcontainerd/client_windows.go
<ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir
<ide> configuration.AllowUnqualifiedDNSQuery = n.AllowUnqualifiedDNSQuery
<ide> continue
<ide> }
<add> if c, ok := option.(*CredentialsOption); ok {
<add> configuration.Credentials = c.Credentials
<add> continue
<add> }
<ide> }
<ide>
<ide> // We must have a layer option with at least one path
<ide><path>libcontainerd/types_windows.go
<ide> type NetworkEndpointsOption struct {
<ide> AllowUnqualifiedDNSQuery bool
<ide> }
<ide>
<add>// CredentialsOption is a CreateOption that indicates the credentials from
<add>// a credential spec to be used to the runtime
<add>type CredentialsOption struct {
<add> Credentials string
<add>}
<add>
<ide> // Checkpoint holds the details of a checkpoint (not supported in windows)
<ide> type Checkpoint struct {
<ide> Name string
<ide><path>libcontainerd/utils_windows.go
<ide> func (h *LayerOption) Apply(interface{}) error {
<ide> func (s *NetworkEndpointsOption) Apply(interface{}) error {
<ide> return nil
<ide> }
<add>
<add>// Apply for the credentials option is a no-op.
<add>func (s *CredentialsOption) Apply(interface{}) error {
<add> return nil
<add>}
<ide><path>runconfig/config.go
<ide> func DecodeContainerConfig(src io.Reader) (*container.Config, *container.HostCon
<ide> if err := ValidateQoS(hc); err != nil {
<ide> return nil, nil, nil, err
<ide> }
<add>
<ide> return w.Config, hc, w.NetworkingConfig, nil
<ide> }
<ide>
<ide><path>runconfig/opts/parse.go
<ide> type ContainerOptions struct {
<ide> autoRemove bool
<ide> init bool
<ide> initPath string
<add> credentialSpec string
<ide>
<ide> Image string
<ide> Args []string
<ide> func AddFlags(flags *pflag.FlagSet) *ContainerOptions {
<ide> flags.BoolVar(&copts.privileged, "privileged", false, "Give extended privileges to this container")
<ide> flags.Var(&copts.securityOpt, "security-opt", "Security Options")
<ide> flags.StringVar(&copts.usernsMode, "userns", "", "User namespace to use")
<add> flags.StringVar(&copts.credentialSpec, "credentialspec", "", "Credential spec for managed service account (Windows only)")
<ide>
<ide> // Network and port publishing flag
<ide> flags.Var(&copts.extraHosts, "add-host", "Add a custom host-to-IP mapping (host:ip)") | 15 |
PHP | PHP | remove item caching from cache manager | 23d5742575acb481a2b34053f3eea6ddfe1dae6e | <ide><path>system/cache.php
<ide> class Cache {
<ide> */
<ide> public static $drivers = array();
<ide>
<del> /**
<del> * All of the items retrieved by the cache drivers.
<del> *
<del> * @var array
<del> */
<del> public static $items = array();
<del>
<ide> /**
<ide> * Get a cache driver instance. If no driver name is specified, the default
<ide> * cache driver will be returned as defined in the cache configuration file.
<ide> public static function driver($driver = null)
<ide> */
<ide> public static function get($key, $default = null, $driver = null)
<ide> {
<del> if (isset(static::$items[$driver][$key]))
<add> if (is_null($driver))
<ide> {
<del> return static::$items[$driver][$key];
<add> $driver = Config::get('cache.driver');
<ide> }
<ide>
<ide> if (is_null($item = static::driver($driver)->get($key)))
<ide> {
<ide> return is_callable($default) ? call_user_func($default) : $default;
<ide> }
<ide>
<del> return static::$items[$driver][$key] = $item;
<add> return $item;
<ide> }
<ide>
<ide> /**
<ide> public static function get($key, $default = null, $driver = null)
<ide> */
<ide> public static function remember($key, $default, $minutes, $driver = null)
<ide> {
<del> if ( ! is_null($item = static::get($key)))
<add> if ( ! is_null($item = static::get($key, null, $driver)))
<ide> {
<ide> return $item;
<ide> } | 1 |
Ruby | Ruby | reduce object allocations in param wrapping | 1bc7cce8fedb7dcf1837ed493e1b2d390fa0bfb5 | <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> def _wrap_parameters(parameters)
<ide> def _extract_parameters(parameters)
<ide> if include_only = _wrapper_options.include
<ide> parameters.slice(*include_only)
<add> elsif _wrapper_options.exclude
<add> exclude = _wrapper_options.exclude + EXCLUDE_PARAMETERS
<add> parameters.except(*exclude)
<ide> else
<del> exclude = _wrapper_options.exclude || []
<del> parameters.except(*(exclude + EXCLUDE_PARAMETERS))
<add> parameters.except(*EXCLUDE_PARAMETERS)
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | remove some service providers and aliases | a68933d34c7cedbb88a8f9a2bb0adfdda73130d4 | <ide><path>config/app.php
<ide> 'Illuminate\Filesystem\FilesystemServiceProvider',
<ide> 'Illuminate\Foundation\Providers\FormRequestServiceProvider',
<ide> 'Illuminate\Hashing\HashServiceProvider',
<del> 'Illuminate\Html\HtmlServiceProvider',
<ide> 'Illuminate\Log\LogServiceProvider',
<ide> 'Illuminate\Mail\MailServiceProvider',
<ide> 'Illuminate\Database\MigrationServiceProvider',
<ide> 'Eloquent' => 'Illuminate\Database\Eloquent\Model',
<ide> 'Event' => 'Illuminate\Support\Facades\Event',
<ide> 'File' => 'Illuminate\Support\Facades\File',
<del> 'Form' => 'Illuminate\Support\Facades\Form',
<ide> 'FormRequest' => 'Illuminate\Foundation\Http\FormRequest',
<ide> 'Hash' => 'Illuminate\Support\Facades\Hash',
<del> 'HTML' => 'Illuminate\Support\Facades\HTML',
<ide> 'Input' => 'Illuminate\Support\Facades\Input',
<ide> 'Lang' => 'Illuminate\Support\Facades\Lang',
<ide> 'Log' => 'Illuminate\Support\Facades\Log',
<ide> 'Seeder' => 'Illuminate\Database\Seeder',
<ide> 'Session' => 'Illuminate\Support\Facades\Session',
<ide> 'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait',
<del> 'SSH' => 'Illuminate\Support\Facades\SSH',
<ide> 'Str' => 'Illuminate\Support\Str',
<ide> 'URL' => 'Illuminate\Support\Facades\URL',
<ide> 'Validator' => 'Illuminate\Support\Facades\Validator', | 1 |
Text | Text | update basic setup instructions | 25d07511ed63959777ab1d0bee9f8e5f79382318 | <ide><path>docs/sources/installation/amazon.md
<ide> Repository.
<ide> your Amazon Linux instance should be running!
<ide> 3. SSH to your instance to install Docker :
<ide> `ssh -i <path to your private key> ec2-user@<your public IP address>`
<del>4. Once connected to the instance, type
<del> `sudo yum install -y docker ; sudo service docker start`
<add>4. Add the ec2-user to the docker group :
<add> `sudo usermod -a -G docker ec2-user`
<add>5. Restart the machine and log back in
<add> `sudo shutdown -r now`
<add>6. Once connected to the instance, type
<add> `sudo yum install -y docker ; sudo service docker start`
<ide> to install and start Docker
<ide>
<ide> **If this is your first AWS instance, you may need to set up your Security Group to allow SSH.** By default all incoming ports to your new instance will be blocked by the AWS Security Group, so you might just get timeouts when you try to connect. | 1 |
Text | Text | add missing feature to 1.6.0-rc.0 | 4a320ab9f01ae32fdbbee35ea513e704529d0580 | <ide><path>CHANGELOG.md
<ide> ensure that Angular 1 can pass the linter checks for Mozilla add-ons.
<ide>
<ide> - **ngModelOptions:** allow options to be inherited from ancestor `ngModelOptions` ([296cfc](https://github.com/angular/angular.js/commit/296cfce40c25e9438bfa46a0eb27240707a10ffa) [#10922](https://github.com/angular/angular.js/issues/10922))
<ide> - **$compile:** set `preAssignBindingsEnabled` to false by default ([bcd0d4](https://github.com/angular/angular.js/commit/bcd0d4d896d0dfdd988ff4f849c1d40366125858) [#15352](https://github.com/angular/angular.js/issues/15352))
<del>
<add>- **input[type=number]:** support `step` ([e1da4bed8](https://github.com/angular/angular.js/commit/e1da4bed8e291003d485a8ad346ab80bed8ae2e3) [#10597](https://github.com/angular/angular.js/issues/10597))
<ide>
<ide> ## Bug Fixes
<ide> | 1 |
Text | Text | change error message to 'not defined' | a7a871476e0116e85b7ae8e5b2eb00761206ab75 | <ide><path>doc/api/errors.md
<ide> are handled using the [`try…catch` construct][try-catch] provided by the
<ide> JavaScript language.
<ide>
<ide> ```js
<del>// Throws with a ReferenceError because z is undefined
<add>// Throws with a ReferenceError because z is not defined.
<ide> try {
<ide> const m = 1;
<ide> const n = m + z; | 1 |
PHP | PHP | change method order | c460b69aa1be9838ea8c74c80417c92444677772 | <ide><path>src/Illuminate/Notifications/HasDatabaseNotifications.php
<ide> public function notifications()
<ide> }
<ide>
<ide> /**
<del> * Get the entity's unread notifications.
<add> * Get the entity's read notifications.
<ide> */
<del> public function unreadNotifications()
<add> public function readNotifications()
<ide> {
<ide> return $this->morphMany(DatabaseNotification::class, 'notifiable')
<del> ->whereNull('read_at')
<add> ->whereNotNull('read_at')
<ide> ->orderBy('created_at', 'desc');
<ide> }
<ide>
<ide> /**
<del> * Get the entity's read notifications.
<add> * Get the entity's unread notifications.
<ide> */
<del> public function readNotifications()
<add> public function unreadNotifications()
<ide> {
<ide> return $this->morphMany(DatabaseNotification::class, 'notifiable')
<del> ->whereNotNull('read_at')
<add> ->whereNull('read_at')
<ide> ->orderBy('created_at', 'desc');
<ide> }
<ide> } | 1 |
Javascript | Javascript | avoid implicit keyframe trimming. | 7714fe8f6dec8fd3ecfa0266c2c4a8ef0e9f61c7 | <ide><path>src/animation/AnimationClip.js
<ide> function AnimationClip( name, duration, tracks ) {
<ide>
<ide> }
<ide>
<del> // maybe only do these on demand, as doing them here could potentially slow down loading
<del> // but leaving these here during development as this ensures a lot of testing of these functions
<del> this.trim();
<ide> this.optimize();
<ide>
<ide> } | 1 |
Text | Text | fix spelling in v8.8.0 changelog | e70038528891aa7bddf44b39b85ee99ee30e6d6b | <ide><path>doc/changelogs/CHANGELOG_V8.md
<ide> - expose ECDH class [#8188](https://github.com/nodejs/node/pull/8188)
<ide> * **http2**:
<ide> - http2 is now exposed by default without the need for a flag [#15685](https://github.com/nodejs/node/pull/15685)
<del> - a new environment varible NODE\_NO\_HTTP2 has been added to allow userland http2 to be required [#15685](https://github.com/nodejs/node/pull/15685)
<add> - a new environment variable NODE\_NO\_HTTP2 has been added to allow userland http2 to be required [#15685](https://github.com/nodejs/node/pull/15685)
<ide> - support has been added for generic `Duplex` streams [#16269](https://github.com/nodejs/node/pull/16269)
<ide> * **module**:
<ide> - resolve and instantiate loader pipeline hooks have been added to the ESM lifecycle [#15445](https://github.com/nodejs/node/pull/15445) | 1 |
Python | Python | fix scheme issue in https case | af54b94263db9bb5056431c263f3953103568c3a | <ide><path>libcloud/http.py
<ide> def _parse_proxy_url(self, proxy_url):
<ide> """
<ide> parsed = urlparse.urlparse(proxy_url)
<ide>
<del> if parsed.scheme != 'http':
<add> if parsed.scheme not in ('http', 'https'):
<ide> raise ValueError('Only http proxies are supported')
<ide>
<ide> if not parsed.hostname or not parsed.port: | 1 |
Text | Text | fix path in 09-advanced.md | 9ac0293b1ab57d058bd736bc175bed1544dd9331 | <ide><path>docs/09-Advanced.md
<ide> var myPieChart = new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>See `sample/line-customTooltips.html` for examples on how to get started.
<add>See `samples/tooltips/line-customTooltips.html` for examples on how to get started.
<ide>
<ide> ### Writing New Scale Types
<ide> | 1 |
Java | Java | add getter for the length of a websocket message | ac968e94ed1b9a1863a0345a030af506b25d9e0d | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/AbstractWebSocketMessage.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public boolean equals(Object other) {
<ide> @Override
<ide> public String toString() {
<ide> return getClass().getSimpleName() + " payload= " + toStringPayload()
<del> + ", length=" + getPayloadSize() + ", last=" + isLast() + "]";
<add> + ", byteCount=" + getPayloadLength() + ", last=" + isLast() + "]";
<ide> }
<ide>
<ide> protected abstract String toStringPayload();
<ide>
<del> protected abstract int getPayloadSize();
<del>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/BinaryMessage.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public BinaryMessage(byte[] payload, int offset, int length, boolean isLast) {
<ide>
<ide>
<ide> @Override
<del> protected int getPayloadSize() {
<add> public int getPayloadLength() {
<ide> return getPayload().remaining();
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PingMessage.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public PingMessage(ByteBuffer payload) {
<ide>
<ide>
<ide> @Override
<del> protected int getPayloadSize() {
<del> return getPayload().remaining();
<add> public int getPayloadLength() {
<add> return (getPayload() != null) ? getPayload().remaining() : 0;
<ide> }
<ide>
<ide> @Override
<ide> protected String toStringPayload() {
<del> return getPayload().toString();
<add> return (getPayload() != null) ? getPayload().toString() : null;
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PongMessage.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public PongMessage(ByteBuffer payload) {
<ide>
<ide>
<ide> @Override
<del> protected int getPayloadSize() {
<add> public int getPayloadLength() {
<ide> return (getPayload() != null) ? getPayload().remaining() : 0;
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/TextMessage.java
<ide>
<ide> package org.springframework.web.socket;
<ide>
<add>import java.nio.charset.Charset;
<add>
<ide> /**
<ide> * A text WebSocket message.
<ide> *
<ide> */
<ide> public final class TextMessage extends AbstractWebSocketMessage<String> {
<ide>
<add> private static final Charset UTF_8 = Charset.forName("UTF-8");
<add>
<add> private final byte[] bytes;
<add>
<ide>
<ide> /**
<ide> * Create a new text WebSocket message from the given CharSequence payload.
<ide> * @param payload the non-null payload
<ide> */
<ide> public TextMessage(CharSequence payload) {
<ide> super(payload.toString(), true);
<add> this.bytes = null;
<add> }
<add>
<add> /**
<add> * Create a new text WebSocket message from the given byte[]. It is assumed the
<add> * byte array can be encoded into an UTF-8 String.
<add> *
<add> * @param payload the non-null payload
<add> */
<add> public TextMessage(byte[] payload) {
<add> super(new String(payload, UTF_8));
<add> this.bytes = payload;
<ide> }
<ide>
<ide> /**
<ide> public TextMessage(CharSequence payload) {
<ide> */
<ide> public TextMessage(CharSequence payload, boolean isLast) {
<ide> super(payload.toString(), isLast);
<add> this.bytes = null;
<ide> }
<ide>
<ide>
<ide> @Override
<del> protected int getPayloadSize() {
<del> return getPayload().length();
<add> public int getPayloadLength() {
<add> return asBytes().length;
<add> }
<add>
<add> public byte[] asBytes() {
<add> return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF_8));
<ide> }
<ide>
<ide> @Override
<ide> protected String toStringPayload() {
<del> return (getPayloadSize() > 10) ? getPayload().substring(0, 10) + ".." : getPayload();
<add> return (getPayloadLength() > 10) ? getPayload().substring(0, 10) + ".." : getPayload();
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketMessage.java
<ide> */
<ide> T getPayload();
<ide>
<add>
<add> /**
<add> * Return the number of bytes contained in the message.
<add> */
<add> int getPayloadLength();
<add>
<ide> /**
<ide> * When partial message support is available and requested via
<ide> * {@link org.springframework.web.socket.WebSocketHandler#supportsPartialMessages()},
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java
<ide>
<ide> import java.io.IOException;
<ide> import java.nio.ByteBuffer;
<del>import java.nio.charset.Charset;
<ide> import java.security.Principal;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> public class StompSubProtocolHandler implements SubProtocolHandler {
<ide>
<ide> /**
<del> * The name of the header set on the CONNECTED frame indicating the name of the user
<del> * authenticated on the WebSocket session.
<add> * The name of the header set on the CONNECTED frame indicating the name
<add> * of the user authenticated on the WebSocket session.
<ide> */
<ide> public static final String CONNECTED_USER_HEADER = "user-name";
<ide>
<del> private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
<del>
<ide> private static final Log logger = LogFactory.getLog(StompSubProtocolHandler.class);
<ide>
<ide>
<ide> public void handleMessageFromClient(WebSocketSession session,
<ide> Throwable decodeFailure = null;
<ide> try {
<ide> Assert.isInstanceOf(TextMessage.class, webSocketMessage);
<del> String payload = ((TextMessage) webSocketMessage).getPayload();
<del> ByteBuffer byteBuffer = ByteBuffer.wrap(payload.getBytes(UTF8_CHARSET));
<add> TextMessage textMessage = (TextMessage) webSocketMessage;
<add> ByteBuffer byteBuffer = ByteBuffer.wrap(textMessage.asBytes());
<ide>
<ide> message = this.stompDecoder.decode(byteBuffer);
<ide> if (message == null) {
<del> decodeFailure = new IllegalStateException("Not a valid STOMP frame: " + payload);
<add> decodeFailure = new IllegalStateException("Not a valid STOMP frame: " + textMessage.getPayload());
<ide> }
<ide> }
<ide> catch (Throwable ex) {
<ide> protected void sendErrorMessage(WebSocketSession session, Throwable error) {
<ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.ERROR);
<ide> headers.setMessage(error.getMessage());
<ide> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
<del> String payload = new String(this.stompEncoder.encode(message), UTF8_CHARSET);
<add> byte[] bytes = this.stompEncoder.encode(message);
<ide> try {
<del> session.sendMessage(new TextMessage(payload));
<add> session.sendMessage(new TextMessage(bytes));
<ide> }
<ide> catch (Throwable ex) {
<ide> // ignore
<ide> else if (SimpMessageType.MESSAGE.equals(headers.getMessageType())) {
<ide> byte[] bytes = this.stompEncoder.encode((Message<byte[]>) message);
<ide>
<ide> synchronized(session) {
<del> session.sendMessage(new TextMessage(new String(bytes, UTF8_CHARSET)));
<add> session.sendMessage(new TextMessage(bytes));
<ide> }
<ide>
<ide> } | 7 |
Javascript | Javascript | add support for k and kk format parsing | 073d3153663c349d4ccc68dae37f8a61c6f06d30 | <ide><path>src/lib/units/hour.js
<ide> addRegexToken('a', matchMeridiem);
<ide> addRegexToken('A', matchMeridiem);
<ide> addRegexToken('H', match1to2);
<ide> addRegexToken('h', match1to2);
<add>addRegexToken('k', match1to2);
<ide> addRegexToken('HH', match1to2, match2);
<ide> addRegexToken('hh', match1to2, match2);
<add>addRegexToken('kk', match1to2, match2);
<ide>
<ide> addRegexToken('hmm', match3to4);
<ide> addRegexToken('hmmss', match5to6);
<ide> addRegexToken('Hmm', match3to4);
<ide> addRegexToken('Hmmss', match5to6);
<ide>
<ide> addParseToken(['H', 'HH'], HOUR);
<add>addParseToken(['k', 'kk'], function (input, array, config) {
<add> var kInput = toInt(input);
<add> array[HOUR] = kInput === 24 ? 0 : kInput;
<add>});
<ide> addParseToken(['a', 'A'], function (input, array, config) {
<ide> config._isPm = config._locale.isPM(input);
<ide> config._meridiem = input;
<ide><path>src/test/moment/create.js
<ide> test('string with format', function (assert) {
<ide> ['h:mm a', '12:00 am'],
<ide> ['h:mm a', '12:30 am'],
<ide> ['HH:mm', '12:00'],
<add> ['kk:mm', '12:00'],
<ide> ['YYYY-MM-DDTHH:mm:ss', '2011-11-11T11:11:11'],
<ide> ['MM-DD-YYYY [M]', '12-02-1999 M'],
<ide> ['ddd MMM DD HH:mm:ss YYYY', 'Tue Apr 07 22:52:51 2009'],
<ide> test('string with format', function (assert) {
<ide> ['HH:mm:ss S', '00:30:00 7'],
<ide> ['HH:mm:ss SS', '00:30:00 78'],
<ide> ['HH:mm:ss SSS', '00:30:00 789'],
<add> ['kk:mm:ss', '12:00:00'],
<add> ['kk:mm:ss', '12:30:00'],
<add> ['kk:mm:ss', '24:00:00'],
<add> ['kk:mm:ss S', '24:30:00 1'],
<add> ['kk:mm:ss SS', '24:30:00 12'],
<add> ['kk:mm:ss SSS', '24:30:00 123'],
<add> ['kk:mm:ss S', '24:30:00 7'],
<add> ['kk:mm:ss SS', '24:30:00 78'],
<add> ['kk:mm:ss SSS', '24:30:00 789'],
<ide> ['X', '1234567890'],
<ide> ['x', '1234567890123'],
<ide> ['LT', '12:30 AM'],
<ide> test('string with array of formats', function (assert) {
<ide>
<ide> assert.equal(moment('11-02-10', ['MM/DD/YY', 'YY MM DD', 'DD-MM-YY']).format('MM DD YYYY'), '02 11 2010', 'all unparsed substrings have influence on format penalty');
<ide> assert.equal(moment('11-02-10', ['MM-DD-YY HH:mm', 'YY MM DD']).format('MM DD YYYY'), '02 10 2011', 'prefer formats without extra tokens');
<del> assert.equal(moment('11-02-10 junk', ['MM-DD-YY', 'YY.MM.DD junk']).format('MM DD YYYY'), '02 10 2011', 'prefer formats that dont result in extra characters');
<add> assert.equal(moment('11-02-10 junk', ['MM-DD-YY', 'YY.MM.DD [junk]']).format('MM DD YYYY'), '02 10 2011', 'prefer formats that dont result in extra characters');
<ide> assert.equal(moment('11-22-10', ['YY-MM-DD', 'YY-DD-MM']).format('MM DD YYYY'), '10 22 2011', 'prefer valid results');
<ide>
<ide> assert.equal(moment('gibberish', ['YY-MM-DD', 'YY-DD-MM']).format('MM DD YYYY'), 'Invalid date', 'doest throw for invalid strings');
<ide> test('string with array of formats', function (assert) {
<ide> test('string with array of formats + ISO', function (assert) {
<ide> assert.equal(moment('1994', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).year(), 1994, 'iso: assert parse YYYY');
<ide> assert.equal(moment('17:15', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).hour(), 17, 'iso: assert parse HH:mm (1)');
<add> assert.equal(moment('24:15', [moment.ISO_8601, 'MM', 'kk:mm', 'YYYY']).hour(), 0, 'iso: assert parse kk:mm');
<ide> assert.equal(moment('17:15', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).minutes(), 15, 'iso: assert parse HH:mm (2)');
<ide> assert.equal(moment('06', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).month(), 6 - 1, 'iso: assert parse MM');
<ide> assert.equal(moment('2012-06-01', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).parsingFlags().iso, true, 'iso: assert parse iso');
<ide> test('invalid dates return invalid for methods that access the _d prop', functio
<ide> assert.ok(momentAsDate instanceof Date, 'toDate returns a Date object');
<ide> assert.ok(isNaN(momentAsDate.getTime()), 'toDate returns an invalid Date invalid');
<ide> });
<add>
<add>test('k, kk', function (assert) {
<add> for (var i = -1; i <= 24; i++) {
<add> var kVal = i + ':15:59';
<add> var kkVal = (i < 10 ? '0' : '') + i + ':15:59';
<add> if (i !== 24) {
<add> assert.ok(moment(kVal, 'k:mm:ss').isSame(moment(kVal, 'H:mm:ss')), kVal + ' k parsing');
<add> assert.ok(moment(kkVal, 'kk:mm:ss').isSame(moment(kkVal, 'HH:mm:ss')), kkVal + ' kk parsing');
<add> } else {
<add> assert.equal(moment(kVal, 'k:mm:ss').format('k:mm:ss'), kVal, kVal + ' k parsing');
<add> assert.equal(moment(kkVal, 'kk:mm:ss').format('kk:mm:ss'), kkVal, kkVal + ' skk parsing');
<add> }
<add> }
<add>});
<add> | 2 |
Ruby | Ruby | use predefined commit author for robustness | bd4f633673e12793d8ec18a45c352a2d4d1fc382 | <ide><path>Library/Homebrew/cmd/tests.rb
<ide> def tests
<ide> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" if ARGV.include? "--coverage"
<ide> ENV["HOMEBREW_NO_COMPAT"] = "1" if ARGV.include? "--no-compat"
<ide>
<add> # Override author/committer as global settings might be invalid and thus
<add> # will cause silent failure during the setup of dummy Git repositories.
<add> %w[AUTHOR COMMITTER].each do |role|
<add> ENV["GIT_#{role}_NAME"] = "brew tests"
<add> ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost"
<add> end
<add>
<ide> Homebrew.install_gem_setup_path! "bundler"
<ide> unless quiet_system("bundle", "check")
<ide> system "bundle", "install", "--path", "vendor/bundle" | 1 |
Python | Python | fix indexerror in _get_order_information | 93db2691a2a143c430603521fb297e3e96e68626 | <ide><path>libcloud/drivers/softlayer.py
<ide> def _get_order_information(self, order_id, timeout=1200, check_interval=5):
<ide> if item['softwareComponents'][0]['passwords']:
<ide> return item
<ide>
<del> except KeyError, IndexError:
<add> except (KeyError, IndexError):
<ide> pass
<ide>
<ide> time.sleep(check_interval) | 1 |
Text | Text | fix url to issue | 88d4da7f422a4ac341efa85541271b1c0e9bcfa3 | <ide><path>CHANGELOG.md
<ide> be found.
<ide>
<ide> ### Misc
<ide>
<del>+ When saving linked images together with `docker save` a subsequent `docker load` will correctly restore their parent/child relationship ([#21385](https://github.com/docker/docker/pull/c))
<add>+ When saving linked images together with `docker save` a subsequent `docker load` will correctly restore their parent/child relationship ([#21385](https://github.com/docker/docker/pull/21385))
<ide> + Support for building the Docker cli for OpenBSD was added ([#21325](https://github.com/docker/docker/pull/21325))
<ide> + Labels can now be applied at network, volume and image creation ([#21270](https://github.com/docker/docker/pull/21270))
<ide> * The `dockremap` is now created as a system user ([#21266](https://github.com/docker/docker/pull/21266)) | 1 |
Python | Python | fix layer norm epsilon in openai gpt | 80607874c1f82e137ceb2cff3397c6a91d6aa963 | <ide><path>pytorch_pretrained_bert/modeling_openai.py
<ide> def __init__(
<ide> resid_pdrop=0.1,
<ide> embd_pdrop=0.1,
<ide> attn_pdrop=0.1,
<add> layer_norm_epsilon=1e-5,
<ide> initializer_range=0.02,
<ide> ):
<ide> """Constructs OpenAIGPTConfig.
<ide> def __init__(
<ide> attn_pdrop: The dropout ratio for the attention
<ide> probabilities.
<ide> embd_pdrop: The dropout ratio for the embeddings.
<add> layer_norm_epsilon: epsilon to use in the layer norm layers
<ide> initializer_range: The sttdev of the truncated_normal_initializer for
<ide> initializing all weight matrices.
<ide> """
<ide> def __init__(
<ide> self.resid_pdrop = resid_pdrop
<ide> self.embd_pdrop = embd_pdrop
<ide> self.attn_pdrop = attn_pdrop
<add> self.layer_norm_epsilon = layer_norm_epsilon
<ide> self.initializer_range = initializer_range
<ide> else:
<ide> raise ValueError(
<ide> def __init__(self, n_ctx, config, scale=False):
<ide> super(Block, self).__init__()
<ide> nx = config.n_embd
<ide> self.attn = Attention(nx, n_ctx, config, scale)
<del> self.ln_1 = LayerNorm(nx)
<add> self.ln_1 = LayerNorm(nx, eps=config.layer_norm_epsilon)
<ide> self.mlp = MLP(4 * nx, config)
<del> self.ln_2 = LayerNorm(nx)
<add> self.ln_2 = LayerNorm(nx, eps=config.layer_norm_epsilon)
<ide>
<ide> def forward(self, x):
<ide> a = self.attn(x) | 1 |
Javascript | Javascript | upgrade tapable for resolverfactory | 53eada6eb33bb95a2fd7d0ea924f8c309f110c6e | <ide><path>lib/ResolverFactory.js
<ide> */
<ide> "use strict";
<ide>
<del>const Tapable = require("tapable-old");
<add>const Tapable = require("tapable").Tapable;
<add>const HookMap = require("tapable").HookMap;
<add>const SyncHook = require("tapable").SyncHook;
<add>const SyncWaterfallHook = require("tapable").SyncWaterfallHook;
<ide> const Factory = require("enhanced-resolve").ResolverFactory;
<ide>
<ide> module.exports = class ResolverFactory extends Tapable {
<ide> constructor() {
<ide> super();
<add> this.hooks = {
<add> resolveOptions: new HookMap(() => new SyncWaterfallHook(["resolveOptions"])),
<add> resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"])),
<add> };
<add> this._pluginCompat.tap("ResolverFactory", options => {
<add> let match;
<add> match = /^resolve-options (.+)$/.exec(options.name);
<add> if(match) {
<add> this.hooks.resolveOptions.tap(match[1], options.fn.name || "unnamed compat plugin", options.fn);
<add> return true;
<add> }
<add> match = /^resolver (.+)$/.exec(options.name);
<add> if(match) {
<add> this.hooks.resolver.tap(match[1], options.fn.name || "unnamed compat plugin", options.fn);
<add> return true;
<add> }
<add> });
<ide> this.cache1 = new WeakMap();
<ide> this.cache2 = new Map();
<ide> }
<ide> module.exports = class ResolverFactory extends Tapable {
<ide> }
<ide>
<ide> _create(type, resolveOptions) {
<del> resolveOptions = this.applyPluginsWaterfall(`resolve-options ${type}`, resolveOptions);
<add> resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions);
<ide> const resolver = Factory.createResolver(resolveOptions);
<ide> if(!resolver) {
<ide> throw new Error("No resolver created");
<ide> }
<del> this.applyPlugins2(`resolver ${type}`, resolver, resolveOptions);
<add> this.hooks.resolver.for(type).call(resolver, resolveOptions);
<ide> return resolver;
<ide> }
<ide> }; | 1 |
Javascript | Javascript | exclude 3mb of markdown files | 2ede9aaf854c7fe1f09adecd2653446d6f215221 | <ide><path>script/lib/include-path-in-packaged-app.js
<ide> const EXCLUDE_REGEXPS_SOURCES = [
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + '_*te?sts?_*' + escapeRegExp(path.sep),
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'docs' + escapeRegExp(path.sep),
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'examples?' + escapeRegExp(path.sep),
<del> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'samples?' + escapeRegExp(path.sep)
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'samples?' + escapeRegExp(path.sep),
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\.md$'
<ide> ]
<ide>
<ide> // Ignore spec directories in all bundled packages | 1 |
Python | Python | remove positionality of kind in isin | 64de8b2eaba62f138be94744ada770aa227aae94 | <ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None):
<ide>
<ide>
<ide> def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None,
<del> kind=None):
<add> *, kind=None):
<ide> return (element, test_elements)
<ide>
<ide>
<ide> @array_function_dispatch(_isin_dispatcher)
<del>def isin(element, test_elements, assume_unique=False, invert=False,
<add>def isin(element, test_elements, assume_unique=False, invert=False, *,
<ide> kind=None):
<ide> """
<ide> Calculates ``element in test_elements``, broadcasting over `element` only. | 1 |
Javascript | Javascript | add test around throwing on trying to change | 58f181a376c11329f097dedee7690cb0c0f95bab | <ide><path>packages/ember-glimmer/tests/integration/components/curly-components-test.js
<ide> moduleFor('Components test: curly components', class extends RenderingTest {
<ide> this.assertComponentElement(this.firstChild, { content: 'hello' });
<ide> }
<ide>
<del> // Note this functionality seems weird
<ide> ['@htmlbars it can have a custom id and it is not bound']() {
<ide> this.registerComponent('foo-bar', { template: '{{id}} {{elementId}}' });
<ide>
<ide> moduleFor('Components test: curly components', class extends RenderingTest {
<ide> this.assertComponentElement(this.firstChild, { tagName: 'div', attrs: { id: 'bizz' }, content: 'bizz bizz' });
<ide> }
<ide>
<add> ['@htmlbars elementId cannot change'](assert) {
<add> let component;
<add> let FooBarComponent = Component.extend({
<add> elementId: 'blahzorz',
<add> init() {
<add> this._super(...arguments);
<add> component = this;
<add> }
<add> });
<add>
<add> this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: '{{elementId}}' });
<add>
<add> this.render('{{foo-bar}}');
<add>
<add> this.assertComponentElement(this.firstChild, { tagName: 'div', attrs: { id: 'blahzorz' }, content: 'blahzorz' });
<add>
<add> // Note: Throws an `EmberError` that is not stripped from production builds
<add> let willThrow = () => set(component, 'elementId', 'herpyderpy');
<add>
<add> assert.throws(willThrow, /Changing a view's elementId after creation is not allowed/);
<add>
<add> this.assertComponentElement(this.firstChild, { tagName: 'div', attrs: { id: 'blahzorz' }, content: 'blahzorz' });
<add> }
<add>
<ide> ['@test it can have a custom tagName']() {
<ide> let FooBarComponent = Component.extend({
<ide> tagName: 'foo-bar' | 1 |
Text | Text | fix man pages | d790469681b65d55e64750fd18d596db90a541df | <ide><path>man/docker-cp.1.md
<ide> docker-cp - Copy files/folders between a container and the local filesystem.
<ide> **docker cp**
<ide> [**--help**]
<ide> CONTAINER:PATH LOCALPATH|-
<add>
<add>**docker cp**
<add>[**--help**]
<ide> LOCALPATH|- CONTAINER:PATH
<ide>
<ide> # DESCRIPTION
<ide><path>man/docker-create.1.md
<ide> The initial status of the container created with **docker create** is 'created'.
<ide> **--add-host**=[]
<ide> Add a custom host-to-IP mapping (host:ip)
<ide>
<del>**--blkio-weight**=0
<add>**--blkio-weight**=*0*
<ide> Block IO weight (relative weight) accepts a weight value between 10 and 1000.
<ide>
<del>**--cpu-shares**=0
<add>**--cpu-shares**=*0*
<ide> CPU shares (relative weight)
<ide>
<ide> **--cap-add**=[]
<ide> The initial status of the container created with **docker create** is 'created'.
<ide> **--cidfile**=""
<ide> Write the container ID to the file
<ide>
<del>**--cpu-period**=0
<add>**--cpu-period**=*0*
<ide> Limit the CPU CFS (Completely Fair Scheduler) period
<ide>
<ide> **--cpuset-cpus**=""
<ide> The initial status of the container created with **docker create** is 'created'.
<ide> then processes in your Docker container will only use memory from the first
<ide> two memory nodes.
<ide>
<del>**--cpu-quota**=0
<add>**--cpu-quota**=*0*
<ide> Limit the CPU CFS (Completely Fair Scheduler) quota
<ide>
<ide> **--device**=[]
<ide> millions of trillions.
<ide> Add link to another container in the form of <name or id>:alias or just
<ide> <name or id> in which case the alias will match the name.
<ide>
<del>**--log-driver**="|*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<add>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<ide> Logging driver for container. Default is defined by daemon `--log-driver` flag.
<ide> **Warning**: the `docker logs` command works only for the `json-file` and
<ide> `journald` logging drivers.
<ide> This value should always larger than **-m**, so you should always use this with
<ide> **--name**=""
<ide> Assign a name to the container
<ide>
<del>**--net**="bridge"
<add>**--net**="*bridge*"
<ide> Set the Network mode for the container
<ide> 'bridge': creates a new network stack for the container on the docker bridge
<ide> 'none': no networking for this container
<ide> This value should always larger than **-m**, so you should always use this with
<ide> When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`)
<ide> (use 'docker port' to see the actual mapping)
<ide>
<del>**--pid**=host
<add>**--pid**=*host*
<ide> Set the PID mode for the container
<ide> **host**: use the host's PID namespace inside the container.
<ide> Note: the host mode gives the container full access to local PID and is therefore considered insecure.
<ide> This value should always larger than **-m**, so you should always use this with
<ide> **--read-only**=*true*|*false*
<ide> Mount the container's root filesystem as read only.
<ide>
<del>**--restart**="no"
<add>**--restart**="*no*"
<ide> Restart policy to apply when a container exits (no, on-failure[:max-retry], always, unless-stopped).
<ide>
<ide> **--security-opt**=[]
<ide> Security Options
<ide>
<del>**--stop-signal**=SIGTERM
<add>**--stop-signal**=*SIGTERM*
<ide> Signal to stop a container. Default is SIGTERM.
<ide>
<ide> **-t**, **--tty**=*true*|*false*
<ide> This value should always larger than **-m**, so you should always use this with
<ide> **--ulimit**=[]
<ide> Ulimit options
<ide>
<del>**--uts**=host
<add>**--uts**=*host*
<ide> Set the UTS mode for the container
<ide> **host**: use the host's UTS namespace inside the container.
<ide> Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure.
<ide><path>man/docker-daemon.8.md
<ide> format.
<ide> **-g**, **--graph**=""
<ide> Path to use as the root of the Docker runtime. Default is `/var/lib/docker`.
<ide>
<del>**-H**, **--host**=[unix:///var/run/docker.sock]: tcp://[host:port] to bind or
<add>**-H**, **--host**=[*unix:///var/run/docker.sock*]: tcp://[host:port] to bind or
<ide> unix://[/path/to/socket] to use.
<ide> The socket(s) to bind to in daemon mode specified using one or more
<ide> tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.
<ide> unix://[/path/to/socket] to use.
<ide> **--ipv6**=*true*|*false*
<ide> Enable IPv6 support. Default is false. Docker will create an IPv6-enabled bridge with address fe80::1 which will allow you to create IPv6-enabled containers. Use together with `--fixed-cidr-v6` to provide globally routable IPv6 addresses. IPv6 forwarding will be enabled if not used with `--ip-forward=false`. This may collide with your host's current IPv6 settings. For more information please consult the documentation about "Advanced Networking - IPv6".
<ide>
<del>**-l**, **--log-level**="*debug*|*info*|*warn*|*error*|*fatal*""
<add>**-l**, **--log-level**="*debug*|*info*|*warn*|*error*|*fatal*"
<ide> Set the logging level. Default is `info`.
<ide>
<ide> **--label**="[]"
<ide> unix://[/path/to/socket] to use.
<ide> **--log-opt**=[]
<ide> Logging driver specific options.
<ide>
<del>**--mtu**=VALUE
<add>**--mtu**=*0*
<ide> Set the containers network mtu. Default is `0`.
<ide>
<ide> **-p**, **--pidfile**=""
<ide> Path to use for daemon PID file. Default is `/var/run/docker.pid`
<ide>
<del>**--registry-mirror**=<scheme>://<host>
<add>**--registry-mirror**=*<scheme>://<host>*
<ide> Prepend a registry mirror to be used for image pulls. May be specified multiple times.
<ide>
<ide> **-s**, **--storage-driver**=""
<ide> unix://[/path/to/socket] to use.
<ide> **--tls**=*true*|*false*
<ide> Use TLS; implied by --tlsverify. Default is false.
<ide>
<del>**--tlscacert**=~/.docker/ca.pem
<add>**--tlscacert**=*~/.docker/ca.pem*
<ide> Trust certs signed only by this CA.
<ide>
<del>**--tlscert**=~/.docker/cert.pem
<add>**--tlscert**=*~/.docker/cert.pem*
<ide> Path to TLS certificate file.
<ide>
<del>**--tlskey**=~/.docker/key.pem
<add>**--tlskey**=*~/.docker/key.pem*
<ide> Path to TLS key file.
<ide>
<ide> **--tlsverify**=*true*|*false*
<ide><path>man/docker-inspect.1.md
<ide> each result.
<ide> **-f**, **--format**=""
<ide> Format the output using the given Go template.
<ide>
<del>**-s**, **--size**=false
<add>**-s**, **--size**=*false*
<ide> Display total file sizes if the type is container.
<ide>
<del>**--type**=*container*|*image*
<add>**--type**="*container*|*image*"
<ide> Return JSON for specified type, permissible values are "image" or "container"
<ide>
<ide> # EXAMPLES
<ide><path>man/docker-kill.1.md
<ide> The main process inside each container specified will be sent SIGKILL,
<ide> **--help**
<ide> Print usage statement
<ide>
<del>**-s**, **--signal**="KILL"
<add>**-s**, **--signal**="*KILL*"
<ide> Signal to send to the container
<ide>
<ide> # HISTORY
<ide><path>man/docker-logs.1.md
<ide> logging drivers.
<ide> **-t**, **--timestamps**=*true*|*false*
<ide> Show timestamps. The default is *false*.
<ide>
<del>**--tail**="all"
<add>**--tail**="*all*"
<ide> Output the specified number of lines at the end of logs (defaults to all logs)
<ide>
<ide> The `--since` option shows only the container logs generated after
<ide><path>man/docker-network-connect.1.md
<ide> docker-network-connect - connect a container to a network
<ide>
<ide> # SYNOPSIS
<del>**docker network connect NAME CONTAINER**
<del>
<add>**docker network connect**
<ide> [**--help**]
<add>NETWORK CONTAINER
<ide>
<ide> # DESCRIPTION
<ide>
<ide> You can connect a container to one or more networks. The networks need not be th
<ide>
<ide>
<ide> # OPTIONS
<del>**NAME**
<del> Specify network driver name
<add>**NETWORK**
<add> Specify network name
<ide>
<ide> **CONTAINER**
<ide> Specify container name
<ide><path>man/docker-network-create.1.md
<ide> docker-network-create - create a new network
<ide>
<ide> # SYNOPSIS
<ide> **docker network create**
<del>
<del>**--aux-address=map[]**
<del>**-d** | **--driver=DRIVER**
<del>**--gateway=[]**
<del>**--help=false**
<del>**--ip-range=[]**
<del>**--ipam-driver=default**
<del>**-o** | **--opt=map[]**
<del>**--subnet=[]**
<add>[**--aux-address**=*map[]*]
<add>[**-d**|**--driver**=*DRIVER*]
<add>[**--gateway**=*[]*]
<add>[**--help**]
<add>[**--ip-range**=*[]*]
<add>[**--ipam-driver**=*default*]
<add>[**-o**|**--opt**=*map[]*]
<add>[**--subnet**=*[]*]
<add>NETWORK-NAME
<ide>
<ide> # DESCRIPTION
<ide>
<ide> specify subnetwork values directly using the the `--subnet` option. On a
<ide> `bridge` network you can only create a single subnet:
<ide>
<ide> ```bash
<del>docker network create -d --subnet=192.168.0.0/16
<add>docker network create -d bridge --subnet=192.168.0.0/16 br0
<ide> ```
<ide> Additionally, you also specify the `--gateway` `--ip-range` and `--aux-address` options.
<ide>
<ide> docker network create -d overlay
<ide> Be sure that your subnetworks do not overlap. If they do, the network create fails and Engine returns an error.
<ide>
<ide> # OPTIONS
<del>**--aux-address=map[]**
<add>**--aux-address**=map[]
<ide> Auxiliary ipv4 or ipv6 addresses used by network driver
<ide>
<del>**-d** | **--driver=DRIVER**
<add>**-d**, **--driver**=*DRIVER*
<ide> Driver to manage the Network bridge or overlay. The default is bridge.
<ide>
<del>**--gateway=[] **
<add>**--gateway**=[]
<ide> ipv4 or ipv6 Gateway for the master subnet
<ide>
<del>**--help=false **
<add>**--help**
<ide> Print usage
<ide>
<del>**--ip-range=[] **
<add>**--ip-range**=[]
<ide> Allocate container ip from a sub-range
<ide>
<del>**--ipam-driver=default **
<add>**--ipam-driver**=*default*
<ide> IP Address Management Driver
<ide>
<del>**-o | --opt=map[]**
<add>**-o**, **--opt**=map[]
<ide> Set custom network plugin options
<ide>
<del>**--subnet=[]**
<add>**--subnet**=[]
<ide> Subnet in CIDR format that represents a network segment
<ide>
<ide> # HISTORY
<ide><path>man/docker-network-disconnect.1.md
<ide> docker-network-disconnect - disconnect a container from a network
<ide>
<ide> # SYNOPSIS
<del>**docker network disconnect NETWORK CONTAINER**
<del>
<add>**docker network disconnect**
<ide> [**--help**]
<add>NETWORK CONTAINER
<ide>
<ide> # DESCRIPTION
<ide>
<ide><path>man/docker-network-inspect.1.md
<ide> docker-network-inspect - inspect a network
<ide>
<ide> # SYNOPSIS
<del>**docker network inspect NETWORK [NETWORK...]**
<del>
<add>**docker network inspect**
<ide> [**--help**]
<add>NETWORK [NETWORK...]
<ide>
<ide> # DESCRIPTION
<ide>
<ide><path>man/docker-network-ls.1.md
<ide> docker-network-ls - list networks
<ide>
<ide> # SYNOPSIS
<ide> **docker network ls**
<del>
<del>[**--no-trunc**]
<del>[**-q** | **--quiet**]
<add>[**--no-trunc**[=*true*|*false*]]
<add>[**-q**|**--quiet**[=*true*|*false*]]
<ide> [**--help**]
<ide>
<ide> # DESCRIPTION
<ide> c288470c46f6c8949c5f7e5099b5b7947b07eabe8d9a27d79a9cbf111adcbf47 host
<ide>
<ide> # OPTIONS
<ide>
<del>[**--no-trunc**]
<add>**--no-trunc**=*true*|*false*
<ide> Do not truncate the output
<ide>
<del>[**-q** | **--quiet**]
<add>**-q**, **--quiet**=*true*|*false*
<ide> Only display numeric IDs
<ide>
<ide> **--help**
<ide><path>man/docker-network-rm.1.md
<ide> docker-network-rm - remove a new network
<ide>
<ide> # SYNOPSIS
<del>**docker network rm NETWORK**
<del>
<add>**docker network rm**
<ide> [**--help**]
<add>NETWORK
<ide>
<ide> # DESCRIPTION
<ide>
<ide> Removes a network by name or identifier. To remove a network, you must first dis
<ide> $ docker network rm my-network
<ide> ```
<ide>
<del>
<ide> # OPTIONS
<ide> **NETWORK**
<ide> Specify network name
<ide><path>man/docker-ps.1.md
<ide> the running containers.
<ide> ancestor=(<image-name>[:tag]|<image-id>|<image@digest>) - filters containers that were
<ide> created from the given image or a descendant.
<ide>
<del>**--format**=*"TEMPLATE"*
<add>**--format**="*TEMPLATE*"
<ide> Pretty-print containers using a Go template.
<ide> Valid placeholders:
<ide> .ID - Container ID
<ide> the running containers.
<ide> **-l**, **--latest**=*true*|*false*
<ide> Show only the latest created container, include non-running ones. The default is *false*.
<ide>
<del>**-n**=-1
<add>**-n**=*-1*
<ide> Show n last created containers, include non-running ones.
<ide>
<ide> **--no-trunc**=*true*|*false*
<ide><path>man/docker-restart.1.md
<ide> Restart each container listed.
<ide> **--help**
<ide> Print usage statement
<ide>
<del>**-t**, **--time**=10
<add>**-t**, **--time**=*10*
<ide> Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.
<ide>
<ide> # HISTORY
<ide><path>man/docker-run.1.md
<ide> each of stdin, stdout, and stderr.
<ide> Add a line to /etc/hosts. The format is hostname:ip. The **--add-host**
<ide> option can be set multiple times.
<ide>
<del>**--blkio-weight**=0
<add>**--blkio-weight**=*0*
<ide> Block IO weight (relative weight) accepts a weight value between 10 and 1000.
<ide>
<del>**--cpu-shares**=0
<add>**--cpu-shares**=*0*
<ide> CPU shares (relative weight)
<ide>
<ide> By default, all containers get the same proportion of CPU cycles. This proportion
<ide> division of CPU shares:
<ide> **--cidfile**=""
<ide> Write the container ID to the file
<ide>
<del>**--cpu-period**=0
<add>**--cpu-period**=*0*
<ide> Limit the CPU CFS (Completely Fair Scheduler) period
<ide>
<ide> Limit the container's CPU usage. This flag tell the kernel to restrict the container's CPU usage to the period you specify.
<ide> division of CPU shares:
<ide> then processes in your Docker container will only use memory from the first
<ide> two memory nodes.
<ide>
<del>**--cpu-quota**=0
<add>**--cpu-quota**=*0*
<ide> Limit the CPU CFS (Completely Fair Scheduler) quota
<ide>
<ide> Limit the container's CPU usage. By default, containers run with the full
<ide> container can access the exposed port via a private networking interface. Docker
<ide> will set some environment variables in the client container to help indicate
<ide> which interface and port to use.
<ide>
<del>**--log-driver**="|*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<add>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<ide> Logging driver for container. Default is defined by daemon `--log-driver` flag.
<ide> **Warning**: the `docker logs` command works only for the `json-file` and
<ide> `journald` logging drivers.
<ide> string name. The name is useful when defining links (see **--link**) (or any
<ide> other place you need to identify a container). This works for both background
<ide> and foreground Docker containers.
<ide>
<del>**--net**="bridge"
<add>**--net**="*bridge*"
<ide> Set the Network mode for the container
<ide> 'bridge': creates a new network stack for the container on the docker bridge
<ide> 'none': no networking for this container
<ide> but not `docker run -p 1230-1236:1230-1240 --name RangeContainerPortsBiggerThanR
<ide> With ip: `docker run -p 127.0.0.1:$HOSTPORT:$CONTAINERPORT --name CONTAINER -t someimage`
<ide> Use `docker port` to see the actual mapping: `docker port CONTAINER $CONTAINERPORT`
<ide>
<del>**--pid**=host
<add>**--pid**=*host*
<ide> Set the PID mode for the container
<ide> **host**: use the host's PID namespace inside the container.
<ide> Note: the host mode gives the container full access to local PID and is therefore considered insecure.
<ide>
<del>**--uts**=host
<add>**--uts**=*host*
<ide> Set the UTS mode for the container
<ide> **host**: use the host's UTS namespace inside the container.
<ide> Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure.
<ide> outside of a container on the host.
<ide> to write files anywhere. By specifying the `--read-only` flag the container will have
<ide> its root filesystem mounted as read only prohibiting any writes.
<ide>
<del>**--restart**="no"
<add>**--restart**="*no*"
<ide> Restart policy to apply when a container exits (no, on-failure[:max-retry], always, unless-stopped).
<ide>
<ide> **--rm**=*true*|*false*
<ide> its root filesystem mounted as read only prohibiting any writes.
<ide> "label:level:LEVEL" : Set the label level for the container
<ide> "label:disable" : Turn off label confinement for the container
<ide>
<del>**--stop-signal**=SIGTERM
<add>**--stop-signal**=*SIGTERM*
<ide> Signal to stop a container. Default is SIGTERM.
<ide>
<ide> **--sig-proxy**=*true*|*false*
<ide> standard input.
<ide>
<ide> Without this argument the command will be run as root in the container.
<ide>
<del>""--ulimit""=[]
<add>**--ulimit**=[]
<ide> Ulimit options
<ide>
<ide> **-v**, **--volume**=[] Create a bind mount
<ide><path>man/docker-search.1.md
<ide> of stars awarded, whether the image is official, and whether it is automated.
<ide> **--no-trunc**=*true*|*false*
<ide> Don't truncate output. The default is *false*.
<ide>
<del>**-s**, **--stars**=X
<add>**-s**, **--stars**=*X*
<ide> Only displays with at least X stars. The default is zero.
<ide>
<ide> # EXAMPLES
<ide><path>man/docker-stats.1.md
<ide> Display a live stream of one or more containers' resource usage statistics
<ide> **--help**
<ide> Print usage statement
<ide>
<del>**--no-stream**="false"
<del> Disable streaming stats and only pull the first result
<add>**--no-stream**=*true*|*false*
<add> Disable streaming stats and only pull the first result, default setting is false.
<ide>
<ide> # EXAMPLES
<ide>
<ide><path>man/docker-stop.1.md
<ide> Stop a container (Send SIGTERM, and then SIGKILL after
<ide> **--help**
<ide> Print usage statement
<ide>
<del>**-t**, **--time**=10
<add>**-t**, **--time**=*10*
<ide> Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.
<ide>
<ide> #See also
<ide><path>man/docker-volume-create.1.md
<ide> different volume drivers may do different things (or nothing at all).
<ide> *Note*: The built-in `local` volume driver does not currently accept any options.
<ide>
<ide> # OPTIONS
<del>**-d**, **--driver**="local"
<add>**-d**, **--driver**="*local*"
<ide> Specify volume driver name
<ide>
<ide> **--help**
<ide><path>man/docker-volume-ls.1.md
<ide> There is a single supported filter `dangling=value` which takes a boolean of `tr
<ide> **--help**
<ide> Print usage statement
<ide>
<del>**-q**, **--quiet**=false
<add>**-q**, **--quiet**=*true*|*false*
<ide> Only display volume names
<ide>
<ide> # HISTORY
<ide><path>man/docker.1.md
<ide> docker \- Docker image and container command line interface
<ide> # SYNOPSIS
<ide> **docker** [OPTIONS] COMMAND [arg...]
<ide>
<del>**docker** daemon [ --help | ... ]
<add>**docker** daemon [--help|...]
<ide>
<del>**docker** [ --help | -v | --version ]
<add>**docker** [--help|-v|--version]
<ide>
<ide> # DESCRIPTION
<ide> **docker** has two distinct functions. It is used for starting the Docker
<ide> To see the man page for a command run **man docker <command>**.
<ide> **-D**, **--debug**=*true*|*false*
<ide> Enable debug mode. Default is false.
<ide>
<del>**-H**, **--host**=[unix:///var/run/docker.sock]: tcp://[host]:[port][path] to bind or
<add>**-H**, **--host**=[*unix:///var/run/docker.sock*]: tcp://[host]:[port][path] to bind or
<ide> unix://[/path/to/socket] to use.
<ide> The socket(s) to bind to in daemon mode specified using one or more
<ide> tcp://host:port/path, unix:///path/to/socket, fd://* or fd://socketfd.
<ide> If the tcp port is not specified, then it will default to either `2375` when
<ide> `--tls` is off, or `2376` when `--tls` is on, or `--tlsverify` is specified.
<ide>
<del>**-l**, **--log-level**="*debug*|*info*|*warn*|*error*|*fatal*""
<add>**-l**, **--log-level**="*debug*|*info*|*warn*|*error*|*fatal*"
<ide> Set the logging level. Default is `info`.
<ide>
<ide> **--tls**=*true*|*false*
<ide> Use TLS; implied by --tlsverify. Default is false.
<ide>
<del>**--tlscacert**=~/.docker/ca.pem
<add>**--tlscacert**=*~/.docker/ca.pem*
<ide> Trust certs signed only by this CA.
<ide>
<del>**--tlscert**=~/.docker/cert.pem
<add>**--tlscert**=*~/.docker/cert.pem*
<ide> Path to TLS certificate file.
<ide>
<del>**--tlskey**=~/.docker/key.pem
<add>**--tlskey**=*~/.docker/key.pem*
<ide> Path to TLS key file.
<ide>
<ide> **--tlsverify**=*true*|*false* | 21 |
Python | Python | add test for andc (u8) | dc4a9e39dfb13aecb61d955445538838fbb2233d | <ide><path>numpy/core/tests/test_simd.py
<ide> def test_operators_logical(self):
<ide> """
<ide> Logical operations for boolean types.
<ide> Test intrinsics:
<del> npyv_xor_##SFX, npyv_and_##SFX, npyv_or_##SFX, npyv_not_##SFX
<add> npyv_xor_##SFX, npyv_and_##SFX, npyv_or_##SFX, npyv_not_##SFX,
<add> npyv_andc_b8, npvy_orc_b8, nvpy_xnor_b8
<ide> """
<ide> data_a = self._data()
<ide> data_b = self._data(reverse=True)
<ide> def test_operators_logical(self):
<ide> vnot = getattr(self, "not")(vdata_a)
<ide> assert vnot == data_b
<ide>
<add> # among the boolean types, andc, orc and xnor only support b8
<add> if self.sfx not in ("b8"):
<add> return
<add>
<add> data_andc = [(a & ~b) & 0xFF for a, b in zip(data_a, data_b)]
<add> vandc = getattr(self, "andc")(vdata_a, vdata_b)
<add> assert data_andc == vandc
<add>
<add> data_orc = [(a | ~b) & 0xFF for a, b in zip(data_a, data_b)]
<add> vorc = getattr(self, "orc")(vdata_a, vdata_b)
<add> assert data_orc == vorc
<add>
<add> data_xnor = [~(a ^ b) & 0xFF for a, b in zip(data_a, data_b)]
<add> vxnor = getattr(self, "xnor")(vdata_a, vdata_b)
<add> assert data_xnor == vxnor
<add>
<ide> def test_tobits(self):
<ide> data2bits = lambda data: sum([int(x != 0) << i for i, x in enumerate(data, 0)])
<ide> for data in (self._data(), self._data(reverse=True)):
<ide> def test_tobits(self):
<ide> tobits = bin(self.tobits(vdata))
<ide> assert tobits == bin(data_bits)
<ide>
<del> def test_andc(self):
<del> if self.sfx not in ("b8"):
<del> return
<del> andc_simd = getattr(self.npyv, f"andc_b8")
<del> # create the vectors
<del> data = self._data()
<del> rdata = self._data(reverse=True)
<del> vdata = self._load_b(data)
<del> vrdata = self._load_b(rdata)
<del> # check andc
<del> sandc = [(~x & y) & 0xFF for x, y in zip(rdata, data)]
<del> vandc = andc_simd(vrdata, vdata)
<del> assert sandc == vandc
<del>
<del> def test_orc(self):
<del> if self.sfx not in ("b8"):
<del> return
<del> orc_simd = getattr(self.npyv, f"orc_b8")
<del> # create the vectors
<del> data = self._data()
<del> rdata = self._data(reverse=True)
<del> vdata = self._load_b(data)
<del> vrdata = self._load_b(rdata)
<del> # check orc
<del> sorc = [(~x | y) & 0xFF for x, y in zip(rdata, data)]
<del> vorc = orc_simd(vrdata, vdata)
<del> assert sorc == vorc
<del>
<del> def test_xnor(self):
<del> if self.sfx not in ("b8"):
<del> return
<del> xnor_simd = getattr(self.npyv, f"xnor_b8")
<del> # create the vectors
<del> data = self._data()
<del> rdata = self._data(reverse=True)
<del> vdata = self._load_b(data)
<del> vrdata = self._load_b(rdata)
<del> # check orc
<del> sxnor = [~(x ^ y) & 0xFF for x, y in zip(rdata, data)]
<del> vxnor = xnor_simd(vrdata, vdata)
<del> assert sxnor == vxnor
<del>
<ide> def test_pack(self):
<ide> """
<ide> Pack multiple vectors into one
<ide> def test_operators_logical(self):
<ide> vnot = cast(getattr(self, "not")(vdata_a))
<ide> assert vnot == data_not
<ide>
<add> if self.sfx not in ("u8"):
<add> return
<add> data_andc = [a & ~b for a, b in zip(data_cast_a, data_cast_b)]
<add> vandc = cast(getattr(self, "andc")(vdata_a, vdata_b))
<add> assert vandc == data_andc
<add>
<ide> def test_conversion_boolean(self):
<ide> bsfx = "b" + self.sfx[1:]
<ide> to_boolean = getattr(self.npyv, "cvt_%s_%s" % (bsfx, self.sfx)) | 1 |
Ruby | Ruby | allow some uncommitted gems | 300d7e4799ebb15eba35ae7e888a0185059df0fe | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_git_status
<ide> end
<ide> next if status.blank?
<ide>
<add> # these will result in uncommitted gems.
<add> if path == HOMEBREW_REPOSITORY
<add> next if ENV["HOMEBREW_SORBET"] || ENV["HOMEBREW_PATCHELF_RB"]
<add> end
<add>
<ide> message ||= ""
<ide> message += "\n" unless message.empty?
<ide> message += <<~EOS | 1 |
Go | Go | simplify skip checks | 69c0b7e47682a2a7a850122a9a2f711259fbb25a | <ide><path>integration/container/ipcmode_linux_test.go
<ide> func testIpcNonePrivateShareable(t *testing.T, mode string, mustBeMounted bool,
<ide> // (--ipc none) works as expected. It makes sure there is no
<ide> // /dev/shm mount inside the container.
<ide> func TestIpcModeNone(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testIpcNonePrivateShareable(t, "none", false, false)
<ide> }
<ide> func TestIpcModeNone(t *testing.T) {
<ide> // of /dev/shm mount from the container, and makes sure there is no
<ide> // such pair on the host.
<ide> func TestIpcModePrivate(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testIpcNonePrivateShareable(t, "private", true, false)
<ide> }
<ide> func TestIpcModePrivate(t *testing.T) {
<ide> // of /dev/shm mount from the container, and makes sure such pair
<ide> // also exists on the host.
<ide> func TestIpcModeShareable(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testIpcNonePrivateShareable(t, "shareable", true, true)
<ide> }
<ide> func testIpcContainer(t *testing.T, donorMode string, mustWork bool) {
<ide> // 1) a container created with --ipc container:ID can use IPC of another shareable container.
<ide> // 2) a container created with --ipc container:ID can NOT use IPC of another private container.
<ide> func TestAPIIpcModeShareableAndContainer(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux")
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testIpcContainer(t, "shareable", true)
<ide>
<ide> func TestAPIIpcModeShareableAndContainer(t *testing.T) {
<ide> * can use IPC of the host system.
<ide> */
<ide> func TestAPIIpcModeHost(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon() || testEnv.IsUserNamespace())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<add> skip.If(t, testEnv.IsUserNamespace)
<ide>
<ide> cfg := containertypes.Config{
<ide> Image: "busybox",
<ide> func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin
<ide>
<ide> // TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended.
<ide> func TestDaemonIpcModeShareable(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testDaemonIpcPrivateShareable(t, true, "--default-ipc-mode", "shareable")
<ide> }
<ide>
<ide> // TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended.
<ide> func TestDaemonIpcModePrivate(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testDaemonIpcPrivateShareable(t, false, "--default-ipc-mode", "private")
<ide> }
<ide> func testDaemonIpcFromConfig(t *testing.T, mode string, mustExist bool) {
<ide>
<ide> // TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended.
<ide> func TestDaemonIpcModePrivateFromConfig(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testDaemonIpcFromConfig(t, "private", false)
<ide> }
<ide>
<ide> // TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended.
<ide> func TestDaemonIpcModeShareableFromConfig(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> testDaemonIpcFromConfig(t, "shareable", true)
<ide> }
<ide><path>integration/container/mounts_linux_test.go
<ide> import (
<ide>
<ide> func TestContainerNetworkMountsNoChown(t *testing.T) {
<ide> // chown only applies to Linux bind mounted volumes; must be same host to verify
<del> skip.If(t, testEnv.DaemonInfo.OSType == "windows" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> defer setupTest(t)()
<ide>
<ide> func TestContainerNetworkMountsNoChown(t *testing.T) {
<ide> }
<ide>
<ide> func TestMountDaemonRoot(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType == "windows" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide>
<ide> defer setupTest(t)()
<ide> client := testEnv.APIClient()
<ide> func TestMountDaemonRoot(t *testing.T) {
<ide> }
<ide>
<ide> func TestContainerBindMountNonRecursive(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon())
<add> skip.If(t, testEnv.IsRemoteDaemon)
<ide> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "BindOptions.NonRecursive requires API v1.40")
<ide>
<ide> defer setupTest(t)() | 2 |
Java | Java | use encode with an object value where feasible | 5fc18064f26a2541cce0432a4cb0fc01104972e8 | <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java
<ide> static DefaultDataBuffer fromEmptyByteBuffer(DefaultDataBufferFactory dataBuffer
<ide>
<ide>
<ide> /**
<del> * Directly exposes the native {@code ByteBuffer} that this buffer is based on.
<add> * Directly exposes the native {@code ByteBuffer} that this buffer is based
<add> * on also updating the {@code ByteBuffer's} position and limit to match
<add> * the current {@link #readPosition()} and {@link #readableByteCount()}.
<ide> * @return the wrapped byte buffer
<ide> */
<ide> public ByteBuffer getNativeBuffer() {
<add> this.byteBuffer.position(this.readPosition);
<add> this.byteBuffer.limit(readableByteCount());
<ide> return this.byteBuffer;
<ide> }
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractEncoderMethodReturnValueHandler.java
<ide> import org.springframework.core.codec.Encoder;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> private Flux<DataBuffer> encodeContent(
<ide>
<ide> Encoder<?> encoder = getEncoder(elementType, mimeType);
<ide>
<del> return Flux.from((Publisher) publisher).concatMap(value ->
<add> return Flux.from((Publisher) publisher).map(value ->
<ide> encodeValue(value, elementType, encoder, bufferFactory, mimeType, hints));
<ide> }
<ide>
<ide> private <T> Encoder<T> getEncoder(ResolvableType elementType, @Nullable MimeType
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private <T> Mono<DataBuffer> encodeValue(
<add> private <T> DataBuffer encodeValue(
<ide> Object element, ResolvableType elementType, @Nullable Encoder<T> encoder,
<ide> DataBufferFactory bufferFactory, @Nullable MimeType mimeType,
<ide> @Nullable Map<String, Object> hints) {
<ide>
<ide> if (encoder == null) {
<ide> encoder = getEncoder(ResolvableType.forInstance(element), mimeType);
<ide> if (encoder == null) {
<del> return Mono.error(new MessagingException(
<del> "No encoder for " + elementType + ", current value type is " + element.getClass()));
<add> throw new MessagingException(
<add> "No encoder for " + elementType + ", current value type is " + element.getClass());
<ide> }
<ide> }
<del> Mono<T> mono = Mono.just((T) element);
<del> Flux<DataBuffer> dataBuffers = encoder.encode(mono, bufferFactory, elementType, mimeType, hints);
<del> return DataBufferUtils.join(dataBuffers);
<add> return encoder.encodeValue((T) element, bufferFactory, elementType, mimeType, hints);
<ide> }
<ide>
<ide> /**
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.Encoder;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide> else if (adapter != null) {
<ide> publisher = adapter.toPublisher(input);
<ide> }
<ide> else {
<del> Mono<Payload> payloadMono = encodeValue(input, ResolvableType.forInstance(input), null)
<add> Mono<Payload> payloadMono = Mono
<add> .fromCallable(() -> encodeValue(input, ResolvableType.forInstance(input), null))
<ide> .map(this::firstPayload)
<add> .doOnDiscard(Payload.class, Payload::release)
<ide> .switchIfEmpty(emptyPayload());
<ide> return new DefaultResponseSpec(payloadMono);
<ide> }
<ide> else if (adapter != null) {
<ide>
<ide> if (adapter != null && !adapter.isMultiValue()) {
<ide> Mono<Payload> payloadMono = Mono.from(publisher)
<del> .flatMap(value -> encodeValue(value, dataType, encoder))
<add> .map(value -> encodeValue(value, dataType, encoder))
<ide> .map(this::firstPayload)
<ide> .switchIfEmpty(emptyPayload());
<ide> return new DefaultResponseSpec(payloadMono);
<ide> }
<ide>
<ide> Flux<Payload> payloadFlux = Flux.from(publisher)
<del> .concatMap(value -> encodeValue(value, dataType, encoder))
<add> .map(value -> encodeValue(value, dataType, encoder))
<ide> .switchOnFirst((signal, inner) -> {
<ide> DataBuffer data = signal.get();
<ide> if (data != null) {
<del> return Flux.concat(
<del> Mono.just(firstPayload(data)),
<del> inner.skip(1).map(PayloadUtils::createPayload));
<add> return Mono.fromCallable(() -> firstPayload(data))
<add> .concatWith(inner.skip(1).map(PayloadUtils::createPayload));
<ide> }
<ide> else {
<ide> return inner.map(PayloadUtils::createPayload);
<ide> }
<ide> })
<add> .doOnDiscard(Payload.class, Payload::release)
<ide> .switchIfEmpty(emptyPayload());
<ide> return new DefaultResponseSpec(payloadFlux);
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private <T> Mono<DataBuffer> encodeValue(T value, ResolvableType valueType, @Nullable Encoder<?> encoder) {
<add> private <T> DataBuffer encodeValue(T value, ResolvableType valueType, @Nullable Encoder<?> encoder) {
<ide> if (encoder == null) {
<ide> encoder = strategies.encoder(ResolvableType.forInstance(value), dataMimeType);
<ide> }
<del> return DataBufferUtils.join(((Encoder<T>) encoder).encode(
<del> Mono.just(value), strategies.dataBufferFactory(), valueType, dataMimeType, EMPTY_HINTS));
<add> return ((Encoder<T>) encoder).encodeValue(
<add> value, strategies.dataBufferFactory(), valueType, dataMimeType, EMPTY_HINTS);
<ide> }
<ide>
<ide> private Payload firstPayload(DataBuffer data) {
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/reactive/MessageMappingMessageHandlerTests.java
<ide> public void handleMonoString() {
<ide> @Test
<ide> public void handleFluxString() {
<ide> MessageMappingMessageHandler messsageHandler = initMesssageHandler();
<del> messsageHandler.handleMessage(message("fluxString", "abc\ndef\nghi")).block(Duration.ofSeconds(5));
<add> messsageHandler.handleMessage(message("fluxString", "abc", "def", "ghi")).block(Duration.ofSeconds(5));
<ide> verifyOutputContent(Arrays.asList("abc::response", "def::response", "ghi::response"));
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/reactive/PayloadMethodArgumentResolverTests.java
<ide> public void string() {
<ide>
<ide> @Test
<ide> public void validateStringMono() {
<add> TestValidator validator = new TestValidator();
<ide> ResolvableType type = ResolvableType.forClassWithGenerics(Mono.class, String.class);
<ide> MethodParameter param = this.testMethod.arg(type);
<del> Mono<Object> mono = resolveValue(param, Mono.just(toDataBuffer("12345")), new TestValidator());
<add> Mono<Object> mono = resolveValue(param, Mono.just(toDataBuffer("12345")), validator);
<ide>
<ide> StepVerifier.create(mono).expectNextCount(0)
<ide> .expectError(MethodArgumentNotValidException.class).verify();
<ide> }
<ide>
<ide> @Test
<ide> public void validateStringFlux() {
<add> TestValidator validator = new TestValidator();
<ide> ResolvableType type = ResolvableType.forClassWithGenerics(Flux.class, String.class);
<ide> MethodParameter param = this.testMethod.arg(type);
<del> Flux<Object> flux = resolveValue(param, Mono.just(toDataBuffer("12345678\n12345")), new TestValidator());
<add> Flux<DataBuffer> content = Flux.just(toDataBuffer("12345678"), toDataBuffer("12345"));
<add> Flux<Object> flux = resolveValue(param, content, validator);
<ide>
<ide> StepVerifier.create(flux)
<ide> .expectNext("12345678")
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageWriter.java
<ide>
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.time.Duration;
<add>import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public Mono<Void> write(Publisher<?> input, ResolvableType elementType, @Nullabl
<ide> }
<ide>
<ide> private Flux<Publisher<DataBuffer>> encode(Publisher<?> input, ResolvableType elementType,
<del> MediaType mediaType, DataBufferFactory factory, Map<String, Object> hints) {
<add> MediaType mediaType, DataBufferFactory bufferFactory, Map<String, Object> hints) {
<ide>
<del> ResolvableType valueType = (ServerSentEvent.class.isAssignableFrom(elementType.toClass()) ?
<add> ResolvableType dataType = (ServerSentEvent.class.isAssignableFrom(elementType.toClass()) ?
<ide> elementType.getGeneric() : elementType);
<ide>
<ide> return Flux.from(input).map(element -> {
<ide> private Flux<Publisher<DataBuffer>> encode(Publisher<?> input, ResolvableType el
<ide> sb.append("data:");
<ide> }
<ide>
<del> Flux<DataBuffer> flux = Flux.concat(
<del> encodeText(sb, mediaType, factory),
<del> encodeData(data, valueType, mediaType, factory, hints),
<del> encodeText("\n", mediaType, factory));
<add> Mono<DataBuffer> bufferMono = Mono.fromCallable(() ->
<add> bufferFactory.join(encodeEvent(sb, data, dataType, mediaType, bufferFactory, hints)));
<ide>
<del> return flux.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> return bufferMono.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide> });
<ide> }
<ide>
<ide> private void writeField(String fieldName, Object fieldValue, StringBuilder sb) {
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private <T> Flux<DataBuffer> encodeData(@Nullable T dataValue, ResolvableType valueType,
<add> private <T> List<DataBuffer> encodeEvent(CharSequence markup, @Nullable T data, ResolvableType dataType,
<ide> MediaType mediaType, DataBufferFactory factory, Map<String, Object> hints) {
<ide>
<del> if (dataValue == null) {
<del> return Flux.empty();
<del> }
<del>
<del> if (dataValue instanceof String) {
<del> String text = (String) dataValue;
<del> return Flux.from(encodeText(StringUtils.replace(text, "\n", "\ndata:") + "\n", mediaType, factory));
<del> }
<del>
<del> if (this.encoder == null) {
<del> return Flux.error(new CodecException("No SSE encoder configured and the data is not String."));
<add> List<DataBuffer> result = new ArrayList<>(4);
<add> result.add(encodeText(markup, mediaType, factory));
<add> if (data != null) {
<add> if (data instanceof String) {
<add> String dataLine = StringUtils.replace((String) data, "\n", "\ndata:") + "\n";
<add> result.add(encodeText(dataLine, mediaType, factory));
<add> }
<add> else if (this.encoder == null) {
<add> throw new CodecException("No SSE encoder configured and the data is not String.");
<add> }
<add> else {
<add> result.add(((Encoder<T>) this.encoder).encodeValue(data, factory, dataType, mediaType, hints));
<add> result.add(encodeText("\n", mediaType, factory));
<add> }
<ide> }
<del>
<del> return ((Encoder<T>) this.encoder)
<del> .encode(Mono.just(dataValue), factory, valueType, mediaType, hints)
<del> .concatWith(encodeText("\n", mediaType, factory));
<add> result.add(encodeText("\n", mediaType, factory));
<add> return result;
<ide> }
<ide>
<del> private Mono<DataBuffer> encodeText(CharSequence text, MediaType mediaType, DataBufferFactory bufferFactory) {
<add> private DataBuffer encodeText(CharSequence text, MediaType mediaType, DataBufferFactory bufferFactory) {
<ide> Assert.notNull(mediaType.getCharset(), "Expected MediaType with charset");
<ide> byte[] bytes = text.toString().getBytes(mediaType.getCharset());
<del> return Mono.just(bufferFactory.wrap(bytes)); // wrapping, not allocating
<add> return bufferFactory.wrap(bytes); // wrapping, not allocating
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.springframework.core.ResolvableType.forClass;
<add>import static org.springframework.core.ResolvableType.*;
<ide>
<ide> /**
<ide> * Unit tests for {@link ServerSentEventHttpMessageWriter}.
<ide> public void writeServerSentEvent() {
<ide> testWrite(source, outputMessage, ServerSentEvent.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("id:c42\nevent:foo\nretry:123\n:bla\n:bla bla\n:bla bla bla\ndata:"))
<del> .consumeNextWith(stringConsumer("bar\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<add> .consumeNextWith(stringConsumer(
<add> "id:c42\nevent:foo\nretry:123\n:bla\n:bla bla\n:bla bla bla\ndata:bar\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writeString() {
<ide> testWrite(source, outputMessage, String.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("foo\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("bar\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<add> .consumeNextWith(stringConsumer("data:foo\n\n"))
<add> .consumeNextWith(stringConsumer("data:bar\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writeMultiLineString() {
<ide> testWrite(source, outputMessage, String.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("foo\ndata:bar\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("foo\ndata:baz\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<add> .consumeNextWith(stringConsumer("data:foo\ndata:bar\n\n"))
<add> .consumeNextWith(stringConsumer("data:foo\ndata:baz\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writeStringWithCustomCharset() {
<ide>
<ide> assertEquals(mediaType, outputMessage.getHeaders().getContentType());
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:"))
<ide> .consumeNextWith(dataBuffer -> {
<del> String value =
<del> DataBufferTestUtils.dumpString(dataBuffer, charset);
<add> String value = DataBufferTestUtils.dumpString(dataBuffer, charset);
<ide> DataBufferUtils.release(dataBuffer);
<del> assertEquals("\u00A3\n", value);
<add> assertEquals("data:\u00A3\n\n", value);
<ide> })
<del> .consumeNextWith(stringConsumer("\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writePojo() {
<ide> testWrite(source, outputMessage, Pojo.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<add> .consumeNextWith(stringConsumer("data:{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n\n"))
<add> .consumeNextWith(stringConsumer("data:{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writePojoWithPrettyPrint() {
<ide> testWrite(source, outputMessage, Pojo.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("{\n" +
<add> .consumeNextWith(stringConsumer("data:{\n" +
<ide> "data: \"foo\" : \"foofoo\",\n" +
<del> "data: \"bar\" : \"barbar\"\n" + "data:}"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("data:"))
<del> .consumeNextWith(stringConsumer("{\n" +
<add> "data: \"bar\" : \"barbar\"\n" + "data:}\n\n"))
<add> .consumeNextWith(stringConsumer("data:{\n" +
<ide> "data: \"foo\" : \"foofoofoo\",\n" +
<del> "data: \"bar\" : \"barbarbar\"\n" + "data:}"))
<del> .consumeNextWith(stringConsumer("\n"))
<del> .consumeNextWith(stringConsumer("\n"))
<add> "data: \"bar\" : \"barbarbar\"\n" + "data:}\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> public void writePojoWithCustomEncoding() {
<ide>
<ide> assertEquals(mediaType, outputMessage.getHeaders().getContentType());
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(dataBuffer1 -> {
<del> String value1 =
<del> DataBufferTestUtils.dumpString(dataBuffer1, charset);
<del> DataBufferUtils.release(dataBuffer1);
<del> assertEquals("data:", value1);
<del> })
<ide> .consumeNextWith(dataBuffer -> {
<ide> String value = DataBufferTestUtils.dumpString(dataBuffer, charset);
<ide> DataBufferUtils.release(dataBuffer);
<del> assertEquals("{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}", value);
<del> })
<del> .consumeNextWith(dataBuffer2 -> {
<del> String value2 =
<del> DataBufferTestUtils.dumpString(dataBuffer2, charset);
<del> DataBufferUtils.release(dataBuffer2);
<del> assertEquals("\n", value2);
<del> })
<del> .consumeNextWith(dataBuffer3 -> {
<del> String value3 =
<del> DataBufferTestUtils.dumpString(dataBuffer3, charset);
<del> DataBufferUtils.release(dataBuffer3);
<del> assertEquals("\n", value3);
<add> assertEquals("data:{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}\n\n", value);
<ide> })
<ide> .expectComplete()
<ide> .verify(); | 7 |
Javascript | Javascript | use jasmine2 as framework | a82a8a5210858e34a0727eba1ac03a389bdd67d8 | <ide><path>protractor-jenkins-conf.js
<ide> exports.config = {
<ide>
<ide> baseUrl: 'http://localhost:8000/',
<ide>
<del> framework: 'jasmine',
<add> framework: 'jasmine2',
<ide>
<ide> onPrepare: function() {
<ide> /* global angular: false, browser: false, jasmine: false */
<ide><path>protractor-shared-conf.js
<ide> exports.config = {
<ide>
<ide> baseUrl: 'http://localhost:8000/',
<ide>
<del> framework: 'jasmine',
<add> framework: 'jasmine2',
<ide>
<ide> onPrepare: function() {
<ide> /* global angular: false, browser: false, jasmine: false */ | 2 |
Ruby | Ruby | fix flakey destroyed_by_association tests | 7f5deeeee6c9e0384ff6667fb51e64fcfe381365 | <ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> class HasOneAssociationsTest < ActiveRecord::TestCase
<ide> self.use_transactional_tests = false unless supports_savepoints?
<ide> fixtures :accounts, :companies, :developers, :projects, :developers_projects,
<del> :ships, :pirates, :authors, :author_addresses, :memberships, :clubs
<add> :ships, :pirates, :authors, :author_addresses, :books, :memberships, :clubs
<ide>
<ide> def setup
<ide> Account.destroyed_account_ids.clear | 1 |
Javascript | Javascript | add crypto check to crypto-lazy-transform | 1777a862a2e1e6034df7beba40703073a373ff7a | <ide><path>test/parallel/test-crypto-lazy-transform-writable.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto) {
<add> common.skip('missing crypto');
<add> return;
<add>}
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide> const Stream = require('stream'); | 1 |
Ruby | Ruby | move options_constraints tests next to each other | 522038aa9dc7d9759520d63b1c9d13086bdb3a21 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(scope, path, options)
<ide> via = Array(options.delete(:via) { [] })
<ide> options_constraints = options.delete :constraints
<ide>
<del> @blocks = blocks(options_constraints, scope[:blocks])
<del>
<ide> path = normalize_path! path, formatted
<ide> ast = path_ast path
<ide> path_params = path_params ast
<ide> def initialize(scope, path, options)
<ide>
<ide> split_constraints path_params, constraints
<ide>
<add> @blocks = blocks(options_constraints, scope[:blocks])
<add>
<ide> if options_constraints.is_a?(Hash)
<ide> split_constraints path_params, options_constraints
<ide> options_constraints.each do |key, default| | 1 |
Text | Text | improve chinese translation in euler-problem-1 | 8704a75844a6cd8401a8cd4cd1ceb5f3973e7548 | <ide><path>curriculum/challenges/chinese/08-coding-interview-prep/project-euler/problem-1-multiples-of-3-and-5.chinese.md
<ide> localeTitle: 问题1:3和5的倍数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果我们列出10以下是3或5的倍数的所有自然数,我们得到3,5,6和9.这些倍数的总和是23.求出所提供参数以下3或5的所有倍数的总和价值<code>number</code> 。 </section>
<add><section id="description">
<add> 如果我们列出所有10以下是3或5的倍数的自然数,我们会得到3,5,6和9。这些倍数的总和是23。
<add> 求出所有在<code>number</code>以下的3或5的倍数的总和。
<add></section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> | 1 |
Python | Python | accept custom run id in ``triggerdagrunoperator`` | cdaa9aac80085b157c606767f2b9958cd6b2e5f0 | <ide><path>airflow/operators/trigger_dagrun.py
<ide> class TriggerDagRunOperator(BaseOperator):
<ide> """
<ide> Triggers a DAG run for a specified ``dag_id``
<ide>
<del> :param trigger_dag_id: the dag_id to trigger (templated)
<add> :param trigger_dag_id: The dag_id to trigger (templated).
<ide> :type trigger_dag_id: str
<del> :param conf: Configuration for the DAG run
<add> :param trigger_run_id: The run ID to use for the triggered DAG run (templated).
<add> If not provided, a run ID will be automatically generated.
<add> :type trigger_run_id: str
<add> :param conf: Configuration for the DAG run.
<ide> :type conf: dict
<del> :param execution_date: Execution date for the dag (templated)
<add> :param execution_date: Execution date for the dag (templated).
<ide> :type execution_date: str or datetime.datetime
<ide> :param reset_dag_run: Whether or not clear existing dag run if already exists.
<ide> This is useful when backfill or rerun an existing dag run.
<ide> class TriggerDagRunOperator(BaseOperator):
<ide> :param poke_interval: Poke interval to check dag run status when wait_for_completion=True.
<ide> (default: 60)
<ide> :type poke_interval: int
<del> :param allowed_states: list of allowed states, default is ``['success']``
<add> :param allowed_states: List of allowed states, default is ``['success']``.
<ide> :type allowed_states: list
<del> :param failed_states: list of failed or dis-allowed states, default is ``None``
<add> :param failed_states: List of failed or dis-allowed states, default is ``None``.
<ide> :type failed_states: list
<ide> """
<ide>
<del> template_fields = ("trigger_dag_id", "execution_date", "conf")
<add> template_fields = ("trigger_dag_id", "trigger_run_id", "execution_date", "conf")
<ide> template_fields_renderers = {"conf": "py"}
<ide> ui_color = "#ffefeb"
<ide>
<ide> def __init__(
<ide> self,
<ide> *,
<ide> trigger_dag_id: str,
<add> trigger_run_id: Optional[str] = None,
<ide> conf: Optional[Dict] = None,
<ide> execution_date: Optional[Union[str, datetime.datetime]] = None,
<ide> reset_dag_run: bool = False,
<ide> def __init__(
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide> self.trigger_dag_id = trigger_dag_id
<add> self.trigger_run_id = trigger_run_id
<ide> self.conf = conf
<ide> self.reset_dag_run = reset_dag_run
<ide> self.wait_for_completion = wait_for_completion
<ide> def execute(self, context: Dict):
<ide> else:
<ide> execution_date = timezone.utcnow()
<ide>
<del> run_id = DagRun.generate_run_id(DagRunType.MANUAL, execution_date)
<add> if self.trigger_run_id:
<add> run_id = self.trigger_run_id
<add> else:
<add> run_id = DagRun.generate_run_id(DagRunType.MANUAL, execution_date)
<add>
<ide> try:
<del> # Ignore MyPy type for self.execution_date
<del> # because it doesn't pick up the timezone.parse() for strings
<ide> dag_run = trigger_dag(
<ide> dag_id=self.trigger_dag_id,
<ide> run_id=run_id,
<ide> conf=self.conf,
<ide> execution_date=self.execution_date,
<ide> replace_microseconds=False,
<ide> )
<del>
<ide> except DagRunAlreadyExists as e:
<ide> if self.reset_dag_run:
<ide> self.log.info("Clearing %s on %s", self.trigger_dag_id, self.execution_date)
<ide> def execute(self, context: Dict):
<ide> raise DagNotFound(f"Dag id {self.trigger_dag_id} not found in DagModel")
<ide>
<ide> dag_bag = DagBag(dag_folder=dag_model.fileloc, read_dags_from_db=True)
<del>
<ide> dag = dag_bag.get_dag(self.trigger_dag_id)
<del>
<ide> dag.clear(start_date=self.execution_date, end_date=self.execution_date)
<del>
<ide> dag_run = DagRun.find(dag_id=dag.dag_id, run_id=run_id)[0]
<ide> else:
<ide> raise e
<ide><path>tests/operators/test_trigger_dagrun.py
<ide> def test_trigger_dagrun(self):
<ide> assert len(dagruns) == 1
<ide> assert dagruns[0].external_trigger
<ide>
<add> def test_trigger_dagrun_custom_run_id(self):
<add> task = TriggerDagRunOperator(
<add> task_id="test_task",
<add> trigger_dag_id=TRIGGERED_DAG_ID,
<add> trigger_run_id="custom_run_id",
<add> dag=self.dag,
<add> )
<add> task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
<add>
<add> with create_session() as session:
<add> dagruns = session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).all()
<add> assert len(dagruns) == 1
<add> assert dagruns[0].run_id == "custom_run_id"
<add>
<ide> def test_trigger_dagrun_with_execution_date(self):
<ide> """Test TriggerDagRunOperator with custom execution_date."""
<ide> utc_now = timezone.utcnow() | 2 |
Ruby | Ruby | remove play, replaced by typesafe-activator | cca11731ca5842b65764344a2ce955764a0c9c42 | <ide><path>Library/Homebrew/blacklist.rb
<ide> def blacklisted? name
<ide> GNU Fortran is now provided as part of GCC, and can be installed with:
<ide> brew install gcc
<ide> EOS
<add> when 'play' then <<-EOS.undent
<add> Since Play 2.3 the play command has become the activator command.
<add> Play has been updated to use Activator. It can be installed with:
<add> brew install typesafe-activator
<add>
<add> You can read more about this change at:
<add> http://www.playframework.com/documentation/2.3.x/Migration23
<add> http://www.playframework.com/documentation/2.3.x/Highlights23
<add> EOS
<ide> end
<ide> end | 1 |
Mixed | Ruby | update security guide for signed cookie rotations | 04a7b7165ad204014c5850f62c921f7291d6ba5d | <ide><path>actionpack/test/dispatch/cookies_test.rb
<ide> def test_use_authenticated_cookie_encryption_uses_legacy_hmac_aes_cbc_encryption
<ide> assert_equal "bar", encryptor.decrypt_and_verify(@response.cookies["foo"])
<ide> end
<ide>
<add> def test_rotating_signed_cookies_digest
<add> @request.env["action_dispatch.signed_cookie_digest"] = "SHA256"
<add> @request.env["action_dispatch.cookies_rotations"].rotate :signed, digest: "SHA1"
<add>
<add> key_generator = @request.env["action_dispatch.key_generator"]
<add>
<add> old_secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
<add> old_value = ActiveSupport::MessageVerifier.new(old_secret).generate(45)
<add>
<add> @request.headers["Cookie"] = "user_id=#{old_value}"
<add> get :get_signed_cookie
<add>
<add> assert_equal 45, @controller.send(:cookies).signed[:user_id]
<add>
<add> secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
<add> verifier = ActiveSupport::MessageVerifier.new(secret, digest: "SHA256")
<add> assert_equal 45, verifier.verify(@response.cookies["user_id"])
<add> end
<add>
<ide> def test_legacy_hmac_aes_cbc_encrypted_marshal_cookie_is_upgraded_to_authenticated_encrypted_cookie
<ide> key_generator = @request.env["action_dispatch.key_generator"]
<ide> encrypted_cookie_salt = @request.env["action_dispatch.encrypted_cookie_salt"]
<ide><path>guides/source/security.md
<ide> you would first assign the new configuration value:
<ide> Rails.application.config.action_dispatch.signed_cookie_digest = "SHA256"
<ide> ```
<ide>
<del>Then you'd set up a rotation with the old configuration to keep it alive.
<add>Now add a rotation for the old SHA1 digest so existing cookies are
<add>seamlessly upgraded to the new SHA256 digest.
<ide>
<ide> ```ruby
<ide> Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies|
<del> cookies.rotate :signed, digest: "SHA256"
<add> cookies.rotate :signed, digest: "SHA1"
<ide> end
<ide> ```
<ide> | 2 |
Text | Text | add ctc members to collaborators list | bec387725af44a1f250c8dcf5f7e584d6d432b77 | <ide><path>README.md
<ide> more information about the governance of the Node.js project, see
<ide>
<ide> * [abouthiroppy](https://github.com/abouthiroppy) -
<ide> **Yuta Hiroto** <[email protected]> (he/him)
<add>* [addaleax](https://github.com/addaleax) -
<add>**Anna Henningsen** <[email protected]> (she/her)
<ide> * [ak239](https://github.com/ak239) -
<ide> **Aleksei Koziatinskii** <[email protected]>
<ide> * [andrasq](https://github.com/andrasq) -
<ide> more information about the governance of the Node.js project, see
<ide> **Benjamin Gruenbaum** <[email protected]>
<ide> * [bmeck](https://github.com/bmeck) -
<ide> **Bradley Farias** <[email protected]>
<add>* [bnoordhuis](https://github.com/bnoordhuis) -
<add>**Ben Noordhuis** <[email protected]>
<ide> * [brendanashworth](https://github.com/brendanashworth) -
<ide> **Brendan Ashworth** <[email protected]>
<ide> * [bzoz](https://github.com/bzoz) -
<ide> **Bartosz Sosnowski** <[email protected]>
<ide> * [calvinmetcalf](https://github.com/calvinmetcalf) -
<ide> **Calvin Metcalf** <[email protected]>
<add>* [ChALkeR](https://github.com/ChALkeR) -
<add>**Сковорода Никита Андреевич** <[email protected]> (he/him)
<add>* [chrisdickinson](https://github.com/chrisdickinson) -
<add>**Chris Dickinson** <[email protected]>
<add>* [cjihrig](https://github.com/cjihrig) -
<add>**Colin Ihrig** <[email protected]>
<ide> * [claudiorodriguez](https://github.com/claudiorodriguez) -
<ide> **Claudio Rodriguez** <[email protected]>
<ide> * [danbev](https://github.com/danbev) -
<ide> more information about the governance of the Node.js project, see
<ide> **Alexander Makarenko** <[email protected]>
<ide> * [eugeneo](https://github.com/eugeneo) -
<ide> **Eugene Ostroukhov** <[email protected]>
<add>* [evanlucas](https://github.com/evanlucas) -
<add>**Evan Lucas** <[email protected]> (he/him)
<add>* [fhinkel](https://github.com/fhinkel) -
<add>**Franziska Hinkelmann** <[email protected]>
<ide> * [firedfox](https://github.com/firedfox) -
<ide> **Daniel Wang** <[email protected]>
<add>* [Fishrock123](https://github.com/Fishrock123) -
<add>**Jeremiah Senkpiel** <[email protected]>
<ide> * [geek](https://github.com/geek) -
<ide> **Wyatt Preul** <[email protected]>
<ide> * [gibfahn](https://github.com/gibfahn) -
<ide> more information about the governance of the Node.js project, see
<ide> **Imran Iqbal** <[email protected]>
<ide> * [imyller](https://github.com/imyller) -
<ide> **Ilkka Myller** <[email protected]>
<add>* [indutny](https://github.com/indutny) -
<add>**Fedor Indutny** <[email protected]>
<add>* [isaacs](https://github.com/isaacs) -
<add>**Isaac Z. Schlueter** <[email protected]>
<ide> * [italoacasas](https://github.com/italoacasas) -
<ide> **Italo A. Casas** <[email protected]> (he/him)
<ide> * [JacksonTian](https://github.com/JacksonTian) -
<ide> **Jackson Tian** <[email protected]>
<add>* [jasnell](https://github.com/jasnell) -
<add>**James M Snell** <[email protected]> (he/him)
<ide> * [jasongin](https://github.com/jasongin) -
<ide> **Jason Ginchereau** <[email protected]>
<ide> * [jbergstroem](https://github.com/jbergstroem) -
<ide> more information about the governance of the Node.js project, see
<ide> **João Reis** <[email protected]>
<ide> * [joshgav](https://github.com/joshgav) -
<ide> **Josh Gavant** <[email protected]>
<add>* [joyeecheung](https://github.com/joyeecheung) -
<add>**Joyee Cheung** <[email protected]> (she/her)
<ide> * [julianduque](https://github.com/julianduque) -
<ide> **Julian Duque** <[email protected]> (he/him)
<ide> * [JungMinu](https://github.com/JungMinu) -
<ide> more information about the governance of the Node.js project, see
<ide> **Aleksey Smolenchuk** <[email protected]>
<ide> * [matthewloring](https://github.com/matthewloring) -
<ide> **Matthew Loring** <[email protected]>
<add>* [mcollina](https://github.com/mcollina) -
<add>**Matteo Collina** <[email protected]> (he/him)
<add>* [mhdawson](https://github.com/mhdawson) -
<add>**Michael Dawson** <[email protected]> (he/him)
<ide> * [micnic](https://github.com/micnic) -
<ide> **Nicu Micleușanu** <[email protected]> (he/him)
<ide> * [mikeal](https://github.com/mikeal) -
<ide> **Mikeal Rogers** <[email protected]>
<add>* [misterdjules](https://github.com/misterdjules) -
<add>**Julien Gilli** <[email protected]>
<ide> * [monsanto](https://github.com/monsanto) -
<ide> **Christopher Monsanto** <[email protected]>
<add>* [mscdex](https://github.com/mscdex) -
<add>**Brian White** <[email protected]>
<add>* [MylesBorins](https://github.com/MylesBorins) -
<add>**Myles Borins** <[email protected]> (he/him)
<ide> * [not-an-aardvark](https://github.com/not-an-aardvark) -
<ide> **Teddy Katz** <[email protected]>
<add>* [ofrobots](https://github.com/ofrobots) -
<add>**Ali Ijaz Sheikh** <[email protected]>
<ide> * [Olegas](https://github.com/Olegas) -
<ide> **Oleg Elifantiev** <[email protected]>
<add>* [orangemocha](https://github.com/orangemocha) -
<add>**Alexis Campailla** <[email protected]>
<ide> * [othiym23](https://github.com/othiym23) -
<ide> **Forrest L Norvell** <[email protected]> (he/him)
<ide> * [petkaantonov](https://github.com/petkaantonov) -
<ide> **Petka Antonov** <[email protected]>
<ide> * [phillipj](https://github.com/phillipj) -
<ide> **Phillip Johnsen** <[email protected]>
<add>* [piscisaureus](https://github.com/piscisaureus) -
<add>**Bert Belder** <[email protected]>
<ide> * [pmq20](https://github.com/pmq20) -
<ide> **Minqi Pan** <[email protected]>
<ide> * [princejwesley](https://github.com/princejwesley) -
<ide> more information about the governance of the Node.js project, see
<ide> **Ron Korving** <[email protected]>
<ide> * [RReverser](https://github.com/RReverser) -
<ide> **Ingvar Stepanyan** <[email protected]>
<add>* [rvagg](https://github.com/rvagg) -
<add>**Rod Vagg** <[email protected]>
<ide> * [saghul](https://github.com/saghul) -
<ide> **Saúl Ibarra Corretgé** <[email protected]>
<ide> * [sam-github](https://github.com/sam-github) -
<ide> more information about the governance of the Node.js project, see
<ide> **Santiago Gimeno** <[email protected]>
<ide> * [seishun](https://github.com/seishun) -
<ide> **Nikolai Vavilov** <[email protected]>
<add>* [shigeki](https://github.com/shigeki) -
<add>**Shigeki Ohtsu** <[email protected]> (he/him)
<ide> * [silverwind](https://github.com/silverwind) -
<ide> **Roman Reiss** <[email protected]>
<ide> * [srl295](https://github.com/srl295) -
<ide> **Steven R Loomis** <[email protected]>
<ide> * [stefanmb](https://github.com/stefanmb) -
<ide> **Stefan Budeanu** <[email protected]>
<add>* [targos](https://github.com/targos) -
<add>**Michaël Zasso** <[email protected]> (he/him)
<ide> * [tellnes](https://github.com/tellnes) -
<ide> **Christian Tellnes** <[email protected]>
<add>* [thefourtheye](https://github.com/thefourtheye) -
<add>**Sakthipriyan Vairamani** <[email protected]> (he/him)
<ide> * [thekemkid](https://github.com/thekemkid) -
<ide> **Glen Keane** <[email protected]> (he/him)
<ide> * [thlorenz](https://github.com/thlorenz) -
<ide> more information about the governance of the Node.js project, see
<ide> **Timothy Gu** <[email protected]> (he/him)
<ide> * [tniessen](https://github.com/tniessen) -
<ide> **Tobias Nießen** <[email protected]>
<add>* [trevnorris](https://github.com/trevnorris) -
<add>**Trevor Norris** <[email protected]>
<add>* [Trott](https://github.com/Trott) -
<add>**Rich Trott** <[email protected]> (he/him)
<ide> * [tunniclm](https://github.com/tunniclm) -
<ide> **Mike Tunnicliffe** <[email protected]>
<ide> * [vkurchatkin](https://github.com/vkurchatkin) -
<ide> more information about the governance of the Node.js project, see
<ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) -
<ide> **Yosuke Furukawa** <[email protected]>
<ide>
<del>Collaborators (which includes CTC members) follow the
<del>[COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in maintaining the Node.js
<del>project.
<add>Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<add>maintaining the Node.js project.
<ide>
<ide> ### Release Team
<ide> | 1 |
Ruby | Ruby | remove formula revision | 96cbce015e0b327bd7d30fc101cbd25452cd2fd8 | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def inreplace_pairs(path, replacement_pairs)
<ide> contents = path.open("r") { |f| Formulary.set_encoding(f).read }
<ide> contents.extend(StringInreplaceExtension)
<ide> replacement_pairs.each do |old, new|
<del> ohai "replace \"#{old}\" with \"#{new}\"" unless ARGV.flag?("--quiet")
<add> unless ARGV.flag?("--quiet")
<add> ohai "replace #{old.inspect} with #{new.inspect}"
<add> end
<ide> contents.gsub!(old, new)
<ide> end
<ide> if contents.errors.any?
<ide> def inreplace_pairs(path, replacement_pairs)
<ide> else
<ide> Utils::Inreplace.inreplace(path) do |s|
<ide> replacement_pairs.each do |old, new|
<del> ohai "replace \"#{old}\" with \"#{new}\"" unless ARGV.flag?("--quiet")
<add> unless ARGV.flag?("--quiet")
<add> ohai "replace #{old.inspect} with #{new.inspect}"
<add> end
<ide> s.gsub!(old, new)
<ide> end
<ide> end
<ide> def bump_formula_pr
<ide>
<ide> old_formula_version = formula_version(formula, requested_spec)
<ide>
<del> replacement_pairs = if new_url_hash
<add> replacement_pairs = []
<add> if requested_spec == :stable && formula.revision != 0
<add> replacement_pairs << [/^ revision \d+\n(\n( head "))?/m, "\\2"]
<add> end
<add>
<add> replacement_pairs += if new_url_hash
<ide> [
<ide> [formula_spec.url, new_url],
<ide> [old_hash, new_hash], | 1 |
Text | Text | add explaination of example | 3c24da1db0ed720adc77bf345d3f42661b98c40f | <ide><path>guide/english/html/elements/comment-tag/index.md
<ide> Comments can also be used to make code inactive without having to delete it enti
<ide> -->
<ide> ```
<ide>
<add>The example would display "Hello Friends", but "Hello Campers" and "Hello Paragraph" would not be displayed as they are comments, and are only visible in code or Inspect Element. | 1 |
PHP | PHP | fix error output leaking into test output | b3e94f83e08e717b62d5db75ca71f45d6b8522a6 | <ide><path>lib/Cake/Error/BaseErrorHandler.php
<ide> public function handleError($code, $description, $file = null, $line = null, $co
<ide> }
<ide> $this->_displayError($data, $debug);
<ide> $this->_logError($log, $data);
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> /**
<ide> public function handleFatalError($code, $description, $file, $line) {
<ide> } else {
<ide> $this->handleException(new InternalErrorException());
<ide> }
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Error/ErrorHandlerTest.php
<ide> <?php
<ide> /**
<del> * ErrorHandlerTest file
<del> *
<ide> * PHP 5
<ide> *
<ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> public function testHandleFatalErrorPage() {
<ide> }
<ide>
<ide> /**
<del> * test handleException generating log.
<add> * test handleFatalError generating log.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testHandleFatalErrorLog() {
<ide> $this->_logger->expects($this->at(0))
<ide> ->method('write')
<ide> ->with('error', $this->logicalAnd(
<del> $this->stringContains(__FILE__ . ', line 327'),
<add> $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 10)),
<ide> $this->stringContains('Fatal Error (1)'),
<ide> $this->stringContains('Something wrong')
<ide> )); | 2 |
Ruby | Ruby | ignore perl opts | bfbdfe8d9da53209dcc66ee0e9980078669a4acd | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> module SharedEnvExtension
<ide> CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS
<ide> MACOSX_DEPLOYMENT_TARGET SDKROOT DEVELOPER_DIR
<ide> CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_FRAMEWORK_PATH
<del> GOBIN GOPATH GOROOT
<add> GOBIN GOPATH GOROOT PERL_MB_OPT PERL_MM_OPT
<ide> LIBRARY_PATH
<ide> ]
<ide> | 1 |
Mixed | Ruby | retain selections with `includes` and `joins` | 2d6088ced5c338a4503816b25861908282b4dea2 | <ide><path>activerecord/CHANGELOG.md
<add>* Retain explicit selections on the base model after applying `includes` and `joins`.
<add>
<add> Resolves #34889.
<add>
<add> *Patrick Rebsch*
<add>
<ide> * Allow attributes to be fetched from Arel node groupings.
<ide>
<ide> *Jeff Emminger*, *Gannon McGibbon*
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def instantiate(result_set, &block)
<ide>
<ide> model_cache = Hash.new { |h, klass| h[klass] = {} }
<ide> parents = model_cache[join_root]
<add>
<ide> column_aliases = aliases.column_aliases join_root
<add> column_aliases += explicit_selections(column_aliases, result_set)
<ide>
<ide> message_bus = ActiveSupport::Notifications.instrumenter
<ide>
<ide> def apply_column_aliases(relation)
<ide> private
<ide> attr_reader :alias_tracker
<ide>
<add> def explicit_selections(root_column_aliases, result_set)
<add> root_names = root_column_aliases.map(&:name).to_set
<add> result_set.columns
<add> .reject { |n| root_names.include?(n) || n =~ /\At\d+_r\d+\z/ }
<add> .map { |n| Aliases::Column.new(n, n) }
<add> end
<add>
<ide> def aliases
<ide> @aliases ||= Aliases.new join_root.each_with_index.map { |join_part, i|
<ide> columns = join_part.column_names.each_with_index.map { |column_name, j|
<ide><path>activerecord/test/cases/relation/select_test.rb
<ide>
<ide> require "cases/helper"
<ide> require "models/post"
<add>require "models/comment"
<ide>
<ide> module ActiveRecord
<ide> class SelectTest < ActiveRecord::TestCase
<del> fixtures :posts
<add> fixtures :posts, :comments
<ide>
<ide> def test_select_with_nil_argument
<ide> expected = Post.select(:title).to_sql
<ide> def test_reselect_with_default_scope_select
<ide>
<ide> assert_equal expected, actual
<ide> end
<add>
<add> def test_aliased_select_using_as_with_joins_and_includes
<add> posts = Post.select("posts.id AS field_alias").joins(:comments).includes(:comments)
<add> assert_includes posts.first.attributes, "field_alias"
<add> end
<add>
<add> def test_aliased_select_not_using_as_with_joins_and_includes
<add> posts = Post.select("posts.id field_alias").joins(:comments).includes(:comments)
<add> assert_includes posts.first.attributes, "field_alias"
<add> end
<add>
<add> def test_star_select_with_joins_and_includes
<add> posts = Post.select("posts.*").joins(:comments).includes(:comments)
<add> assert_not_includes posts.first.attributes, "posts.*"
<add> end
<ide> end
<ide> end | 3 |
PHP | PHP | put docblock @return parameters in correct order | 9332c6003d47dee946b180360668fdfd1dd36f0c | <ide><path>src/Illuminate/Routing/Route.php
<ide> protected function extractOptionalParameters()
<ide> * Get or set the middlewares attached to the route.
<ide> *
<ide> * @param array|string|null $middleware
<del> * @return array|$this
<add> * @return $this|array
<ide> */
<ide> public function middleware($middleware = null)
<ide> { | 1 |
PHP | PHP | add deprecated notice to _classname in entitytrait | 5f880f67ed53f3049a8344b1941545c8cbbc4e23 | <ide><path>src/Datasource/EntityTrait.php
<ide> trait EntityTrait
<ide> */
<ide> protected $_virtual = [];
<ide>
<add> /**
<add> * Holds the name of the class for the instance object
<add> *
<add> * @var string
<add> *
<add> * @deprecated 3.2 This field is no longer being used
<add> */
<add> protected $_className;
<add>
<ide> /**
<ide> * Holds a list of the properties that were modified or added after this object
<ide> * was originally created. | 1 |
Python | Python | allow text generation for prophetnetforcausallm | fb36c273a299da6e53052f56e8ebd96fae6b09cb | <ide><path>src/transformers/models/prophetnet/modeling_prophetnet.py
<ide> def get_decoder(self):
<ide> )
<ide> class ProphetNetForCausalLM(ProphetNetPreTrainedModel):
<ide> def __init__(self, config):
<del> super().__init__(config)
<ide> # set config for CLM
<ide> config = copy.deepcopy(config)
<ide> config.is_decoder = True
<ide> config.is_encoder_decoder = False
<add> super().__init__(config)
<ide> self.prophetnet = ProphetNetDecoderWrapper(config)
<ide>
<ide> self.padding_idx = config.pad_token_id
<ide><path>tests/test_modeling_prophetnet.py
<ide> def create_and_check_generate_with_past_key_value_states(
<ide> output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)
<ide> self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
<ide>
<add> def create_and_check_decoder_generate_with_past_key_value_states(
<add> self,
<add> config,
<add> input_ids,
<add> decoder_input_ids,
<add> attention_mask,
<add> decoder_attention_mask,
<add> lm_labels,
<add> ):
<add> model = ProphetNetForCausalLM(config=config).to(torch_device).eval()
<add> torch.manual_seed(0)
<add> output_without_past_cache = model.generate(
<add> input_ids[:1], num_beams=2, max_length=10, do_sample=True, use_cache=False
<add> )
<add> torch.manual_seed(0)
<add> output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=10, do_sample=True)
<add> self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
<add>
<ide> def create_and_check_model_fp16_forward(
<ide> self,
<ide> config,
<ide> def test_decoder_model_generate(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_generate_with_past_key_value_states(*config_and_inputs)
<ide>
<add> def test_encoder_decoder_model_generate(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_decoder_generate_with_past_key_value_states(*config_and_inputs)
<add>
<ide> def test_attn_mask_model(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.check_model_with_attn_mask(*config_and_inputs) | 2 |
Javascript | Javascript | add id to body | 59bbf859869f8040e85ca0695aab13da41cc6bad | <ide><path>website/src/html.js
<ide> export default function HTML(props) {
<ide> />
<ide> {props.headComponents}
<ide> </head>
<del> <body {...props.bodyAttributes}>
<add> <body id="top" {...props.bodyAttributes}>
<ide> {props.preBodyComponents}
<ide> <noscript key="noscript" id="gatsby-noscript">
<ide> This app works best with JavaScript enabled. | 1 |
Text | Text | add fields in volume api for 1.24, 1.25 | b015fd4fb3a8def4812491bae702275efc6ab0cb | <ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Return low-level information about the `exec` command `id`.
<ide> {
<ide> "Name": "tardis",
<ide> "Driver": "local",
<del> "Mountpoint": "/var/lib/docker/volumes/tardis"
<add> "Mountpoint": "/var/lib/docker/volumes/tardis",
<add> "Labels": null,
<add> "Scope": "local"
<ide> }
<ide> ],
<ide> "Warnings": []
<ide> Create a volume
<ide> "com.example.some-label": "some-value",
<ide> "com.example.some-other-label": "some-other-value"
<ide> },
<add> "Driver": "custom"
<ide> }
<ide>
<ide> **Example response**:
<ide> Create a volume
<ide>
<ide> {
<ide> "Name": "tardis",
<del> "Driver": "local",
<add> "Driver": "custom",
<ide> "Mountpoint": "/var/lib/docker/volumes/tardis",
<del> "Status": null,
<add> "Status": {
<add> "hello": "world"
<add> },
<ide> "Labels": {
<ide> "com.example.some-label": "some-value",
<ide> "com.example.some-other-label": "some-other-value"
<ide> },
<add> "Scope": "local"
<ide> }
<ide>
<ide> **Status codes**:
<ide> Create a volume
<ide> - **Driver** - Name of the volume driver to use. Defaults to `local` for the name.
<ide> - **DriverOpts** - A mapping of driver options and values. These options are
<ide> passed directly to the driver and are driver specific.
<del>- **Labels** - Labels to set on the volume, specified as a map: `{"key":"value" [,"key2":"value2"]}`
<add>- **Labels** - Labels to set on the volume, specified as a map: `{"key":"value","key2":"value2"}`
<ide>
<add>**JSON fields in response**:
<add>
<add>Refer to the [inspect a volume](#inspect-a-volume) section or details about the
<add>JSON fields returned in the response.
<add>
<ide> ### Inspect a volume
<ide>
<ide> `GET /volumes/(name)`
<ide> Return low-level information on the volume `name`
<ide>
<ide> {
<ide> "Name": "tardis",
<del> "Driver": "local",
<add> "Driver": "custom",
<ide> "Mountpoint": "/var/lib/docker/volumes/tardis/_data",
<add> "Status": {
<add> "hello": "world"
<add> },
<ide> "Labels": {
<ide> "com.example.some-label": "some-value",
<ide> "com.example.some-other-label": "some-other-value"
<del> }
<add> },
<add> "Scope": "local"
<ide> }
<ide>
<ide> **Status codes**:
<ide> Return low-level information on the volume `name`
<ide> - **404** - no such volume
<ide> - **500** - server error
<ide>
<add>**JSON fields in response**:
<add>
<add>The following fields can be returned in the API response. Empty fields, or
<add>fields that are not supported by the volume's driver may be omitted in the
<add>response.
<add>
<add>- **Name** - Name of the volume.
<add>- **Driver** - Name of the volume driver used by the volume.
<add>- **Mountpoint** - Mount path of the volume on the host.
<add>- **Status** - Low-level details about the volume, provided by the volume driver.
<add> Details are returned as a map with key/value pairs: `{"key":"value","key2":"value2"}`.
<add> The `Status` field is optional, and is omitted if the volume driver does not
<add> support this feature.
<add>- **Labels** - Labels set on the volume, specified as a map: `{"key":"value","key2":"value2"}`.
<add>- **Scope** - Scope describes the level at which the volume exists, can be one of
<add> `global` for cluster-wide or `local` for machine level. The default is `local`.
<add>
<ide> ### Remove a volume
<ide>
<ide> `DELETE /volumes/(name)`
<ide><path>docs/reference/api/docker_remote_api_v1.25.md
<ide> Return low-level information about the `exec` command `id`.
<ide> {
<ide> "Name": "tardis",
<ide> "Driver": "local",
<del> "Mountpoint": "/var/lib/docker/volumes/tardis"
<add> "Mountpoint": "/var/lib/docker/volumes/tardis",
<add> "Labels":{
<add> "com.example.some-label": "some-value",
<add> "com.example.some-other-label": "some-other-value"
<add> },
<add> "Scope": "local"
<ide> }
<ide> ],
<ide> "Warnings": []
<ide> Create a volume
<ide>
<ide> {
<ide> "Name": "tardis",
<del> "Driver": "local",
<add> "Driver": "custom",
<ide> "Mountpoint": "/var/lib/docker/volumes/tardis",
<del> "Status": null,
<add> "Status": {
<add> "hello": "world"
<add> },
<ide> "Labels": {
<ide> "com.example.some-label": "some-value",
<ide> "com.example.some-other-label": "some-other-value"
<ide> },
<add> "Scope": "local"
<ide> }
<ide>
<ide> **Status codes**:
<ide> Create a volume
<ide> - **Driver** - Name of the volume driver to use. Defaults to `local` for the name.
<ide> - **DriverOpts** - A mapping of driver options and values. These options are
<ide> passed directly to the driver and are driver specific.
<del>- **Labels** - Labels to set on the volume, specified as a map: `{"key":"value" [,"key2":"value2"]}`
<add>- **Labels** - Labels to set on the volume, specified as a map: `{"key":"value","key2":"value2"}`
<add>
<add>**JSON fields in response**:
<add>
<add>Refer to the [inspect a volume](#inspect-a-volume) section or details about the
<add>JSON fields returned in the response.
<ide>
<ide> ### Inspect a volume
<ide>
<ide> Return low-level information on the volume `name`
<ide>
<ide> {
<ide> "Name": "tardis",
<del> "Driver": "local",
<add> "Driver": "custom",
<add> "Status": {
<add> "hello": "world"
<add> },
<ide> "Mountpoint": "/var/lib/docker/volumes/tardis/_data",
<ide> "Labels": {
<ide> "com.example.some-label": "some-value",
<ide> "com.example.some-other-label": "some-other-value"
<del> }
<add> },
<add> "Scope": "local"
<ide> }
<ide>
<ide> **Status codes**:
<ide> Return low-level information on the volume `name`
<ide> - **404** - no such volume
<ide> - **500** - server error
<ide>
<add>**JSON fields in response**:
<add>
<add>The following fields can be returned in the API response. Empty fields, or
<add>fields that are not supported by the volume's driver may be omitted in the
<add>response.
<add>
<add>- **Name** - Name of the volume.
<add>- **Driver** - Name of the volume driver used by the volume.
<add>- **Mountpoint** - Mount path of the volume on the host.
<add>- **Status** - Low-level details about the volume, provided by the volume driver.
<add> Details are returned as a map with key/value pairs: `{"key":"value","key2":"value2"}`.
<add> The `Status` field is optional, and is omitted if the volume driver does not
<add> support this feature.
<add>- **Labels** - Labels set on the volume, specified as a map: `{"key":"value","key2":"value2"}`.
<add>- **Scope** - Scope describes the level at which the volume exists, can be one of
<add> `global` for cluster-wide or `local` for machine level. The default is `local`.
<add>
<ide> ### Remove a volume
<ide>
<ide> `DELETE /volumes/(name)` | 2 |
Text | Text | expand stub to full article | f430694458cf780b8c36ed13ec029afa4fb46f58 | <ide><path>guide/spanish/network-engineering/ipv4-header/index.md
<ide> title: IPv4 Header
<ide> localeTitle: Encabezado IPv4
<ide> ---
<add>La traduccion de este articulo fue basado en la version igles, escrito por cmccormack, disponible aqui, https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/network-engineering/ipv4-header/index.md
<add>
<ide> ## Formato de encabezado IPv4
<ide>
<del>Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/network-engineering/ipv4-header/index.md) .
<add>El imagen del formato del encabezado IPv4 segun [RFC791](https://tools.ietf.org/html/rfc791):
<add>
<add>
<add>
<add>##### Version [4-bits]
<add> * Internet Protocol (IP) version number (decimal 4, binary 0100, hex 4)
<add> * Numero de version de protocolo de internet (IP) (decimal 4, binario 0100, hex 4)
<add>##### Internet Header Length (IHL) [4-bits]
<add> * La larga del encabezado IPv4
<add> * El IHL es medido en 32-bit palabras.
<add> * A value of 5 specifies the length of the header is 5 * 32-bits = 160bits = 20 bytes
<add> * Por ejemplo, un valor de 5 significa que la larga del encabezado es 5 * 32 bits = 160 bits = 20 bytes
<add> * El valor minimo del encabezado IPv4 es 20 bytes
<add>
<add>##### Differentiated Services Code Point (DSCP) [6-bits]
<add> * Este valor es usado por despositivos red para determinar la precedencia de un pacquete IP [[RFC2474](https://tools.ietf.org/html/rfc2474)]
<add> * Reglas puede ser hehco en despositivos red para manejar valores DSCP deferentes apropriadamente
<add> * Por ejemplo - trafico VoIP podria dado un valor DSCP de 46 (binario 101110, hex 0x2E) cual puede informar un despositivo red que este paquete deberia dado una proridad alto
<add>
<add>##### Explicit Congestion Notification (ECN) [2-bits]
<add> * Una caracteristica opcional que permite serividores identificar congestion red sin dejando caer paquetes neceariamente.
<add> * ECN feature is only available if the underlying network infrastructure also supports it.
<add> * Caracterisitca ECN solo solo esta disponible si la infrastructura de red lo apyoy.
<add>##### Total Length [16-bits]
<add> * La larga del paqutete entero, incuyendo el encabezado.
<add> * Este valor es medida en bytes (8-bits), y tiene un valor maximo de 2^16 - 1 = 65,535 bytes
<add>##### Identification [16-bits]
<add> * Asignado por el remitente servidor para ayudar en reuniendo los fragmentos de un paquete
<add>##### Flags [3-bits]
<add> * Usado para determinar si el paquete puede ser fragmentado o para informar el servidor destinatario que fragmento addiconales esta de llegada.
<add> * El bit Do Not Fragment (DF) es usado cuando es necesario que un paquete no es fragmentado. Si un despoitivo tiene que fragmentar el paqute porque es mas grande que el Maximum Transmission Unit (MTU) del enlace, el paquete esta dejado caer.
<add>##### Fragment Offset [13-bits]
<add> * El offset calculado por un paquete fragementado, relativo al principo del paquete desfragmentado original
<add> * Medida en bloques de 8-bytes
<add> * El valor maximo es (2^13 - 1) * 8 = 65,528 bytes
<add>##### Time To Live (TTL) [8-bits]
<add> * El cantidad de tiempo (en segundos) que un paquete esta permitido quedarse en la red
<add> * Este valor es aumentao por un segundo en cada despositivo red encontrado
<add> * Cuando el valor alcanza cero, el paquete esta descartado
<add>##### Protocol [8-bits]
<add> * Parecido al campo Next Header en IPv6, este campo significa el protocolo encapsulado en el paquete IPv4
<add> * Por ejemplo, protocolo TCP Numero 6 en binario serio 110, o 0x6 en hex
<add>##### Header Checksum [16-bits]
<add> * La suma de control es el 16-bit [complemento de unos](https://www.cs.uaf.edu/2004/fall/cs301/notes/node41.html) de la suma del complemento de unos de todas las palabras 16-bit en el encabezado. [[RFC792](https://tools.ietf.org/html/rfc791#page-14)]
<add>##### Source IP Address [32-bits]
<add> * La direccion IP del remitente del paquete
<add>##### Destination IP Address [32-bits]
<add> * La direccion IP destino para el destinaatario del paquete
<add>##### Options [32-bits]
<add> * Espefica opciones adicionales
<add> * Solo esta presente si el IHL es mas grande que 5, significando que la larga es mas que 5 * 32-bit palabras o 160-bits o 20 bytes - la larga de una IPv4 encabezado estandar sin opcinones
<add> * Opciones tiene que incluir relleno adicional si no llenan completamente el limite de 32-bit palabras
<add>
<ide>
<del>[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .
<add>#### Mas informacion (en ingles):
<add> * IP Option Numbers [[iana.org]](https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml)
<add> * List of IP protocol numbers used in the Next Header [[iana.org]](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml)
<ide>
<del>#### Más información:
<ide>\ No newline at end of file | 1 |
Text | Text | add missing entries to changelog | 543dcf910913bebd2b5963593d536573728fc4f1 | <ide><path>CHANGELOG.md
<ide> * Components are lazily looked up.
<ide> * Renaming everyBy and anyBy to isEvery and isAny.
<ide>
<add>###Ember 1.2.1 _(January 14, 2014)_
<add>
<add>* [SECURITY] Ensure primitive value contexts are escaped.
<add>* [SECURITY] Ensure {{group}} helper escapes properly.
<add>
<ide> ###Ember 1.2.0 _(November 22, 2013)_
<ide>
<ide> * [BUGFIX] Publish ember-handlebars-compiler along with builds.
<ide> * Allow apps with custom jquery builds to exclude the event-alias module
<ide> * Removes long-deprecated getPath/setPath
<ide>
<add>###Ember 1.1.3 _(January 13, 2014)_
<add>
<add>* [SECURITY] Ensure primitive value contexts are escaped.
<add>* [SECURITY] Ensure {{group}} helper escapes properly.
<add>
<add>###Ember 1.1.2 _(October 25, 2013)
<add>
<add>* [BUGFIX] Fix failures in component rendering. - Fixes #3637
<add>
<add>###Ember 1.1.1 _(October 23, 2013)_
<add>
<add>* [BUGFIX] Allow Ember.Object.create to accept an Ember.Object.
<add>
<ide> ### Ember 1.1.0 _(October 21, 2013)_
<ide>
<ide> * Make Ember.run.later more flexible with arguments - Fixes #3072 | 1 |
PHP | PHP | add a method for generating pagination meta links | e7f76a983a35ad351e220a3fe2cc7072b332b185 | <ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php
<ide> public function testWithZeroPages() {
<ide> $expected = '0 of 1';
<ide> $this->assertEquals($expected, $result);
<ide> }
<add>
<add>/**
<add> * Verify that no next and prev links are created for single page results
<add> *
<add> * @return void
<add> */
<add> public function testMetaPage0() {
<add> $this->Paginator->request['paging'] = array(
<add> 'Article' => array(
<add> 'page' => 1,
<add> 'prevPage' => false,
<add> 'nextPage' => false,
<add> 'pageCount' => 1,
<add> )
<add> );
<add> $expected = '';
<add> $result = $this->Paginator->meta();
<add> $this->assertSame($expected, $result);
<add> }
<add>
<add>/**
<add> * Verify that page 1 only has a next link
<add> *
<add> * @return void
<add> */
<add> public function testMetaPage1() {
<add> $this->Paginator->request['paging'] = array(
<add> 'Article' => array(
<add> 'page' => 1,
<add> 'prevPage' => false,
<add> 'nextPage' => true,
<add> 'pageCount' => 2,
<add> 'options' => array(),
<add> 'paramType' => 'querystring'
<add> )
<add> );
<add> $expected = '<link href="/?page=2" rel="next" />';
<add> $result = $this->Paginator->meta();
<add> $this->assertSame($expected, $result);
<add> }
<add>
<add>/**
<add> * Verify that the method will append to a block
<add> *
<add> * @return void
<add> */
<add> public function testMetaPage1InlineFalse() {
<add> $this->Paginator->request['paging'] = array(
<add> 'Article' => array(
<add> 'page' => 1,
<add> 'prevPage' => false,
<add> 'nextPage' => true,
<add> 'pageCount' => 2,
<add> 'options' => array(),
<add> 'paramType' => 'querystring'
<add> )
<add> );
<add> $expected = '<link href="/?page=2" rel="next" />';
<add> $this->Paginator->meta(array('block' => true));
<add> $result = $this->View->fetch('meta');
<add> $this->assertSame($expected, $result);
<add> }
<add>
<add>/**
<add> * Verify that the last page only has a prev link
<add> *
<add> * @return void
<add> */
<add> public function testMetaPage1Last() {
<add> $this->Paginator->request['paging'] = array(
<add> 'Article' => array(
<add> 'page' => 2,
<add> 'prevPage' => true,
<add> 'nextPage' => false,
<add> 'pageCount' => 2,
<add> 'options' => array(),
<add> 'paramType' => 'querystring'
<add> )
<add> );
<add> $expected = '<link href="/" rel="prev" />';
<add> $result = $this->Paginator->meta();
<add> $this->assertSame($expected, $result);
<add> }
<add>
<add>/**
<add> * Verify that a page in the middle has both links
<add> *
<add> * @return void
<add> */
<add> public function testMetaPage10Last() {
<add> $this->Paginator->request['paging'] = array(
<add> 'Article' => array(
<add> 'page' => 5,
<add> 'prevPage' => true,
<add> 'nextPage' => true,
<add> 'pageCount' => 10,
<add> 'options' => array(),
<add> 'paramType' => 'querystring'
<add> )
<add> );
<add> $expected = '<link href="/?page=4" rel="prev" />';
<add> $expected .= '<link href="/?page=6" rel="next" />';
<add> $result = $this->Paginator->meta();
<add> $this->assertSame($expected, $result);
<add> }
<add>
<ide> }
<ide><path>lib/Cake/View/Helper/PaginatorHelper.php
<ide> public function last($last = 'last >>', $options = array()) {
<ide> return $out;
<ide> }
<ide>
<add>/**
<add> * Returns the meta-links for a paginated result set
<add> *
<add> * `echo $this->Paginator->meta();`
<add> *
<add> * Echos the links directly, will output nothing of there is neither a previous nor next page.
<add> *
<add> * `$this->Paginator->meta(array('block' => true));`
<add> *
<add> * Will append the output of the meta function to the named block - if true is passed the "meta"
<add> * block is used
<add> *
<add> * ### Options:
<add> *
<add> * - `model` The model to use defaults to PaginatorHelper::defaultModel()
<add> * - `block` The block name to append the output to, or false/absenst to return as a string
<add> *
<add> * @param array $options Array of options
<add> * @return string|null meta links
<add> */
<add> public function meta($options = array()) {
<add> $model = isset($options['model']) ? $options['model'] : null;
<add> $params = $this->params($model);
<add> $links = array();
<add> if ($this->hasPrev()) {
<add> $links[] = $this->Html->meta(array(
<add> 'rel' => 'prev',
<add> 'link' => $this->url(array('page' => $params['page'] - 1), true)
<add> ));
<add> }
<add> if ($this->hasNext()) {
<add> $links[] = $this->Html->meta(array(
<add> 'rel' => 'next',
<add> 'link' => $this->url(array('page' => $params['page'] + 1), true)
<add> ));
<add> }
<add> $out = implode($links);
<add> if (empty($options['block'])) {
<add> return $out;
<add> }
<add> if ($options['block'] === true) {
<add> $options['block'] = __FUNCTION__;
<add> }
<add> $this->_View->append($options['block'], $out);
<add> }
<add>
<ide> } | 2 |
Text | Text | fix the ulimit link | 8f3c0fdff3846c5d7999c200c69c9d67751acc08 | <ide><path>docs/reference/commandline/build.md
<ide> flag](../run.md#specifying-custom-cgroups).
<ide>
<ide> Using the `--ulimit` option with `docker build` will cause each build step's
<ide> container to be started using those [`--ulimit`
<del>flag values](../run.md#setting-ulimits-in-a-container).
<add>flag values](./run.md#set-ulimits-in-container-ulimit).
<ide>
<ide> ### Set build-time variables (--build-arg)
<ide> | 1 |
Javascript | Javascript | promote 'features' to the prototype | c0f91674e44c8d6ccccf591719595eed001e99bc | <ide><path>src/js/control-bar/mute-toggle.js
<ide> vjs.MuteToggle = vjs.Button.extend({
<ide> player.on('volumechange', vjs.bind(this, this.update));
<ide>
<ide> // hide mute toggle if the current tech doesn't support volume control
<del> if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) {
<add> if (player.tech && player.tech['volumeControl'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech.features && player.tech.features['volumeControl'] === false) {
<add> if (player.tech['volumeControl'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/control-bar/playback-rate-menu-button.js
<ide> vjs.PlaybackRateMenuButton.prototype.onClick = function(){
<ide>
<ide> vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){
<ide> return this.player().tech
<del> && this.player().tech.features['playbackRate']
<add> && this.player().tech['playbackRate']
<ide> && this.player().options()['playbackRates']
<ide> && this.player().options()['playbackRates'].length > 0
<ide> ;
<ide><path>src/js/control-bar/volume-control.js
<ide> vjs.VolumeControl = vjs.Component.extend({
<ide> vjs.Component.call(this, player, options);
<ide>
<ide> // hide volume controls when they're not supported by the current tech
<del> if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) {
<add> if (player.tech && player.tech['volumeControl'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech.features && player.tech.features['volumeControl'] === false) {
<add> if (player.tech['volumeControl'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/control-bar/volume-menu-button.js
<ide> vjs.VolumeMenuButton = vjs.MenuButton.extend({
<ide> player.on('volumechange', vjs.bind(this, this.update));
<ide>
<ide> // hide mute toggle if the current tech doesn't support volume control
<del> if (player.tech && player.tech.features && player.tech.features.volumeControl === false) {
<add> if (player.tech && player.tech.volumeControl === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech.features && player.tech.features.volumeControl === false) {
<add> if (player.tech.volumeControl === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/exports.js
<ide> goog.exportSymbol('videojs.CaptionsButton', vjs.CaptionsButton);
<ide> goog.exportSymbol('videojs.ChaptersButton', vjs.ChaptersButton);
<ide>
<ide> goog.exportSymbol('videojs.MediaTechController', vjs.MediaTechController);
<del>goog.exportProperty(vjs.MediaTechController.prototype, 'features', vjs.MediaTechController.prototype.features);
<del>goog.exportProperty(vjs.MediaTechController.prototype.features, 'volumeControl', vjs.MediaTechController.prototype.features.volumeControl);
<del>goog.exportProperty(vjs.MediaTechController.prototype.features, 'fullscreenResize', vjs.MediaTechController.prototype.features.fullscreenResize);
<del>goog.exportProperty(vjs.MediaTechController.prototype.features, 'progressEvents', vjs.MediaTechController.prototype.features.progressEvents);
<del>goog.exportProperty(vjs.MediaTechController.prototype.features, 'timeupdateEvents', vjs.MediaTechController.prototype.features.timeupdateEvents);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'volumeControl', vjs.MediaTechController.prototype.volumeControl);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'fullscreenResize', vjs.MediaTechController.prototype.fullscreenResize);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'progressEvents', vjs.MediaTechController.prototype.progressEvents);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'timeupdateEvents', vjs.MediaTechController.prototype.timeupdateEvents);
<ide> goog.exportProperty(vjs.MediaTechController.prototype, 'setPoster', vjs.MediaTechController.prototype.setPoster);
<ide>
<ide>
<ide> goog.exportSymbol('videojs.createTimeRange', vjs.createTimeRange);
<ide>
<ide> goog.exportSymbol('videojs.util', vjs.util);
<ide> goog.exportProperty(vjs.util, 'mergeOptions', vjs.util.mergeOptions);
<del>goog.exportProperty(vjs, 'addLanguage', vjs.addLanguage);
<ide>\ No newline at end of file
<add>goog.exportProperty(vjs, 'addLanguage', vjs.addLanguage);
<ide><path>src/js/media/html5.js
<ide> vjs.Html5 = vjs.MediaTechController.extend({
<ide> /** @constructor */
<ide> init: function(player, options, ready){
<ide> // volume cannot be changed from 1 on iOS
<del> this.features['volumeControl'] = vjs.Html5.canControlVolume();
<add> this['volumeControl'] = vjs.Html5.canControlVolume();
<ide>
<ide> // just in case; or is it excessively...
<del> this.features['playbackRate'] = vjs.Html5.canControlPlaybackRate();
<add> this['playbackRate'] = vjs.Html5.canControlPlaybackRate();
<ide>
<ide> // In iOS, if you move a video element in the DOM, it breaks video playback.
<del> this.features['movingMediaElementInDOM'] = !vjs.IS_IOS;
<add> this['movingMediaElementInDOM'] = !vjs.IS_IOS;
<ide>
<ide> // HTML video is able to automatically resize when going to fullscreen
<del> this.features['fullscreenResize'] = true;
<add> this['fullscreenResize'] = true;
<ide>
<ide> // HTML video supports progress events
<ide> this.features['progressEvents'] = true;
<ide> vjs.Html5.prototype.createEl = function(){
<ide> // Check if this browser supports moving the element into the box.
<ide> // On the iPhone video will break if you move the element,
<ide> // So we have to create a brand new element.
<del> if (!el || this.features['movingMediaElementInDOM'] === false) {
<add> if (!el || this['movingMediaElementInDOM'] === false) {
<ide>
<ide> // If the original tag is still there, clone and remove it.
<ide> if (el) {
<ide><path>src/js/media/media.js
<ide> vjs.MediaTechController = vjs.Component.extend({
<ide> init: function(player, options, ready){
<ide> options = options || {};
<ide>
<del> // Make sure that `this.features` isn't directly tied to `vjs.MediaTechController.prototype.features`
<del> // Using `vjs.obj.create` allows us to receive default updates from the prototype if we haven't changed the value.
<del> this.features = vjs.obj.create(vjs.MediaTechController.prototype.features);
<del>
<ide> // we don't want the tech to report user activity automatically.
<ide> // This is done manually in addControlsListeners
<ide> options.reportTouchActivity = false;
<ide> vjs.MediaTechController.prototype.setCurrentTime = function() {
<ide> */
<ide> vjs.MediaTechController.prototype.setPoster = function(){};
<ide>
<del>vjs.MediaTechController.prototype.features = {
<del> 'volumeControl': true,
<add>vjs.MediaTechController.prototype[ 'volumeControl' ] = true;
<ide>
<del> // Resizing plugins using request fullscreen reloads the plugin
<del> 'fullscreenResize': false,
<del> 'playbackRate': false,
<add>// Resizing plugins using request fullscreen reloads the plugin
<add>vjs.MediaTechController.prototype[ 'fullscreenResize' ] = false;
<add>vjs.MediaTechController.prototype[ 'playbackRate' ] = false;
<ide>
<del> // Optional events that we can manually mimic with timers
<del> // currently not triggered by video-js-swf
<del> 'progressEvents': false,
<del> 'timeupdateEvents': false
<del>};
<add>// Optional events that we can manually mimic with timers
<add>// currently not triggered by video-js-swf
<add>vjs.MediaTechController.prototype[ 'progressEvents' ] = false;
<add>vjs.MediaTechController.prototype[ 'timeupdateEvents' ] = false;
<ide>
<ide> vjs.media = {};
<ide><path>src/js/player.js
<ide> vjs.Player.prototype.unloadTech = function(){
<ide> // vjs.log('loadedTech')
<ide> // },
<ide>
<del>
<ide> // /* Player event handlers (how the player reacts to certain events)
<ide> // ================================================================================ */
<ide>
<ide> vjs.Player.prototype.playbackRate = function(rate) {
<ide> return this;
<ide> }
<ide>
<del> if (this.tech && this.tech.features && this.tech.features['playbackRate']) {
<add> if (this.tech && this.tech['playbackRate']) {
<ide> return this.techGet('playbackRate');
<ide> } else {
<ide> return 1.0; | 8 |
PHP | PHP | reorganize operators in most-used order | 1f21898515f8a049b4f4529351fc427690795d8f | <ide><path>src/Illuminate/Support/Collection.php
<ide> protected function operatorForWhere($key, $operator, $value)
<ide> default:
<ide> case '=':
<ide> case '==': return $retrieved == $value;
<del> case '===': return $retrieved === $value;
<del> case '<=': return $retrieved <= $value;
<del> case '>=': return $retrieved >= $value;
<add> case '!=':
<add> case '<>': return $retrieved != $value;
<ide> case '<': return $retrieved < $value;
<ide> case '>': return $retrieved > $value;
<del> case '<>':
<del> case '!=': return $retrieved != $value;
<add> case '<=': return $retrieved <= $value;
<add> case '>=': return $retrieved >= $value;
<add> case '===': return $retrieved === $value;
<ide> case '!==': return $retrieved !== $value;
<ide> }
<ide> }; | 1 |
Ruby | Ruby | prevent extra `through_scope` | d807e3f59d93dd9f590af83e708d0a21f208094a | <ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb
<ide> def source_reflection
<ide> end
<ide>
<ide> def associated_records_by_owner(preloader)
<add> through_scope = through_scope()
<add>
<ide> preloader.preload(owners,
<ide> through_reflection.name,
<ide> through_scope)
<ide> def associated_records_by_owner(preloader)
<ide> [owner, Array(center)]
<ide> end
<ide>
<del> reset_association owners, through_reflection.name
<add> reset_association(owners, through_reflection.name, through_scope)
<ide>
<ide> middle_records = through_records.flat_map(&:last)
<ide>
<ide> def id_to_index_map(ids)
<ide> id_map
<ide> end
<ide>
<del> def reset_association(owners, association_name)
<add> def reset_association(owners, association_name, through_scope)
<ide> should_reset = (through_scope != through_reflection.klass.unscoped) ||
<ide> (reflection.options[:source_type] && through_reflection.collection?)
<ide> | 1 |
Mixed | Python | implement transformer xl | 2c98b4b0a49a53f80042e92de7049e679ff9abab | <ide><path>official/nlp/modeling/layers/README.md
<ide> assemble new layers, networks, or models.
<ide> * [GatedFeedforward](gated_feedforward.py) implements the gated linear layer
<ide> feedforward as described in
<ide> ["GLU Variants Improve Transformer"](https://arxiv.org/abs/2002.05202).
<add>
<add>* [MultiHeadRelativeAttention](relative_attention.py) implements a variant
<add> of multi-head attention with support for relative position encodings as
<add> described in "Transformer-XL: Attentive Language Models Beyond a
<add> Fixed-Length Context"(https://arxiv.org/abs/1901.02860). This also has
<add> extended support for segment-based attention, a re-parameterization
<add> introduced in "XLNet: Generalized Autoregressive Pretraining for Language
<add> Understanding" (https://arxiv.org/abs/1906.08237).
<add>
<add>* [TwoStreamRelativeAttention](relative_attention.py) implements a variant
<add> of multi-head relative attention as described in "XLNet: Generalized
<add> Autoregressive Pretraining for Language Understanding"
<add> (https://arxiv.org/abs/1906.08237). This takes in a query and content
<add> stream and applies self attention.
<add>
<add>* [TransformerXL](transformer_xl.py) implements Transformer XL introduced in
<add> "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
<add> (https://arxiv.org/abs/1901.02860). This contains `TransformerXLBlock`, a
<add> block containing either one or two stream relative self-attention as well as
<add> subsequent feedforward networks. It also contains `TransformerXL`, which
<add> contains attention biases as well as multiple `TransformerXLBlocks`.
<ide><path>official/nlp/modeling/layers/__init__.py
<ide> from official.nlp.modeling.layers.multi_channel_attention import *
<ide> from official.nlp.modeling.layers.on_device_embedding import OnDeviceEmbedding
<ide> from official.nlp.modeling.layers.position_embedding import RelativePositionEmbedding
<add>from official.nlp.modeling.layers.relative_attention import MultiHeadRelativeAttention
<add>from official.nlp.modeling.layers.relative_attention import TwoStreamRelativeAttention
<ide> from official.nlp.modeling.layers.rezero_transformer import ReZeroTransformer
<ide> from official.nlp.modeling.layers.self_attention_mask import SelfAttentionMask
<ide> from official.nlp.modeling.layers.talking_heads_attention import TalkingHeadsAttention
<ide> from official.nlp.modeling.layers.tn_transformer_expand_condense import TNTransformerExpandCondense
<ide> from official.nlp.modeling.layers.transformer import *
<ide> from official.nlp.modeling.layers.transformer_scaffold import TransformerScaffold
<add>from official.nlp.modeling.layers.transformer_xl import TransformerXL
<add>from official.nlp.modeling.layers.transformer_xl import TransformerXLBlock
<ide><path>official/nlp/modeling/layers/transformer_xl.py
<ide> from official.nlp.modeling.layers import relative_attention
<ide>
<ide>
<add>def _cache_memory(current_state, previous_state, memory_length, reuse_length=0):
<add> """Caches hidden states into memory.
<add>
<add> Arguments:
<add> current_state: `Tensor`, the current state.
<add> previous_state: `Tensor`, the previous state.
<add> memory_length: `int`, the number of tokens to cache.
<add> reuse_length: `int`, the number of tokens in the current batch to be cached
<add> and reused in the future.
<add>
<add> Returns:
<add> A `Tensor`, representing the cached state with stopped gradients.
<add>
<add> """
<add> if memory_length is None or memory_length == 0:
<add> return None
<add> else:
<add> if reuse_length > 0:
<add> current_state = current_state[:, :reuse_length, :]
<add>
<add> if previous_state is None:
<add> new_mem = current_state[:, -memory_length:, :]
<add> else:
<add> new_mem = tf.concat(
<add> [previous_state, current_state], 1)[:, -memory_length:, :]
<add>
<add> return tf.stop_gradient(new_mem)
<add>
<add>
<ide> @tf.keras.utils.register_keras_serializable(package="Text")
<ide> class TransformerXLBlock(tf.keras.layers.Layer):
<ide> """Transformer XL block.
<ide> def call(self,
<ide>
<ide> return attention_output
<ide>
<add>
<add>class TransformerXL(tf.keras.layers.Layer):
<add> """Transformer XL.
<add>
<add> This layer combines multiple Transformer XL blocks from "Transformer-XL:
<add> Attentive Language Models Beyond a Fixed-Length Context"
<add> (https://arxiv.org/abs/1901.02860).
<add>
<add> This layer handles the attention biases as well as memory caching and reuse
<add> as in Transformer XL and XLNet.
<add>
<add>
<add> Attributes:
<add> vocab_size: The number of tokens in vocabulary.
<add> num_layers: The number of layers.
<add> hidden_size: The hidden size.
<add> num_attention_heads: The number of attention heads.
<add> head_size: The dimension size of each attention head.
<add> inner_size: The hidden size in feed-forward layers.
<add> dropout_rate: Dropout rate used in each Transformer XL block.
<add> attention_dropout_rate: Dropout rate on attention probabilities.
<add> two_stream: Whether or not to use `TwoStreamRelativeAttention` used
<add> in the XLNet pretrainer. If `False`, then it will use
<add> `MultiHeadRelativeAttention` as in Transformer XL.
<add> initializer: The initializer to use for attention biases.
<add> tie_attention_biases: Whether or not to tie biases together. If `True`, then
<add> each Transformer XL block shares the same trainable attention bias. If
<add> `False`, then each block has its own attention bias. This is usually set
<add> to `True`.
<add> memory_length: The number of tokens to cache.
<add> reuse_length: The number of tokens in the current batch to be cached
<add> and reused in the future.
<add> inner_activation: The activation to use in the inner layers
<add> for Transformer XL blocks. Typically "relu" or "gelu".
<add> """
<add>
<add> def __init__(self,
<add> vocab_size,
<add> num_layers,
<add> hidden_size,
<add> num_attention_heads,
<add> head_size,
<add> inner_size,
<add> dropout_rate,
<add> attention_dropout_rate,
<add> initializer,
<add> two_stream=False,
<add> tie_attention_biases=True,
<add> memory_length=None,
<add> reuse_length=None,
<add> inner_activation="relu",
<add> **kwargs):
<add> """Initializes TransformerXL."""
<add> super(TransformerXL, self).__init__(**kwargs)
<add>
<add> self._vocab_size = vocab_size
<add> self._initializer = initializer
<add> self._num_layers = num_layers
<add> self._hidden_size = hidden_size
<add> self._num_attention_heads = num_attention_heads
<add> self._head_size = head_size
<add> self._inner_size = inner_size
<add> self._inner_activation = inner_activation
<add> self._dropout_rate = dropout_rate
<add> self._attention_dropout_rate = attention_dropout_rate
<add> self._tie_attention_biases = tie_attention_biases
<add> self._two_stream = two_stream
<add>
<add> self._memory_length = memory_length
<add> self._reuse_length = reuse_length
<add>
<add> if self._tie_attention_biases:
<add> attention_bias_shape = [self._num_attention_heads, self._head_size]
<add> else:
<add> attention_bias_shape = [self._num_layers, self._num_attention_heads,
<add> self._head_size]
<add>
<add> self.content_attention_bias = self.add_weight(
<add> "content_attention_bias",
<add> shape=attention_bias_shape,
<add> dtype=tf.float32,
<add> initializer=self._initializer)
<add> self.positional_attention_bias = self.add_weight(
<add> "positional_attention_bias",
<add> shape=attention_bias_shape,
<add> dtype=tf.float32,
<add> initializer=self._initializer)
<add> self.segment_attention_bias = self.add_weight(
<add> "segment_attention_bias",
<add> shape=attention_bias_shape,
<add> dtype=tf.float32,
<add> initializer=self._initializer)
<add>
<add> self.transformer_xl_layers = []
<add> for i in range(self._num_layers):
<add> self.transformer_xl_layers.append(
<add> TransformerXLBlock(
<add> vocab_size=self._vocab_size,
<add> hidden_size=self._head_size * self._num_attention_heads,
<add> num_attention_heads=self._num_attention_heads,
<add> head_size=self._head_size,
<add> inner_size=self._inner_size,
<add> dropout_rate=self._dropout_rate,
<add> attention_dropout_rate=self._attention_dropout_rate,
<add> norm_epsilon=1e-12,
<add> inner_activation=self._inner_activation,
<add> two_stream=self._two_stream,
<add> kernel_initializer="variance_scaling",
<add> name="layer_%d" % i))
<add>
<add> self.output_dropout = tf.keras.layers.Dropout(rate=self._dropout_rate)
<add>
<add> def get_config(self):
<add> config = {
<add> "vocab_size":
<add> self._vocab_size,
<add> "num_layers":
<add> self._num_layers,
<add> "hidden_size":
<add> self._hidden_size,
<add> "num_attention_heads":
<add> self._num_attention_heads,
<add> "head_size":
<add> self._head_size,
<add> "inner_size":
<add> self._inner_size,
<add> "dropout_rate":
<add> self._dropout_rate,
<add> "attention_dropout_rate":
<add> self._attention_dropout_rate,
<add> "initializer":
<add> self._initializer,
<add> "two_stream":
<add> self._two_stream,
<add> "tie_attention_biases":
<add> self._tie_attention_biases,
<add> "memory_length":
<add> self._memory_length,
<add> "reuse_length":
<add> self._reuse_length,
<add> "inner_activation":
<add> self._inner_activation,
<add> }
<add> base_config = super(TransformerXL, self).get_config()
<add> return dict(list(base_config.items()) + list(config.items()))
<add>
<add> def call(self,
<add> content_stream,
<add> relative_position_encoding,
<add> segment_matrix=None,
<add> segment_embedding=None,
<add> state=None,
<add> content_attention_mask=None,
<add> query_stream=None,
<add> query_attention_mask=None,
<add> target_mapping=None):
<add> """Implements call() for the layer.
<add>
<add> Arguments:
<add> content_stream: `Tensor`, the input content stream. This is the standard
<add> input to Transformer XL and is commonly referred to as `h` in XLNet.
<add> relative_position_encoding: Relative positional encoding `Tensor` of shape
<add> `[B, L, dim]`.
<add> segment_matrix: Optional `Tensor` of shape `[B, S, S + M]`. Used in XLNet,
<add> but not in Transformer XL.
<add> segment_embedding: Optional `Tensor` of shape `[2, num_heads, dim]`. Used
<add> in XLNet, but not in Transformer XL.
<add> state: Optional `Tensor` of shape `[B, M, E]`, where M is the length of
<add> the state or memory. If passed, this is also attended over as in
<add> Transformer XL.
<add> content_attention_mask: Optional `Tensor` representing the mask that is
<add> added to content attention logits. If state is not None, the mask source
<add> sequence dimension should extend M.
<add> query_stream: Optional `Tensor`, the query stream. This is introduced in
<add> `TwoStreamRelativeAttention`/XLNet pretrainer. This is ignored if
<add> `two_stream` is `False`.
<add> query_attention_mask: Optional `Tensor` representing the mask that is
<add> added to query attention logits. If state is not None, the mask source
<add> sequence dimension should extend M.
<add> target_mapping: Optional `Tensor` representing the target mapping when
<add> calculating query attention.
<add>
<add> Returns:
<add> A tuple consisting of the attention output and the list of cached memory
<add> states.
<add> The attention output is `content_attention` if `two_stream` is `False`,
<add> otherwise it is `query_attention`.
<add> """
<add> new_mems = []
<add>
<add> if state is None:
<add> state = [None] * self._num_layers
<add> for i in range(self._num_layers):
<add> # cache new mems
<add> new_mems.append(
<add> _cache_memory(content_stream, state[i],
<add> self._memory_length, self._reuse_length))
<add>
<add> # segment bias
<add> if segment_matrix is None:
<add> segment_attention_bias = None
<add> segment_encoding = None
<add> else:
<add> segment_attention_bias = (self.segment_attention_bias
<add> if self._tie_attention_biases
<add> else self.segment_attention_bias[i])
<add> segment_encoding = segment_embedding[i]
<add>
<add> content_attention_bias = (self.content_attention_bias
<add> if self._tie_attention_biases
<add> else self.content_attention_bias[i])
<add> positional_attention_bias = (self.positional_attention_bias
<add> if self._tie_attention_biases
<add> else self.positional_attention_bias[i])
<add> transformer_xl_layer = self.transformer_xl_layers[i]
<add> transformer_xl_output = transformer_xl_layer(
<add> content_stream=content_stream,
<add> content_attention_bias=content_attention_bias,
<add> positional_attention_bias=positional_attention_bias,
<add> relative_position_encoding=relative_position_encoding,
<add> segment_matrix=segment_matrix,
<add> segment_encoding=segment_encoding,
<add> segment_attention_bias=segment_attention_bias,
<add> state=state[i],
<add> content_attention_mask=content_attention_mask,
<add> query_attention_mask=query_attention_mask,
<add> query_stream=query_stream,
<add> target_mapping=target_mapping)
<add> content_stream = transformer_xl_output["content_attention"]
<add> if self._two_stream:
<add> query_stream = transformer_xl_output["query_attention"]
<add> else:
<add> query_stream = None
<add>
<add> if self._two_stream:
<add> output_stream = query_stream
<add> else:
<add> output_stream = content_stream
<add>
<add> return output_stream, new_mems
<ide><path>official/nlp/modeling/layers/transformer_xl_test.py
<ide> def create_mock_transformer_xl_data(
<ide> memory_length=0,
<ide> num_predictions=2,
<ide> two_stream=False,
<add> num_layers=1,
<add> include_biases=True,
<ide> include_state=False,
<ide> include_mask=False,
<ide> include_segment=False):
<ide> def create_mock_transformer_xl_data(
<ide> num_predictions: `int`, the number of predictions used in two stream
<ide> attention.
<ide> two_stream: `bool`, whether or not to generate two stream data.
<add> num_layers: `int`, the number of Transformer XL blocks.
<add> include_biases: optional `bool`, whether or not to include attention biases.
<ide> include_state: optional `bool`, whether or not to include state data.
<ide> include_mask: optional `bool`, whether or not to include mask data.
<ide> include_segment: optional `bool`, whether or not to include segment data.
<ide> def create_mock_transformer_xl_data(
<ide> A dictionary with `str` as keys and `Tensor` as values.
<ide> """
<ide> encoding_shape = (batch_size, seq_length * 2, hidden_size)
<del> attention_bias_shape = (num_heads, head_size)
<ide>
<ide> data = dict(
<del> content_stream=tf.random.normal(
<del> shape=(batch_size, seq_length, hidden_size)),
<ide> relative_position_encoding=tf.random.normal(shape=encoding_shape),
<del> content_attention_bias=tf.random.normal(shape=attention_bias_shape),
<del> positional_attention_bias=tf.random.normal(shape=attention_bias_shape))
<add> content_stream=tf.random.normal(
<add> shape=(batch_size, seq_length, hidden_size)))
<add>
<add> if include_biases:
<add> attention_bias_shape = (num_heads, head_size)
<add> data.update(dict(
<add> content_attention_bias=tf.random.normal(shape=attention_bias_shape),
<add> segment_attention_bias=tf.random.normal(shape=attention_bias_shape),
<add> positional_attention_bias=tf.random.normal(shape=attention_bias_shape)))
<ide>
<ide> if two_stream:
<del> two_stream_data = dict(
<add> data.update(dict(
<ide> query_stream=tf.random.normal(
<ide> shape=(batch_size, num_predictions, hidden_size)),
<ide> target_mapping=tf.random.normal(
<del> shape=(batch_size, num_predictions, seq_length)))
<del> data.update(two_stream_data)
<add> shape=(batch_size, num_predictions, seq_length))))
<ide>
<ide> if include_state:
<ide> total_seq_length = seq_length + memory_length
<del> data["state"] = tf.random.normal(
<del> shape=(batch_size, memory_length, hidden_size))
<add> if num_layers > 1:
<add> state_shape = (num_layers, batch_size, memory_length, hidden_size)
<add> else:
<add> state_shape = (batch_size, memory_length, hidden_size)
<add> data.update(dict(
<add> state=tf.random.normal(shape=state_shape)))
<ide> else:
<ide> total_seq_length = seq_length
<ide>
<ide> def create_mock_transformer_xl_data(
<ide> data["query_attention_mask"] = mask_data
<ide>
<ide> if include_segment:
<del> segment_encoding_shape = (2, num_heads, head_size)
<add> # A transformer XL block takes an individual segment "encoding" from the
<add> # entirety of the Transformer XL segment "embedding".
<add> if num_layers > 1:
<add> segment_encoding_shape = (num_layers, 2, num_heads, head_size)
<add> segment_encoding_name = "segment_embedding"
<add> else:
<add> segment_encoding_shape = (2, num_heads, head_size)
<add> segment_encoding_name = "segment_encoding"
<add>
<ide> segment_matrix = np.random.randint(
<ide> 2, size=(batch_size, seq_length, total_seq_length))
<del> segment_matrix = tf.math.equal(segment_matrix, 1)
<del> segment_data = dict(
<del> segment_attention_bias=tf.random.normal(shape=attention_bias_shape),
<del> segment_encoding=tf.random.normal(shape=segment_encoding_shape),
<del> segment_matrix=segment_matrix)
<del> data.update(segment_data)
<add> data["segment_matrix"] = tf.math.equal(segment_matrix, 1)
<add> data[segment_encoding_name] = tf.random.normal(shape=segment_encoding_shape)
<ide>
<ide> return data
<ide>
<ide> class TransformerXLBlockTest(keras_parameterized.TestCase):
<ide> state=[True, False],
<ide> mask=[True, False],
<ide> segment=[True, False]))
<del> def test_transformer_xl(self,
<del> two_stream,
<del> memory_length,
<del> state,
<del> mask,
<del> segment):
<del> """Tests combinations of Transformer XL calculations."""
<add> def test_transformer_xl_block(
<add> self,
<add> two_stream,
<add> memory_length,
<add> state,
<add> mask,
<add> segment):
<add> """Tests combinations of Transformer XL block calculations."""
<ide> batch_size, num_heads, head_size, seq_length = 2, 12, 64, 8
<ide> hidden_size, num_predictions, inner_size = 24, 8, 12
<ide>
<ide> data = create_mock_transformer_xl_data(
<add> include_biases=True,
<ide> num_heads=num_heads,
<ide> head_size=head_size,
<ide> hidden_size=hidden_size,
<ide> def test_get_config(self):
<ide> self.assertEqual(transformer_xl_block_config, new_block.get_config())
<ide>
<ide>
<add>@keras_parameterized.run_all_keras_modes
<add>class TransformerXLTest(keras_parameterized.TestCase):
<add>
<add> @combinations.generate(combinations.combine(
<add> two_stream=[True, False],
<add> memory_length=[0, 4],
<add> reuse_length=[0, 4],
<add> tie_attention_biases=[True, False],
<add> state=[True, False],
<add> mask=[True, False],
<add> segment=[True, False]))
<add> def test_transformer_xl(
<add> self,
<add> two_stream,
<add> memory_length,
<add> reuse_length,
<add> tie_attention_biases,
<add> state,
<add> mask,
<add> segment):
<add> batch_size, num_heads, head_size, seq_length = 2, 12, 64, 8
<add> hidden_size, num_predictions, inner_size = 24, 8, 12
<add> num_layers = 3
<add>
<add> data = create_mock_transformer_xl_data(
<add> include_biases=False,
<add> num_heads=num_heads,
<add> head_size=head_size,
<add> hidden_size=hidden_size,
<add> seq_length=seq_length,
<add> batch_size=batch_size,
<add> memory_length=memory_length,
<add> num_predictions=num_predictions,
<add> two_stream=two_stream,
<add> num_layers=num_layers,
<add> include_state=state,
<add> include_mask=mask,
<add> include_segment=segment)
<add> transformer_xl_layer = transformer_xl.TransformerXL(
<add> vocab_size=32000,
<add> num_layers=num_layers,
<add> head_size=head_size,
<add> hidden_size=hidden_size,
<add> num_attention_heads=num_heads,
<add> inner_size=inner_size,
<add> dropout_rate=0.,
<add> attention_dropout_rate=0.,
<add> initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
<add> two_stream=two_stream,
<add> tie_attention_biases=tie_attention_biases,
<add> memory_length=memory_length,
<add> reuse_length=reuse_length,
<add> inner_activation="relu")
<add> attention_output, cached_memory_states = transformer_xl_layer(**data)
<add> if two_stream:
<add> self.assertEqual(attention_output.shape,
<add> [batch_size, num_predictions, hidden_size])
<add> else:
<add> self.assertEqual(attention_output.shape,
<add> [batch_size, seq_length, hidden_size])
<add> self.assertEqual(len(cached_memory_states), num_layers)
<add>
<add> def test_get_config(self):
<add> transformer_xl_layer = transformer_xl.TransformerXL(
<add> vocab_size=32000,
<add> num_layers=12,
<add> hidden_size=36,
<add> head_size=12,
<add> num_attention_heads=12,
<add> inner_size=12,
<add> dropout_rate=0.,
<add> attention_dropout_rate=0.,
<add> initializer=tf.keras.initializers.RandomNormal(stddev=0.1),
<add> two_stream=False,
<add> tie_attention_biases=True,
<add> memory_length=0,
<add> reuse_length=0,
<add> inner_activation="relu")
<add> transformer_xl_config = transformer_xl_layer.get_config()
<add> new_transformer_xl = transformer_xl.TransformerXL.from_config(
<add> transformer_xl_config)
<add> self.assertEqual(transformer_xl_config, new_transformer_xl.get_config())
<add>
<add>
<ide> if __name__ == "__main__":
<ide> np.random.seed(0)
<ide> tf.random.set_seed(0) | 4 |
Text | Text | update translation binary-search | 1cc626e546f8c99ad142ed0c515fc5a84b184c3b | <ide><path>guide/portuguese/algorithms/search-algorithms/binary-search/index.md
<ide> para pequenos conjuntos, a pesquisa linear é melhor, mas em grandes, é muito m
<ide>
<ide> Em detalhes, quantas vezes você pode dividir N por 2 até ter 1? Essencialmente, isso significa fazer uma pesquisa binária (metade dos elementos) até encontrá-la. Em uma fórmula, isso seria:
<ide> ```
<del>1 = N / 2x
<add>1 = N / 2^x
<ide> ```
<ide>
<ide> Multiplique por 2x:
<ide> ```
<del>2x = N
<add>2^x = N
<ide> ```
<ide>
<ide> Agora faça o log2:
<ide> ```
<del>log2(2x) = log2 N
<del> x * log2(2) = log2 N
<del> x * 1 = log2 N
<add>log2(2^x) = log2 N
<add>x * log2(2) = log2 N
<add>x * 1 = log2 N
<ide> ```
<ide>
<ide> Isso significa que você pode dividir o log N vezes até que você tenha tudo dividido. O que significa que você tem que dividir o log N ("faça a etapa de busca binária") até encontrar seu elemento.
<ide> def binary_search(arr, l, r, target):
<ide> return -1
<ide> ```
<ide>
<del>### Exemplo em C ++
<add>### Exemplo em C++
<add>
<add>Abordagem recursiva!
<ide>
<ide> ```cpp
<ide> // Binary Search using iteration
<ide> def binary_search(arr, l, r, target):
<ide> }
<ide> ```
<ide>
<add>Abordagem recursiva!
<add>
<ide> ```cpp
<ide> // Binary Search using recursion
<ide> int binary_search(int arr[], int beg, int end, int num)
<ide> def binary_search(arr, l, r, target):
<ide> ```
<ide>
<ide> ### Exemplo em C ++
<del>
<ide> Abordagem recursiva!
<ide>
<del>\`\` \`C ++ - abordagem recursiva int binarySearch (int arr \[\], int início, int fim, int x) { if (end> = start) { int mid = start + (end - start) / 2; if (arr \[meio\] == x)
<del>retorno no meio;
<add>```cpp
<add>int binarySearch(int arr[], int start, int end, int x)
<add>{
<add> if (end >= start)
<add> {
<add> int mid = (start + (end - start))/2;
<add> if (arr[mid] == x)
<add> return mid;
<add>
<add> if (arr[mid] > x)
<add> return binarySearch(arr, start, mid-1, x);
<add>
<add> return binarySearch(arr, mid+1, end, x);
<add> }
<add> return -1;
<add>}
<ide> ```
<del> if (arr[mid] > x)
<del> return binarySearch(arr, start, mid-1, x);
<del>
<del> return binarySearch(arr, mid+1, end, x);
<add>
<add>Abordagem iterativa!
<add>
<add>```cpp
<add>int binarySearch(int arr[], int start, int end, int x)
<add>{
<add> while (start <= end)
<add> {
<add> int mid = (start + (end - start))/2;
<add> if (arr[mid] == x)
<add> return mid;
<add> if (arr[mid] < x)
<add> start = mid + 1;
<add> else
<add> end = mid - 1;
<add> }
<add> return -1;
<add>}
<ide> ```
<ide>
<del>} return -1; }
<add>### Example in Swift
<add>
<add>```Swift
<add>func binarySearch(for number: Int, in numbers: [Int]) -> Int? {
<add> var lowerBound = 0
<add> var upperBound = numbers.count
<add> while lowerBound < upperBound {
<add> let index = lowerBound + (upperBound - lowerBound) / 2
<add> if numbers[index] == number {
<add> return index // we found the given number at this index
<add> } else if numbers[index] < number {
<add> lowerBound = index + 1
<add> } else {
<add> upperBound = index
<add> }
<add> }
<add> return nil // the given number was not found
<add>}
<ide> ```
<del>Iterative approach!
<add>
<add>### Example in Java
<add>
<add>```Java
<add>// Iterative Approach in Java
<add>int binarySearch(int[] arr, int start, int end, int element)
<add>{
<add> while(start <= end)
<add> {
<add> int mid = start + ( end - start ) / 2;
<add> if(arr[mid] == element)
<add> return mid;
<add> if(arr[mid] < element)
<add> start = mid+1;
<add> else
<add> end = mid-1;
<add> }
<add> return -1;
<add>}
<ide> ```
<add>```Java
<add>// Recursive Approach in Java
<add>int binarySearch(int[] arr, int start,int end , int element)
<add>{
<add> if (end >= start)
<add> {
<add> int mid = start + ( end - start ) / 2;
<add> if(arr[mid] == element)
<add> return mid;
<add> if(arr[mid] < element)
<add> return binarySearch( arr , mid + 1 , end , element );
<add> else
<add> return binarySearch( arr, start, mid - 1 , element);
<add> }
<add> return -1;
<add>}
<ide>
<del>C ++ - abordagem iterativa int binarySearch (int arr \[\], int início, int fim, int x) { while (início <= fim) { int mid = start + (end - start) / 2; if (arr \[meio\] == x) retorno no meio; if (arr \[mid\] <x) start = mid + 1; outro end = mid - 1; } return -1; } \`\` \`
<add>```
<ide>
<ide> ### Mais Informações
<ide>
<del>* [Pesquisa binária (vídeo do YouTube)](https://youtu.be/P3YID7liBug)
<del>* [Pesquisa binária - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)
<ide>\ No newline at end of file
<add>* [Pesquisa binária (vídeo do YouTube)](https://youtu.be/P3YID7liBug)
<add>* [Pesquisa binária - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)
<add>* [Binary Search - MyCodeSchool](https://www.youtube.com/watch?v=j5uXyPJ0Pew&list=PL2_aWCzGMAwL3ldWlrii6YeLszojgH77j) | 1 |
Javascript | Javascript | reduce element.point size | 09bcac9b5c699c75909b77dc40dc40b5a3af1030 | <ide><path>src/elements/element.point.js
<ide> module.exports = function(Chart) {
<ide> var radius = vm.radius;
<ide>
<ide> var xOffset,
<del> yOffset;
<add> yOffset,
<add> beginPath = "beginPath",
<add> moveTo = "moveTo",
<add> lineTo = "lineTo",
<add> closePath = "closePath",
<add> fillRect = "fillRect",
<add> strokeRect = "strokeRect";
<ide>
<ide> switch (pointStyle) {
<ide> // Default includes circle
<ide> default:
<del> ctx.beginPath();
<add> ctx[beginPath]();
<ide> ctx.arc(x, y, radius, 0, Math.PI * 2);
<del> ctx.closePath();
<add> ctx[closePath]();
<ide> ctx.fill();
<ide> break;
<ide> case 'triangle':
<del> ctx.beginPath();
<add> ctx[beginPath]();
<ide> var edgeLength = 3 * radius / Math.sqrt(3);
<ide> var height = edgeLength * Math.sqrt(3) / 2;
<del> ctx.moveTo(x - edgeLength / 2, y + height / 3);
<del> ctx.lineTo(x + edgeLength / 2, y + height / 3);
<del> ctx.lineTo(x, y - 2 * height / 3);
<del> ctx.closePath();
<add> ctx[moveTo](x - edgeLength / 2, y + height / 3);
<add> ctx[lineTo](x + edgeLength / 2, y + height / 3);
<add> ctx[lineTo](x, y - 2 * height / 3);
<add> ctx[closePath]();
<ide> ctx.fill();
<ide> break;
<ide> case 'rect':
<del> ctx.fillRect(x - 1 / Math.SQRT2 * radius, y - 1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<del> ctx.strokeRect(x - 1 / Math.SQRT2 * radius, y - 1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<add> ctx[fillRect](x - 1 / Math.SQRT2 * radius, y - 1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<add> ctx[strokeRect](x - 1 / Math.SQRT2 * radius, y - 1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<ide> break;
<ide> case 'rectRot':
<ide> ctx.translate(x, y);
<ide> ctx.rotate(Math.PI / 4);
<del> ctx.fillRect(-1 / Math.SQRT2 * radius, -1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<del> ctx.strokeRect(-1 / Math.SQRT2 * radius, -1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<add> ctx[fillRect](-1 / Math.SQRT2 * radius, -1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<add> ctx[strokeRect](-1 / Math.SQRT2 * radius, -1 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius, 2 / Math.SQRT2 * radius);
<ide> ctx.setTransform(1, 0, 0, 1, 0, 0);
<ide> break;
<ide> case 'cross':
<del> ctx.beginPath();
<del> ctx.moveTo(x, y + radius);
<del> ctx.lineTo(x, y - radius);
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<del> ctx.closePath();
<add> ctx[beginPath]();
<add> ctx[moveTo](x, y + radius);
<add> ctx[lineTo](x, y - radius);
<add> ctx[moveTo](x - radius, y);
<add> ctx[lineTo](x + radius, y);
<add> ctx[closePath]();
<ide> break;
<ide> case 'crossRot':
<del> ctx.beginPath();
<add> ctx[beginPath]();
<ide> xOffset = Math.cos(Math.PI / 4) * radius;
<ide> yOffset = Math.sin(Math.PI / 4) * radius;
<del> ctx.moveTo(x - xOffset, y - yOffset);
<del> ctx.lineTo(x + xOffset, y + yOffset);
<del> ctx.moveTo(x - xOffset, y + yOffset);
<del> ctx.lineTo(x + xOffset, y - yOffset);
<del> ctx.closePath();
<add> ctx[moveTo](x - xOffset, y - yOffset);
<add> ctx[lineTo](x + xOffset, y + yOffset);
<add> ctx[moveTo](x - xOffset, y + yOffset);
<add> ctx[lineTo](x + xOffset, y - yOffset);
<add> ctx[closePath]();
<ide> break;
<ide> case 'star':
<del> ctx.beginPath();
<del> ctx.moveTo(x, y + radius);
<del> ctx.lineTo(x, y - radius);
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<add> ctx[beginPath]();
<add> ctx[moveTo](x, y + radius);
<add> ctx[lineTo](x, y - radius);
<add> ctx[moveTo](x - radius, y);
<add> ctx[lineTo](x + radius, y);
<ide> xOffset = Math.cos(Math.PI / 4) * radius;
<ide> yOffset = Math.sin(Math.PI / 4) * radius;
<del> ctx.moveTo(x - xOffset, y - yOffset);
<del> ctx.lineTo(x + xOffset, y + yOffset);
<del> ctx.moveTo(x - xOffset, y + yOffset);
<del> ctx.lineTo(x + xOffset, y - yOffset);
<del> ctx.closePath();
<add> ctx[moveTo](x - xOffset, y - yOffset);
<add> ctx[lineTo](x + xOffset, y + yOffset);
<add> ctx[moveTo](x - xOffset, y + yOffset);
<add> ctx[lineTo](x + xOffset, y - yOffset);
<add> ctx[closePath]();
<ide> break;
<ide> case 'line':
<del> ctx.beginPath();
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<del> ctx.closePath();
<add> ctx[beginPath]();
<add> ctx[moveTo](x - radius, y);
<add> ctx[lineTo](x + radius, y);
<add> ctx[closePath]();
<ide> break;
<ide> case 'dash':
<del> ctx.beginPath();
<del> ctx.moveTo(x, y);
<del> ctx.lineTo(x + radius, y);
<del> ctx.closePath();
<add> ctx[beginPath]();
<add> ctx[moveTo](x, y);
<add> ctx[lineTo](x + radius, y);
<add> ctx[closePath]();
<ide> break;
<ide> }
<ide> | 1 |
Javascript | Javascript | fix more nits | 9d3c91b150eec9dd56ccfad85c354eb9b5d5af52 | <ide><path>src/config.js
<ide> class Config {
<ide> }
<ide>
<ide> _clearUnscopedSettingsForSource (source) {
<del> switch (source) {
<del> case (this.projectFile):
<del> this.projectSettings = {}
<del> return
<del> default:
<del> this.settings = {}
<add> if (source === this.projectFile) {
<add> this.projectSettings = {}
<add> } else {
<add> this.settings = {}
<ide> }
<ide> }
<ide>
<ide> class Config {
<ide> value = getValueAtKeyPath(this.settings, keyPath)
<ide> if (this.projectFile != null) {
<ide> const projectValue = getValueAtKeyPath(this.projectSettings, keyPath)
<del> value = projectValue || value
<add> value = (projectValue === undefined) ? value : projectValue
<ide> }
<ide> }
<ide>
<ide><path>src/main-process/parse-command-line.js
<ide> module.exports = function parseCommandLine (processArgs) {
<ide>
<ide> let projectSpecification = {}
<ide> if (projectSpecificationFile) {
<del> const contents = Object.assign({}, readProjectSpecificationSync(projectSpecificationFile, executedFrom))
<del> const config = contents.config
<del> const originPath = projectSpecificationFile
<add> const readPath = path.isAbsolute(projectSpecificationFile)
<add> ? projectSpecificationFile
<add> : path.join(executedFrom, projectSpecificationFile)
<add>
<add> const contents = Object.assign({}, readProjectSpecificationSync(readPath, executedFrom))
<ide> const pathToProjectFile = path.join(executedFrom, projectSpecificationFile)
<ide> const base = path.dirname(pathToProjectFile)
<del> const paths = contents.paths.map(curPath => path.resolve(base, curPath))
<ide> pathsToOpen.push(path.dirname(projectSpecificationFile))
<del> projectSpecification = { originPath, paths, config }
<add> projectSpecification = {
<add> originPath: projectSpecificationFile,
<add> paths: contents.paths.map(curPath => path.resolve(base, curPath)),
<add> config: contents.config
<add> }
<ide> }
<ide>
<ide> if (devMode) {
<ide> module.exports = function parseCommandLine (processArgs) {
<ide>
<ide> function readProjectSpecificationSync (filepath, executedFrom) {
<ide> try {
<del> const readPath = path.isAbsolute(filepath) ? filepath : path.join(executedFrom, filepath)
<ide> const contents = CSON.readFileSync(readPath)
<add> } catch (e) {
<add> throw new Error('Unable to read supplied project specification file.')
<add> }
<ide>
<del> if (contents.paths == null) {
<del> contents.paths = [path.dirname(readPath)]
<del> }
<del> if (contents.config) {
<del> return contents
<del> }
<del> } catch (e) {}
<del> const errorMessage = 'Unable to read supplied project specification file. This file must have a valid array of paths, as well as a valid config object.'
<del> throw new Error(errorMessage)
<add> if (contents.paths == null) {
<add> contents.paths = [path.dirname(readPath)]
<add> }
<add> return (contents.config == null) ? {} : contents
<ide> }
<ide>
<ide> function normalizeDriveLetterName (filePath) { | 2 |
Python | Python | assert prints for more clarity | b20351792acba1bcd28998bed80171f5b6caa59f | <ide><path>spacy/tests/test_requirements.py
<ide> def test_build_dependencies(en_vocab):
<ide> lib, v = _parse_req(line)
<ide> if lib and not lib.startswith("cupy") and lib not in libs_ignore_setup:
<ide> req_v = req_dict.get(lib, None)
<del> assert req_v is not None # if fail: setup.cfg contains a lib not in requirements.txt
<del> assert (lib+v) == (lib+req_v) # if fail: setup.cfg & requirements.txt have conflicting versions
<add> assert req_v is not None, "{} in setup.cfg but not in requirements.txt".format(lib)
<add> assert (lib+v) == (lib+req_v), "{} has different version in setup.cfg and in requirements.txt: " \
<add> "{} and {} respectively".format(lib, v, req_v)
<ide> setup_keys.add(lib)
<ide> assert sorted(setup_keys) == sorted(req_dict.keys()) # if fail: requirements.txt contains a lib not in setup.cfg
<ide>
<ide> def test_build_dependencies(en_vocab):
<ide> lib, v = _parse_req(line)
<ide> if lib:
<ide> req_v = req_dict.get(lib, None)
<del> assert (lib+v) == (lib+req_v) # if fail: pyproject.toml & requirements.txt have conflicting versions
<add> assert (lib+v) == (lib+req_v), "{} has different version in pyproject.toml and in requirements.txt: " \
<add> "{} and {} respectively".format(lib, v, req_v)
<ide>
<ide>
<ide> def _parse_req(line): | 1 |
Java | Java | improve documentation of @bean 'lite' mode | 94c9f96449960a94e49edd7709d49b243de4a5f1 | <ide><path>spring-context/src/main/java/org/springframework/context/annotation/Bean.java
<ide> /**
<ide> * Indicates that a method produces a bean to be managed by the Spring container.
<ide> *
<add> * <h3>Overview</h3>
<add> *
<ide> * <p>The names and semantics of the attributes to this annotation are intentionally
<ide> * similar to those of the {@code <bean/>} element in the Spring XML schema. For
<ide> * example:
<ide> * return obj;
<ide> * }</pre>
<ide> *
<del> * <h3>Scope, Primary, and Lazy</h3>
<add> * <h3>Scope, DependsOn, Primary, and Lazy</h3>
<ide> *
<ide> * <p>Note that the {@code @Bean} annotation does not provide attributes for scope,
<del> * primary, or lazy. Rather, it should be used in conjunction with {@link Scope @Scope},
<del> * {@link Primary @Primary}, and {@link Lazy @Lazy} annotations to achieve those
<del> * semantics. For example:
<add> * depends-on, primary, or lazy. Rather, it should be used in conjunction with
<add> * {@link Scope @Scope}, {@link DependsOn @DependsOn}, {@link Primary @Primary},
<add> * and {@link Lazy @Lazy} annotations to achieve those semantics. For example:
<ide> *
<ide> * <pre class="code">
<ide> * @Bean
<ide> * // ...
<ide> * }</pre>
<ide> *
<del> * <h3>Configuration Class <i>Lite</i> Mode</h3>
<add> * <h3>{@code @Bean} <em>Lite</em> Mode</h3>
<add> *
<add> * <p>{@code @Bean} methods may also be declared within classes that are <em>not</em>
<add> * annotated with {@code @Configuration}. For example, bean methods may be declared
<add> * in a {@code @Component} class or even in a <em>plain old class</em>. In such cases,
<add> * a {@code @Bean} method will get processed in a configuration class <em>'lite'</em>
<add> * mode.
<ide> *
<del> * <p>{@code @Bean} methods may also be declared within any {@code @Component} class, in
<del> * which case they will get processed in a configuration class <em>'lite'</em> mode in which
<del> * they will simply be called as plain factory methods from the container (similar to
<del> * {@code factory-method} declarations in XML) but with <b><i>prototype</i></b> semantics.
<del> * The containing component classes remain unmodified in this case, and there are no
<del> * unusual constraints for factory methods; however, scoping semantics are <b>not</b>
<del> * respected as described above for inter-bean method invocations in this mode. For example:
<add> * <p>In contrast to bean methods in {@code @Configuration} classes as described
<add> * above, bean methods in <em>lite</em> mode will be called as plain <em>factory
<add> * methods</em> from the container (similar to {@code factory-method} declarations
<add> * in XML) but with <b><em>prototype</em></b> semantics. The containing class remains
<add> * unmodified in this case, and there are no unusual constraints for factory methods;
<add> * however, scoping semantics are <b>not</b> respected as described above for
<add> * 'inter-bean method invocations in this mode. For example:
<ide> *
<ide> * <pre class="code">
<ide> * @Component
<ide> */
<ide> String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
<ide>
<del>}
<add>}
<ide>\ No newline at end of file | 1 |
Go | Go | adjust deprecation comments | 0f1b68df1610e0b377f16cd0cf72e226ade1dce5 | <ide><path>pkg/fileutils/fileutils.go
<ide> func NewPatternMatcher(patterns []string) (*PatternMatcher, error) {
<ide> //
<ide> // Matches is not safe to call concurrently.
<ide> //
<del>// This implementation is buggy (it only checks a single parent dir against the
<del>// pattern) and will be removed soon. Use either MatchesOrParentMatches or
<del>// MatchesUsingParentResult instead.
<add>// Deprecated: This implementation is buggy (it only checks a single parent dir
<add>// against the pattern) and will be removed soon. Use either
<add>// MatchesOrParentMatches or MatchesUsingParentResults instead.
<ide> func (pm *PatternMatcher) Matches(file string) (bool, error) {
<ide> matched := false
<ide> file = filepath.FromSlash(file)
<ide> func (pm *PatternMatcher) MatchesOrParentMatches(file string) (bool, error) {
<ide> //
<ide> // MatchesUsingParentResult is not safe to call concurrently.
<ide> //
<del>// Deprecated in favor of MatchesUsingParentResults: this function does behave
<del>// correctly in some cases (see https://github.com/docker/buildx/issues/850).
<add>// Deprecated: this function does behave correctly in some cases (see
<add>// https://github.com/docker/buildx/issues/850).
<add>//
<add>// Use MatchesUsingParentResults instead.
<ide> func (pm *PatternMatcher) MatchesUsingParentResult(file string, parentMatched bool) (bool, error) {
<ide> matched := parentMatched
<ide> file = filepath.FromSlash(file) | 1 |
Java | Java | replace use of stringbuffer with stringbuilder | 948f5999c3dc8bc82c7b0476954a08fe9ed2011c | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private static String expand(String route, Object... routeVars) {
<ide> if (ObjectUtils.isEmpty(routeVars)) {
<ide> return route;
<ide> }
<del> StringBuffer sb = new StringBuffer();
<add> StringBuilder sb = new StringBuilder();
<ide> int index = 0;
<ide> Matcher matcher = VARS_PATTERN.matcher(route);
<ide> while (matcher.find()) {
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponents.java
<ide> static String expandUriComponent(@Nullable String source, UriTemplateVariables u
<ide> source = sanitizeSource(source);
<ide> }
<ide> Matcher matcher = NAMES_PATTERN.matcher(source);
<del> StringBuffer sb = new StringBuffer();
<add> StringBuilder sb = new StringBuilder();
<ide> while (matcher.find()) {
<ide> String match = matcher.group(1);
<ide> String varName = getVariableName(match); | 2 |
Java | Java | expose handled exception as request attribute | 476864f3e91411b1f75c8777154c7d118341a6e3 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
<ide> public class DispatcherServlet extends FrameworkServlet {
<ide> */
<ide> public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";
<ide>
<add> /**
<add> * Name of request attribute that exposes an Exception resolved with an
<add> * {@link HandlerExceptionResolver} but where no view was rendered
<add> * (e.g. setting the status code).
<add> */
<add> public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION";
<add>
<ide> /** Log category to use when no mapped handler is found for a request. */
<ide> public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
<ide>
<ide> protected ModelAndView processHandlerException(HttpServletRequest request, HttpS
<ide> }
<ide> if (exMv != null) {
<ide> if (exMv.isEmpty()) {
<add> request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
<ide> return null;
<ide> }
<ide> // We might still need view name translation for a plain error model... | 1 |
Javascript | Javascript | remove keymirror in specpolicy | e3b2c6e650d80bfcfd32eb47354eb269269f77c8 | <ide><path>src/isomorphic/classic/class/ReactClass.js
<ide> var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
<ide>
<ide> var emptyObject = require('emptyObject');
<ide> var invariant = require('invariant');
<del>var keyMirror = require('keyMirror');
<ide> var keyOf = require('keyOf');
<ide> var warning = require('warning');
<ide>
<ide> var MIXINS_KEY = keyOf({mixins: null});
<ide> /**
<ide> * Policies that describe methods in `ReactClassInterface`.
<ide> */
<del>var SpecPolicy = keyMirror({
<add>type SpecPolicy =
<ide> /**
<ide> * These methods may be defined only once by the class specification or mixin.
<ide> */
<del> DEFINE_ONCE: null,
<add> 'DEFINE_ONCE' |
<ide> /**
<ide> * These methods may be defined by both the class specification and mixins.
<ide> * Subsequent definitions will be chained. These methods must return void.
<ide> */
<del> DEFINE_MANY: null,
<add> 'DEFINE_MANY' |
<ide> /**
<ide> * These methods are overriding the base class.
<ide> */
<del> OVERRIDE_BASE: null,
<add> 'OVERRIDE_BASE' |
<ide> /**
<ide> * These methods are similar to DEFINE_MANY, except we assume they return
<ide> * objects. We try to merge the keys of the return values of all the mixed in
<ide> * functions. If there is a key conflict we throw.
<ide> */
<del> DEFINE_MANY_MERGED: null,
<del>});
<add> 'DEFINE_MANY_MERGED';
<ide>
<ide>
<ide> /**
<ide> var SpecPolicy = keyMirror({
<ide> * @interface ReactClassInterface
<ide> * @internal
<ide> */
<del>var ReactClassInterface = {
<add>var ReactClassInterface: {[key: string]: SpecPolicy} = {
<ide>
<ide> /**
<ide> * An array of Mixin objects to include when defining your component.
<ide> *
<ide> * @type {array}
<ide> * @optional
<ide> */
<del> mixins: SpecPolicy.DEFINE_MANY,
<add> mixins: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * An object containing properties and methods that should be defined on
<ide> var ReactClassInterface = {
<ide> * @type {object}
<ide> * @optional
<ide> */
<del> statics: SpecPolicy.DEFINE_MANY,
<add> statics: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Definition of prop types for this component.
<ide> *
<ide> * @type {object}
<ide> * @optional
<ide> */
<del> propTypes: SpecPolicy.DEFINE_MANY,
<add> propTypes: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Definition of context types for this component.
<ide> *
<ide> * @type {object}
<ide> * @optional
<ide> */
<del> contextTypes: SpecPolicy.DEFINE_MANY,
<add> contextTypes: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Definition of context types this component sets for its children.
<ide> *
<ide> * @type {object}
<ide> * @optional
<ide> */
<del> childContextTypes: SpecPolicy.DEFINE_MANY,
<add> childContextTypes: 'DEFINE_MANY',
<ide>
<ide> // ==== Definition methods ====
<ide>
<ide> var ReactClassInterface = {
<ide> * @return {object}
<ide> * @optional
<ide> */
<del> getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
<add> getDefaultProps: 'DEFINE_MANY_MERGED',
<ide>
<ide> /**
<ide> * Invoked once before the component is mounted. The return value will be used
<ide> var ReactClassInterface = {
<ide> * @return {object}
<ide> * @optional
<ide> */
<del> getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
<add> getInitialState: 'DEFINE_MANY_MERGED',
<ide>
<ide> /**
<ide> * @return {object}
<ide> * @optional
<ide> */
<del> getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
<add> getChildContext: 'DEFINE_MANY_MERGED',
<ide>
<ide> /**
<ide> * Uses props from `this.props` and state from `this.state` to render the
<ide> var ReactClassInterface = {
<ide> * @nosideeffects
<ide> * @required
<ide> */
<del> render: SpecPolicy.DEFINE_ONCE,
<add> render: 'DEFINE_ONCE',
<ide>
<ide>
<ide>
<ide> var ReactClassInterface = {
<ide> *
<ide> * @optional
<ide> */
<del> componentWillMount: SpecPolicy.DEFINE_MANY,
<add> componentWillMount: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Invoked when the component has been mounted and has a DOM representation.
<ide> var ReactClassInterface = {
<ide> * @param {DOMElement} rootNode DOM element representing the component.
<ide> * @optional
<ide> */
<del> componentDidMount: SpecPolicy.DEFINE_MANY,
<add> componentDidMount: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Invoked before the component receives new props.
<ide> var ReactClassInterface = {
<ide> * @param {object} nextProps
<ide> * @optional
<ide> */
<del> componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
<add> componentWillReceiveProps: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Invoked while deciding if the component should be updated as a result of
<ide> var ReactClassInterface = {
<ide> * @return {boolean} True if the component should update.
<ide> * @optional
<ide> */
<del> shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
<add> shouldComponentUpdate: 'DEFINE_ONCE',
<ide>
<ide> /**
<ide> * Invoked when the component is about to update due to a transition from
<ide> var ReactClassInterface = {
<ide> * @param {ReactReconcileTransaction} transaction
<ide> * @optional
<ide> */
<del> componentWillUpdate: SpecPolicy.DEFINE_MANY,
<add> componentWillUpdate: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Invoked when the component's DOM representation has been updated.
<ide> var ReactClassInterface = {
<ide> * @param {DOMElement} rootNode DOM element representing the component.
<ide> * @optional
<ide> */
<del> componentDidUpdate: SpecPolicy.DEFINE_MANY,
<add> componentDidUpdate: 'DEFINE_MANY',
<ide>
<ide> /**
<ide> * Invoked when the component is about to be removed from its parent and have
<ide> var ReactClassInterface = {
<ide> *
<ide> * @optional
<ide> */
<del> componentWillUnmount: SpecPolicy.DEFINE_MANY,
<add> componentWillUnmount: 'DEFINE_MANY',
<ide>
<ide>
<ide>
<ide> var ReactClassInterface = {
<ide> * @internal
<ide> * @overridable
<ide> */
<del> updateComponent: SpecPolicy.OVERRIDE_BASE,
<add> updateComponent: 'OVERRIDE_BASE',
<ide>
<ide> };
<ide>
<ide> function validateMethodOverride(isAlreadyDefined, name) {
<ide> // Disallow overriding of base class methods unless explicitly allowed.
<ide> if (ReactClassMixin.hasOwnProperty(name)) {
<ide> invariant(
<del> specPolicy === SpecPolicy.OVERRIDE_BASE,
<add> specPolicy === 'OVERRIDE_BASE',
<ide> 'ReactClassInterface: You are attempting to override ' +
<ide> '`%s` from your class specification. Ensure that your method names ' +
<ide> 'do not overlap with React methods.',
<ide> function validateMethodOverride(isAlreadyDefined, name) {
<ide> // Disallow defining methods more than once unless explicitly allowed.
<ide> if (isAlreadyDefined) {
<ide> invariant(
<del> specPolicy === SpecPolicy.DEFINE_MANY ||
<del> specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
<add> specPolicy === 'DEFINE_MANY' ||
<add> specPolicy === 'DEFINE_MANY_MERGED',
<ide> 'ReactClassInterface: You are attempting to define ' +
<ide> '`%s` on your component more than once. This conflict may be due ' +
<ide> 'to a mixin.',
<ide> function mixSpecIntoComponent(Constructor, spec) {
<ide> // These cases should already be caught by validateMethodOverride.
<ide> invariant(
<ide> isReactClassMethod && (
<del> specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
<del> specPolicy === SpecPolicy.DEFINE_MANY
<add> specPolicy === 'DEFINE_MANY_MERGED' ||
<add> specPolicy === 'DEFINE_MANY'
<ide> ),
<ide> 'ReactClass: Unexpected spec policy %s for key %s ' +
<ide> 'when mixing in component specs.',
<ide> function mixSpecIntoComponent(Constructor, spec) {
<ide>
<ide> // For methods which are defined more than once, call the existing
<ide> // methods before calling the new property, merging if appropriate.
<del> if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
<add> if (specPolicy === 'DEFINE_MANY_MERGED') {
<ide> proto[name] = createMergedResultFunction(proto[name], property);
<del> } else if (specPolicy === SpecPolicy.DEFINE_MANY) {
<add> } else if (specPolicy === 'DEFINE_MANY') {
<ide> proto[name] = createChainedFunction(proto[name], property);
<ide> }
<ide> } else { | 1 |
Go | Go | fix race on containerattachraw | 32ca1214fa55f55c54a54061ecf752b75f2c72c3 | <ide><path>builder/builder.go
<ide> type Backend interface {
<ide> // PullOnBuild tells Docker to pull image referenced by `name`.
<ide> PullOnBuild(ctx context.Context, name string, authConfigs map[string]types.AuthConfig, output io.Writer) (Image, error)
<ide> // ContainerAttachRaw attaches to container.
<del> ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error
<add> ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool, attached chan struct{}) error
<ide> // ContainerCreate creates a new Docker container and returns potential warnings
<ide> ContainerCreate(config types.ContainerCreateConfig) (container.ContainerCreateCreatedBody, error)
<ide> // ContainerRm removes a container specified by `id`.
<ide><path>builder/dockerfile/internals.go
<ide> func (b *Builder) create() (string, error) {
<ide> var errCancelled = errors.New("build cancelled")
<ide>
<ide> func (b *Builder) run(cID string) (err error) {
<add> attached := make(chan struct{})
<ide> errCh := make(chan error)
<ide> go func() {
<del> errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true)
<add> errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true, attached)
<ide> }()
<ide>
<add> select {
<add> case err := <-errCh:
<add> return err
<add> case <-attached:
<add> }
<add>
<ide> finished := make(chan struct{})
<ide> cancelErrCh := make(chan error, 1)
<ide> go func() {
<ide><path>builder/dockerfile/mockbackend_test.go
<ide> func (m *MockBackend) PullOnBuild(ctx context.Context, name string, authConfigs
<ide> return nil, nil
<ide> }
<ide>
<del>func (m *MockBackend) ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error {
<add>func (m *MockBackend) ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool, attached chan struct{}) error {
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/attach.go
<ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerA
<ide> }
<ide>
<ide> // ContainerAttachRaw attaches the provided streams to the container's stdio
<del>func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadCloser, stdout, stderr io.Writer, doStream bool) error {
<add>func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadCloser, stdout, stderr io.Writer, doStream bool, attached chan struct{}) error {
<ide> container, err := daemon.GetContainer(prefixOrName)
<ide> if err != nil {
<ide> return err
<ide> func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadClose
<ide> CloseStdin: container.Config.StdinOnce,
<ide> }
<ide> container.StreamConfig.AttachStreams(&cfg)
<add> close(attached)
<ide> if cfg.UseStdin {
<ide> cfg.Stdin = stdin
<ide> } | 4 |
PHP | PHP | remove the crossschematableexpression | b5787a0979e161204d833c66053b7516ebf7f146 | <ide><path>src/Database/Connection.php
<ide> public function log($sql)
<ide> $this->logger()->log($query);
<ide> }
<ide>
<del> /**
<del> * Check if cross talk is supported between two connections
<del> *
<del> * @param ConnectionInterface $target Connection to check cross talk with
<del> *
<del> * @return bool
<del> */
<del> public function supportsCrossWith(ConnectionInterface $target)
<del> {
<del> $sourceConfig = $this->config();
<del> $targetConfig = $target->config();
<del>
<del> // No need to do report cross support in case the same connection is being used
<del> if ($sourceConfig['name'] === $targetConfig['name']) {
<del> return false;
<del> }
<del>
<del> $configToCheck = [
<del> 'driver',
<del> 'host',
<del> 'port'
<del> ];
<del>
<del> foreach ($configToCheck as $config) {
<del> if ((isset($sourceConfig[$config])) && ($sourceConfig[$config] !== $targetConfig[$config])) {
<del> return false;
<del> }
<del> }
<del>
<del> return true;
<del> }
<del>
<ide> /**
<ide> * Returns a new statement object that will log the activity
<ide> * for the passed original statement instance.
<ide><path>src/Database/Expression/CrossSchemaTableExpression.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 3.3.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Database\Expression;
<del>
<del>use Cake\Database\ExpressionInterface;
<del>use Cake\Database\ValueBinder;
<del>
<del>/**
<del> * An expression object that represents a cross schema table name
<del> *
<del> * @internal
<del> */
<del>class CrossSchemaTableExpression implements ExpressionInterface
<del>{
<del>
<del> /**
<del> * Name of the schema
<del> *
<del> * @var \Cake\Database\ExpressionInterface|string
<del> */
<del> protected $_schema;
<del>
<del> /**
<del> * Name of the table
<del> *
<del> * @var \Cake\Database\ExpressionInterface|string
<del> */
<del> protected $_table;
<del>
<del> /**
<del> * @inheritDoc
<del> *
<del> * @param string\\Cake\Database\ExpressionInterface $schema Name of the schema
<del> * @param string|\Cake\Database\ExpressionInterface $table Name of the table
<del> */
<del> public function __construct($schema, $table)
<del> {
<del> $this->_schema = $schema;
<del> $this->_table = $table;
<del> }
<del>
<del> /**
<del> * Get or set the schema to use
<del> *
<del> * @param null|string|\Cake\Database\ExpressionInterface $schema The schema to set
<del> * @return $this|string|\Cake\Database\ExpressionInterface The schema that has been set
<del> */
<del> public function schema($schema = null)
<del> {
<del> if ($schema !== null) {
<del> $this->_schema = $schema;
<del>
<del> return $this;
<del> }
<del>
<del> return $this->_schema;
<del> }
<del>
<del> /**
<del> * Get or set the schema to use
<del> *
<del> * @param null|string|\Cake\Database\ExpressionInterface $table The table to set
<del> * @return $this|string|\Cake\Database\ExpressionInterface The table that has been set
<del> */
<del> public function table($table = null)
<del> {
<del> if ($table !== null) {
<del> $this->_table = $table;
<del>
<del> return $this;
<del> }
<del>
<del> return $this->_table;
<del> }
<del>
<del> /**
<del> * Converts the Node into a SQL string fragment.
<del> *
<del> * @param \Cake\Database\ValueBinder $generator Placeholder generator object
<del> * @return string
<del> */
<del> public function sql(ValueBinder $generator)
<del> {
<del> $schema = $this->_schema;
<del> if ($schema instanceof ExpressionInterface) {
<del> $schema = $schema->sql($generator);
<del> }
<del>
<del> $table = $this->_table;
<del> if ($table instanceof ExpressionInterface) {
<del> $table = $table->sql($generator);
<del> }
<del>
<del> return sprintf('%s.%s', $schema, $table);
<del> }
<del>
<del> /**
<del> * Iterates over each part of the expression recursively for every
<del> * level of the expressions tree and executes the $visitor callable
<del> * passing as first parameter the instance of the expression currently
<del> * being iterated.
<del> *
<del> * @param callable $visitor The callable to apply to all nodes.
<del> * @return void
<del> */
<del> public function traverse(callable $visitor)
<del> {
<del> if ($this->_schema instanceof ExpressionInterface) {
<del> $visitor($this->_schema);
<del> $this->_schema->traverse($visitor);
<del> }
<del> if ($this->_table instanceof ExpressionInterface) {
<del> $visitor($this->_table);
<del> $this->_table->traverse($visitor);
<del> }
<del> }
<del>}
<ide><path>src/Database/IdentifierQuoter.php
<ide> */
<ide> namespace Cake\Database;
<ide>
<del>use Cake\Database\Expression\CrossSchemaTableExpression;
<ide> use Cake\Database\Expression\FieldInterface;
<ide> use Cake\Database\Expression\IdentifierExpression;
<ide> use Cake\Database\Expression\OrderByExpression;
<ide> public function quoteExpression($expression)
<ide> if ($expression instanceof IdentifierExpression) {
<ide> $this->_quoteIdentifierExpression($expression);
<ide>
<del> return;
<del> }
<del> if ($expression instanceof CrossSchemaTableExpression) {
<del> $this->_quoteCrossSchemaTableExpression($expression);
<del>
<ide> return;
<ide> }
<ide> }
<ide> protected function _quoteIdentifierExpression(IdentifierExpression $expression)
<ide> $this->_driver->quoteIdentifier($expression->getIdentifier())
<ide> );
<ide> }
<del>
<del> /**
<del> * Quotes the cross schema table identifier
<del> *
<del> * @param CrossSchemaTableExpression $expression The identifier to quote
<del> * @return void
<del> */
<del> protected function _quoteCrossSchemaTableExpression(CrossSchemaTableExpression $expression)
<del> {
<del> if (!$expression->schema() instanceof ExpressionInterface) {
<del> $expression->schema($this->_driver->quoteIdentifier($expression->schema()));
<del> }
<del> if (!$expression->table() instanceof ExpressionInterface) {
<del> $expression->table($this->_driver->quoteIdentifier($expression->table()));
<del> }
<del> }
<ide> }
<ide><path>src/ORM/Association.php
<ide>
<ide> use Cake\Collection\Collection;
<ide> use Cake\Core\ConventionsTrait;
<del>use Cake\Database\Expression\CrossSchemaTableExpression;
<ide> use Cake\Database\Expression\IdentifierExpression;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\ResultSetDecorator;
<ide> public function attachTo(Query $query, array $options = [])
<ide> {
<ide> $target = $this->target();
<ide> $joinType = empty($options['joinType']) ? $this->joinType() : $options['joinType'];
<del>
<ide> $table = $target->table();
<del> if ($this->source()->connection()->supportsCrossWith($target->connection())) {
<del> $table = new CrossSchemaTableExpression(
<del> $target->connection()->driver()->schema(),
<del> $table
<del> );
<del> }
<ide>
<ide> $options += [
<ide> 'includeFields' => true,
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testSchemaCollection()
<ide> $connection->schemaCollection($schema);
<ide> $this->assertSame($schema, $connection->schemaCollection());
<ide> }
<del>
<del> /**
<del> * Tests supportsCrossWith
<del> *
<del> * @return void
<del> */
<del> public function testSupportsCrossWith()
<del> {
<del> $connection = new Connection(ConnectionManager::config('test'));
<del> $targetConnection = new Connection(ConnectionManager::config('test'));
<del>
<del> $this->assertFalse($connection->supportsCrossWith($targetConnection), 'The same connection can\'t used in cross');
<del>
<del> $connection = new Connection(ConnectionManager::config('test'));
<del> $targetConnection = new Connection(['name' => 'test2'] + ConnectionManager::config('test'));
<del>
<del> $this->assertTrue($connection->supportsCrossWith($targetConnection), 'Cross should be supported on databases on the same server');
<del>
<del> $connection = new Connection(ConnectionManager::config('test'));
<del> $targetConnection = new Connection(['port' => 999999] + ConnectionManager::config('test'));
<del>
<del> $this->assertFalse($connection->supportsCrossWith($targetConnection), 'Cross is not supported across different server instances');
<del>
<del> $connection = new Connection(ConnectionManager::config('test'));
<del> $targetConnection = new Connection(['host' => 'db2.example.com'] + ConnectionManager::config('test'));
<del>
<del> $this->assertFalse($connection->supportsCrossWith($targetConnection), 'Cross is not supported across different server instances');
<del> }
<ide> }
<ide><path>tests/TestCase/Database/Expression/CrossSchemaTableExpressionTest.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 3.3.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\Database\Expression;
<del>
<del>use Cake\Database\Expression\CrossSchemaTableExpression;
<del>use Cake\Database\Expression\IdentifierExpression;
<del>use Cake\Database\ValueBinder;
<del>use Cake\TestSuite\TestCase;
<del>
<del>/**
<del> * Tests CrossSchemaTableExpression class
<del> */
<del>class CrossSchemaTableExpressionTest extends TestCase
<del>{
<del>
<del> /**
<del> * Test sql method with ExpressionInterfaces passed and without
<del> */
<del> public function testSql()
<del> {
<del> $expression = new CrossSchemaTableExpression(
<del> new IdentifierExpression('schema'),
<del> new IdentifierExpression('table')
<del> );
<del>
<del> $this->assertEquals('schema.table', $expression->sql(new ValueBinder()));
<del>
<del> $expression = new CrossSchemaTableExpression('schema', 'table');
<del>
<del> $this->assertEquals('schema.table', $expression->sql(new ValueBinder()));
<del> }
<del>
<del> /**
<del> * Test traverse method with ExpressionInterfaces passed and without
<del> */
<del> public function testTraverse()
<del> {
<del> $expressions = [];
<del>
<del> $collector = function ($e) use (&$expressions) {
<del> $expressions[] = $e;
<del> };
<del>
<del> $expression = new CrossSchemaTableExpression(
<del> new IdentifierExpression('schema'),
<del> new IdentifierExpression('table')
<del> );
<del> $expression->traverse($collector);
<del> $this->assertEquals([
<del> new IdentifierExpression('schema'),
<del> new IdentifierExpression('table')
<del> ], $expressions);
<del>
<del> $expressions = [];
<del> $expression = new CrossSchemaTableExpression('schema', 'table');
<del> $expression->traverse($collector);
<del> $this->assertEquals([], $expressions);
<del> }
<del>} | 6 |
Javascript | Javascript | call imports with the correct context | 6842d50cf9c5e112e5c5eb0651153d07d966cf95 | <ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> dep.namespaceObjectAsContext = true;
<ide> dep.loc = expr.callee.loc;
<ide> parser.state.current.addDependency(dep);
<del> return true;
<del> });
<del> parser.plugin("call imported var", (expr) => {
<del> const args = expr.arguments;
<del> const fullExpr = expr;
<del> expr = expr.callee;
<del> const name = expr.name;
<del> const settings = parser.state.harmonySpecifier[`$${name}`];
<del> const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence);
<del> dep.directImport = true;
<del> dep.callArgs = args;
<del> dep.call = fullExpr;
<del> dep.loc = expr.loc;
<del> parser.state.current.addDependency(dep);
<del> if(args)
<del> parser.walkExpressions(args);
<add> if(expr.arguments)
<add> parser.walkExpressions(expr.arguments);
<ide> return true;
<ide> });
<ide> }
<add> parser.plugin("call imported var", (expr) => {
<add> const args = expr.arguments;
<add> const fullExpr = expr;
<add> expr = expr.callee;
<add> const name = expr.name;
<add> const settings = parser.state.harmonySpecifier[`$${name}`];
<add> const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence);
<add> dep.directImport = true;
<add> dep.callArgs = args;
<add> dep.call = fullExpr;
<add> dep.loc = expr.loc;
<add> parser.state.current.addDependency(dep);
<add> if(args)
<add> parser.walkExpressions(args);
<add> return true;
<add> });
<ide> parser.plugin("hot accept callback", (expr, requests) => {
<ide> const dependencies = requests
<ide> .filter(request => HarmonyModulesHelpers.checkModuleVar(parser.state, request))
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate {
<ide> let content;
<ide> if(dep.id === null) {
<ide> content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`;
<add> } else if(dep.namespaceObjectAsContext) {
<add> content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__[${JSON.stringify(dep.id)}]`;
<ide> } else {
<ide> const exportIdx = (module.providedExports).indexOf(dep.id);
<ide> content = exportIdx === -1 ? "undefined" : `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportIdx}__`;
<ide><path>test/cases/parsing/harmony-this/abc.js
<add>function returnThis() {
<add> if(typeof this === "undefined") return "undefined";
<add> return this;
<add>}
<add>
<add>var a = returnThis;
<add>var b = returnThis;
<add>
<add>export {
<add> a,
<add> b
<add>}
<add>
<add>export default returnThis;
<ide><path>test/cases/parsing/harmony-this/index.js
<add>"use strict";
<add>
<add>import d, {a, b as B} from "./abc";
<add>
<add>import * as abc from "./abc";
<add>
<add>function x() { throw new Error("should not be executed"); }
<add>it("should have this = undefined on imported non-strict functions", function() {
<add> x
<add> d().should.be.eql("undefined");
<add> x
<add> a().should.be.eql("undefined");
<add> x
<add> B().should.be.eql("undefined");
<add>});
<add>
<add>import C2, { C } from "./new";
<add>
<add>import * as New from "./new";
<add>
<add>it("should be possible to use new correctly", function() {
<add> x
<add> new C().should.match({ok: true});
<add> x
<add> new C2().should.match({ok: true});
<add> x
<add> new New.C().should.match({ok: true});
<add>});
<ide><path>test/cases/parsing/harmony-this/new.js
<add>function C() {
<add> this.ok = this.pok;
<add>}
<add>
<add>C.prototype.pok = true;
<add>
<add>export default C;
<add>export {
<add> C
<add>};
<ide><path>test/configCases/parsing/harmony-this-concat/abc.js
<add>function returnThis() {
<add> if(typeof this === "undefined") return "undefined";
<add> return this;
<add>}
<add>
<add>var a = returnThis;
<add>var b = returnThis;
<add>
<add>export {
<add> a,
<add> b
<add>}
<add>
<add>export default returnThis;
<ide><path>test/configCases/parsing/harmony-this-concat/index.js
<add>"use strict";
<add>
<add>import d, {a, b as B} from "./abc";
<add>
<add>import * as abc from "./abc";
<add>
<add>function x() { throw new Error("should not be executed"); }
<add>it("should have this = undefined on imported non-strict functions", function() {
<add> x
<add> d().should.be.eql("undefined");
<add> x
<add> a().should.be.eql("undefined");
<add> x
<add> B().should.be.eql("undefined");
<add> x
<add> abc.a().should.be.type("object");
<add> x
<add> var thing = abc.a();
<add> Object.keys(thing).should.be.eql(["a", "b", "default"]);
<add>});
<add>
<add>import C2, { C } from "./new";
<add>
<add>import * as New from "./new";
<add>
<add>it("should be possible to use new correctly", function() {
<add> x
<add> new C().should.match({ok: true});
<add> x
<add> new C2().should.match({ok: true});
<add> x
<add> new New.C().should.match({ok: true});
<add>});
<ide><path>test/configCases/parsing/harmony-this-concat/new.js
<add>function C() {
<add> this.ok = this.pok;
<add>}
<add>
<add>C.prototype.pok = true;
<add>
<add>export default C;
<add>export {
<add> C
<add>};
<ide><path>test/configCases/parsing/harmony-this-concat/webpack.config.js
<add>var webpack = require("../../../../");
<add>module.exports = {
<add> module: {
<add> strictThisContextOnImports: true
<add> },
<add> plugins: [
<add> new webpack.optimize.ModuleConcatenationPlugin()
<add> ]
<add>};
<ide><path>test/configCases/scope-hoisting/strictThisContextOnImports/index.js
<add>import value, { identity } from "./module";
<add>import * as m from "./module";
<add>
<add>it("should parse and translate identifiers correctly", function() {
<add> identity(value).should.be.eql(1234);
<add> m.identity(value).should.be.eql(1234);
<add> m.identity(identity).should.be.eql(identity);
<add> m.identity(m.identity).should.be.eql(m.identity);
<add> identity(m.identity).should.be.eql(m.identity);
<add> identity(m.default).should.be.eql(1234);
<add>});
<ide><path>test/configCases/scope-hoisting/strictThisContextOnImports/module.js
<add>export function identity(a) { return a; }
<add>export default 1234;
<ide><path>test/configCases/scope-hoisting/strictThisContextOnImports/webpack.config.js
<add>var webpack = require("../../../../");
<add>module.exports = {
<add> module: {
<add> strictThisContextOnImports: true
<add> },
<add> plugins: [
<add> new webpack.optimize.ModuleConcatenationPlugin()
<add> ]
<add>}; | 12 |
Python | Python | fix goldparse init when token count differs | a04f8020993568e5677cdbce96e93c82cf6e012f | <ide><path>spacy/scorer.py
<ide> def score(self, doc, gold, verbose=False, punct_labels=("p", "punct")):
<ide> """
<ide> if len(doc) != len(gold):
<ide> gold = GoldParse.from_annot_tuples(
<del> doc, tuple(zip(*gold.orig_annot)) + (gold.cats,)
<add> doc, zip(*gold.orig_annot), cats=gold.cats,
<ide> )
<ide> gold_deps = set()
<ide> gold_deps_per_dep = {} | 1 |
Python | Python | fix retrieval of the right branch in pre-commits | d93908deb7bfea2bc7cfe5a69830b01e4df06676 | <ide><path>scripts/ci/pre_commit/pre_commit_flake8.py
<ide>
<ide> AIRFLOW_SOURCES = Path(__file__).parents[3].absolute()
<ide> GITHUB_REPOSITORY = os.environ.get('GITHUB_REPOSITORY', "apache/airflow")
<del>AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/main/ci/python3.7"
<ide>
<ide> if __name__ == '__main__':
<add> sys.path.insert(0, str(Path(__file__).parents[3].absolute() / "dev" / "breeze" / "src"))
<add> from airflow_breeze.branch_defaults import AIRFLOW_BRANCH
<add>
<add> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/{AIRFLOW_BRANCH}/ci/python3.7"
<add>
<ide> if subprocess.call(args=["docker", "inspect", AIRFLOW_CI_IMAGE], stdout=subprocess.DEVNULL) != 0:
<ide> print(f'[red]The image {AIRFLOW_CI_IMAGE} is not available.[/]\n')
<ide> print("\n[yellow]Please run at the earliest convenience:[/]\n\nbreeze build-image --python 3.7\n\n")
<ide><path>scripts/ci/pre_commit/pre_commit_migration_reference.py
<ide>
<ide> AIRFLOW_SOURCES = Path(__file__).parents[3].absolute()
<ide> GITHUB_REPOSITORY = os.environ.get('GITHUB_REPOSITORY', "apache/airflow")
<del>AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/main/ci/python3.7"
<ide>
<ide> if __name__ == '__main__':
<add> sys.path.insert(0, str(Path(__file__).parents[3].absolute() / "dev" / "breeze" / "src"))
<add> from airflow_breeze.branch_defaults import AIRFLOW_BRANCH
<add>
<add> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/{AIRFLOW_BRANCH}/ci/python3.7"
<ide> if subprocess.call(args=["docker", "inspect", AIRFLOW_CI_IMAGE], stdout=subprocess.DEVNULL) != 0:
<ide> print(f'[red]The image {AIRFLOW_CI_IMAGE} is not available.[/]\n')
<ide> print("\n[yellow]Please run at the earliest convenience:[/]\n\nbreeze build-image --python 3.7\n\n")
<ide><path>scripts/ci/pre_commit/pre_commit_mypy.py
<ide> f"To run this script, run the ./{__file__} command"
<ide> )
<ide>
<add>
<ide> AIRFLOW_SOURCES = Path(__file__).parents[3].absolute()
<ide> GITHUB_REPOSITORY = os.environ.get('GITHUB_REPOSITORY', "apache/airflow")
<del>AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/main/ci/python3.7"
<ide>
<ide> if __name__ == '__main__':
<add> sys.path.insert(0, str(Path(__file__).parents[3].absolute() / "dev" / "breeze" / "src"))
<add> from airflow_breeze.branch_defaults import AIRFLOW_BRANCH
<add>
<add> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/{AIRFLOW_BRANCH}/ci/python3.7"
<add>
<ide> if subprocess.call(args=["docker", "inspect", AIRFLOW_CI_IMAGE], stdout=subprocess.DEVNULL) != 0:
<ide> print(f'[red]The image {AIRFLOW_CI_IMAGE} is not available.[/]\n')
<ide> print("\n[yellow]Please run at the earliest convenience:[/]\n\nbreeze build-image --python 3.7\n\n")
<ide><path>scripts/ci/pre_commit/pre_commit_ui_lint.py
<ide> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/main/ci/python3.7"
<ide>
<ide> if __name__ == '__main__':
<add> sys.path.insert(0, str(Path(__file__).parents[3].absolute() / "dev" / "breeze" / "src"))
<add> from airflow_breeze.branch_defaults import AIRFLOW_BRANCH
<add>
<add> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/{AIRFLOW_BRANCH}/ci/python3.7"
<ide> if subprocess.call(args=["docker", "inspect", AIRFLOW_CI_IMAGE], stdout=subprocess.DEVNULL) != 0:
<ide> print(f'[red]The image {AIRFLOW_CI_IMAGE} is not available.[/]\n')
<ide> print("\n[yellow]Please run at the earliest convenience:[/]\n\nbreeze build-image --python 3.7\n\n")
<ide><path>scripts/ci/pre_commit/pre_commit_www_lint.py
<ide> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/main/ci/python3.7"
<ide>
<ide> if __name__ == '__main__':
<add> sys.path.insert(0, str(Path(__file__).parents[3].absolute() / "dev" / "breeze" / "src"))
<add> from airflow_breeze.branch_defaults import AIRFLOW_BRANCH
<add>
<add> AIRFLOW_CI_IMAGE = f"ghcr.io/{GITHUB_REPOSITORY}/{AIRFLOW_BRANCH}/ci/python3.7"
<ide> if subprocess.call(args=["docker", "inspect", AIRFLOW_CI_IMAGE], stdout=subprocess.DEVNULL) != 0:
<ide> print(f'[red]The image {AIRFLOW_CI_IMAGE} is not available.[/]\n')
<ide> print("\n[yellow]Please run at the earliest convenience:[/]\n\nbreeze build-image --python 3.7\n\n") | 5 |
Java | Java | fix javadoc in mockhttpservletrequestbuilder | fc7e60678cf8e63037f4163c4d77013a2f088104 | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
<ide> * requests in {@link MockMvc}.
<ide> *
<ide> * <p>Application tests will typically access this builder through the static factory
<del> * methods in {@link org.springframework.test.web.servlet.setup.MockMvcBuilders}.
<add> * methods in {@link MockMvcRequestBuilders}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Arjen Poutsma | 1 |
Python | Python | return lowercase form as default except for propn | 8cba0e41d8e2797763110e8dd1b3b2ec8a29e719 | <ide><path>spacy/lemmatizer.py
<ide> def __call__(self, string, univ_pos, morphology=None):
<ide> index_table = self.lookups.get_table("lemma_index", {})
<ide> exc_table = self.lookups.get_table("lemma_exc", {})
<ide> rules_table = self.lookups.get_table("lemma_rules", {})
<add> if not any((index_table.get(univ_pos), exc_table.get(univ_pos), rules_table.get(univ_pos))):
<add> if univ_pos == "propn":
<add> return [string]
<add> else:
<add> return [string.lower()]
<ide> lemmas = self.lemmatize(
<ide> string,
<ide> index_table.get(univ_pos, {}), | 1 |
Text | Text | remove unnecessary `to`s | 909ec375b1716e9909ceb91a53631157a0e98058 | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> class MyView extends View
<ide>
<ide> You should not need to change anything to use the new `TextEditorView`! See the [docs][TextEditorView] for more info.
<ide>
<del>### Upgrading to classes extending ScrollView
<add>### Upgrading classes extending ScrollView
<ide>
<ide> The `ScrollView` has very minor changes.
<ide>
<ide> class ResultsView extends ScrollView
<ide> * Check out [an example](https://github.com/atom/find-and-replace/pull/311/files#diff-9) from find-and-replace.
<ide> * See the [docs][ScrollView] for all the options.
<ide>
<del>### Upgrading to classes extending SelectListView
<add>### Upgrading classes extending SelectListView
<ide>
<ide> Your SelectListView might look something like this:
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.