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
|
---|---|---|---|---|---|
Python | Python | restore changes from nn-beam-parser to spacy/_ml | fe90dfc390c98b154c544c10f07f2138d9b03384 | <ide><path>spacy/_ml.py
<ide>
<ide> from thinc.neural._classes.convolution import ExtractWindow
<ide> from thinc.neural._classes.static_vectors import StaticVectors
<del>from thinc.neural._classes.batchnorm import BatchNorm
<add>from thinc.neural._classes.batchnorm import BatchNorm as BN
<ide> from thinc.neural._classes.layernorm import LayerNorm as LN
<ide> from thinc.neural._classes.resnet import Residual
<ide> from thinc.neural import ReLu
<ide> from thinc.neural._classes.attention import ParametricAttention
<ide> from thinc.linear.linear import LinearModel
<ide> from thinc.api import uniqued, wrap, flatten_add_lengths
<add>from thinc.neural._classes.rnn import BiLSTM
<ide>
<ide>
<ide> from .attrs import ID, ORTH, LOWER, NORM, PREFIX, SUFFIX, SHAPE, TAG, DEP
<ide> def Tok2Vec(width, embed_size, preprocess=None):
<ide> suffix = get_col(cols.index(SUFFIX)) >> HashEmbed(width, embed_size//2, name='embed_suffix')
<ide> shape = get_col(cols.index(SHAPE)) >> HashEmbed(width, embed_size//2, name='embed_shape')
<ide>
<del> embed = (norm | prefix | suffix | shape ) >> Maxout(width, width*4, pieces=3)
<add> embed = (norm | prefix | suffix | shape ) >> LN(Maxout(width, width*4, pieces=3))
<ide> tok2vec = (
<ide> with_flatten(
<ide> asarray(Model.ops, dtype='uint64')
<ide> >> uniqued(embed, column=5)
<ide> >> drop_layer(
<ide> Residual(
<del> (ExtractWindow(nW=1) >> ReLu(width, width*3))
<add> (ExtractWindow(nW=1) >> BN(Maxout(width, width*3)))
<ide> )
<ide> ) ** 4, pad=4
<ide> ) | 1 |
Javascript | Javascript | prevent non user from hitting delete page | 75090415118f37d564a15e9c68faeefd005e4051 | <ide><path>server/boot/user.js
<ide> module.exports = function(app) {
<ide> router.get('/email-signin', getEmailSignin);
<ide> router.get('/deprecated-signin', getDepSignin);
<ide> router.get('/update-email', getUpdateEmail);
<del> router.get('/delete-my-account', showDelete);
<add> router.get(
<add> '/delete-my-account',
<add> sendNonUserToMap,
<add> showDelete
<add> );
<ide> api.post(
<ide> '/account/delete',
<ide> ifNoUser401, | 1 |
Javascript | Javascript | use test port instead of 8000 in test-http-304 | 141565046375db6fa427ba014113abcc9f4d5833 | <ide><path>test/simple/test-http-304.js
<ide> s = http.createServer(function (request, response) {
<ide> response.writeHead(304);
<ide> response.end();
<ide> })
<del>s.listen(8000);
<del>sys.puts('Server running at http://127.0.0.1:8000/')
<add>s.listen(PORT);
<add>sys.puts('Server running at http://127.0.0.1:'+PORT+'/')
<ide>
<ide> s.addListener('listening', function () {
<ide>
<del> childProcess.exec('curl http://127.0.0.1:8000/', function (err, stdout, stderr) {
<add> childProcess.exec('curl http://127.0.0.1:'+PORT+'/', function (err, stdout, stderr) {
<ide> if (err) throw err;
<ide> s.close();
<ide> sys.puts('curled response correctly'); | 1 |
PHP | PHP | fix typehints and docblocks | 8a27ca2c824b9f40f533777cb74acfdca23f8f74 | <ide><path>src/Database/Type.php
<ide> class Type
<ide> /**
<ide> * Contains a map of type object instances to be reused if needed.
<ide> *
<del> * @var \Cake\Database\Type[]
<add> * @var \Cake\Database\TypeInterface[]
<ide> */
<ide> protected static $_builtTypes = [];
<ide>
<ide> class Type
<ide> *
<ide> * @param string $name type identifier
<ide> * @throws \InvalidArgumentException If type identifier is unknown
<del> * @return \Cake\Database\Type
<add> * @return \Cake\Database\TypeInterface
<ide> */
<ide> public static function build($name)
<ide> {
<ide> public static function buildAll()
<ide> {
<ide> $result = [];
<ide> foreach (static::$_types as $name => $type) {
<del> $result[$name] = isset(static::$_builtTypes[$name]) ? static::$_builtTypes[$name] : static::build($name);
<add> $result[$name] = isset(static::$_builtTypes[$name])
<add> ? static::$_builtTypes[$name]
<add> : static::build($name);
<ide> }
<ide>
<ide> return $result;
<ide> public static function buildAll()
<ide> * Returns a Type object capable of converting a type identified by $name
<ide> *
<ide> * @param string $name The type identifier you want to set.
<del> * @param \Cake\Database\Type $instance The type instance you want to set.
<add> * @param \Cake\Database\TypeInterface $instance The type instance you want to set.
<ide> * @return void
<ide> */
<del> public static function set($name, Type $instance)
<add> public static function set($name, TypeInterface $instance)
<ide> {
<ide> static::$_builtTypes[$name] = $instance;
<ide> }
<ide> public static function set($name, Type $instance)
<ide> * If called with no arguments it will return current types map array
<ide> * If $className is omitted it will return mapped class for $type
<ide> *
<del> * Deprecated: The usage of $type as \Cake\Database\Type[] is deprecated. Please always use string[] if you pass an array
<del> * as first argument.
<del> *
<del> * @param string|string[]|\Cake\Database\Type[]|null $type If string name of type to map, if array list of arrays to be mapped
<del> * @param string|\Cake\Database\Type|null $className The classname or object instance of it to register.
<add> * @param string|string[]|null $type If string name of type to map, if array list of arrays to be mapped
<add> * @param string|\Cake\Database\TypeInterface|null $className The classname or object instance of it to register.
<ide> * @return array|string|null If $type is null then array with current map, if $className is null string
<ide> * configured class name for give $type, null otherwise
<ide> */ | 1 |
PHP | PHP | avoid string manipulation | a93e9272318f9a01e97a7912d931b3ed034a488b | <ide><path>src/Filesystem/File.php
<ide> public function exists(): bool
<ide> public function perms()
<ide> {
<ide> if ($this->exists()) {
<del> return substr(sprintf('%o', fileperms($this->path)), -3);
<add> return decoct(fileperms($this->path) & 0777);
<ide> }
<ide>
<ide> return false; | 1 |
Javascript | Javascript | prefer param function check over args length | 7cf56797dddc7a00f76b6c9ffda7270c15f8c6d3 | <ide><path>lib/fs.js
<ide> function open(path, flags, mode, callback) {
<ide> callback = flags;
<ide> flags = 'r';
<ide> mode = 0o666;
<del> } else if (arguments.length === 3) {
<add> } else if (typeof mode === 'function') {
<ide> callback = mode;
<ide> mode = 0o666;
<ide> }
<ide> function readdirSync(path, options) {
<ide> }
<ide>
<ide> function fstat(fd, options, callback) {
<del> if (arguments.length < 3) {
<add> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide> }
<ide> function fstat(fd, options, callback) {
<ide> }
<ide>
<ide> function lstat(path, options, callback) {
<del> if (arguments.length < 3) {
<add> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide> }
<ide> function lstat(path, options, callback) {
<ide> }
<ide>
<ide> function stat(path, options, callback) {
<del> if (arguments.length < 3) {
<add> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide> } | 1 |
Text | Text | use serial comma in modules docs | 74cf01a8e8c66f1ffbb13282e45abc777ef4bd64 | <ide><path>doc/api/modules.md
<ide> wrapper that looks like the following:
<ide>
<ide> By doing this, Node.js achieves a few things:
<ide>
<del>* It keeps top-level variables (defined with `var`, `const` or `let`) scoped to
<add>* It keeps top-level variables (defined with `var`, `const`, or `let`) scoped to
<ide> the module rather than the global object.
<ide> * It helps to provide some global-looking variables that are actually specific
<ide> to the module, such as: | 1 |
Text | Text | fix typo rtc to rct | bc432ae3248d3a886ff61c131513babbcd544194 | <ide><path>docs/NativeModulesIOS.md
<ide> RCT_EXPORT_METHOD(doSomethingExpensive:(NSString *)param callback:(RCTResponseSe
<ide> ## Dependency Injection
<ide> The bridge initializes any registered RCTBridgeModules automatically, however you may wish to instantiate your own module instances (so you may inject dependencies, for example).
<ide>
<del>You can do this by creating a class that implements the RTCBridgeDelegate Protocol, initializing an RTCBridge with the delegate as an argument and initialising a RTCRootView with the initialized bridge.
<add>You can do this by creating a class that implements the RCTBridgeDelegate Protocol, initializing an RCTBridge with the delegate as an argument and initialising a RCTRootView with the initialized bridge.
<ide>
<ide> ```objective-c
<del>id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRTCBridgeDelegate alloc] init];
<add>id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRCTBridgeDelegate alloc] init];
<ide>
<ide> RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:moduleInitialiser launchOptions:nil];
<ide> | 1 |
PHP | PHP | start tests for magic finder methods | ad11d7f04b2fd4fc3ce50022b7972507bfcc5913 | <ide><path>Cake/Test/TestCase/ORM/TableTest.php
<ide> public function testAfterValidate() {
<ide> $this->assertEquals(['Not good'], $entity->errors('username'));
<ide> }
<ide>
<add>/**
<add> * Test magic findByXX method.
<add> *
<add> * @return void
<add> */
<add> public function testMagicFindFirst() {
<add> $table = TableRegistry::get('Users');
<add>
<add> $result = $table->findByUsername('garrett');
<add> $this->assertInstanceOf('Cake\ORM\Query', $result);
<add> $this->assertEquals(1, $result->limit());
<add> $this->assertEquals(['username' => 'garrett'], $result->clause('where'));
<add>
<add> $result = $table->findByUsernameAndId('garrett', 4);
<add> $this->assertInstanceOf('Cake\ORM\Query', $result);
<add> $this->assertEquals(1, $result->limit());
<add> $this->assertEquals(['username' => 'garrett'], $result->clause('where'));
<add> }
<add>
<add>/**
<add> * Test magic findAllByXX method.
<add> *
<add> * @return void
<add> */
<add> public function testMagicFindAll() {
<add> $table = TableRegistry::get('Articles');
<add>
<add> $result = $table->findAllByAuthorId(1);
<add> $this->assertInstanceOf('Cake\ORM\Query', $result);
<add> $this->assertEquals(null, $result->limit());
<add> $this->assertEquals(['author_id' => '1'], $result->clause('where'));
<add>
<add> $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
<add> $this->assertInstanceOf('Cake\ORM\Query', $result);
<add> $this->assertEquals(null, $result->limit());
<add> $expected = [
<add> 'author_id' => 1,
<add> 'published' => 'Y',
<add> ];
<add> $this->assertEquals($expected, $result->clause('where'));
<add> }
<add>
<ide> } | 1 |
Java | Java | add value() attribute to @payload | bcfbd862c73db17d7bd8dfe5b669d1a8fc17bcbf | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java
<ide> @Documented
<ide> public @interface Payload {
<ide>
<add> /**
<add> * A SpEL expression to be evaluated against the payload object as the root context.
<add> * This attribute may or may not be supported depending on whether the message being
<add> * handled contains a non-primitive Object as its payload or is in serialized form
<add> * and requires message conversion.
<add> * <p>
<add> * When processing STOMP over WebSocket messages this attribute is not supported.
<add> */
<add> String value() default "";
<add>
<ide> /**
<ide> * Whether payload content is required.
<ide> * <p>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolver.java
<ide> import org.springframework.messaging.support.converter.MessageConverter;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ClassUtils;
<add>import org.springframework.util.StringUtils;
<ide>
<ide>
<ide> /**
<ide> public Object resolveArgument(MethodParameter parameter, Message<?> message) thr
<ide> }
<ide> }
<ide>
<add> if ((annot != null) && StringUtils.hasText(annot.value())) {
<add> throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver.");
<add> }
<add>
<ide> return this.converter.fromMessage(message, targetClass);
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolverTests.java
<ide> public class PayloadArgumentResolverTests {
<ide>
<ide> private MethodParameter param;
<ide> private MethodParameter paramNotRequired;
<add> private MethodParameter paramWithSpelExpression;
<ide>
<ide>
<ide> @Before
<ide> public void setup() throws Exception {
<ide> this.resolver = new PayloadArgumentResolver(messageConverter );
<ide>
<ide> Method method = PayloadArgumentResolverTests.class.getDeclaredMethod("handleMessage",
<del> String.class, String.class);
<add> String.class, String.class, String.class);
<ide>
<ide> this.param = new MethodParameter(method , 0);
<ide> this.paramNotRequired = new MethodParameter(method , 1);
<add> this.paramWithSpelExpression = new MethodParameter(method , 2);
<ide> }
<ide>
<ide>
<ide> public void resolveNotRequired() throws Exception {
<ide> assertEquals("ABC", this.resolver.resolveArgument(this.paramNotRequired, notEmptyMessage));
<ide> }
<ide>
<add> @Test(expected=IllegalStateException.class)
<add> public void resolveSpelExpressionNotSupported() throws Exception {
<add> Message<?> message = MessageBuilder.withPayload("ABC".getBytes()).build();
<add> this.resolver.resolveArgument(this.paramWithSpelExpression, message);
<add> }
<add>
<ide>
<ide> @SuppressWarnings("unused")
<ide> private void handleMessage(
<ide> @Payload String param,
<del> @Payload(required=false) String paramNotRequired) {
<add> @Payload(required=false) String paramNotRequired,
<add> @Payload("foo.bar") String paramWithSpelExpression) {
<ide> }
<ide>
<ide> } | 3 |
Ruby | Ruby | require test/unit and sort test order | 9342492e1445c47b02db392ba8430ecb9218fc47 | <ide><path>activerecord/test/cases/helper.rb
<ide>
<ide> require 'config'
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'stringio'
<ide> require 'mocha'
<ide>
<ide><path>activesupport/lib/active_support/test_case.rb
<ide> def self.for_tag(tag)
<ide> yield if $tags[tag]
<ide> end
<ide>
<add> # FIXME: we have tests that depend on run order, we should fix that and
<add> # remove this method.
<add> def self.test_order # :nodoc:
<add> :sorted
<add> end
<add>
<ide> include ActiveSupport::Testing::SetupAndTeardown
<ide> include ActiveSupport::Testing::Assertions
<ide> include ActiveSupport::Testing::Deprecation | 2 |
Javascript | Javascript | move auth functions to central location | a4e220e2bc77a7fd3233cb8443fded52a3ae11d1 | <ide><path>common/models/User-Identity.js
<del>import assign from 'object.assign';
<ide> import debugFactory from 'debug';
<ide>
<add>import {
<add> setProfileFromGithub,
<add> getFirstImageFromProfile
<add>} from '../../server/utils/auth';
<add>
<ide> const debug = debugFactory('freecc:models:userIdent');
<ide>
<ide> const { defaultProfileImage } = require('../utils/constantStrings.json');
<ide>
<del>function getFirstImageFromProfile(profile) {
<del> return profile && profile.photos && profile.photos[0] ?
<del> profile.photos[0].value :
<del> null;
<del>}
<del>
<del>// using es6 argument destructing
<del>function setProfileFromGithub(
<del> user,
<del> {
<del> profileUrl: githubURL,
<del> username
<del> },
<del> {
<del> id: githubId,
<del> 'avatar_url': picture,
<del> email: githubEmail,
<del> 'created_at': joinedGithubOn,
<del> blog: website,
<del> location,
<del> name
<del> }
<del>) {
<del> return assign(
<del> user,
<del> { isGithubCool: true, isMigrationGrandfathered: false },
<del> {
<del> name,
<del> username: username.toLowerCase(),
<del> location,
<del> joinedGithubOn,
<del> website,
<del> picture,
<del> githubId,
<del> githubURL,
<del> githubEmail,
<del> githubProfile: githubURL
<del> }
<del> );
<del>}
<del>
<ide> export default function(UserIdent) {
<ide> UserIdent.observe('before save', function(ctx, next) {
<ide> var userIdent = ctx.currentInstance || ctx.instance;
<ide><path>server/server.js
<ide> var uuid = require('node-uuid'),
<ide> path = require('path'),
<ide> passportProviders = require('./passport-providers');
<ide>
<add>var setProfileFromGithub = require('./utils/auth').setProfileFromGithub;
<ide> var generateKey =
<ide> require('loopback-component-passport/lib/models/utils').generateKey;
<del>/**
<del> * Create Express server.
<del> */
<add>
<ide> var app = loopback();
<ide>
<ide> expressState.extend(app);
<ide> passportConfigurator.setupModels({
<ide> userCredentialModel: app.models.userCredential
<ide> });
<ide>
<del>// using es6 argument destructing
<del>function setProfileFromGithub(
<del> user,
<del> {
<del> profileUrl: githubURL,
<del> username
<del> },
<del> {
<del> id: githubId,
<del> 'avatar_url': picture,
<del> email: githubEmail,
<del> 'created_at': joinedGithubOn,
<del> blog: website,
<del> location,
<del> name
<del> }
<del>) {
<del> return assign(
<del> user,
<del> { isGithubCool: true, isMigrationGrandfathered: false },
<del> {
<del> name,
<del> username: username.toLowerCase(),
<del> location,
<del> joinedGithubOn,
<del> website,
<del> picture,
<del> githubId,
<del> githubURL,
<del> githubEmail,
<del> githubProfile: githubURL
<del> }
<del> );
<del>}
<del>
<ide> var passportOptions = {
<ide> emailOptional: true,
<ide> profileToUser: function(provider, profile) {
<ide><path>server/utils/auth.js
<add>import assign from 'object.assign';
<add>
<add>// using es6 argument destructing
<add>export function setProfileFromGithub(
<add> user,
<add> {
<add> profileUrl: githubURL,
<add> username
<add> },
<add> {
<add> id: githubId,
<add> 'avatar_url': picture,
<add> email: githubEmail,
<add> 'created_at': joinedGithubOn,
<add> blog: website,
<add> location,
<add> name
<add> }
<add>) {
<add> return assign(
<add> user,
<add> { isGithubCool: true, isMigrationGrandfathered: false },
<add> {
<add> name,
<add> username: username.toLowerCase(),
<add> location,
<add> joinedGithubOn,
<add> website,
<add> picture,
<add> githubId,
<add> githubURL,
<add> githubEmail,
<add> githubProfile: githubURL
<add> }
<add> );
<add>}
<add>
<add>export function getFirstImageFromProfile(profile) {
<add> return profile && profile.photos && profile.photos[0] ?
<add> profile.photos[0].value :
<add> null;
<add>} | 3 |
PHP | PHP | fix cs error | e72ec8fd2aadcbd90f8b46182a72725a6c14132a | <ide><path>src/View/View.php
<ide> public function __get($name)
<ide> *
<ide> * @param string $name Name to property.
<ide> * @param mixed $value Value for property.
<add> * @return void
<ide> */
<ide> public function __set($name, $value)
<ide> { | 1 |
Text | Text | add datumo.io to airflow family | 4e352f9c5e0e8d6714fe5d9c20f9b7cf33697245 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [DataFox](https://www.datafox.com/) [[@sudowork](https://github.com/sudowork)]
<ide> 1. [DataSprints](https://datasprints.com/) [[@lopesdiego12](https://github.com/lopesdiego12) & [@rafaelsantanaep](https://github.com/rafaelsantanaep)]
<ide> 1. [Datamaran](https://www.datamaran.com) [[@valexharo](https://github.com/valexharo)]
<add>1. [Datumo](https://datumo.io) [[@michalmisiewicz](https://github.com/michalmisiewicz)]
<ide> 1. [Dentsu Inc.](http://www.dentsu.com/) [[@bryan831](https://github.com/bryan831) & [@loozhengyuan](https://github.com/loozhengyuan)]
<ide> 1. [Deseret Digital Media](http://deseretdigital.com/) [[@formigone](https://github.com/formigone)
<ide> 1. [Digital First Media](http://www.digitalfirstmedia.com/) [[@duffn](https://github.com/duffn) & [@mschmo](https://github.com/mschmo) & [@seanmuth](https://github.com/seanmuth)] | 1 |
Javascript | Javascript | fix property | a7de96e860559468081f752bee37220a307f8f73 | <ide><path>examples/jsm/controls/TrackballControls.js
<ide> class TrackballControls extends EventDispatcher {
<ide>
<ide> case 2:
<ide> _state = STATE.TOUCH_ZOOM_PAN;
<del> _moveCurr.copy( getMouseOnCircle( event.pageX - _movePrev.pageX, event.pageY - _movePrev.pageY ) );
<add> _moveCurr.copy( getMouseOnCircle( event.pageX - _movePrev.x, event.pageY - _movePrev.y ) );
<ide> _movePrev.copy( _moveCurr );
<ide> break;
<ide> | 1 |
Python | Python | use threadpoolexecutor instead of threadpool | 204f9318e5d32a3616913d0d4f16e6c63efb6ce8 | <ide><path>numpy/distutils/ccompiler.py
<ide> def single_compile(args):
<ide>
<ide> if len(build) > 1 and jobs > 1:
<ide> # build parallel
<del> import multiprocessing.pool
<del> pool = multiprocessing.pool.ThreadPool(jobs)
<del> pool.map(single_compile, build_items)
<del> pool.close()
<add> from concurrent.futures import ThreadPoolExecutor
<add> with ThreadPoolExecutor(jobs) as pool:
<add> pool.map(single_compile, build_items)
<ide> else:
<ide> # build serial
<ide> for o in build_items: | 1 |
PHP | PHP | add missing coverage for attributes with secure() | 9201375dd1e3358844d880947744918bdda4db1d | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormSecurityInputUnlockedFields() {
<ide> );
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = $this->Form->secure($expected);
<add> $result = $this->Form->secure($expected, ['data-foo' => 'bar']);
<ide>
<ide> $hash = '2981c38990f3f6ba935e6561dc77277966fabd6d%3AAddresses.id';
<ide> $expected = array(
<ide> 'div' => array('style' => 'display:none;'),
<ide> array('input' => array(
<ide> 'type' => 'hidden',
<ide> 'name' => '_Token[fields]',
<del> 'value' => $hash
<add> 'value' => $hash,
<add> 'data-foo' => 'bar',
<ide> )),
<ide> array('input' => array(
<ide> 'type' => 'hidden',
<ide> 'name' => '_Token[unlocked]',
<ide> 'value' => 'address%7Cfirst_name',
<add> 'data-foo' => 'bar',
<ide> )),
<ide> '/div'
<ide> ); | 1 |
PHP | PHP | fix cs errors | 9c32a1f1e1afb704f869817715786d60371b3500 | <ide><path>src/Shell/PluginAssetsShell.php
<ide> protected function _list() {
<ide> /**
<ide> * Process plugins
<ide> *
<add> * @param array $plugins List of plugins to process
<ide> * @return void
<ide> */
<ide> protected function _process($plugins) {
<ide> protected function _process($plugins) {
<ide> * Create directory
<ide> *
<ide> * @param string $dir Directory name
<del> * @return boolean
<add> * @return bool
<ide> */
<ide> protected function _createDirectory($dir) {
<ide> $old = umask(0);
<ide> protected function _createDirectory($dir) {
<ide> *
<ide> * @param string $target Target directory
<ide> * @param string $link Link name
<del> * @return boolean
<add> * @return bool
<ide> */
<ide> protected function _createSymlink($target, $link) {
<ide> // @codingStandardsIgnoreStart
<ide> protected function _createSymlink($target, $link) {
<ide> *
<ide> * @param string $source Source directory
<ide> * @param string $destination Destination directory
<del> * @return boolean
<add> * @return bool
<ide> */
<ide> protected function _copyDirectory($source, $destination) {
<ide> $folder = new Folder($source); | 1 |
Javascript | Javascript | fix error emit handling | 04ae4862e670a8849454e6d8db4d8f73d0492190 | <ide><path>lib/domain.js
<ide> EventEmitter.init = function() {
<ide> const eventEmit = EventEmitter.prototype.emit;
<ide> EventEmitter.prototype.emit = function emit(...args) {
<ide> const domain = this.domain;
<del> if (domain === null || domain === undefined || this === process) {
<del> return Reflect.apply(eventEmit, this, args);
<del> }
<ide>
<ide> const type = args[0];
<del> // edge case: if there is a domain and an existing non error object is given,
<del> // it should not be errorized
<del> // see test/parallel/test-event-emitter-no-error-provided-to-error-event.js
<del> if (type === 'error' && args.length > 1 && args[1] &&
<del> !(args[1] instanceof Error)) {
<del> domain.emit('error', args[1]);
<del> return false;
<del> }
<add> const shouldEmitError = type === 'error' &&
<add> this.listenerCount(type) > 0;
<ide>
<del> domain.enter();
<del> try {
<add> // Just call original `emit` if current EE instance has `error`
<add> // handler, there's no active domain or this is process
<add> if (shouldEmitError || domain === null || domain === undefined ||
<add> this === process) {
<ide> return Reflect.apply(eventEmit, this, args);
<del> } catch (er) {
<del> if (typeof er === 'object' && er !== null) {
<add> }
<add>
<add> if (type === 'error') {
<add> const er = args.length > 1 && args[1] ?
<add> args[1] : new errors.Error('ERR_UNHANDLED_ERROR');
<add>
<add> if (typeof er === 'object') {
<ide> er.domainEmitter = this;
<ide> er.domain = domain;
<ide> er.domainThrown = false;
<ide> }
<add>
<ide> domain.emit('error', er);
<ide> return false;
<del> } finally {
<del> domain.exit();
<ide> }
<add>
<add> domain.enter();
<add> const ret = Reflect.apply(eventEmit, this, args);
<add> domain.exit();
<add>
<add> return ret;
<ide> };
<ide><path>test/parallel/test-domain-ee-error-listener.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const domain = require('domain').create();
<add>const EventEmitter = require('events');
<add>
<add>domain.on('error', common.mustNotCall());
<add>
<add>const ee = new EventEmitter();
<add>
<add>const plainObject = { justAn: 'object' };
<add>ee.once('error', common.mustCall((err) => {
<add> assert.deepStrictEqual(err, plainObject);
<add>}));
<add>ee.emit('error', plainObject);
<add>
<add>const err = new Error('test error');
<add>ee.once('error', common.expectsError(err));
<add>ee.emit('error', err); | 2 |
Go | Go | fix the use for secret create | 5cef55ba9178604c67d99774526cf055c7d0aafe | <ide><path>cli/command/secret/create.go
<ide> func newSecretCreateCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> }
<ide>
<ide> cmd := &cobra.Command{
<del> Use: "create [OPTIONS] SECRET [SECRET...]",
<add> Use: "create [OPTIONS] SECRET",
<ide> Short: "Create a secret using stdin as content",
<del> Args: cli.RequiresMinArgs(1),
<add> Args: cli.ExactArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide> createOpts.name = args[0]
<ide> return runSecretCreate(dockerCli, createOpts) | 1 |
Ruby | Ruby | add homebrew.install_gem_setup_path! function | 9e8103cf38f10a4240f0a796bbecdb635dbc74d4 | <ide><path>Library/Homebrew/cmd/man.rb
<ide> def man
<ide> end
<ide> end
<ide>
<del> which("ronn") || odie("You need to \"gem install ronn\" and put it in your path.")
<add> Homebrew.install_gem_setup_path! "ronn"
<ide>
<ide> if ARGV.include?("--server") || ARGV.include?("-s")
<ide> puts "Man page test server: http://localhost:1207/"
<ide><path>Library/Homebrew/cmd/tests.rb
<ide> module Homebrew
<ide> def tests
<del> (HOMEBREW_LIBRARY/'Homebrew/test').cd do
<del> ENV['TESTOPTS'] = '-v' if ARGV.verbose?
<del> quiet_system("gem", "list", "--installed", "bundler") || \
<del> system("gem", "install", "--no-ri", "--no-rdoc",
<del> "--user-install", "bundler")
<del> require 'rubygems'
<del> ENV["PATH"] = "#{Gem.user_dir}/bin:#{ENV["PATH"]}"
<add> (HOMEBREW_LIBRARY/"Homebrew/test").cd do
<add> ENV["TESTOPTS"] = "-v" if ARGV.verbose?
<add> Homebrew.install_gem_setup_path! "bundler"
<ide> quiet_system("bundle", "check") || \
<ide> system("bundle", "install", "--path", "vendor/bundle")
<ide> system "bundle", "exec", "rake", "test"
<ide><path>Library/Homebrew/utils.rb
<ide> def self.git_head
<ide> def self.git_last_commit
<ide> HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle }
<ide> end
<add>
<add> def self.install_gem_setup_path! gem
<add> return if quiet_system "gem", "list", "--installed", gem
<add> system "gem", "install", "--no-ri", "--no-rdoc",
<add> "--user-install", gem
<add> require "rubygems"
<add> ENV["PATH"] = "#{Gem.user_dir}/bin:#{ENV["PATH"]}"
<add> end
<ide> end
<ide>
<ide> def with_system_path | 3 |
Python | Python | set version to v2.1.0a6.dev0 | fe4e68cb71e4630283b445982e942b887566c635 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a5"
<add>__version__ = "2.1.0a6.dev0"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI"
<ide> __email__ = "[email protected]"
<ide> __license__ = "MIT"
<del>__release__ = True
<add>__release__ = False
<ide>
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Ruby | Ruby | fix secret_key_base for railties | e0c6bce203237592ddd5ae5e227b463322f28c20 | <ide><path>railties/test/application/url_generation_test.rb
<ide> class MyApp < Rails::Application
<ide> config.active_support.deprecation = :log
<ide> config.eager_load = false
<ide> config.hosts << proc { true }
<add> config.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33"
<ide> end
<ide>
<ide> Rails.application.initialize!
<ide><path>railties/test/rails_info_controller_test.rb
<ide> class Base
<ide>
<ide> class InfoControllerTest < ActionController::TestCase
<ide> tests Rails::InfoController
<add> Rails.application.config.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33"
<ide>
<ide> def setup
<ide> Rails.application.routes.draw do | 2 |
Mixed | Javascript | translate title and dashname correctly | 1b895e7809a6ab964a56099aa51db6bda01c4722 | <ide><path>curriculum/__fixtures__/chinese/challenge-stripped.md
<ide> ---
<del>localeTitle: 向HTML Elements说你好
<add>title: 向HTML Elements说你好
<ide> forumTopicId: 18276
<ide> ---
<ide>
<ide><path>curriculum/__fixtures__/chinese/challenge.md
<ide> ---
<ide> id: bd7123c8c441eddfaeb5bdef
<del>title: Say Hello to HTML Elements
<add>title: 向HTML Elements说你好
<ide> challengeType: 0
<ide> videoUrl: ''
<ide> forumTopicId: 18276
<del>localeTitle: 向HTML Elements说你好
<ide> ---
<ide>
<ide> ## Description
<ide><path>curriculum/__fixtures__/combined-html-comments.md
<ide> ---
<ide> id: bd7123c8c441eddfaeb5bdef
<del>title: Say Hello to HTML Elements
<add>originalTitle: Say Hello to HTML Elements
<ide> challengeType: 0
<ide> videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gpt2'
<ide> forumTopicId: 18276
<del>localeTitle: 向HTML Elements说你好
<add>title: 向HTML Elements说你好
<ide> ---
<ide>
<ide> ## Description
<ide><path>curriculum/__fixtures__/combined-js-comments.md
<ide> ---
<ide> id: bd7123c8c441eddfaeb5bdef
<del>title: Say Hello to HTML Elements
<add>originalTitle: Say Hello to HTML Elements
<ide> challengeType: 0
<ide> videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gpt2'
<ide> forumTopicId: 18276
<del>localeTitle: 向HTML Elements说你好
<add>title: 向HTML Elements说你好
<ide> ---
<ide>
<ide> ## Description
<ide><path>curriculum/__fixtures__/combined-jsx-comments.md
<ide> ---
<ide> id: bd7123c8c441eddfaeb5bdef
<del>title: Say Hello to HTML Elements
<add>originalTitle: Say Hello to HTML Elements
<ide> challengeType: 0
<ide> videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gpt2'
<ide> forumTopicId: 18276
<del>localeTitle: 向HTML Elements说你好
<add>title: 向HTML Elements说你好
<ide> ---
<ide>
<ide> ## Description
<ide><path>curriculum/__fixtures__/combined.md
<ide> ---
<ide> id: bd7123c8c441eddfaeb5bdef
<del>title: Say Hello to HTML Elements
<add>originalTitle: Say Hello to HTML Elements
<ide> challengeType: 0
<ide> videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gpt2'
<ide> forumTopicId: 18276
<del>localeTitle: 向HTML Elements说你好
<add>title: 向HTML Elements说你好
<ide> ---
<ide>
<ide> ## Description
<ide><path>curriculum/getChallenges.js
<ide> ${getFullPath('english')}
<ide> time
<ide> } = meta;
<ide> challenge.block = blockName;
<del> challenge.dashedName = dasherize(challenge.title);
<add> challenge.dashedName =
<add> lang === 'english'
<add> ? dasherize(challenge.title)
<add> : dasherize(challenge.originalTitle);
<add> delete challenge.originalTitle;
<ide> challenge.order = order;
<ide> challenge.superOrder = superOrder;
<ide> challenge.superBlock = superBlock;
<ide><path>curriculum/schema/challengeSchema.js
<ide> const fileJoi = Joi.object().keys({
<ide> history: [Joi.array().items(Joi.string().allow('')), Joi.string().allow('')]
<ide> });
<ide>
<del>function getSchemaForLang(lang) {
<del> let schema = Joi.object().keys({
<del> block: Joi.string(),
<del> blockId: Joi.objectId(),
<del> challengeOrder: Joi.number(),
<del> challengeType: Joi.number()
<del> .min(0)
<del> .max(11)
<add>const schema = Joi.object().keys({
<add> block: Joi.string(),
<add> blockId: Joi.objectId(),
<add> challengeOrder: Joi.number(),
<add> challengeType: Joi.number()
<add> .min(0)
<add> .max(11)
<add> .required(),
<add> checksum: Joi.number(),
<add> dashedName: Joi.string(),
<add> description: Joi.when('challengeType', {
<add> is: Joi.only([challengeTypes.step, challengeTypes.video]),
<add> then: Joi.string().allow(''),
<add> otherwise: Joi.string().required()
<add> }),
<add> fileName: Joi.string(),
<add> files: Joi.object().keys({
<add> indexcss: fileJoi,
<add> indexhtml: fileJoi,
<add> indexjs: fileJoi,
<add> indexjsx: fileJoi
<add> }),
<add> guideUrl: Joi.string().uri({ scheme: 'https' }),
<add> videoUrl: Joi.string().allow(''),
<add> forumTopicId: Joi.number(),
<add> helpRoom: Joi.string(),
<add> id: Joi.objectId().required(),
<add> instructions: Joi.string().allow(''),
<add> isComingSoon: Joi.bool(),
<add> isLocked: Joi.bool(),
<add> isPrivate: Joi.bool(),
<add> name: Joi.string(),
<add> order: Joi.number(),
<add> // video challenges only:
<add> videoId: Joi.when('challengeType', {
<add> is: challengeTypes.video,
<add> then: Joi.string().required()
<add> }),
<add> question: Joi.object().keys({
<add> text: Joi.string().required(),
<add> answers: Joi.array()
<add> .items(Joi.string())
<ide> .required(),
<del> checksum: Joi.number(),
<del> dashedName: Joi.string(),
<del> description: Joi.when('challengeType', {
<del> is: Joi.only([challengeTypes.step, challengeTypes.video]),
<del> then: Joi.string().allow(''),
<del> otherwise: Joi.string().required()
<del> }),
<del> fileName: Joi.string(),
<del> files: Joi.object().keys({
<add> solution: Joi.number().required()
<add> }),
<add> required: Joi.array().items(
<add> Joi.object().keys({
<add> link: Joi.string(),
<add> raw: Joi.bool(),
<add> src: Joi.string(),
<add> crossDomain: Joi.bool()
<add> })
<add> ),
<add> solutions: Joi.array().items(
<add> Joi.object().keys({
<ide> indexcss: fileJoi,
<ide> indexhtml: fileJoi,
<ide> indexjs: fileJoi,
<del> indexjsx: fileJoi
<del> }),
<del> guideUrl: Joi.string().uri({ scheme: 'https' }),
<del> videoUrl: Joi.string().allow(''),
<del> forumTopicId: Joi.number(),
<del> helpRoom: Joi.string(),
<del> id: Joi.objectId().required(),
<del> instructions: Joi.string().allow(''),
<del> isComingSoon: Joi.bool(),
<del> isLocked: Joi.bool(),
<del> isPrivate: Joi.bool(),
<del> name: Joi.string(),
<del> order: Joi.number(),
<del> // video challenges only:
<del> videoId: Joi.when('challengeType', {
<del> is: challengeTypes.video,
<del> then: Joi.string().required()
<del> }),
<del> question: Joi.object().keys({
<add> indexjsx: fileJoi,
<add> indexpy: fileJoi
<add> })
<add> ),
<add> superBlock: Joi.string(),
<add> superOrder: Joi.number(),
<add> suborder: Joi.number(),
<add> tests: Joi.array().items(
<add> // public challenges
<add> Joi.object().keys({
<ide> text: Joi.string().required(),
<del> answers: Joi.array()
<del> .items(Joi.string())
<del> .required(),
<del> solution: Joi.number().required()
<add> testString: Joi.string()
<add> .allow('')
<add> .required()
<ide> }),
<del> required: Joi.array().items(
<del> Joi.object().keys({
<del> link: Joi.string(),
<del> raw: Joi.bool(),
<del> src: Joi.string(),
<del> crossDomain: Joi.bool()
<del> })
<del> ),
<del> solutions: Joi.array().items(
<del> Joi.object().keys({
<del> indexcss: fileJoi,
<del> indexhtml: fileJoi,
<del> indexjs: fileJoi,
<del> indexjsx: fileJoi,
<del> indexpy: fileJoi
<del> })
<del> ),
<del> superBlock: Joi.string(),
<del> superOrder: Joi.number(),
<del> suborder: Joi.number(),
<del> tests: Joi.array().items(
<del> // public challenges
<del> Joi.object().keys({
<del> text: Joi.string().required(),
<del> testString: Joi.string()
<del> .allow('')
<del> .required()
<del> }),
<del> // our tests used in certification verification
<del> Joi.object().keys({
<del> id: Joi.string().required(),
<del> title: Joi.string().required()
<del> })
<del> ),
<del> template: Joi.string().allow(''),
<del> time: Joi.string().allow(''),
<del> title: Joi.string().required()
<del> });
<add> // our tests used in certification verification
<add> Joi.object().keys({
<add> id: Joi.string().required(),
<add> title: Joi.string().required()
<add> })
<add> ),
<add> template: Joi.string().allow(''),
<add> time: Joi.string().allow(''),
<add> title: Joi.string().required()
<add>});
<ide>
<del> if (lang !== 'english') {
<del> // TODO: make this required again once all current challenges have it.
<del> schema = schema.append({
<del> localeTitle: Joi.string().allow('')
<del> });
<del> }
<del> return schema;
<del>}
<del>exports.challengeSchemaValidator = lang => {
<del> const schema = getSchemaForLang(lang);
<add>exports.challengeSchemaValidator = () => {
<ide> return challenge => Joi.validate(challenge, schema);
<ide> };
<ide><path>curriculum/test/test-challenges.js
<ide> function validateBlock(challenge) {
<ide> function populateTestsForLang({ lang, challenges, meta }) {
<ide> const mongoIds = new MongoIds();
<ide> const challengeTitles = new ChallengeTitles();
<del> const validateChallenge = challengeSchemaValidator(lang);
<add> const validateChallenge = challengeSchemaValidator();
<ide>
<ide> describe(`Check challenges (${lang})`, function() {
<ide> this.timeout(5000);
<ide> challenges.forEach((challenge, id) => {
<ide> const dashedBlockName = dasherize(challenge.block);
<ide> describe(challenge.block || 'No block', function() {
<ide> describe(challenge.title || 'No title', function() {
<del> it('Matches a title in meta.json', function() {
<del> const index = meta[dashedBlockName].findIndex(
<del> arr => arr[1] === challenge.title
<del> );
<del>
<del> if (index < 0) {
<del> throw new AssertionError(
<del> `Cannot find title "${challenge.title}" in meta.json file`
<del> );
<del> }
<del> });
<del>
<add> // Note: the title in meta.json are purely for human readability and
<add> // do not include translations, so we do not validate against them.
<ide> it('Matches an ID in meta.json', function() {
<ide> const index = meta[dashedBlockName].findIndex(
<ide> arr => arr[0] === challenge.id
<ide><path>tools/challenge-md-parser/translation-parser/__fixtures__/challenge-objects.js
<ide> const ENGLISH_VIDEO_CHALLENGE = {
<ide>
<ide> const TRANSLATED_CERTIFICATE = {
<ide> id: '561add10cb82ac38a17513bc',
<del> title: 'Responsive Web Design Certificate',
<add> title: '响应式网页设计证书',
<ide> challengeType: 7,
<ide> isPrivate: true,
<ide> videoUrl: '',
<del> localeTitle: '响应式网页设计证书',
<ide> tests: [
<ide> { id: 'bd7158d8c442eddfaeb5bd18', title: 'Build a Tribute Page' },
<ide> { id: '587d78af367417b2b2512b03', title: 'Build a Survey Form' },
<ide> const TRANSLATED_CERTIFICATE = {
<ide>
<ide> const TRANSLATED_CHALLENGE = {
<ide> id: 'id',
<del> title: 'Title',
<add> title: 'Translated title',
<add> challengeType: 0,
<add> videoUrl: 'https://scrimba.com/',
<add> forumTopicId: 9876,
<add> tests: [
<add> {
<add> text: 'Translated test text',
<add> testString: 'Translated assertions, should be ignored'
<add> },
<add> {
<add> text: 'Translated test text2',
<add> testString: 'Translated assertions, should be ignored2'
<add> }
<add> ],
<add> solutions: ['Translated solution html string, should be ignored'],
<add> description: 'Translated description html string',
<add> instructions: 'Translated instructions html string',
<add> files: [
<add> {
<add> key: 'indexhtml',
<add> ext: 'html',
<add> name: 'index',
<add> contents: 'Translated seed html string, should be ignored',
<add> head: 'Translated head string, should be ignored',
<add> tail: 'Translated tail string, should be ignored'
<add> }
<add> ]
<add>};
<add>
<add>const TRANSLATED_CHALLENGE_NO_TITLE = {
<add> id: 'id',
<ide> challengeType: 0,
<ide> videoUrl: 'https://scrimba.com/',
<ide> forumTopicId: 9876,
<del> localeTitle: 'Translated title',
<ide> tests: [
<ide> {
<ide> text: 'Translated test text',
<ide> const TRANSLATED_VIDEO_CHALLENGE = {
<ide>
<ide> const WRONG_NUM_TESTS_CHALLENGE = {
<ide> id: 'id',
<del> title: 'Title',
<add> title: 'Translated title',
<ide> challengeType: 0,
<ide> videoUrl: 'https://scrimba.com/',
<ide> forumTopicId: 12345,
<del> localeTitle: 'Translated title',
<ide> tests: [
<ide> {
<ide> text: 'Translated test text',
<ide> exports.ENGLISH_CHALLENGE_NO_FILES = ENGLISH_CHALLENGE_NO_FILES;
<ide> exports.ENGLISH_VIDEO_CHALLENGE = ENGLISH_VIDEO_CHALLENGE;
<ide> exports.TRANSLATED_CERTIFICATE = TRANSLATED_CERTIFICATE;
<ide> exports.TRANSLATED_CHALLENGE = TRANSLATED_CHALLENGE;
<add>exports.TRANSLATED_CHALLENGE_NO_TITLE = TRANSLATED_CHALLENGE_NO_TITLE;
<ide> exports.TRANSLATED_VIDEO_CHALLENGE = TRANSLATED_VIDEO_CHALLENGE;
<ide> exports.WRONG_NUM_TESTS_CHALLENGE = WRONG_NUM_TESTS_CHALLENGE;
<ide><path>tools/challenge-md-parser/translation-parser/translation-parser.js
<add>const { isEmpty } = require('lodash');
<ide> const clone = require('lodash/cloneDeep');
<ide>
<ide> exports.translateComments = (text, lang, dict, codeLang) => {
<ide> exports.mergeChallenges = (engChal, transChal) => {
<ide> ...engChal,
<ide> description: transChal.description,
<ide> instructions: transChal.instructions,
<del> localeTitle: transChal.localeTitle,
<add> originalTitle: engChal.title,
<add> // TODO: throw in production?
<add> title: isEmpty(transChal.title) ? engChal.title : transChal.title,
<ide> forumTopicId: transChal.forumTopicId
<ide> };
<ide> if (!hasTests)
<ide> throw Error(
<ide> `Both challenges must have tests or questions.
<ide> title: ${engChal.title}
<del> localeTitle: ${transChal.localeTitle}`
<add> translated title: ${transChal.title}`
<ide> );
<ide> // TODO: this should break the build when we go to production, but
<ide> // not for testing.
<ide> if (transChal.tests && transChal.tests.length !== engChal.tests.length) {
<ide> console.error(
<ide> `Challenges in both languages must have the same number of tests.
<ide> title: ${engChal.title}
<del> localeTitle: ${transChal.localeTitle}`
<add> translated title: ${transChal.title}`
<ide> );
<ide> return challenge;
<ide> }
<ide>
<ide> // throw Error(
<ide> // `Challenges in both languages must have the same number of tests.
<ide> // title: ${engChal.title}
<del> // localeTitle: ${transChal.localeTitle}`
<add> // translated title: ${transChal.title}`
<ide> // );
<ide>
<ide> if (transChal.tests) {
<ide><path>tools/challenge-md-parser/translation-parser/translation-parser.test.js
<ide> const {
<ide> ENGLISH_VIDEO_CHALLENGE,
<ide> TRANSLATED_CERTIFICATE,
<ide> TRANSLATED_CHALLENGE,
<add> TRANSLATED_CHALLENGE_NO_TITLE,
<ide> TRANSLATED_VIDEO_CHALLENGE
<ide> // WRONG_NUM_TESTS_CHALLENGE
<ide> } = require('./__fixtures__/challenge-objects');
<ide> const COMBINED_CHALLENGE = mergeChallenges(
<ide> TRANSLATED_CHALLENGE
<ide> );
<ide>
<add>const COMBINED_CHALLENGE_NO_TITLE = mergeChallenges(
<add> ENGLISH_CHALLENGE,
<add> TRANSLATED_CHALLENGE_NO_TITLE
<add>);
<add>
<ide> const COMBINED_CHALLENGE_TWO_SOLUTIONS = mergeChallenges(
<ide> ENGLISH_CHALLENGE_TWO_SOLUTIONS,
<ide> TRANSLATED_CHALLENGE
<ide> describe('translation parser', () => {
<ide> expect(actualStrings[i]).toBe(expectedStrings[i]);
<ide> }
<ide> });
<del> it('takes the localTitle from the second challenge', () => {
<del> expect(COMBINED_CHALLENGE.localeTitle).toBe(
<del> TRANSLATED_CHALLENGE.localeTitle
<del> );
<add> it('takes the title from the second challenge', () => {
<add> expect(COMBINED_CHALLENGE.title).toBe(TRANSLATED_CHALLENGE.title);
<add> });
<add>
<add> // TODO: throw in production?
<add> it("takes the first challenge's title if the second is missing", () => {
<add> expect(COMBINED_CHALLENGE_NO_TITLE.title).toBe(ENGLISH_CHALLENGE.title);
<add> });
<add>
<add> // 'originalTitle' is just used to create the dashedName (which must be
<add> // the same in both challenges, but only gets added after parsing)
<add> it('creates originalTitle from the first challenge', () => {
<add> expect(COMBINED_CHALLENGE.originalTitle).toBe(ENGLISH_CHALLENGE.title);
<ide> });
<ide> // TODO: reinstate this after alpha testing.
<ide> // it('throws an error if the numbers of tests do not match', () => { | 12 |
Go | Go | remove tagger and newtagger | ff81dc3544b018a85a7bad4d8934fe41cb3276ea | <ide><path>api/server/backend/build/backend.go
<ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string
<ide> options := config.Options
<ide> useBuildKit := options.Version == types.BuilderBuildKit
<ide>
<del> tagger, err := NewTagger(b.imageComponent, config.ProgressWriter.StdoutFormatter, options.Tags)
<add> tags, err := sanitizeRepoAndTags(options.Tags)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string
<ide> fmt.Fprintf(stdout, "Successfully built %s\n", stringid.TruncateID(imageID))
<ide> }
<ide> if imageID != "" {
<del> err = tagger.TagImages(image.ID(imageID))
<add> err = tagImages(b.imageComponent, config.ProgressWriter.StdoutFormatter, image.ID(imageID), tags)
<ide> }
<ide> return imageID, err
<ide> }
<ide><path>api/server/backend/build/tag.go
<ide> import (
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<del>// Tagger is responsible for tagging an image created by a builder
<del>type Tagger struct {
<del> imageComponent ImageComponent
<del> stdout io.Writer
<del> repoAndTags []reference.Named
<del>}
<del>
<del>// NewTagger returns a new Tagger for tagging the images of a build.
<del>// If any of the names are invalid tags an error is returned.
<del>func NewTagger(backend ImageComponent, stdout io.Writer, names []string) (*Tagger, error) {
<del> reposAndTags, err := sanitizeRepoAndTags(names)
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &Tagger{
<del> imageComponent: backend,
<del> stdout: stdout,
<del> repoAndTags: reposAndTags,
<del> }, nil
<del>}
<del>
<del>// TagImages creates image tags for the imageID
<del>func (bt *Tagger) TagImages(imageID image.ID) error {
<del> for _, rt := range bt.repoAndTags {
<del> if err := bt.imageComponent.TagImageWithReference(imageID, rt); err != nil {
<add>// tagImages creates image tags for the imageID.
<add>func tagImages(ic ImageComponent, stdout io.Writer, imageID image.ID, repoAndTags []reference.Named) error {
<add> for _, rt := range repoAndTags {
<add> if err := ic.TagImageWithReference(imageID, rt); err != nil {
<ide> return err
<ide> }
<del> fmt.Fprintf(bt.stdout, "Successfully tagged %s\n", reference.FamiliarString(rt))
<add> _, _ = fmt.Fprintln(stdout, "Successfully tagged", reference.FamiliarString(rt))
<ide> }
<ide> return nil
<ide> } | 2 |
Javascript | Javascript | add missing semicolon | 9b70e82246e791f3045e9434d9282a555d5a97b0 | <ide><path>examples/quadratic/example.js
<ide> var QuadraticCalculator = React.createClass({
<ide> render: function() {
<ide> var a = this.state.a;
<ide> var b = this.state.b;
<del> var c = this.state.c
<add> var c = this.state.c;
<ide> var x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
<ide> var x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
<ide> return ( | 1 |
PHP | PHP | put the opening { in the new line | e44fa69f127f47f1d4a3c54ed28f04f341db3bf9 | <ide><path>src/View/View.php
<ide> protected function _getViewFileName($name = null)
<ide> * @param string $name Name of file which should be inflected.
<ide> * @return string File name after conversion
<ide> */
<del> protected function _inflectViewFileName($name) {
<add> protected function _inflectViewFileName($name)
<add> {
<ide> return Inflector::underscore($name);
<ide> }
<ide> | 1 |
PHP | PHP | apply fixes from styleci | e0766cfd81a164bd5f0a0070216400b430d30185 | <ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> use Illuminate\Database\Connection;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Query\Expression;
<del>use Illuminate\Database\SQLiteConnection;
<ide> use Illuminate\Database\Schema\Grammars\Grammar;
<add>use Illuminate\Database\SQLiteConnection;
<ide> use Illuminate\Support\Fluent;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> | 1 |
Javascript | Javascript | update example to use ngmodel best practices | d40749caabfbdaf867973bb6e8de75f64902f13a | <ide><path>src/ng/directive/input.js
<ide> var inputType = {
<ide> <script>
<ide> angular.module('textInputExample', [])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.text = 'guest';
<del> $scope.word = /^\s*\w*\s*$/;
<add> $scope.example = {
<add> text: 'guest',
<add> word: /^\s*\w*\s*$/
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="ExampleController">
<del> Single word: <input type="text" name="input" ng-model="text"
<del> ng-pattern="word" required ng-trim="false">
<add> Single word: <input type="text" name="input" ng-model="example.text"
<add> ng-pattern="example.word" required ng-trim="false">
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.pattern">
<ide> Single word only!</span>
<ide>
<del> <tt>text = {{text}}</tt><br/>
<add> <tt>text = {{example.text}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var text = element(by.binding('text'));
<add> var text = element(by.binding('example.text'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('text'));
<add> var input = element(by.model('example.text'));
<ide>
<ide> it('should initialize to model', function() {
<ide> expect(text.getText()).toContain('guest');
<ide> var inputType = {
<ide> <script>
<ide> angular.module('dateInputExample', [])
<ide> .controller('DateController', ['$scope', function($scope) {
<del> $scope.value = new Date(2013, 9, 22);
<add> $scope.example = {
<add> value: new Date(2013, 9, 22)
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="DateController as dateCtrl">
<ide> Pick a date in 2013:
<del> <input type="date" id="exampleInput" name="input" ng-model="value"
<add> <input type="date" id="exampleInput" name="input" ng-model="example.value"
<ide> placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.date">
<ide> Not a valid date!</span>
<del> <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
<add> <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value | date: "yyyy-MM-dd"'));
<add> var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> // currently protractor/webdriver does not support
<ide> // sending keys to all known HTML5 input controls
<ide> var inputType = {
<ide> <script>
<ide> angular.module('dateExample', [])
<ide> .controller('DateController', ['$scope', function($scope) {
<del> $scope.value = new Date(2010, 11, 28, 14, 57);
<add> $scope.example = {
<add> value: new Date(2010, 11, 28, 14, 57)
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="DateController as dateCtrl">
<ide> Pick a date between in 2013:
<del> <input type="datetime-local" id="exampleInput" name="input" ng-model="value"
<add> <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
<ide> placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.datetimelocal">
<ide> Not a valid date!</span>
<del> <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<add> <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
<add> var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> // currently protractor/webdriver does not support
<ide> // sending keys to all known HTML5 input controls
<ide> var inputType = {
<ide> <script>
<ide> angular.module('timeExample', [])
<ide> .controller('DateController', ['$scope', function($scope) {
<del> $scope.value = new Date(1970, 0, 1, 14, 57, 0);
<add> $scope.example = {
<add> value: new Date(1970, 0, 1, 14, 57, 0)
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="DateController as dateCtrl">
<ide> Pick a between 8am and 5pm:
<del> <input type="time" id="exampleInput" name="input" ng-model="value"
<add> <input type="time" id="exampleInput" name="input" ng-model="example.value"
<ide> placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.time">
<ide> Not a valid date!</span>
<del> <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
<add> <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value | date: "HH:mm:ss"'));
<add> var value = element(by.binding('example.value | date: "HH:mm:ss"'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> // currently protractor/webdriver does not support
<ide> // sending keys to all known HTML5 input controls
<ide> var inputType = {
<ide> <script>
<ide> angular.module('weekExample', [])
<ide> .controller('DateController', ['$scope', function($scope) {
<del> $scope.value = new Date(2013, 0, 3);
<add> $scope.example = {
<add> value: new Date(2013, 0, 3)
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="DateController as dateCtrl">
<ide> Pick a date between in 2013:
<del> <input id="exampleInput" type="week" name="input" ng-model="value"
<add> <input id="exampleInput" type="week" name="input" ng-model="example.value"
<ide> placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.week">
<ide> Not a valid date!</span>
<del> <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
<add> <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value | date: "yyyy-Www"'));
<add> var value = element(by.binding('example.value | date: "yyyy-Www"'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> // currently protractor/webdriver does not support
<ide> // sending keys to all known HTML5 input controls
<ide> var inputType = {
<ide> <script>
<ide> angular.module('monthExample', [])
<ide> .controller('DateController', ['$scope', function($scope) {
<del> $scope.value = new Date(2013, 9, 1);
<add> $scope.example = {
<add> value: new Date(2013, 9, 1)
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="DateController as dateCtrl">
<ide> Pick a month in 2013:
<del> <input id="exampleInput" type="month" name="input" ng-model="value"
<add> <input id="exampleInput" type="month" name="input" ng-model="example.value"
<ide> placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.month">
<ide> Not a valid month!</span>
<del> <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
<add> <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value | date: "yyyy-MM"'));
<add> var value = element(by.binding('example.value | date: "yyyy-MM"'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> // currently protractor/webdriver does not support
<ide> // sending keys to all known HTML5 input controls
<ide> var inputType = {
<ide> <script>
<ide> angular.module('numberExample', [])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.value = 12;
<add> $scope.example = {
<add> value: 12
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="ExampleController">
<del> Number: <input type="number" name="input" ng-model="value"
<add> Number: <input type="number" name="input" ng-model="example.value"
<ide> min="0" max="99" required>
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.number">
<ide> Not valid number!</span>
<del> <tt>value = {{value}}</tt><br/>
<add> <tt>value = {{example.value}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var value = element(by.binding('value'));
<add> var value = element(by.binding('example.value'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('value'));
<add> var input = element(by.model('example.value'));
<ide>
<ide> it('should initialize to model', function() {
<ide> expect(value.getText()).toContain('12');
<ide> var inputType = {
<ide> <script>
<ide> angular.module('urlExample', [])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.text = 'http://google.com';
<add> $scope.url = {
<add> text: 'http://google.com'
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="ExampleController">
<del> URL: <input type="url" name="input" ng-model="text" required>
<add> URL: <input type="url" name="input" ng-model="url.text" required>
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.url">
<ide> Not valid url!</span>
<del> <tt>text = {{text}}</tt><br/>
<add> <tt>text = {{url.text}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> var inputType = {
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var text = element(by.binding('text'));
<add> var text = element(by.binding('url.text'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('text'));
<add> var input = element(by.model('url.text'));
<ide>
<ide> it('should initialize to model', function() {
<ide> expect(text.getText()).toContain('http://google.com');
<ide> var inputType = {
<ide> <script>
<ide> angular.module('emailExample', [])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.text = '[email protected]';
<add> $scope.email = {
<add> text: '[email protected]'
<add> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="ExampleController">
<del> Email: <input type="email" name="input" ng-model="text" required>
<add> Email: <input type="email" name="input" ng-model="email.text" required>
<ide> <span class="error" ng-show="myForm.input.$error.required">
<ide> Required!</span>
<ide> <span class="error" ng-show="myForm.input.$error.email">
<ide> Not valid email!</span>
<del> <tt>text = {{text}}</tt><br/>
<add> <tt>text = {{email.text}}</tt><br/>
<ide> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<ide> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<ide> var inputType = {
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<del> var text = element(by.binding('text'));
<add> var text = element(by.binding('email.text'));
<ide> var valid = element(by.binding('myForm.input.$valid'));
<del> var input = element(by.model('text'));
<add> var input = element(by.model('email.text'));
<ide>
<ide> it('should initialize to model', function() {
<ide> expect(text.getText()).toContain('[email protected]');
<ide> var inputType = {
<ide> <script>
<ide> angular.module('radioExample', [])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.color = 'blue';
<add> $scope.color = {
<add> name: 'blue'
<add> };
<ide> $scope.specialValue = {
<ide> "id": "12345",
<ide> "value": "green"
<ide> };
<ide> }]);
<ide> </script>
<ide> <form name="myForm" ng-controller="ExampleController">
<del> <input type="radio" ng-model="color" value="red"> Red <br/>
<del> <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<del> <input type="radio" ng-model="color" value="blue"> Blue <br/>
<del> <tt>color = {{color | json}}</tt><br/>
<add> <input type="radio" ng-model="color.name" value="red"> Red <br/>
<add> <input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/>
<add> <input type="radio" ng-model="color.name" value="blue"> Blue <br/>
<add> <tt>color = {{color.name | json}}</tt><br/>
<ide> </form>
<ide> Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<ide> it('should change state', function() {
<del> var color = element(by.binding('color'));
<add> var color = element(by.binding('color.name'));
<ide>
<ide> expect(color.getText()).toContain('blue');
<ide>
<del> element.all(by.model('color')).get(0).click();
<add> element.all(by.model('color.name')).get(0).click();
<ide>
<ide> expect(color.getText()).toContain('red');
<ide> }); | 1 |
Javascript | Javascript | avoid stack overflow | 9e650b1807f58662fbe51ad4aaec4e753efe5f1e | <ide><path>lib/FileSystemInfo.js
<ide> class FileSystemInfo {
<ide> path: directory
<ide> });
<ide> }
<del> callback();
<add> process.nextTick(callback);
<ide> break;
<ide> }
<ide> case RBDT_DIRECTORY_DEPENDENCIES: { | 1 |
Python | Python | add a test for fix | 9cafdd1854ccd5215b7a188c5896fb498a59d725 | <ide><path>tests/test_routers.py
<ide> def detail_custom_route_get(self, request, *args, **kwargs):
<ide> return Response({'method': 'link2'})
<ide>
<ide>
<add>class SubDynamicListAndDetailViewSet(DynamicListAndDetailViewSet):
<add> pass
<add>
<add>
<ide> class TestDynamicListAndDetailRouter(TestCase):
<ide> def setUp(self):
<ide> self.router = SimpleRouter()
<ide>
<del> def test_list_and_detail_route_decorators(self):
<del> routes = self.router.get_routes(DynamicListAndDetailViewSet)
<add> def _test_list_and_detail_route_decorators(self, viewset):
<add> routes = self.router.get_routes(viewset)
<ide> decorator_routes = [r for r in routes if not (r.name.endswith('-list') or r.name.endswith('-detail'))]
<ide>
<ide> MethodNamesMap = namedtuple('MethodNamesMap', 'method_name url_path')
<ide> def test_list_and_detail_route_decorators(self):
<ide> else:
<ide> method_map = 'get'
<ide> self.assertEqual(route.mapping[method_map], method_name)
<add>
<add> def test_list_and_detail_route_decorators(self):
<add> self._test_list_and_detail_route_decorators(DynamicListAndDetailViewSet)
<add>
<add> def test_inherited_list_and_detail_route_decorators(self):
<add> self._test_list_and_detail_route_decorators(SubDynamicListAndDetailViewSet) | 1 |
Python | Python | fix py3 compat bug | bb0084f5bef9b871a82f0451ed71131ffb7a43b3 | <ide><path>flask/testsuite/templating.py
<ide> def test_template_loader_debugging(self):
<ide> class _TestHandler(logging.Handler):
<ide> def handle(x, record):
<ide> called.append(True)
<del> text = unicode(record.msg)
<add> text = str(record.msg)
<ide> self.assert_('1: trying loader of application '
<ide> '"blueprintapp"' in text)
<ide> self.assert_('2: trying loader of blueprint "admin" ' | 1 |
Python | Python | create factorial_python.py (#530) | 459a4f35a5bba49248a220f18b9baef066535d15 | <ide><path>factorial_python.py
<add># Python program to find the factorial of a number provided by the user.
<add>
<add># change the value for a different result
<add>num = 10
<add>
<add># uncomment to take input from the user
<add>#num = int(input("Enter a number: "))
<add>
<add>factorial = 1
<add>
<add># check if the number is negative, positive or zero
<add>if num < 0:
<add> print("Sorry, factorial does not exist for negative numbers")
<add>elif num == 0:
<add> print("The factorial of 0 is 1")
<add>else:
<add> for i in range(1,num + 1):
<add> factorial = factorial*i
<add> print("The factorial of",num,"is",factorial) | 1 |
PHP | PHP | remove unused argument | 5099ba134ece2fc00a0a15e8661bb824b91afc4a | <ide><path>src/ORM/EagerLoader.php
<ide> protected function _fixStrategies()
<ide> }
<ide> foreach ($configs as $loadable) {
<ide> if (strpos($loadable->aliasPath(), '.')) {
<del> $this->_correctStrategy($loadable, $alias);
<add> $this->_correctStrategy($loadable);
<ide> }
<ide> }
<ide> }
<ide> protected function _fixStrategies()
<ide> * under the same direct associations chain
<ide> *
<ide> * @param \Cake\ORM\EagerLoader $loadable The association config
<del> * @param string $alias the name of the association to evaluate
<ide> * @return void
<ide> */
<del> protected function _correctStrategy($loadable, $alias)
<add> protected function _correctStrategy($loadable)
<ide> {
<ide> $config = $loadable->config();
<ide> $currentStrategy = isset($config['strategy']) ?
<ide> protected function _resolveJoins($associations, $matching = [])
<ide> }
<ide>
<ide> if ($inMatching) {
<del> $this->_correctStrategy($loadable, $table);
<add> $this->_correctStrategy($loadable);
<ide> }
<ide>
<ide> $loadable->canBeJoined(false); | 1 |
Python | Python | fix lint error in test file | be4fb940be3b09cee538ee72869267395bb2365f | <ide><path>libcloud/test/compute/test_dimensiondata.py
<ide> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_07e3621a_a920
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_deleteServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer_INPROGRESS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deleteServer_INPROGRESS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_deleteServer_RESOURCEBUSY.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}rebootServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_rebootServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer_INPROGRESS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_rebootServer_INPROGRESS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}rebootServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_rebootServer_RESOURCEBUSY.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server(self, method, url, body, headers):
<ide> if url.endswith('datacenterId=NA3'):
<ide> body = self.fixtures.load(
<ide> 'server_server_NA3.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server(self, method,
<ide> 'server_server.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGESIZE50(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGESIZE50(self, method, url, body, headers):
<ide> if not url.endswith('pageSize=50'):
<ide> raise ValueError("pageSize is not set as expected")
<ide> body = self.fixtures.load(
<ide> 'server_server.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_EMPTY(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_EMPTY(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_server_paginated_empty.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGED_THEN_EMPTY(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGED_THEN_EMPTY(self, method, url, body, headers):
<ide> if 'pageNumber=2' in url:
<ide> body = self.fixtures.load(
<ide> 'server_server_paginated_empty.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGED_THEN_EMP
<ide> 'server_server_paginated.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATED(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATED(self, method, url, body, headers):
<ide> if 'pageNumber=2' in url:
<ide> body = self.fixtures.load(
<ide> 'server_server.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATED(self
<ide> 'server_server_paginated.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATEDEMPTY(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_PAGINATEDEMPTY(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_server_paginated_empty.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_ALLFILTERS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters:
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_ALLFILTERS(sel
<ide> 'server_server.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_antiAffinityRule_list.xml'
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_ALLFILTERS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters:
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_ALLF
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_PAGINATED(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_PAGINATED(self, method, url, body, headers):
<ide> if 'pageNumber=2' in url:
<ide> body = self.fixtures.load(
<ide> 'server_antiAffinityRule_list.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_antiAffinityRule_PAGI
<ide> 'server_antiAffinityRule_list_PAGINATED.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter(self, method, url, body, headers):
<ide> if url.endswith('id=NA9'):
<ide> body = self.fixtures.load(
<ide> 'infrastructure_datacenter_NA9.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter(se
<ide> 'infrastructure_datacenter.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter_ALLFILTERS(self, method, url, body, headers):
<ide> if url.endswith('id=NA9'):
<ide> body = self.fixtures.load(
<ide> 'infrastructure_datacenter_NA9.xml')
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_infrastructure_datacenter_AL
<ide> 'infrastructure_datacenter.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_updateVmwareTools(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_updateVmwareTools(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}updateVmwareTools":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_updateVmwareTools.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}startServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_startServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer_INPROGRESS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_startServer_INPROGRESS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}startServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_startServer_INPROGRESS.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}shutdownServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_shutdownServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer_INPROGRESS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_shutdownServer_INPROGRESS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}shutdownServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_shutdownServer_INPROGRESS.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_resetServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_resetServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}resetServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_resetServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}powerOffServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_powerOffServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer_INPROGRESS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_powerOffServer_INPROGRESS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}powerOffServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_powerOffServer_INPROGRESS.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_networkDomain.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_ALLFILTERS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters:
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_ALLFIL
<ide> 'network_networkDomain.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_vlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_ALLFILTERS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters:
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_ALLFILTERS(self
<ide> 'network_vlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deployServer":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_deployServer(self, me
<ide> 'server_deployServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_e75ead52_692f_4314_8725_c8a4f4d13a87(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_server_e75ead52_692f_4314_8725_c8a4f4d13a87(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_server_e75ead52_692f_4314_8725_c8a4f4d13a87.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployNetworkDomain(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployNetworkDomain(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deployNetworkDomain":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deployNetworkDomain.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be_ALLFILTERS(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_networkDomain_8cdfd607_f429_4df6_9352_162cfc0891be.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editNetworkDomain(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editNetworkDomain(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}editNetworkDomain":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_editNetworkDomain.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNetworkDomain(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNetworkDomain(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteNetworkDomain":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deleteNetworkDomain.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployVlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deployVlan(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deployVlan":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deployVlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_0e56433f_d808_4669_821d_812769517ff8(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_vlan_0e56433f_d808_4669_821d_812769517ff8(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_vlan_0e56433f_d808_4669_821d_812769517ff8.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editVlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editVlan(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}editVlan":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_editVlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteVlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteVlan(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteVlan":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deleteVlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_expandVlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_expandVlan(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}expandVlan":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_expandVlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_addPublicIpBlock(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_addPublicIpBlock(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}addPublicIpBlock":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_addPublicIpBlock.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_4487241a_f0ca_11e3_9315_d4bed9b167ba(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_4487241a_f0ca_11e3_9315_d4bed9b167ba(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_publicIpBlock_4487241a_f0ca_11e3_9315_d4bed9b167ba.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_publicIpBlock.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_9945dc4a_bdce_11e4_8c14_b8ca3a5d9ef8(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_publicIpBlock_9945dc4a_bdce_11e4_8c14_b8ca3a5d9ef8(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_publicIpBlock_9945dc4a_bdce_11e4_8c14_b8ca3a5d9ef8.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_removePublicIpBlock(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_removePublicIpBlock(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}removePublicIpBlock":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_removePublicIpBlock.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_firewallRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createFirewallRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createFirewallRule(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}createFirewallRule":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_createFirewallRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule_d0a20f59_77b9_4f28_a63b_e58496b73a6c(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_firewallRule_d0a20f59_77b9_4f28_a63b_e58496b73a6c(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_firewallRule_d0a20f59_77b9_4f28_a63b_e58496b73a6c.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editFirewallRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_editFirewallRule(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}editFirewallRule":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_editFirewallRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteFirewallRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteFirewallRule(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteFirewallRule":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deleteFirewallRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createNatRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_createNatRule(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}createNatRule":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_createNatRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_natRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule_2187a636_7ebb_49a1_a2ff_5d617f496dce(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_natRule_2187a636_7ebb_49a1_a2ff_5d617f496dce(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'network_natRule_2187a636_7ebb_49a1_a2ff_5d617f496dce.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNatRule(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_network_deleteNatRule(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteNatRule":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'network_deleteNatRule.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addNic(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addNic(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}addNic":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_addNic.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeNic(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeNic(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}removeNic":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_removeNic.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_disableServerMonitoring(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_disableServerMonitoring(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}disableServerMonitoring":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_disableServerMonitoring.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_enableServerMonitoring(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_enableServerMonitoring(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}enableServerMonitoring":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_enableServerMonitoring.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_changeServerMonitoringPlan(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_changeServerMonitoringPlan(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}changeServerMonitoringPlan":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_changeServerMonitoringPlan.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_c14b1a46_2428_44c1_9c1a_b20e6418d08c(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_c14b1a46_2428_44c1_9c1a_b20e6418d08c(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage_c14b1a46_2428_44c1_9c1a_b20e6418d08c.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_6b4fb0c7_a57b_4f58_b59c_9958f94f971a(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_6b4fb0c7_a57b_4f58_b59c_9958f94f971a(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage_6b4fb0c7_a57b_4f58_b59c_9958f94f971a.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage_BAD_REQUEST.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage_BAD_REQUEST.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_FAKE_IMAGE_ID(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_osImage_FAKE_IMAGE_ID(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_osImage_BAD_REQUEST.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_customerImage.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_customerImage_5234e5c7_01de_4411_8b6e_baeb8d91cf5d.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_customerImage_2ffa36c8_1848_49eb_b4fa_9d908775f68c.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_FAKE_IMAGE_ID(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_image_customerImage_FAKE_IMAGE_ID(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'image_customerImage_BAD_REQUEST.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_reconfigureServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_reconfigureServer(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}reconfigureServer":
<ide> raise InvalidRequestError(request.tag)
<ide> body = self.fixtures.load(
<ide> 'server_reconfigureServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_cleanServer(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_cleanServer(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_cleanServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addDisk(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_addDisk(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_addDisk.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeDisk(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_removeDisk(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server_removeDisk.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}createTagKey":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey(self, metho
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_ALLPARAMS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_ALLPARAMS(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}createTagKey":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_ALLPARAMS(s
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_BADREQUEST(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_createTagKey_BADREQUEST(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_createTagKey_BADREQUEST.xml')
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_tagKey_list.xml'
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_SINGLE(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_SINGLE(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_tagKey_list_SINGLE.xml'
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_ALLFILTERS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_ALLFILTERS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters:
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_ALLFILTERS(self,
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_tagKey_5ab77f5f_5aa9_426f_8459_4eab34e03d54.xml'
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075_NOEXIST(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tagKey_d047c609_93d7_4bc5_8fc9_732c85840075_NOEXIST(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_tagKey_5ab77f5f_5aa9_426f_8459_4eab34e03d54_BADREQUEST.xml'
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NAME(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NAME(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}editTagKey":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NAME(self, me
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOTNAME(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOTNAME(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}editTagKey":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOTNAME(self,
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOCHANGE(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_editTagKey_NOCHANGE(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_editTagKey_BADREQUEST.xml'
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}deleteTagKey":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey(self, metho
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey_NOEXIST(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_deleteTagKey_NOEXIST(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_deleteTagKey_BADREQUEST.xml'
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}applyTags":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags(self, method,
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOVALUE(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOVALUE(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}applyTags":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOVALUE(self,
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOTAGKEY(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_applyTags_NOTAGKEY(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_applyTags_BADREQUEST.xml'
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags(self, method, url, body, headers):
<ide> request = ET.fromstring(body)
<ide> if request.tag != "{urn:didata.com:api:cloud:types}removeTags":
<ide> raise InvalidRequestError(request.tag)
<ide> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags(self, method,
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags_NOTAG(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_removeTags_NOTAG(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_removeTag_BADREQUEST.xml'
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'tag_tag_list.xml'
<ide> )
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag_ALLPARAMS(self, method, url, body, headers):
<add> def _caas_2_3_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_tag_tag_ALLPARAMS(self, method, url, body, headers):
<ide> (_, params) = url.split('?')
<ide> parameters = params.split('&')
<ide> for parameter in parameters: | 1 |
Text | Text | add markdown explanation to video challenge docs | b4c5bb9cf223fc6f6b5960525843d036eacdf848 | <ide><path>docs/how-to-help-with-video-challenges.md
<ide> An optional description with helpful information related to the video.
<ide> <section id='tests'>
<ide>
<ide> ```yml
<del>tests:
<add>question:
<ide> text: 'Question'
<ide> answers:
<ide> - 'Answer One'
<ide> You can add the question locally or directly throught the GitHub interface. To a
<ide> If a question has not yet been added to a particular video challenge, it will have the following default question:
<ide>
<ide> ```yml
<del>tests:
<add>question:
<ide> text: Question
<ide> answers:
<ide> - one
<ide> Update the word “Question” with your question. Update the “one”, “two
<ide>
<ide> Questions and answers can contain certain HTML tags like `<br>` for a new line. Surround code with `<pre></pre>` You will need to add a `<br>` at the end of each line of code.
<ide>
<add>#### Use markdown to format your question
<add>
<add>You can also use markdown in your question as well as HTML. The simplest way to ensure that it is formatted correctly is to start the question with `text: |`, like this:
<add>
<add>```yml
<add>question:
<add> text: |
<add> Question
<add> answers:
<add> - one
<add> - two
<add> - three
<add> solution: 3
<add>```
<add>
<add>Then you need to make sure that your question is on a new line and indented one level more than `text: |`.
<add>
<ide> Make sure each answer is plausible but there is only one correct answer.
<ide>
<ide> ## Question examples
<ide>
<del>Here are a few examples:
<add>#### Here are a few examples with HTML:
<ide> ```yml
<ide> question:
<ide> text: 'What will print out after running this code:<pre>width = 15<br>height = 12.0<br>print(height/3)</pre>'
<ide> question:
<ide> solution: 3
<ide> ```
<ide>
<add>#### Example with markdown:
<add>````yml
<add>question:
<add> text: |
<add> What does this JavaScript code log to the console?
<add> ```js
<add> console.log('hello world');
<add> ```
<add>
<add> New paragraph after an empty line.
<add> answers:
<add> - hello *world*
<add> - '**hello** world' # the string cannot start with a *, hence the quotes.
<add> - hello world
<add> solution: 3
<add>````
<add>
<ide> For more examples, you can look at the markdown files for the following video course. All the challenges already have questions: [Python for Everybody Course](https://github.com/freeCodeCamp/freeCodeCamp/tree/next-python-projects/curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody)
<ide>
<ide> ## Open a pull request | 1 |
PHP | PHP | fix sortdir() to read default params | dde19f97c784952ba716b841eddd482a2c70184b | <ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php
<ide> public function testSortKeyFallbackToParams() {
<ide>
<ide> $result = $this->Paginator->sortKey('Article');
<ide> $this->assertEquals('Article.body', $result);
<add>
<add> $this->Paginator->request->params['paging']['Article']['order'] = array(
<add> 'Article.body' => 'DESC'
<add> );
<add> $result = $this->Paginator->sortKey();
<add> $this->assertEquals('Article.body', $result);
<add>
<add> $result = $this->Paginator->sortKey('Article');
<add> $this->assertEquals('Article.body', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testSortDir() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test that sortDir falls back to the default sorting options set
<add> * in the $params which are the default pagination options.
<add> *
<add> * @return void
<add> */
<add> public function testSortDirFallbackToParams() {
<add> $this->Paginator->request->params['paging']['Article']['order'] = array(
<add> 'Article.body' => 'ASC'
<add> );
<add> $result = $this->Paginator->sortDir();
<add> $this->assertEquals('asc', $result);
<add>
<add> $result = $this->Paginator->sortDir('Article');
<add> $this->assertEquals('asc', $result);
<add>
<add> $this->Paginator->request->params['paging']['Article']['order'] = array(
<add> 'Article.body' => 'DESC'
<add> );
<add> $result = $this->Paginator->sortDir();
<add> $this->assertEquals('desc', $result);
<add>
<add> $result = $this->Paginator->sortDir('Article');
<add> $this->assertEquals('desc', $result);
<add> }
<add>
<ide> /**
<ide> * testSortAdminLinks method
<ide> *
<ide><path>lib/Cake/View/Helper/PaginatorHelper.php
<ide> public function sortDir($model = null, $options = array()) {
<ide> $dir = strtolower($options['direction']);
<ide> } elseif (isset($options['order']) && is_array($options['order'])) {
<ide> $dir = strtolower(current($options['order']));
<add> } elseif (isset($params['order']) && is_array($params['order'])) {
<add> $dir = strtolower(current($params['order']));
<ide> }
<ide>
<ide> if ($dir == 'desc') { | 2 |
Javascript | Javascript | fix eslint error | a90d0cbbba7a88f0ddacf95136a72abeb932363f | <ide><path>docs/app/src/directives.js
<ide> directivesModule
<ide> bindings: {
<ide> items: '<'
<ide> },
<del> controller: ['$location', function($location) {
<add> controller: ['$location', /** @this */ function($location) {
<ide> this.path = $location.path().replace(/^\/?(.+?)(\/index)?\/?$/, '$1');
<ide> }]
<ide> }) | 1 |
Text | Text | fix the example of linear radial axis | 48fefd92b6dc61345021c6508b23698830ff392f | <ide><path>docs/axes/radial/linear.md
<ide> This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5
<ide>
<ide> ```javascript
<ide> let options = {
<del> scales: {
<del> yAxes: [{
<del> ticks: {
<del> max: 5,
<del> min: 0,
<del> stepSize: 0.5
<del> }
<del> }]
<add> scale: {
<add> ticks: {
<add> max: 5,
<add> min: 0,
<add> stepSize: 0.5
<add> }
<ide> }
<ide> };
<ide> ``` | 1 |
Java | Java | add test to assess claims in spr-10411 | b305f0005b2836faf49da234015cc1f9f83ffb85 | <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java
<ide>
<ide> package org.springframework.beans.factory.support;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertNotSame;
<del>import static org.junit.Assert.assertNull;
<del>import static org.junit.Assert.assertSame;
<del>import static org.junit.Assert.assertTrue;
<del>import static org.junit.Assert.fail;
<del>
<add>import java.lang.reflect.InvocationHandler;
<add>import java.lang.reflect.Method;
<add>import java.lang.reflect.Proxy;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URI;
<ide> import java.net.URL;
<ide> import org.springframework.core.io.UrlResource;
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<del>
<ide> import org.springframework.tests.sample.beans.GenericBean;
<ide> import org.springframework.tests.sample.beans.GenericIntegerBean;
<ide> import org.springframework.tests.sample.beans.GenericSetOfIntegerBean;
<ide> import org.springframework.tests.sample.beans.TestBean;
<ide>
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * @author Juergen Hoeller
<ide> public void testGenericListPropertyWithInvalidElementType() {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<ide> RootBeanDefinition rbd = new RootBeanDefinition(GenericIntegerBean.class);
<ide>
<del> List input = new ArrayList();
<add> List<Integer> input = new ArrayList<Integer>();
<ide> input.add(1);
<ide> rbd.getPropertyValues().add("testBeanList", input);
<ide>
<ide> public void testSetBean() throws Exception {
<ide> }
<ide>
<ide> /**
<del> * Tests support for parameterized {@code factory-method} declarations such
<del> * as Mockito {@code mock()} method which has the following signature.
<del> *
<del> * <pre>{@code
<add> * Tests support for parameterized static {@code factory-method} declarations such as
<add> * Mockito's {@code mock()} method which has the following signature.
<add> *
<add> * <pre>
<add> * {@code
<ide> * public static <T> T mock(Class<T> classToMock)
<del> * }</pre>
<del> *
<add> * }
<add> * </pre>
<add> *
<add> * <p>
<ide> * See SPR-9493
<add> *
<ide> * @since 3.2
<ide> */
<ide> @Test
<del> public void parameterizedFactoryMethod() {
<add> public void parameterizedStaticFactoryMethod() {
<ide> RootBeanDefinition rbd = new RootBeanDefinition(Mockito.class);
<ide> rbd.setFactoryMethodName("mock");
<ide> rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
<ide> public void parameterizedFactoryMethod() {
<ide> assertEquals(1, beans.size());
<ide> }
<ide>
<add> /**
<add> * Tests support for parameterized instance {@code factory-method} declarations such
<add> * as EasyMock's {@code IMocksControl.createMock()} method which has the following
<add> * signature.
<add> *
<add> * <pre>
<add> * {@code
<add> * public <T> T createMock(Class<T> toMock)
<add> * }
<add> * </pre>
<add> *
<add> * <p>
<add> * See SPR-10411
<add> *
<add> * @since 4.0
<add> */
<add> @Test
<add> public void parameterizedInstanceFactoryMethod() {
<add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<add>
<add> RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
<add> bf.registerBeanDefinition("mocksControl", rbd);
<add>
<add> rbd = new RootBeanDefinition();
<add> rbd.setFactoryBeanName("mocksControl");
<add> rbd.setFactoryMethodName("createMock");
<add> rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
<add>
<add> bf.registerBeanDefinition("mock", rbd);
<add>
<add> Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
<add> assertEquals(1, beans.size());
<add> }
<ide>
<ide> @SuppressWarnings("serial")
<ide> public static class NamedUrlList extends LinkedList<URL> {
<ide> public void setUrlNames(Set<URI> urlNames) throws MalformedURLException {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Pseudo-implementation of EasyMock's {@code MocksControl} class.
<add> */
<add> public static class MocksControl {
<add>
<add> @SuppressWarnings("unchecked")
<add> public <T> T createMock(Class<T> toMock) {
<add>
<add> return (T) Proxy.newProxyInstance(
<add> BeanFactoryGenericsTests.class.getClassLoader(),
<add> new Class[] { toMock }, new InvocationHandler() {
<add>
<add> @Override
<add> public Object invoke(Object proxy, Method method, Object[] args)
<add> throws Throwable {
<add> throw new UnsupportedOperationException("mocked!");
<add> }
<add> });
<add> }
<add> }
<add>
<ide> } | 1 |
Python | Python | fix race condition when starting dagprocessoragent | 525484388464619832a14d1b28e06e3a097aac97 | <ide><path>airflow/dag_processing/manager.py
<ide> def _run_processor_manager(
<ide> os.environ['AIRFLOW__LOGGING__COLORED_CONSOLE_LOG'] = 'False'
<ide> # Replicating the behavior of how logging module was loaded
<ide> # in logging_config.py
<add>
<add> # TODO: This reloading should be removed when we fix our logging behaviour
<add> # In case of "spawn" method of starting processes for multiprocessing, reinitializing of the
<add> # SQLAlchemy engine causes extremely unexpected behaviour of messing with objects already loaded
<add> # in a parent process (likely via resources shared in memory by the ORM libraries).
<add> # This caused flaky tests in our CI for many months and has been discovered while
<add> # iterating on https://github.com/apache/airflow/pull/19860
<add> # The issue that describes the problem and possible remediation is
<add> # at https://github.com/apache/airflow/issues/19934
<add>
<ide> importlib.reload(import_module(airflow.settings.LOGGING_CLASS_PATH.rsplit('.', 1)[0])) # type: ignore
<ide> importlib.reload(airflow.settings)
<ide> airflow.settings.initialize()
<ide><path>airflow/utils/process_utils.py
<ide>
<ide>
<ide> def reap_process_group(
<del> pgid: int,
<add> process_group_id: int,
<ide> logger,
<ide> sig: 'signal.Signals' = signal.SIGTERM,
<ide> timeout: int = DEFAULT_TIME_TO_WAIT_AFTER_SIGTERM,
<ide> def reap_process_group(
<ide> sig (SIGTERM) to the process group of pid. If any process is alive after timeout
<ide> a SIGKILL will be send.
<ide>
<del> :param pgid: process group id to kill
<add> :param process_group_id: process group id to kill.
<add> The process that wants to create the group should run `os.setpgid(0, 0)` as the first
<add> command it executes which will set group id = process_id. Effectively the process that is the
<add> "root" of the group has pid = gid and all other processes in the group have different
<add> pids but the same gid (equal the pid of the root process)
<ide> :param logger: log handler
<ide> :param sig: signal type
<ide> :param timeout: how much time a process has to terminate
<ide> def on_terminate(p):
<ide>
<ide> def signal_procs(sig):
<ide> try:
<del> os.killpg(pgid, sig)
<del> except OSError as err:
<add> logger.info("Sending the signal %s to group %s", sig, process_group_id)
<add> os.killpg(process_group_id, sig)
<add> except OSError as err_killpg:
<ide> # If operation not permitted error is thrown due to run_as_user,
<ide> # use sudo -n(--non-interactive) to kill the process
<del> if err.errno == errno.EPERM:
<add> if err_killpg.errno == errno.EPERM:
<ide> subprocess.check_call(
<del> ["sudo", "-n", "kill", "-" + str(int(sig))] + [str(p.pid) for p in children]
<add> ["sudo", "-n", "kill", "-" + str(int(sig))]
<add> + [str(p.pid) for p in all_processes_in_the_group]
<add> )
<add> elif err_killpg.errno == errno.ESRCH:
<add> # There is a rare condition that the process has not managed yet to change it's process
<add> # group. In this case os.killpg fails with ESRCH error
<add> # So we additionally send a kill signal to the process itself.
<add> logger.info(
<add> "Sending the signal %s to process %s as process group is missing.", sig, process_group_id
<ide> )
<add> try:
<add> os.kill(process_group_id, sig)
<add> except OSError as err_kill:
<add> if err_kill.errno == errno.EPERM:
<add> subprocess.check_call(["sudo", "-n", "kill", "-" + str(process_group_id)])
<add> else:
<add> raise
<ide> else:
<ide> raise
<ide>
<del> if pgid == os.getpgid(0):
<add> if process_group_id == os.getpgid(0):
<ide> raise RuntimeError("I refuse to kill myself")
<ide>
<ide> try:
<del> parent = psutil.Process(pgid)
<add> parent = psutil.Process(process_group_id)
<ide>
<del> children = parent.children(recursive=True)
<del> children.append(parent)
<add> all_processes_in_the_group = parent.children(recursive=True)
<add> all_processes_in_the_group.append(parent)
<ide> except psutil.NoSuchProcess:
<ide> # The process already exited, but maybe it's children haven't.
<del> children = []
<add> all_processes_in_the_group = []
<ide> for proc in psutil.process_iter():
<ide> try:
<del> if os.getpgid(proc.pid) == pgid and proc.pid != 0:
<del> children.append(proc)
<add> if os.getpgid(proc.pid) == process_group_id and proc.pid != 0:
<add> all_processes_in_the_group.append(proc)
<ide> except OSError:
<ide> pass
<ide>
<del> logger.info("Sending %s to GPID %s", sig, pgid)
<add> logger.info(
<add> "Sending %s to group %s. PIDs of all processes in the group: %s",
<add> sig,
<add> process_group_id,
<add> [p.pid for p in all_processes_in_the_group],
<add> )
<ide> try:
<ide> signal_procs(sig)
<ide> except OSError as err:
<ide> def signal_procs(sig):
<ide> if err.errno == errno.ESRCH:
<ide> return returncodes
<ide>
<del> _, alive = psutil.wait_procs(children, timeout=timeout, callback=on_terminate)
<add> _, alive = psutil.wait_procs(all_processes_in_the_group, timeout=timeout, callback=on_terminate)
<ide>
<ide> if alive:
<ide> for proc in alive:
<ide><path>tests/dag_processing/test_processor.py
<ide>
<ide> from airflow import settings
<ide> from airflow.configuration import TEST_DAGS_FOLDER, conf
<add>from airflow.dag_processing.manager import DagFileProcessorAgent
<ide> from airflow.dag_processing.processor import DagFileProcessor
<ide> from airflow.models import DagBag, DagModel, SlaMiss, TaskInstance, errors
<ide> from airflow.models.taskinstance import SimpleTaskInstance
<ide> def test_process_file_should_deactivate_missing_dags(self):
<ide> dags = session.query(DagModel).all()
<ide> assert [dag.dag_id for dag in dags if dag.is_active] == ['test_only_dummy_tasks']
<ide> assert [dag.dag_id for dag in dags if not dag.is_active] == ['missing_dag']
<add>
<add>
<add>class TestProcessorAgent:
<add> @pytest.fixture(autouse=True)
<add> def per_test(self):
<add> self.processor_agent = None
<add> yield
<add> if self.processor_agent:
<add> self.processor_agent.end()
<add>
<add> def test_error_when_waiting_in_async_mode(self, tmp_path):
<add> self.processor_agent = DagFileProcessorAgent(
<add> dag_directory=str(tmp_path),
<add> max_runs=1,
<add> processor_timeout=datetime.timedelta(1),
<add> dag_ids=[],
<add> pickle_dags=False,
<add> async_mode=True,
<add> )
<add> self.processor_agent.start()
<add> with pytest.raises(RuntimeError, match="wait_until_finished should only be called in sync_mode"):
<add> self.processor_agent.wait_until_finished()
<add>
<add> def test_default_multiprocessing_behaviour(self, tmp_path):
<add> self.processor_agent = DagFileProcessorAgent(
<add> dag_directory=str(tmp_path),
<add> max_runs=1,
<add> processor_timeout=datetime.timedelta(1),
<add> dag_ids=[],
<add> pickle_dags=False,
<add> async_mode=False,
<add> )
<add> self.processor_agent.start()
<add> self.processor_agent.run_single_parsing_loop()
<add> self.processor_agent.wait_until_finished()
<add>
<add> @conf_vars({("core", "mp_start_method"): "spawn"})
<add> def test_spawn_multiprocessing_behaviour(self, tmp_path):
<add> self.processor_agent = DagFileProcessorAgent(
<add> dag_directory=str(tmp_path),
<add> max_runs=1,
<add> processor_timeout=datetime.timedelta(1),
<add> dag_ids=[],
<add> pickle_dags=False,
<add> async_mode=False,
<add> )
<add> self.processor_agent.start()
<add> self.processor_agent.run_single_parsing_loop()
<add> self.processor_agent.wait_until_finished() | 3 |
Javascript | Javascript | ignore debug code | dc743d2197f35f1d50bc453a24d69d5f4af5ffcc | <ide><path>lib/ChunkGroup.js
<ide> class ChunkGroup {
<ide> this.options.name = value;
<ide> }
<ide>
<add> /* istanbul ignore next */
<ide> /**
<ide> * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's
<ide> * @returns {string} a unique concatenation of chunk debugId's
<ide> class ChunkGroup {
<ide> return this._modulePostOrderIndices.get(module);
<ide> }
<ide>
<add> /* istanbul ignore next */
<ide> checkConstraints() {
<ide> const chunk = this;
<ide> for (const child of chunk._children) { | 1 |
PHP | PHP | fix doc comment errors in acl classes | 70589212755c0c5a5caf00e28e138290cd878552 | <ide><path>lib/Cake/Controller/Component/Acl/AclInterface.php
<ide> public function inherit($aro, $aco, $action = "*");
<ide> /**
<ide> * Initialization method for the Acl implementation
<ide> *
<del> * @param AclComponent $component
<add> * @param Component $component The AclComponent instance.
<ide> * @return void
<ide> */
<ide> public function initialize(Component $component);
<ide><path>lib/Cake/Controller/Component/Acl/DbAcl.php
<ide> public function __construct() {
<ide> /**
<ide> * Initializes the containing component and sets the Aro/Aco objects to it.
<ide> *
<del> * @param AclComponent $component
<add> * @param AclComponent $component The AclComponent instance.
<ide> * @return void
<ide> */
<ide> public function initialize(Component $component) {
<ide><path>lib/Cake/Controller/Component/Acl/IniAcl.php
<ide> class IniAcl extends Object implements AclInterface {
<ide> /**
<ide> * Initialize method
<ide> *
<del> * @param Component $component
<add> * @param Component $component The AclComponent instance.
<ide> * @return void
<ide> */
<ide> public function initialize(Component $component) { | 3 |
Python | Python | ignore false positive lint warning | aef56dbc6302a6dc4cf6a2d7f6d180b49ac81afc | <ide><path>libcloud/common/google.py
<ide> def _receive_code_through_local_loopback(self):
<ide> class AccessCodeReceiver(BaseHTTPRequestHandler):
<ide>
<ide> # noinspection PyMethodParameters,PyPep8Naming
<del> def do_GET(self_):
<add> def do_GET(self_): # pylint: disable=noo-self-argument
<ide> query = urlparse.urlparse(self_.path).query
<ide> query_components = dict(qc.split("=") for qc in query.split("&"))
<ide> if "state" in query_components and query_components["state"] != urllib.parse.quote( | 1 |
Text | Text | change a word in performance docs | 0833d897835b1fd20ebca043b9448981e87521f7 | <ide><path>docs/docs/11-advanced-performance.md
<ide> One of the first questions people ask when considering React for a project is wh
<ide>
<ide> ## Use the production build
<ide>
<del>If you're benchmarking or seeing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
<add>If you're benchmarking or experiencing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.
<ide>
<ide> ## Avoiding reconciling the DOM
<ide> | 1 |
PHP | PHP | remove unused property | 60520dc6d218985f3ecdb35cd867dcfb193ee639 | <ide><path>tests/TestCase/View/ViewTest.php
<ide> class ViewPostsController extends Controller
<ide> */
<ide> public $name = 'Posts';
<ide>
<del> /**
<del> * uses property
<del> *
<del> * @var mixed
<del> */
<del> public $uses = null;
<del>
<ide> /**
<ide> * index method
<ide> * | 1 |
Ruby | Ruby | form => form_for | 77c8cd75162e0771dd45930a4309d3183707731a | <ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> def convert_to_model(object)
<ide> #
<ide> # Example:
<ide> #
<del> # <%= form(@post) do |f| %>
<add> # <%= form_for(@post) do |f| %>
<ide> # <% f.fields_for(:comments, :include_id => false) do |cf| %>
<ide> # ...
<ide> # <% end %> | 1 |
Javascript | Javascript | use custom elements on pane container element | 2a1e10a9f9fb0cffa843b6abee2de4aa14f5370d | <ide><path>spec/pane-container-element-spec.js
<ide> describe('PaneContainerElement', function() {
<ide> expect(document.activeElement).toBe(rightPaneElement);
<ide>
<ide> rightPane.destroy();
<add> expect(containerElement).toHaveClass('panes')
<ide> return expect(document.activeElement).toBe(leftPaneElement);
<ide> });
<ide> });
<ide><path>src/pane-container-element.js
<ide> const { CompositeDisposable } = require('event-kit');
<ide>
<ide> class PaneContainerElement extends HTMLElement {
<del> createdCallback() {
<add> constructor() {
<add> super()
<ide> this.subscriptions = new CompositeDisposable();
<del> this.classList.add('panes');
<ide> }
<ide>
<ide> initialize(model, { views }) {
<ide> class PaneContainerElement extends HTMLElement {
<ide> return this;
<ide> }
<ide>
<add> connectedCallback() {
<add> this.classList.add('panes');
<add> }
<add>
<ide> rootChanged(root) {
<ide> const focusedElement = this.hasFocus() ? document.activeElement : null;
<ide> if (this.firstChild != null) {
<ide> class PaneContainerElement extends HTMLElement {
<ide> }
<ide> }
<ide>
<del>module.exports = document.registerElement('atom-pane-container', {
<del> prototype: PaneContainerElement.prototype
<del>});
<add>window.customElements.define('atom-pane-container', PaneContainerElement)
<add>
<add>function createPaneContainerElement() {
<add> return document.createElement('atom-pane-container')
<add>}
<add>
<add>module.exports = {
<add> createPaneContainerElement
<add>}
<ide><path>src/pane-container.js
<ide> const { find } = require('underscore-plus');
<ide> const { Emitter, CompositeDisposable } = require('event-kit');
<ide> const Pane = require('./pane');
<ide> const ItemRegistry = require('./item-registry');
<del>const PaneContainerElement = require('./pane-container-element');
<add>const {createPaneContainerElement} = require('./pane-container-element');
<ide>
<ide> const SERIALIZATION_VERSION = 1;
<ide> const STOPPED_CHANGING_ACTIVE_PANE_ITEM_DELAY = 100;
<ide> module.exports = class PaneContainer {
<ide> getElement() {
<ide> return this.element != null
<ide> ? this.element
<del> : (this.element = new PaneContainerElement().initialize(this, {
<add> : (this.element = createPaneContainerElement().initialize(this, {
<ide> views: this.viewRegistry
<ide> }));
<ide> } | 3 |
Text | Text | add creditas to airflow users | a3c5783f51763901ffba399aaad6dd485b4eda14 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<ide> 1. [CreditCards.com](https://www.creditcards.com/)[[@vmAggies](https://github.com/vmAggies) & [@jay-wallaby](https://github.com/jay-wallaby)]
<ide> 1. [Credit Karma](https://www.creditkarma.com/) [[@preete-dixit-ck](https://github.com/preete-dixit-ck) & [@harish-gaggar-ck](https://github.com/harish-gaggar-ck) & [@greg-finley-ck](https://github.com/greg-finley-ck)]
<add>1. [Creditas](https://www.creditas.com.br) [[@dcassiano](https://github.com/dcassiano)]
<ide> 1. [DataFox](https://www.datafox.com/) [[@sudowork](https://github.com/sudowork)]
<ide> 1. [Data Reply](https://www.datareply.co.uk/) [[@kaxil](https://github.com/kaxil)]
<ide> 1. [Digital First Media](http://www.digitalfirstmedia.com/) [[@duffn](https://github.com/duffn) & [@mschmo](https://github.com/mschmo) & [@seanmuth](https://github.com/seanmuth)] | 1 |
Python | Python | move function to compat | 579f77ceaa03a216a7a635c3d3a4d83b0e5868f8 | <ide><path>rest_framework/compat.py
<ide> def apply_markdown(text):
<ide> oauth2_provider_forms = None
<ide> oauth2_provider_scope = None
<ide> oauth2_constants = None
<add>
<add># Handle lazy strings
<add>from django.utils.functional import Promise
<add>
<add>if six.PY3:
<add> def is_non_str_iterable(obj):
<add> if (isinstance(obj, str) or
<add> (isinstance(obj, Promise) and obj._delegate_text)):
<add> return False
<add> return hasattr(obj, '__iter__')
<add>else:
<add> def is_non_str_iterable(obj):
<add> return hasattr(obj, '__iter__')
<ide><path>rest_framework/fields.py
<ide> from django import forms
<ide> from django.forms import widgets
<ide> from django.utils.encoding import is_protected_type
<del>from django.utils.functional import Promise
<ide> from django.utils.translation import ugettext_lazy as _
<ide> from django.utils.datastructures import SortedDict
<ide>
<ide> from rest_framework import ISO_8601
<ide> from rest_framework.compat import timezone, parse_date, parse_datetime, parse_time
<ide> from rest_framework.compat import BytesIO
<ide> from rest_framework.compat import six
<del>from rest_framework.compat import smart_text, force_text
<add>from rest_framework.compat import smart_text, force_text, is_non_str_iterable
<ide> from rest_framework.settings import api_settings
<ide>
<ide>
<ide> def is_simple_callable(obj):
<ide> len_defaults = len(defaults) if defaults else 0
<ide> return len_args <= len_defaults
<ide>
<del>if six.PY3:
<del> def is_non_str_iterable(obj):
<del> if (isinstance(obj, str) or
<del> (isinstance(obj, Promise) and obj._delegate_text)):
<del> return False
<del> return hasattr(obj, '__iter__')
<del>else:
<del> def is_non_str_iterable(obj):
<del> return hasattr(obj, '__iter__')
<del>
<ide> def get_component(obj, attr_name):
<ide> """
<ide> Given an object, and an attribute name, | 2 |
Go | Go | remove useless debug message | f1b59d64d21d5a0f54536b26161a31441697ca61 | <ide><path>daemon/execdriver/native/driver.go
<ide> func NewDriver(root, initPath string, options []string) (*driver, error) {
<ide> }
<ide> }
<ide>
<del> logrus.Debugf("Using %v as native.cgroupdriver", cgm)
<del>
<ide> f, err := libcontainer.New(
<ide> root,
<ide> cgm, | 1 |
Java | Java | add interface for reactshadownode | 08befb730b7abbb21c58176ea9d55962fae6a30b | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatReactModalShadowNode.java
<ide> import android.view.Display;
<ide> import android.view.Surface;
<ide> import android.view.WindowManager;
<del>
<del>import com.facebook.react.uimanager.ReactShadowNode;
<del>import com.facebook.yoga.YogaValue;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.yoga.YogaUnit;
<add>import com.facebook.yoga.YogaValue;
<ide>
<ide> /**
<ide> * FlatReactModalShadowNode
<ide> class FlatReactModalShadowNode extends FlatShadowNode implements AndroidView {
<ide>
<ide> /**
<ide> * We need to set the styleWidth and styleHeight of the one child (represented by the <View/>
<del> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<add> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<ide> */
<ide> @Override
<ide> @TargetApi(16)
<del> public void addChildAt(ReactShadowNode child, int i) {
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<ide> super.addChildAt(child, i);
<ide>
<ide> Context context = getThemedContext();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java
<ide>
<ide> package com.facebook.react.flat;
<ide>
<del>import javax.annotation.Nullable;
<del>
<ide> import android.graphics.Rect;
<del>
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.uimanager.LayoutShadowNode;
<ide> import com.facebook.react.uimanager.OnLayoutEvent;
<add>import com.facebook.react.uimanager.ReactClippingViewGroupHelper;
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.ReactStylesDiffMap;
<ide> import com.facebook.react.uimanager.ViewProps;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<del>import com.facebook.react.uimanager.ReactClippingViewGroupHelper;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * FlatShadowNode is a base class for all shadow node used in FlatUIImplementation. It extends
<ide> public final int getScreenHeight() {
<ide> }
<ide>
<ide> @Override
<del> public void addChildAt(ReactShadowNode child, int i) {
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<ide> super.addChildAt(child, i);
<ide> if (mForceMountChildrenToView && child instanceof FlatShadowNode) {
<ide> ((FlatShadowNode) child).forceMountToView();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/MoveProxy.java
<ide>
<ide> package com.facebook.react.flat;
<ide>
<del>import javax.annotation.Nullable;
<del>
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * Helper class that sorts moveFrom/moveTo arrays in lockstep.
<ide> private @Nullable ReadableArray mMoveTo;
<ide> private int mSize;
<ide> private int[] mMapping = new int[8];
<del> private ReactShadowNode[] mChildren = new ReactShadowNode[4];
<add> private ReactShadowNode[] mChildren = new ReactShadowNodeImpl[4];
<ide>
<ide> /**
<ide> * Retuns size of underlying moveTo/moveFrom arrays
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/NativeViewWrapper.java
<ide> package com.facebook.react.flat;
<ide>
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.ReactStylesDiffMap;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide> import com.facebook.react.uimanager.UIViewOperationQueue;
<ide> import com.facebook.yoga.YogaMeasureFunction;
<ide> import com.facebook.yoga.YogaUnit;
<ide> import com.facebook.yoga.YogaValue;
<del>
<ide> import javax.annotation.Nullable;
<ide>
<ide> /* package */ final class NativeViewWrapper extends FlatShadowNode implements AndroidView {
<ide> public void setThemedContext(ThemedReactContext themedContext) {
<ide> }
<ide>
<ide> @Override
<del> public void addChildAt(ReactShadowNode child, int i) {
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<ide> super.addChildAt(child, i);
<ide> if (mForceMountGrandChildrenToView && child instanceof FlatShadowNode) {
<ide> ((FlatShadowNode) child).forceMountChildrenToView();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTVirtualText.java
<ide>
<ide> package com.facebook.react.flat;
<ide>
<del>import javax.annotation.Nullable;
<del>
<ide> import android.graphics.Typeface;
<ide> import android.text.Spannable;
<ide> import android.text.SpannableStringBuilder;
<ide> import android.text.TextUtils;
<del>
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.uimanager.PixelUtil;
<del>import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.ViewProps;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * RCTVirtualText is a {@link FlatTextShadowNode} that can contain font styling information.
<ide> private ShadowStyleSpan mShadowStyleSpan = ShadowStyleSpan.INSTANCE;
<ide>
<ide> @Override
<del> public void addChildAt(ReactShadowNode child, int i) {
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<ide> super.addChildAt(child, i);
<ide> notifyChanged(true);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/processing/ReactPropertyProcessor.java
<ide>
<ide> package com.facebook.react.processing;
<ide>
<add>import static javax.lang.model.element.Modifier.ABSTRACT;
<add>import static javax.lang.model.element.Modifier.PRIVATE;
<add>import static javax.lang.model.element.Modifier.PUBLIC;
<add>import static javax.tools.Diagnostic.Kind.ERROR;
<add>import static javax.tools.Diagnostic.Kind.WARNING;
<add>
<add>import com.facebook.infer.annotation.SuppressFieldNotInitialized;
<add>import com.facebook.react.bridge.Dynamic;
<add>import com.facebook.react.bridge.ReadableArray;
<add>import com.facebook.react.bridge.ReadableMap;
<add>import com.facebook.react.uimanager.annotations.ReactProp;
<add>import com.facebook.react.uimanager.annotations.ReactPropGroup;
<add>import com.facebook.react.uimanager.annotations.ReactPropertyHolder;
<add>import com.squareup.javapoet.ClassName;
<add>import com.squareup.javapoet.CodeBlock;
<add>import com.squareup.javapoet.JavaFile;
<add>import com.squareup.javapoet.MethodSpec;
<add>import com.squareup.javapoet.ParameterizedTypeName;
<add>import com.squareup.javapoet.TypeName;
<add>import com.squareup.javapoet.TypeSpec;
<add>import com.squareup.javapoet.TypeVariableName;
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.Comparator;
<add>import java.util.HashMap;
<add>import java.util.HashSet;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Set;
<ide> import javax.annotation.Nullable;
<ide> import javax.annotation.processing.AbstractProcessor;
<ide> import javax.annotation.processing.Filer;
<ide> import javax.lang.model.util.Elements;
<ide> import javax.lang.model.util.Types;
<ide>
<del>import java.io.IOException;
<del>import java.util.ArrayList;
<del>import java.util.Collections;
<del>import java.util.Comparator;
<del>import java.util.HashMap;
<del>import java.util.HashSet;
<del>import java.util.List;
<del>import java.util.Map;
<del>import java.util.Set;
<del>
<del>import com.facebook.infer.annotation.SuppressFieldNotInitialized;
<del>import com.facebook.react.bridge.ReadableArray;
<del>import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.bridge.Dynamic;
<del>import com.facebook.react.uimanager.annotations.ReactPropertyHolder;
<del>import com.facebook.react.uimanager.annotations.ReactProp;
<del>import com.facebook.react.uimanager.annotations.ReactPropGroup;
<del>
<del>import com.squareup.javapoet.ClassName;
<del>import com.squareup.javapoet.CodeBlock;
<del>import com.squareup.javapoet.JavaFile;
<del>import com.squareup.javapoet.MethodSpec;
<del>import com.squareup.javapoet.ParameterizedTypeName;
<del>import com.squareup.javapoet.TypeName;
<del>import com.squareup.javapoet.TypeSpec;
<del>import com.squareup.javapoet.TypeVariableName;
<del>
<del>import static javax.lang.model.element.Modifier.*;
<del>import static javax.tools.Diagnostic.Kind.ERROR;
<del>import static javax.tools.Diagnostic.Kind.WARNING;
<del>
<ide> /**
<ide> * This annotation processor crawls subclasses of ReactShadowNode and ViewManager and finds their
<ide> * exported properties with the @ReactProp or @ReactGroupProp annotation. It generates a class
<ide> private TypeName getTargetType(TypeMirror mirror) {
<ide> TypeName typeName = TypeName.get(mirror);
<ide> if (typeName instanceof ParameterizedTypeName) {
<ide> ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
<del> if (parameterizedTypeName.rawType.equals(VIEW_MANAGER_TYPE)) {
<add> if (parameterizedTypeName.rawType.equals(VIEW_MANAGER_TYPE)
<add> || parameterizedTypeName.rawType.equals(SHADOW_NODE_TYPE)) {
<ide> return parameterizedTypeName.typeArguments.get(0);
<ide> }
<del> } else if (typeName.equals(SHADOW_NODE_TYPE)) {
<del> return SHADOW_NODE_TYPE;
<ide> } else if (typeName.equals(TypeName.OBJECT)) {
<del> throw new IllegalArgumentException("Could not find target type");
<add> throw new IllegalArgumentException("Could not find target type " + typeName);
<ide> }
<ide>
<ide> List<? extends TypeMirror> types = mTypes.directSupertypes(mirror);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import javax.annotation.Nullable;
<del>
<del>
<ide> import com.facebook.react.bridge.Dynamic;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReadableType;
<del>
<add>import com.facebook.react.uimanager.annotations.ReactProp;
<add>import com.facebook.react.uimanager.annotations.ReactPropGroup;
<ide> import com.facebook.yoga.YogaAlign;
<ide> import com.facebook.yoga.YogaConstants;
<ide> import com.facebook.yoga.YogaDisplay;
<ide> import com.facebook.yoga.YogaPositionType;
<ide> import com.facebook.yoga.YogaUnit;
<ide> import com.facebook.yoga.YogaWrap;
<del>import com.facebook.react.uimanager.annotations.ReactProp;
<del>import com.facebook.react.uimanager.annotations.ReactPropGroup;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<del> * Supply setters for base view layout properties such as width, height, flex properties,
<del> * borders, etc.
<add> * Supply setters for base view layout properties such as width, height, flex properties, borders,
<add> * etc.
<ide> *
<del> * Checking for isVirtual everywhere is a hack to get around the fact that some virtual nodes still
<del> * have layout properties set on them in JS: for example, a component that returns a <Text> may
<del> * or may not be embedded in a parent text. There are better solutions that should probably be
<add> * <p>Checking for isVirtual everywhere is a hack to get around the fact that some virtual nodes
<add> * still have layout properties set on them in JS: for example, a component that returns a <Text>
<add> * may or may not be embedded in a parent text. There are better solutions that should probably be
<ide> * explored, namely using the VirtualText class in JS and setting the correct set of validAttributes
<ide> */
<del>public class LayoutShadowNode extends ReactShadowNode {
<add>public class LayoutShadowNode extends ReactShadowNodeImpl {
<ide>
<ide> /**
<ide> * A Mutable version of com.facebook.yoga.YogaValue
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import javax.annotation.Nullable;
<del>
<del>import java.util.Arrays;
<del>import java.util.ArrayList;
<del>
<add>import com.facebook.react.uimanager.annotations.ReactPropertyHolder;
<ide> import com.facebook.yoga.YogaAlign;
<del>import com.facebook.yoga.YogaConfig;
<del>import com.facebook.yoga.YogaDisplay;
<del>import com.facebook.yoga.YogaEdge;
<del>import com.facebook.yoga.YogaConstants;
<add>import com.facebook.yoga.YogaBaselineFunction;
<ide> import com.facebook.yoga.YogaDirection;
<add>import com.facebook.yoga.YogaDisplay;
<ide> import com.facebook.yoga.YogaFlexDirection;
<ide> import com.facebook.yoga.YogaJustify;
<del>import com.facebook.yoga.YogaBaselineFunction;
<ide> import com.facebook.yoga.YogaMeasureFunction;
<ide> import com.facebook.yoga.YogaNode;
<ide> import com.facebook.yoga.YogaOverflow;
<ide> import com.facebook.yoga.YogaPositionType;
<ide> import com.facebook.yoga.YogaValue;
<ide> import com.facebook.yoga.YogaWrap;
<del>import com.facebook.infer.annotation.Assertions;
<del>import com.facebook.react.uimanager.annotations.ReactPropertyHolder;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<del> * Base node class for representing virtual tree of React nodes. Shadow nodes are used primarily
<del> * for layouting therefore it extends {@link YogaNode} to allow that. They also help with handling
<add> * Base node class for representing virtual tree of React nodes. Shadow nodes are used primarily for
<add> * layouting therefore it extends {@link YogaNode} to allow that. They also help with handling
<ide> * Common base subclass of {@link YogaNode} for all layout nodes for react-based view. It extends
<ide> * {@link YogaNode} by adding additional capabilities.
<ide> *
<del> * Instances of this class receive property updates from JS via @{link UIManagerModule}. Subclasses
<del> * may use {@link #updateShadowNode} to persist some of the updated fields in the node instance that
<del> * corresponds to a particular view type.
<add> * <p>Instances of this class receive property updates from JS via @{link UIManagerModule}.
<add> * Subclasses may use {@link #updateShadowNode} to persist some of the updated fields in the node
<add> * instance that corresponds to a particular view type.
<ide> *
<del> * Subclasses of {@link ReactShadowNode} should be created only from {@link ViewManager} that
<add> * <p>Subclasses of {@link ReactShadowNode} should be created only from {@link ViewManager} that
<ide> * corresponds to a certain type of native view. They will be updated and accessed only from JS
<ide> * thread. Subclasses of {@link ViewManager} may choose to use base class {@link ReactShadowNode} or
<ide> * custom subclass of it if necessary.
<ide> *
<del> * The primary use-case for {@link ReactShadowNode} nodes is to calculate layouting. Although this
<del> * might be extended. For some examples please refer to ARTGroupYogaNode or ReactTextYogaNode.
<add> * <p>The primary use-case for {@link ReactShadowNode} nodes is to calculate layouting. Although
<add> * this might be extended. For some examples please refer to ARTGroupYogaNode or ReactTextYogaNode.
<ide> *
<del> * This class allows for the native view hierarchy to not be an exact copy of the hierarchy received
<del> * from JS by keeping track of both JS children (e.g. {@link #getChildCount()} and separately native
<del> * children (e.g. {@link #getNativeChildCount()}). See {@link NativeViewHierarchyOptimizer} for more
<del> * information.
<add> * <p>This class allows for the native view hierarchy to not be an exact copy of the hierarchy
<add> * received from JS by keeping track of both JS children (e.g. {@link #getChildCount()} and
<add> * separately native children (e.g. {@link #getNativeChildCount()}). See {@link
<add> * NativeViewHierarchyOptimizer} for more information.
<ide> */
<ide> @ReactPropertyHolder
<del>public class ReactShadowNode {
<del>
<del> private int mReactTag;
<del> private @Nullable String mViewClassName;
<del> private @Nullable ReactShadowNode mRootNode;
<del> private @Nullable ThemedReactContext mThemedContext;
<del> private boolean mShouldNotifyOnLayout;
<del> private boolean mNodeUpdated = true;
<del> private @Nullable ArrayList<ReactShadowNode> mChildren;
<del> private @Nullable ReactShadowNode mParent;
<del>
<del> // layout-only nodes
<del> private boolean mIsLayoutOnly;
<del> private int mTotalNativeChildren = 0;
<del> private @Nullable ReactShadowNode mNativeParent;
<del> private @Nullable ArrayList<ReactShadowNode> mNativeChildren;
<del> private int mScreenX;
<del> private int mScreenY;
<del> private int mScreenWidth;
<del> private int mScreenHeight;
<del> private final Spacing mDefaultPadding = new Spacing(0);
<del> private final float[] mPadding = new float[Spacing.ALL + 1];
<del> private final boolean[] mPaddingIsPercent = new boolean[Spacing.ALL + 1];
<del> private final YogaNode mYogaNode;
<del> private static YogaConfig sYogaConfig;
<del>
<del> public ReactShadowNode() {
<del> if (!isVirtual()) {
<del> YogaNode node = YogaNodePool.get().acquire();
<del> if (sYogaConfig == null) {
<del> sYogaConfig = new YogaConfig();
<del> sYogaConfig.setPointScaleFactor(0f);
<del> sYogaConfig.setUseLegacyStretchBehaviour(true);
<del> }
<del> if (node == null) {
<del> node = new YogaNode(sYogaConfig);
<del> }
<del> mYogaNode = node;
<del> Arrays.fill(mPadding, YogaConstants.UNDEFINED);
<del> } else {
<del> mYogaNode = null;
<del> }
<del> }
<add>public interface ReactShadowNode<T extends ReactShadowNode> {
<ide>
<ide> /**
<ide> * Nodes that return {@code true} will be treated as "virtual" nodes. That is, nodes that are not
<ide> * mapped into native views (e.g. nested text node). By default this method returns {@code false}.
<ide> */
<del> public boolean isVirtual() {
<del> return false;
<del> }
<add> boolean isVirtual();
<ide>
<ide> /**
<ide> * Nodes that return {@code true} will be treated as a root view for the virtual nodes tree. It
<ide> * means that {@link NativeViewHierarchyManager} will not try to perform {@code manageChildren}
<del> * operation on such views. Good example is {@code InputText} view that may have children
<del> * {@code Text} nodes but this whole hierarchy will be mapped to a single android {@link EditText}
<del> * view.
<add> * operation on such views. Good example is {@code InputText} view that may have children {@code
<add> * Text} nodes but this whole hierarchy will be mapped to a single android {@link EditText} view.
<ide> */
<del> public boolean isVirtualAnchor() {
<del> return false;
<del> }
<add> boolean isVirtualAnchor();
<ide>
<ide> /**
<del> * Nodes that return {@code true} will not manage (and and remove) child Yoga nodes.
<del> * For example {@link ReactTextInputShadowNode} or {@link ReactTextShadowNode} have child nodes,
<del> * which do not want Yoga to lay out, so in the eyes of Yoga it is a leaf node.
<del> * Override this method in subclass to enforce this requirement.
<add> * Nodes that return {@code true} will not manage (and and remove) child Yoga nodes. For example
<add> * {@link ReactTextInputShadowNode} or {@link ReactTextShadowNode} have child nodes, which do not
<add> * want Yoga to lay out, so in the eyes of Yoga it is a leaf node. Override this method in
<add> * subclass to enforce this requirement.
<ide> */
<del> public boolean isYogaLeafNode() {
<del> return isMeasureDefined();
<del> }
<del>
<del> public final String getViewClass() {
<del> return Assertions.assertNotNull(mViewClassName);
<del> }
<del>
<del> public final boolean hasUpdates() {
<del> return mNodeUpdated || hasNewLayout() || isDirty();
<del> }
<del>
<del> public final void markUpdateSeen() {
<del> mNodeUpdated = false;
<del> if (hasNewLayout()) {
<del> markLayoutSeen();
<del> }
<del> }
<del>
<del> public void markUpdated() {
<del> if (mNodeUpdated) {
<del> return;
<del> }
<del> mNodeUpdated = true;
<del> ReactShadowNode parent = getParent();
<del> if (parent != null) {
<del> parent.markUpdated();
<del> }
<del> }
<del>
<del> public final boolean hasUnseenUpdates() {
<del> return mNodeUpdated;
<del> }
<del>
<del> public void dirty() {
<del> if (!isVirtual()) {
<del> mYogaNode.dirty();
<del> }
<del> }
<del>
<del> public final boolean isDirty() {
<del> return mYogaNode != null && mYogaNode.isDirty();
<del> }
<del>
<del> public void addChildAt(ReactShadowNode child, int i) {
<del> if (child.mParent != null) {
<del> throw new IllegalViewOperationException(
<del> "Tried to add child that already has a parent! Remove it from its parent first.");
<del> }
<del> if (mChildren == null) {
<del> mChildren = new ArrayList<ReactShadowNode>(4);
<del> }
<del> mChildren.add(i, child);
<del> child.mParent = this;
<del>
<del> // If a CSS node has measure defined, the layout algorithm will not visit its children. Even
<del> // more, it asserts that you don't add children to nodes with measure functions.
<del> if (mYogaNode != null && !isYogaLeafNode()) {
<del> YogaNode childYogaNode = child.mYogaNode;
<del> if (childYogaNode == null) {
<del> throw new RuntimeException(
<del> "Cannot add a child that doesn't have a YogaNode to a parent without a measure " +
<del> "function! (Trying to add a '" + child.getClass().getSimpleName() + "' to a '" +
<del> getClass().getSimpleName() + "')");
<del> }
<del> mYogaNode.addChildAt(childYogaNode, i);
<del> }
<del> markUpdated();
<del>
<del> int increase = child.mIsLayoutOnly ? child.mTotalNativeChildren : 1;
<del> mTotalNativeChildren += increase;
<del>
<del> updateNativeChildrenCountInParent(increase);
<del> }
<del>
<del> public ReactShadowNode removeChildAt(int i) {
<del> if (mChildren == null) {
<del> throw new ArrayIndexOutOfBoundsException(
<del> "Index " + i + " out of bounds: node has no children");
<del> }
<del> ReactShadowNode removed = mChildren.remove(i);
<del> removed.mParent = null;
<del>
<del> if (mYogaNode != null && !isYogaLeafNode()) {
<del> mYogaNode.removeChildAt(i);
<del> }
<del> markUpdated();
<del>
<del> int decrease = removed.mIsLayoutOnly ? removed.mTotalNativeChildren : 1;
<del> mTotalNativeChildren -= decrease;
<del> updateNativeChildrenCountInParent(-decrease);
<del> return removed;
<del> }
<del>
<del> public final int getChildCount() {
<del> return mChildren == null ? 0 : mChildren.size();
<del> }
<del>
<del> public final ReactShadowNode getChildAt(int i) {
<del> if (mChildren == null) {
<del> throw new ArrayIndexOutOfBoundsException(
<del> "Index " + i + " out of bounds: node has no children");
<del> }
<del> return mChildren.get(i);
<del> }
<del>
<del> public final int indexOf(ReactShadowNode child) {
<del> return mChildren == null ? -1 : mChildren.indexOf(child);
<del> }
<del>
<del> public void removeAndDisposeAllChildren() {
<del> if (getChildCount() == 0) {
<del> return;
<del> }
<del>
<del> int decrease = 0;
<del> for (int i = getChildCount() - 1; i >= 0; i--) {
<del> if (mYogaNode != null && !isYogaLeafNode()) {
<del> mYogaNode.removeChildAt(i);
<del> }
<del> ReactShadowNode toRemove = getChildAt(i);
<del> toRemove.mParent = null;
<del> toRemove.dispose();
<del>
<del> decrease += toRemove.mIsLayoutOnly ? toRemove.mTotalNativeChildren : 1;
<del> }
<del> Assertions.assertNotNull(mChildren).clear();
<del> markUpdated();
<del>
<del> mTotalNativeChildren -= decrease;
<del> updateNativeChildrenCountInParent(-decrease);
<del> }
<del>
<del> private void updateNativeChildrenCountInParent(int delta) {
<del> if (mIsLayoutOnly) {
<del> ReactShadowNode parent = getParent();
<del> while (parent != null) {
<del> parent.mTotalNativeChildren += delta;
<del> if (!parent.mIsLayoutOnly) {
<del> break;
<del> }
<del> parent = parent.getParent();
<del> }
<del> }
<del> }
<add> boolean isYogaLeafNode();
<add>
<add> String getViewClass();
<add>
<add> boolean hasUpdates();
<add>
<add> void markUpdateSeen();
<add>
<add> void markUpdated();
<add>
<add> boolean hasUnseenUpdates();
<add>
<add> void dirty();
<add>
<add> boolean isDirty();
<add>
<add> void addChildAt(T child, int i);
<add>
<add> T removeChildAt(int i);
<add>
<add> int getChildCount();
<add>
<add> T getChildAt(int i);
<add>
<add> int indexOf(T child);
<add>
<add> void removeAndDisposeAllChildren();
<ide>
<ide> /**
<ide> * This method will be called by {@link UIManagerModule} once per batch, before calculating
<del> * layout. Will be only called for nodes that are marked as updated with {@link #markUpdated()}
<del> * or require layouting (marked with {@link #dirty()}).
<add> * layout. Will be only called for nodes that are marked as updated with {@link #markUpdated()} or
<add> * require layouting (marked with {@link #dirty()}).
<ide> */
<del> public void onBeforeLayout() {
<del> }
<add> void onBeforeLayout();
<ide>
<del> public final void updateProperties(ReactStylesDiffMap props) {
<del> ViewManagerPropertyUpdater.updateProps(this, props);
<del> onAfterUpdateTransaction();
<del> }
<add> void updateProperties(ReactStylesDiffMap props);
<ide>
<del> public void onAfterUpdateTransaction() {
<del> // no-op
<del> }
<add> void onAfterUpdateTransaction();
<ide>
<ide> /**
<ide> * Called after layout step at the end of the UI batch from {@link UIManagerModule}. May be used
<del> * to enqueue additional ui operations for the native view. Will only be called on nodes marked
<del> * as updated either with {@link #dirty()} or {@link #markUpdated()}.
<add> * to enqueue additional ui operations for the native view. Will only be called on nodes marked as
<add> * updated either with {@link #dirty()} or {@link #markUpdated()}.
<ide> *
<ide> * @param uiViewOperationQueue interface for enqueueing UI operations
<ide> */
<del> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {
<del> }
<add> void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue);
<ide>
<del> /**
<del> * @return true if layout (position or dimensions) changed, false otherwise.
<del> */
<add> /** @return true if layout (position or dimensions) changed, false otherwise. */
<ide> /* package */ boolean dispatchUpdates(
<ide> float absoluteX,
<ide> float absoluteY,
<ide> UIViewOperationQueue uiViewOperationQueue,
<del> NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) {
<del> if (mNodeUpdated) {
<del> onCollectExtraUpdates(uiViewOperationQueue);
<del> }
<del>
<del> if (hasNewLayout()) {
<del> float layoutX = getLayoutX();
<del> float layoutY = getLayoutY();
<del> int newAbsoluteLeft = Math.round(absoluteX + layoutX);
<del> int newAbsoluteTop = Math.round(absoluteY + layoutY);
<del> int newAbsoluteRight = Math.round(absoluteX + layoutX + getLayoutWidth());
<del> int newAbsoluteBottom = Math.round(absoluteY + layoutY + getLayoutHeight());
<del>
<del> int newScreenX = Math.round(layoutX);
<del> int newScreenY = Math.round(layoutY);
<del> int newScreenWidth = newAbsoluteRight - newAbsoluteLeft;
<del> int newScreenHeight = newAbsoluteBottom - newAbsoluteTop;
<del>
<del> boolean layoutHasChanged =
<del> newScreenX != mScreenX ||
<del> newScreenY != mScreenY ||
<del> newScreenWidth != mScreenWidth ||
<del> newScreenHeight != mScreenHeight;
<del>
<del> mScreenX = newScreenX;
<del> mScreenY = newScreenY;
<del> mScreenWidth = newScreenWidth;
<del> mScreenHeight = newScreenHeight;
<del>
<del> if (layoutHasChanged) {
<del> nativeViewHierarchyOptimizer.handleUpdateLayout(this);
<del> }
<del>
<del> return layoutHasChanged;
<del> } else {
<del> return false;
<del> }
<del> }
<del>
<del> public final int getReactTag() {
<del> return mReactTag;
<del> }
<del>
<del> public void setReactTag(int reactTag) {
<del> mReactTag = reactTag;
<del> }
<del>
<del> public final ReactShadowNode getRootNode() {
<del> return Assertions.assertNotNull(mRootNode);
<del> }
<del>
<del> /* package */ final void setRootNode(ReactShadowNode rootNode) {
<del> mRootNode = rootNode;
<del> }
<del>
<del> /* package */ final void setViewClassName(String viewClassName) {
<del> mViewClassName = viewClassName;
<del> }
<del>
<del> public final @Nullable ReactShadowNode getParent() {
<del> return mParent;
<del> }
<add> NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer);
<add>
<add> int getReactTag();
<add>
<add> void setReactTag(int reactTag);
<add>
<add> T getRootNode();
<add>
<add> void setRootNode(T rootNode);
<add>
<add> void setViewClassName(String viewClassName);
<add>
<add> @Nullable
<add> T getParent();
<ide>
<ide> /**
<ide> * Get the {@link ThemedReactContext} associated with this {@link ReactShadowNode}. This will
<ide> * never change during the lifetime of a {@link ReactShadowNode} instance, but different instances
<ide> * can have different contexts; don't cache any calculations based on theme values globally.
<ide> */
<del> public final ThemedReactContext getThemedContext() {
<del> return Assertions.assertNotNull(mThemedContext);
<del> }
<add> ThemedReactContext getThemedContext();
<ide>
<del> public void setThemedContext(ThemedReactContext themedContext) {
<del> mThemedContext = themedContext;
<del> }
<add> void setThemedContext(ThemedReactContext themedContext);
<ide>
<del> public final boolean shouldNotifyOnLayout() {
<del> return mShouldNotifyOnLayout;
<del> }
<add> boolean shouldNotifyOnLayout();
<ide>
<del> public void calculateLayout() {
<del> mYogaNode.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
<del> }
<add> void calculateLayout();
<ide>
<del> public final boolean hasNewLayout() {
<del> return mYogaNode != null && mYogaNode.hasNewLayout();
<del> }
<add> boolean hasNewLayout();
<ide>
<del> public final void markLayoutSeen() {
<del> if (mYogaNode != null) {
<del> mYogaNode.markLayoutSeen();
<del> }
<del> }
<add> void markLayoutSeen();
<ide>
<ide> /**
<ide> * Adds a child that the native view hierarchy will have at this index in the native view
<ide> * corresponding to this node.
<ide> */
<del> public final void addNativeChildAt(ReactShadowNode child, int nativeIndex) {
<del> Assertions.assertCondition(!mIsLayoutOnly);
<del> Assertions.assertCondition(!child.mIsLayoutOnly);
<del>
<del> if (mNativeChildren == null) {
<del> mNativeChildren = new ArrayList<>(4);
<del> }
<del>
<del> mNativeChildren.add(nativeIndex, child);
<del> child.mNativeParent = this;
<del> }
<del>
<del> public final ReactShadowNode removeNativeChildAt(int i) {
<del> Assertions.assertNotNull(mNativeChildren);
<del> ReactShadowNode removed = mNativeChildren.remove(i);
<del> removed.mNativeParent = null;
<del> return removed;
<del> }
<del>
<del> public final void removeAllNativeChildren() {
<del> if (mNativeChildren != null) {
<del> for (int i = mNativeChildren.size() - 1; i >= 0; i--) {
<del> mNativeChildren.get(i).mNativeParent = null;
<del> }
<del> mNativeChildren.clear();
<del> }
<del> }
<del>
<del> public final int getNativeChildCount() {
<del> return mNativeChildren == null ? 0 : mNativeChildren.size();
<del> }
<del>
<del> public final int indexOfNativeChild(ReactShadowNode nativeChild) {
<del> Assertions.assertNotNull(mNativeChildren);
<del> return mNativeChildren.indexOf(nativeChild);
<del> }
<del>
<del> public final @Nullable ReactShadowNode getNativeParent() {
<del> return mNativeParent;
<del> }
<add> void addNativeChildAt(T child, int nativeIndex);
<add>
<add> T removeNativeChildAt(int i);
<add>
<add> void removeAllNativeChildren();
<add>
<add> int getNativeChildCount();
<add>
<add> int indexOfNativeChild(T nativeChild);
<add>
<add> @Nullable
<add> T getNativeParent();
<ide>
<ide> /**
<del> * Sets whether this node only contributes to the layout of its children without doing any
<del> * drawing or functionality itself.
<add> * Sets whether this node only contributes to the layout of its children without doing any drawing
<add> * or functionality itself.
<ide> */
<del> public final void setIsLayoutOnly(boolean isLayoutOnly) {
<del> Assertions.assertCondition(getParent() == null, "Must remove from no opt parent first");
<del> Assertions.assertCondition(mNativeParent == null, "Must remove from native parent first");
<del> Assertions.assertCondition(getNativeChildCount() == 0, "Must remove all native children first");
<del> mIsLayoutOnly = isLayoutOnly;
<del> }
<del>
<del> public final boolean isLayoutOnly() {
<del> return mIsLayoutOnly;
<del> }
<del>
<del> public final int getTotalNativeChildren() {
<del> return mTotalNativeChildren;
<del> }
<del>
<del> public boolean isDescendantOf(ReactShadowNode ancestorNode) {
<del> ReactShadowNode parentNode = getParent();
<del>
<del> boolean isDescendant = false;
<del>
<del> while (parentNode != null) {
<del> if (parentNode == ancestorNode) {
<del> isDescendant = true;
<del> break;
<del> } else {
<del> parentNode = parentNode.getParent();
<del> }
<del> }
<del>
<del> return isDescendant;
<del> }
<add> void setIsLayoutOnly(boolean isLayoutOnly);
<add>
<add> boolean isLayoutOnly();
<add>
<add> int getTotalNativeChildren();
<add>
<add> boolean isDescendantOf(T ancestorNode);
<ide>
<ide> /**
<ide> * Returns the offset within the native children owned by all layout-only nodes in the subtree
<ide> public boolean isDescendantOf(ReactShadowNode ancestorNode) {
<ide> * in this subtree (which means that the given child will be a sibling of theirs in the final
<ide> * native hierarchy since they'll get attached to the same native parent).
<ide> *
<del> * Basically, a view might have children that have been optimized away by
<del> * {@link NativeViewHierarchyOptimizer}. Since those children will then add their native children
<del> * to this view, we now have ranges of native children that correspond to single unoptimized
<del> * children. The purpose of this method is to return the index within the native children that
<del> * corresponds to the **start** of the native children that belong to the given child. Also, note
<del> * that all of the children of a view might be optimized away, so this could return the same value
<del> * for multiple different children.
<add> * <p>Basically, a view might have children that have been optimized away by {@link
<add> * NativeViewHierarchyOptimizer}. Since those children will then add their native children to this
<add> * view, we now have ranges of native children that correspond to single unoptimized children. The
<add> * purpose of this method is to return the index within the native children that corresponds to
<add> * the **start** of the native children that belong to the given child. Also, note that all of the
<add> * children of a view might be optimized away, so this could return the same value for multiple
<add> * different children.
<ide> *
<del> * Example. Native children are represented by (N) where N is the no-opt child they came from. If
<del> * no children are optimized away it'd look like this: (0) (1) (2) (3) ... (n)
<add> * <p>Example. Native children are represented by (N) where N is the no-opt child they came from.
<add> * If no children are optimized away it'd look like this: (0) (1) (2) (3) ... (n)
<ide> *
<del> * In case some children are optimized away, it might look like this:
<del> * (0) (1) (1) (1) (3) (3) (4)
<add> * <p>In case some children are optimized away, it might look like this: (0) (1) (1) (1) (3) (3)
<add> * (4)
<ide> *
<del> * In that case:
<del> * getNativeOffsetForChild(Node 0) => 0
<del> * getNativeOffsetForChild(Node 1) => 1
<del> * getNativeOffsetForChild(Node 2) => 4
<del> * getNativeOffsetForChild(Node 3) => 4
<add> * <p>In that case: getNativeOffsetForChild(Node 0) => 0 getNativeOffsetForChild(Node 1) => 1
<add> * getNativeOffsetForChild(Node 2) => 4 getNativeOffsetForChild(Node 3) => 4
<ide> * getNativeOffsetForChild(Node 4) => 6
<ide> */
<del> public final int getNativeOffsetForChild(ReactShadowNode child) {
<del> int index = 0;
<del> boolean found = false;
<del> for (int i = 0; i < getChildCount(); i++) {
<del> ReactShadowNode current = getChildAt(i);
<del> if (child == current) {
<del> found = true;
<del> break;
<del> }
<del> index += (current.mIsLayoutOnly ? current.getTotalNativeChildren() : 1);
<del> }
<del> if (!found) {
<del> throw new RuntimeException("Child " + child.mReactTag + " was not a child of " + mReactTag);
<del> }
<del> return index;
<del> }
<del>
<del> public final float getLayoutX() {
<del> return mYogaNode.getLayoutX();
<del> }
<del>
<del> public final float getLayoutY() {
<del> return mYogaNode.getLayoutY();
<del> }
<del>
<del> public final float getLayoutWidth() {
<del> return mYogaNode.getLayoutWidth();
<del> }
<del>
<del> public final float getLayoutHeight() {
<del> return mYogaNode.getLayoutHeight();
<del> }
<add> int getNativeOffsetForChild(T child);
<ide>
<del> /**
<del> * @return the x position of the corresponding view on the screen, rounded to pixels
<del> */
<del> public int getScreenX() {
<del> return mScreenX;
<del> }
<add> float getLayoutX();
<ide>
<del> /**
<del> * @return the y position of the corresponding view on the screen, rounded to pixels
<del> */
<del> public int getScreenY() {
<del> return mScreenY;
<del> }
<add> float getLayoutY();
<ide>
<del> /**
<del> * @return width corrected for rounding to pixels.
<del> */
<del> public int getScreenWidth() {
<del> return mScreenWidth;
<del> }
<add> float getLayoutWidth();
<ide>
<del> /**
<del> * @return height corrected for rounding to pixels.
<del> */
<del> public int getScreenHeight() {
<del> return mScreenHeight;
<del> }
<add> float getLayoutHeight();
<add>
<add> /** @return the x position of the corresponding view on the screen, rounded to pixels */
<add> int getScreenX();
<add>
<add> /** @return the y position of the corresponding view on the screen, rounded to pixels */
<add> int getScreenY();
<add>
<add> /** @return width corrected for rounding to pixels. */
<add> int getScreenWidth();
<add>
<add> /** @return height corrected for rounding to pixels. */
<add> int getScreenHeight();
<add>
<add> YogaDirection getLayoutDirection();
<add>
<add> void setLayoutDirection(YogaDirection direction);
<add>
<add> YogaValue getStyleWidth();
<add>
<add> void setStyleWidth(float widthPx);
<add>
<add> void setStyleWidthPercent(float percent);
<add>
<add> void setStyleWidthAuto();
<add>
<add> void setStyleMinWidth(float widthPx);
<add>
<add> void setStyleMinWidthPercent(float percent);
<add>
<add> void setStyleMaxWidth(float widthPx);
<add>
<add> void setStyleMaxWidthPercent(float percent);
<add>
<add> YogaValue getStyleHeight();
<add>
<add> void setStyleHeight(float heightPx);
<add>
<add> void setStyleHeightPercent(float percent);
<add>
<add> void setStyleHeightAuto();
<add>
<add> void setStyleMinHeight(float widthPx);
<add>
<add> void setStyleMinHeightPercent(float percent);
<add>
<add> void setStyleMaxHeight(float widthPx);
<add>
<add> void setStyleMaxHeightPercent(float percent);
<add>
<add> void setFlex(float flex);
<add>
<add> void setFlexGrow(float flexGrow);
<add>
<add> void setFlexShrink(float flexShrink);
<add>
<add> void setFlexBasis(float flexBasis);
<add>
<add> void setFlexBasisAuto();
<add>
<add> void setFlexBasisPercent(float percent);
<add>
<add> void setStyleAspectRatio(float aspectRatio);
<add>
<add> void setFlexDirection(YogaFlexDirection flexDirection);
<add>
<add> void setFlexWrap(YogaWrap wrap);
<add>
<add> void setAlignSelf(YogaAlign alignSelf);
<add>
<add> void setAlignItems(YogaAlign alignItems);
<add>
<add> void setAlignContent(YogaAlign alignContent);
<add>
<add> void setJustifyContent(YogaJustify justifyContent);
<add>
<add> void setOverflow(YogaOverflow overflow);
<add>
<add> void setDisplay(YogaDisplay display);
<add>
<add> void setMargin(int spacingType, float margin);
<add>
<add> void setMarginPercent(int spacingType, float percent);
<add>
<add> void setMarginAuto(int spacingType);
<ide>
<del> public final YogaDirection getLayoutDirection() {
<del> return mYogaNode.getLayoutDirection();
<del> }
<add> float getPadding(int spacingType);
<ide>
<del> public void setLayoutDirection(YogaDirection direction) {
<del> mYogaNode.setDirection(direction);
<del> }
<add> YogaValue getStylePadding(int spacingType);
<ide>
<del> public final YogaValue getStyleWidth() {
<del> return mYogaNode.getWidth();
<del> }
<add> void setDefaultPadding(int spacingType, float padding);
<ide>
<del> public void setStyleWidth(float widthPx) {
<del> mYogaNode.setWidth(widthPx);
<del> }
<add> void setPadding(int spacingType, float padding);
<ide>
<del> public void setStyleWidthPercent(float percent) {
<del> mYogaNode.setWidthPercent(percent);
<del> }
<add> void setPaddingPercent(int spacingType, float percent);
<ide>
<del> public void setStyleWidthAuto() {
<del> mYogaNode.setWidthAuto();
<del> }
<add> void setBorder(int spacingType, float borderWidth);
<ide>
<del> public void setStyleMinWidth(float widthPx) {
<del> mYogaNode.setMinWidth(widthPx);
<del> }
<add> void setPosition(int spacingType, float position);
<ide>
<del> public void setStyleMinWidthPercent(float percent) {
<del> mYogaNode.setMinWidthPercent(percent);
<del> }
<add> void setPositionPercent(int spacingType, float percent);
<ide>
<del> public void setStyleMaxWidth(float widthPx) {
<del> mYogaNode.setMaxWidth(widthPx);
<del> }
<add> void setPositionType(YogaPositionType positionType);
<ide>
<del> public void setStyleMaxWidthPercent(float percent) {
<del> mYogaNode.setMaxWidthPercent(percent);
<del> }
<add> void setShouldNotifyOnLayout(boolean shouldNotifyOnLayout);
<ide>
<del> public final YogaValue getStyleHeight() {
<del> return mYogaNode.getHeight();
<del> }
<add> void setBaselineFunction(YogaBaselineFunction baselineFunction);
<ide>
<del> public void setStyleHeight(float heightPx) {
<del> mYogaNode.setHeight(heightPx);
<del> }
<add> void setMeasureFunction(YogaMeasureFunction measureFunction);
<ide>
<del> public void setStyleHeightPercent(float percent) {
<del> mYogaNode.setHeightPercent(percent);
<del> }
<add> boolean isMeasureDefined();
<ide>
<del> public void setStyleHeightAuto() {
<del> mYogaNode.setHeightAuto();
<del> }
<del>
<del> public void setStyleMinHeight(float widthPx) {
<del> mYogaNode.setMinHeight(widthPx);
<del> }
<del>
<del> public void setStyleMinHeightPercent(float percent) {
<del> mYogaNode.setMinHeightPercent(percent);
<del> }
<del>
<del> public void setStyleMaxHeight(float widthPx) {
<del> mYogaNode.setMaxHeight(widthPx);
<del> }
<del>
<del> public void setStyleMaxHeightPercent(float percent) {
<del> mYogaNode.setMaxHeightPercent(percent);
<del> }
<del>
<del> public void setFlex(float flex) {
<del> mYogaNode.setFlex(flex);
<del> }
<del>
<del> public void setFlexGrow(float flexGrow) {
<del> mYogaNode.setFlexGrow(flexGrow);
<del> }
<del>
<del> public void setFlexShrink(float flexShrink) {
<del> mYogaNode.setFlexShrink(flexShrink);
<del> }
<del>
<del> public void setFlexBasis(float flexBasis) {
<del> mYogaNode.setFlexBasis(flexBasis);
<del> }
<del>
<del> public void setFlexBasisAuto() {
<del> mYogaNode.setFlexBasisAuto();
<del> }
<del>
<del> public void setFlexBasisPercent(float percent) {
<del> mYogaNode.setFlexBasisPercent(percent);
<del> }
<del>
<del> public void setStyleAspectRatio(float aspectRatio) {
<del> mYogaNode.setAspectRatio(aspectRatio);
<del> }
<del>
<del> public void setFlexDirection(YogaFlexDirection flexDirection) {
<del> mYogaNode.setFlexDirection(flexDirection);
<del> }
<del>
<del> public void setFlexWrap(YogaWrap wrap) {
<del> mYogaNode.setWrap(wrap);
<del> }
<del>
<del> public void setAlignSelf(YogaAlign alignSelf) {
<del> mYogaNode.setAlignSelf(alignSelf);
<del> }
<del>
<del> public void setAlignItems(YogaAlign alignItems) {
<del> mYogaNode.setAlignItems(alignItems);
<del> }
<del>
<del> public void setAlignContent(YogaAlign alignContent) {
<del> mYogaNode.setAlignContent(alignContent);
<del> }
<del>
<del> public void setJustifyContent(YogaJustify justifyContent) {
<del> mYogaNode.setJustifyContent(justifyContent);
<del> }
<del>
<del> public void setOverflow(YogaOverflow overflow) {
<del> mYogaNode.setOverflow(overflow);
<del> }
<del>
<del> public void setDisplay(YogaDisplay display) {
<del> mYogaNode.setDisplay(display);
<del> }
<del>
<del> public void setMargin(int spacingType, float margin) {
<del> mYogaNode.setMargin(YogaEdge.fromInt(spacingType), margin);
<del> }
<del>
<del> public void setMarginPercent(int spacingType, float percent) {
<del> mYogaNode.setMarginPercent(YogaEdge.fromInt(spacingType), percent);
<del> }
<del>
<del> public void setMarginAuto(int spacingType) {
<del> mYogaNode.setMarginAuto(YogaEdge.fromInt(spacingType));
<del> }
<del>
<del> public final float getPadding(int spacingType) {
<del> return mYogaNode.getLayoutPadding(YogaEdge.fromInt(spacingType));
<del> }
<del>
<del> public final YogaValue getStylePadding(int spacingType) {
<del> return mYogaNode.getPadding(YogaEdge.fromInt(spacingType));
<del> }
<del>
<del> public void setDefaultPadding(int spacingType, float padding) {
<del> mDefaultPadding.set(spacingType, padding);
<del> updatePadding();
<del> }
<del>
<del> public void setPadding(int spacingType, float padding) {
<del> mPadding[spacingType] = padding;
<del> mPaddingIsPercent[spacingType] = false;
<del> updatePadding();
<del> }
<del>
<del> public void setPaddingPercent(int spacingType, float percent) {
<del> mPadding[spacingType] = percent;
<del> mPaddingIsPercent[spacingType] = !YogaConstants.isUndefined(percent);
<del> updatePadding();
<del> }
<del>
<del> private void updatePadding() {
<del> for (int spacingType = Spacing.LEFT; spacingType <= Spacing.ALL; spacingType++) {
<del> if (spacingType == Spacing.LEFT ||
<del> spacingType == Spacing.RIGHT ||
<del> spacingType == Spacing.START ||
<del> spacingType == Spacing.END) {
<del> if (YogaConstants.isUndefined(mPadding[spacingType]) &&
<del> YogaConstants.isUndefined(mPadding[Spacing.HORIZONTAL]) &&
<del> YogaConstants.isUndefined(mPadding[Spacing.ALL])) {
<del> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<del> continue;
<del> }
<del> } else if (spacingType == Spacing.TOP || spacingType == Spacing.BOTTOM) {
<del> if (YogaConstants.isUndefined(mPadding[spacingType]) &&
<del> YogaConstants.isUndefined(mPadding[Spacing.VERTICAL]) &&
<del> YogaConstants.isUndefined(mPadding[Spacing.ALL])) {
<del> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<del> continue;
<del> }
<del> } else {
<del> if (YogaConstants.isUndefined(mPadding[spacingType])) {
<del> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<del> continue;
<del> }
<del> }
<del>
<del> if (mPaddingIsPercent[spacingType]) {
<del> mYogaNode.setPaddingPercent(YogaEdge.fromInt(spacingType), mPadding[spacingType]);
<del> } else {
<del> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mPadding[spacingType]);
<del> }
<del> }
<del> }
<del>
<del> public void setBorder(int spacingType, float borderWidth) {
<del> mYogaNode.setBorder(YogaEdge.fromInt(spacingType), borderWidth);
<del> }
<del>
<del> public void setPosition(int spacingType, float position) {
<del> mYogaNode.setPosition(YogaEdge.fromInt(spacingType), position);
<del> }
<del>
<del> public void setPositionPercent(int spacingType, float percent) {
<del> mYogaNode.setPositionPercent(YogaEdge.fromInt(spacingType), percent);
<del> }
<del>
<del> public void setPositionType(YogaPositionType positionType) {
<del> mYogaNode.setPositionType(positionType);
<del> }
<del>
<del> public void setShouldNotifyOnLayout(boolean shouldNotifyOnLayout) {
<del> mShouldNotifyOnLayout = shouldNotifyOnLayout;
<del> }
<del>
<del> public void setBaselineFunction(YogaBaselineFunction baselineFunction) {
<del> mYogaNode.setBaselineFunction(baselineFunction);
<del> }
<del>
<del> public void setMeasureFunction(YogaMeasureFunction measureFunction) {
<del> if ((measureFunction == null ^ mYogaNode.isMeasureDefined()) &&
<del> getChildCount() != 0) {
<del> throw new RuntimeException(
<del> "Since a node with a measure function does not add any native yoga children, it's " +
<del> "not safe to transition to/from having a measure function unless a node has no children");
<del> }
<del> mYogaNode.setMeasureFunction(measureFunction);
<del> }
<del>
<del> public boolean isMeasureDefined() {
<del> return mYogaNode.isMeasureDefined();
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> StringBuilder sb = new StringBuilder();
<del> toStringWithIndentation(sb, 0);
<del> return sb.toString();
<del> }
<del>
<del> private void toStringWithIndentation(StringBuilder result, int level) {
<del> // Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead.
<del> for (int i = 0; i < level; ++i) {
<del> result.append("__");
<del> }
<del>
<del> result
<del> .append(getClass().getSimpleName())
<del> .append(" ");
<del> if (mYogaNode != null) {
<del> result
<del> .append(getLayoutWidth())
<del> .append(",")
<del> .append(getLayoutHeight());
<del> } else {
<del> result.append("(virtual node)");
<del> }
<del> result.append("\n");
<del>
<del> if (getChildCount() == 0) {
<del> return;
<del> }
<del>
<del> for (int i = 0; i < getChildCount(); i++) {
<del> getChildAt(i).toStringWithIndentation(result, level + 1);
<del> }
<del> }
<del>
<del> public void dispose() {
<del> if (mYogaNode != null) {
<del> mYogaNode.reset();
<del> YogaNodePool.get().release(mYogaNode);
<del> }
<del> }
<add> void dispose();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.uimanager;
<add>
<add>import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.yoga.YogaAlign;
<add>import com.facebook.yoga.YogaBaselineFunction;
<add>import com.facebook.yoga.YogaConfig;
<add>import com.facebook.yoga.YogaConstants;
<add>import com.facebook.yoga.YogaDirection;
<add>import com.facebook.yoga.YogaDisplay;
<add>import com.facebook.yoga.YogaEdge;
<add>import com.facebook.yoga.YogaFlexDirection;
<add>import com.facebook.yoga.YogaJustify;
<add>import com.facebook.yoga.YogaMeasureFunction;
<add>import com.facebook.yoga.YogaNode;
<add>import com.facebook.yoga.YogaOverflow;
<add>import com.facebook.yoga.YogaPositionType;
<add>import com.facebook.yoga.YogaValue;
<add>import com.facebook.yoga.YogaWrap;
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import javax.annotation.Nullable;
<add>
<add>/**
<add> * Base node class for representing virtual tree of React nodes. Shadow nodes are used primarily for
<add> * layouting therefore it extends {@link YogaNode} to allow that. They also help with handling
<add> * Common base subclass of {@link YogaNode} for all layout nodes for react-based view. It extends
<add> * {@link YogaNode} by adding additional capabilities.
<add> *
<add> * <p>Instances of this class receive property updates from JS via @{link UIManagerModule}.
<add> * Subclasses may use {@link #updateShadowNode} to persist some of the updated fields in the node
<add> * instance that corresponds to a particular view type.
<add> *
<add> * <p>Subclasses of {@link ReactShadowNodeImpl} should be created only from {@link ViewManager} that
<add> * corresponds to a certain type of native view. They will be updated and accessed only from JS
<add> * thread. Subclasses of {@link ViewManager} may choose to use base class {@link
<add> * ReactShadowNodeImpl} or custom subclass of it if necessary.
<add> *
<add> * <p>The primary use-case for {@link ReactShadowNodeImpl} nodes is to calculate layouting. Although
<add> * this might be extended. For some examples please refer to ARTGroupYogaNode or ReactTextYogaNode.
<add> *
<add> * <p>This class allows for the native view hierarchy to not be an exact copy of the hierarchy
<add> * received from JS by keeping track of both JS children (e.g. {@link #getChildCount()} and
<add> * separately native children (e.g. {@link #getNativeChildCount()}). See {@link
<add> * NativeViewHierarchyOptimizer} for more information.
<add> */
<add>public class ReactShadowNodeImpl implements ReactShadowNode<ReactShadowNodeImpl> {
<add>
<add> private int mReactTag;
<add> private @Nullable String mViewClassName;
<add> private @Nullable ReactShadowNodeImpl mRootNode;
<add> private @Nullable ThemedReactContext mThemedContext;
<add> private boolean mShouldNotifyOnLayout;
<add> private boolean mNodeUpdated = true;
<add> private @Nullable ArrayList<ReactShadowNodeImpl> mChildren;
<add> private @Nullable ReactShadowNodeImpl mParent;
<add>
<add> // layout-only nodes
<add> private boolean mIsLayoutOnly;
<add> private int mTotalNativeChildren = 0;
<add> private @Nullable ReactShadowNodeImpl mNativeParent;
<add> private @Nullable ArrayList<ReactShadowNodeImpl> mNativeChildren;
<add> private int mScreenX;
<add> private int mScreenY;
<add> private int mScreenWidth;
<add> private int mScreenHeight;
<add> private final Spacing mDefaultPadding = new Spacing(0);
<add> private final float[] mPadding = new float[Spacing.ALL + 1];
<add> private final boolean[] mPaddingIsPercent = new boolean[Spacing.ALL + 1];
<add> private final YogaNode mYogaNode;
<add> private static YogaConfig sYogaConfig;
<add>
<add> public ReactShadowNodeImpl() {
<add> if (!isVirtual()) {
<add> YogaNode node = YogaNodePool.get().acquire();
<add> if (sYogaConfig == null) {
<add> sYogaConfig = new YogaConfig();
<add> sYogaConfig.setPointScaleFactor(0f);
<add> sYogaConfig.setUseLegacyStretchBehaviour(true);
<add> }
<add> if (node == null) {
<add> node = new YogaNode(sYogaConfig);
<add> }
<add> mYogaNode = node;
<add> Arrays.fill(mPadding, YogaConstants.UNDEFINED);
<add> } else {
<add> mYogaNode = null;
<add> }
<add> }
<add>
<add> /**
<add> * Nodes that return {@code true} will be treated as "virtual" nodes. That is, nodes that are not
<add> * mapped into native views (e.g. nested text node). By default this method returns {@code false}.
<add> */
<add> @Override
<add> public boolean isVirtual() {
<add> return false;
<add> }
<add>
<add> /**
<add> * Nodes that return {@code true} will be treated as a root view for the virtual nodes tree. It
<add> * means that {@link NativeViewHierarchyManager} will not try to perform {@code manageChildren}
<add> * operation on such views. Good example is {@code InputText} view that may have children {@code
<add> * Text} nodes but this whole hierarchy will be mapped to a single android {@link EditText} view.
<add> */
<add> @Override
<add> public boolean isVirtualAnchor() {
<add> return false;
<add> }
<add>
<add> /**
<add> * Nodes that return {@code true} will not manage (and and remove) child Yoga nodes. For example
<add> * {@link ReactTextInputShadowNode} or {@link ReactTextShadowNode} have child nodes, which do not
<add> * want Yoga to lay out, so in the eyes of Yoga it is a leaf node. Override this method in
<add> * subclass to enforce this requirement.
<add> */
<add> @Override
<add> public boolean isYogaLeafNode() {
<add> return isMeasureDefined();
<add> }
<add>
<add> @Override
<add> public final String getViewClass() {
<add> return Assertions.assertNotNull(mViewClassName);
<add> }
<add>
<add> @Override
<add> public final boolean hasUpdates() {
<add> return mNodeUpdated || hasNewLayout() || isDirty();
<add> }
<add>
<add> @Override
<add> public final void markUpdateSeen() {
<add> mNodeUpdated = false;
<add> if (hasNewLayout()) {
<add> markLayoutSeen();
<add> }
<add> }
<add>
<add> @Override
<add> public void markUpdated() {
<add> if (mNodeUpdated) {
<add> return;
<add> }
<add> mNodeUpdated = true;
<add> ReactShadowNodeImpl parent = getParent();
<add> if (parent != null) {
<add> parent.markUpdated();
<add> }
<add> }
<add>
<add> @Override
<add> public final boolean hasUnseenUpdates() {
<add> return mNodeUpdated;
<add> }
<add>
<add> @Override
<add> public void dirty() {
<add> if (!isVirtual()) {
<add> mYogaNode.dirty();
<add> }
<add> }
<add>
<add> @Override
<add> public final boolean isDirty() {
<add> return mYogaNode != null && mYogaNode.isDirty();
<add> }
<add>
<add> @Override
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<add> if (child.getParent() != null) {
<add> throw new IllegalViewOperationException(
<add> "Tried to add child that already has a parent! Remove it from its parent first.");
<add> }
<add> if (mChildren == null) {
<add> mChildren = new ArrayList<ReactShadowNodeImpl>(4);
<add> }
<add> mChildren.add(i, child);
<add> child.mParent = this;
<add>
<add> // If a CSS node has measure defined, the layout algorithm will not visit its children. Even
<add> // more, it asserts that you don't add children to nodes with measure functions.
<add> if (mYogaNode != null && !isYogaLeafNode()) {
<add> YogaNode childYogaNode = child.mYogaNode;
<add> if (childYogaNode == null) {
<add> throw new RuntimeException(
<add> "Cannot add a child that doesn't have a YogaNode to a parent without a measure " +
<add> "function! (Trying to add a '" + child.getClass().getSimpleName() + "' to a '" +
<add> getClass().getSimpleName() + "')");
<add> }
<add> mYogaNode.addChildAt(childYogaNode, i);
<add> }
<add> markUpdated();
<add>
<add> int increase = child.isLayoutOnly() ? child.getTotalNativeChildren() : 1;
<add> mTotalNativeChildren += increase;
<add>
<add> updateNativeChildrenCountInParent(increase);
<add> }
<add>
<add> @Override
<add> public ReactShadowNodeImpl removeChildAt(int i) {
<add> if (mChildren == null) {
<add> throw new ArrayIndexOutOfBoundsException(
<add> "Index " + i + " out of bounds: node has no children");
<add> }
<add> ReactShadowNodeImpl removed = mChildren.remove(i);
<add> removed.mParent = null;
<add>
<add> if (mYogaNode != null && !isYogaLeafNode()) {
<add> mYogaNode.removeChildAt(i);
<add> }
<add> markUpdated();
<add>
<add> int decrease = removed.isLayoutOnly() ? removed.getTotalNativeChildren() : 1;
<add> mTotalNativeChildren -= decrease;
<add> updateNativeChildrenCountInParent(-decrease);
<add> return removed;
<add> }
<add>
<add> @Override
<add> public final int getChildCount() {
<add> return mChildren == null ? 0 : mChildren.size();
<add> }
<add>
<add> @Override
<add> public final ReactShadowNodeImpl getChildAt(int i) {
<add> if (mChildren == null) {
<add> throw new ArrayIndexOutOfBoundsException(
<add> "Index " + i + " out of bounds: node has no children");
<add> }
<add> return mChildren.get(i);
<add> }
<add>
<add> @Override
<add> public final int indexOf(ReactShadowNodeImpl child) {
<add> return mChildren == null ? -1 : mChildren.indexOf(child);
<add> }
<add>
<add> @Override
<add> public void removeAndDisposeAllChildren() {
<add> if (getChildCount() == 0) {
<add> return;
<add> }
<add>
<add> int decrease = 0;
<add> for (int i = getChildCount() - 1; i >= 0; i--) {
<add> if (mYogaNode != null && !isYogaLeafNode()) {
<add> mYogaNode.removeChildAt(i);
<add> }
<add> ReactShadowNodeImpl toRemove = getChildAt(i);
<add> toRemove.mParent = null;
<add> toRemove.dispose();
<add>
<add> decrease += toRemove.isLayoutOnly() ? toRemove.getTotalNativeChildren() : 1;
<add> }
<add> Assertions.assertNotNull(mChildren).clear();
<add> markUpdated();
<add>
<add> mTotalNativeChildren -= decrease;
<add> updateNativeChildrenCountInParent(-decrease);
<add> }
<add>
<add> private void updateNativeChildrenCountInParent(int delta) {
<add> if (mIsLayoutOnly) {
<add> ReactShadowNodeImpl parent = getParent();
<add> while (parent != null) {
<add> parent.mTotalNativeChildren += delta;
<add> if (!parent.isLayoutOnly()) {
<add> break;
<add> }
<add> parent = parent.getParent();
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * This method will be called by {@link UIManagerModule} once per batch, before calculating
<add> * layout. Will be only called for nodes that are marked as updated with {@link #markUpdated()} or
<add> * require layouting (marked with {@link #dirty()}).
<add> */
<add> @Override
<add> public void onBeforeLayout() {}
<add>
<add> @Override
<add> public final void updateProperties(ReactStylesDiffMap props) {
<add> ViewManagerPropertyUpdater.updateProps(this, props);
<add> onAfterUpdateTransaction();
<add> }
<add>
<add> @Override
<add> public void onAfterUpdateTransaction() {
<add> // no-op
<add> }
<add>
<add> /**
<add> * Called after layout step at the end of the UI batch from {@link UIManagerModule}. May be used
<add> * to enqueue additional ui operations for the native view. Will only be called on nodes marked as
<add> * updated either with {@link #dirty()} or {@link #markUpdated()}.
<add> *
<add> * @param uiViewOperationQueue interface for enqueueing UI operations
<add> */
<add> @Override
<add> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {}
<add>
<add> /** @return true if layout (position or dimensions) changed, false otherwise. */
<add> @Override
<add> public boolean dispatchUpdates(
<add> float absoluteX,
<add> float absoluteY,
<add> UIViewOperationQueue uiViewOperationQueue,
<add> NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) {
<add> if (mNodeUpdated) {
<add> onCollectExtraUpdates(uiViewOperationQueue);
<add> }
<add>
<add> if (hasNewLayout()) {
<add> float layoutX = getLayoutX();
<add> float layoutY = getLayoutY();
<add> int newAbsoluteLeft = Math.round(absoluteX + layoutX);
<add> int newAbsoluteTop = Math.round(absoluteY + layoutY);
<add> int newAbsoluteRight = Math.round(absoluteX + layoutX + getLayoutWidth());
<add> int newAbsoluteBottom = Math.round(absoluteY + layoutY + getLayoutHeight());
<add>
<add> int newScreenX = Math.round(layoutX);
<add> int newScreenY = Math.round(layoutY);
<add> int newScreenWidth = newAbsoluteRight - newAbsoluteLeft;
<add> int newScreenHeight = newAbsoluteBottom - newAbsoluteTop;
<add>
<add> boolean layoutHasChanged =
<add> newScreenX != mScreenX ||
<add> newScreenY != mScreenY ||
<add> newScreenWidth != mScreenWidth ||
<add> newScreenHeight != mScreenHeight;
<add>
<add> mScreenX = newScreenX;
<add> mScreenY = newScreenY;
<add> mScreenWidth = newScreenWidth;
<add> mScreenHeight = newScreenHeight;
<add>
<add> if (layoutHasChanged) {
<add> nativeViewHierarchyOptimizer.handleUpdateLayout(this);
<add> }
<add>
<add> return layoutHasChanged;
<add> } else {
<add> return false;
<add> }
<add> }
<add>
<add> @Override
<add> public final int getReactTag() {
<add> return mReactTag;
<add> }
<add>
<add> @Override
<add> public void setReactTag(int reactTag) {
<add> mReactTag = reactTag;
<add> }
<add>
<add> @Override
<add> public final ReactShadowNodeImpl getRootNode() {
<add> return Assertions.assertNotNull(mRootNode);
<add> }
<add>
<add> @Override
<add> public final void setRootNode(ReactShadowNodeImpl rootNode) {
<add> mRootNode = rootNode;
<add> }
<add>
<add> @Override
<add> public final void setViewClassName(String viewClassName) {
<add> mViewClassName = viewClassName;
<add> }
<add>
<add> @Override
<add> public final @Nullable ReactShadowNodeImpl getParent() {
<add> return mParent;
<add> }
<add>
<add> /**
<add> * Get the {@link ThemedReactContext} associated with this {@link ReactShadowNodeImpl}. This will
<add> * never change during the lifetime of a {@link ReactShadowNodeImpl} instance, but different
<add> * instances can have different contexts; don't cache any calculations based on theme values
<add> * globally.
<add> */
<add> @Override
<add> public final ThemedReactContext getThemedContext() {
<add> return Assertions.assertNotNull(mThemedContext);
<add> }
<add>
<add> @Override
<add> public void setThemedContext(ThemedReactContext themedContext) {
<add> mThemedContext = themedContext;
<add> }
<add>
<add> @Override
<add> public final boolean shouldNotifyOnLayout() {
<add> return mShouldNotifyOnLayout;
<add> }
<add>
<add> @Override
<add> public void calculateLayout() {
<add> mYogaNode.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
<add> }
<add>
<add> @Override
<add> public final boolean hasNewLayout() {
<add> return mYogaNode != null && mYogaNode.hasNewLayout();
<add> }
<add>
<add> @Override
<add> public final void markLayoutSeen() {
<add> if (mYogaNode != null) {
<add> mYogaNode.markLayoutSeen();
<add> }
<add> }
<add>
<add> /**
<add> * Adds a child that the native view hierarchy will have at this index in the native view
<add> * corresponding to this node.
<add> */
<add> @Override
<add> public final void addNativeChildAt(ReactShadowNodeImpl child, int nativeIndex) {
<add> Assertions.assertCondition(!mIsLayoutOnly);
<add> Assertions.assertCondition(!child.mIsLayoutOnly);
<add>
<add> if (mNativeChildren == null) {
<add> mNativeChildren = new ArrayList<>(4);
<add> }
<add>
<add> mNativeChildren.add(nativeIndex, child);
<add> child.mNativeParent = this;
<add> }
<add>
<add> @Override
<add> public final ReactShadowNodeImpl removeNativeChildAt(int i) {
<add> Assertions.assertNotNull(mNativeChildren);
<add> ReactShadowNodeImpl removed = mNativeChildren.remove(i);
<add> removed.mNativeParent = null;
<add> return removed;
<add> }
<add>
<add> @Override
<add> public final void removeAllNativeChildren() {
<add> if (mNativeChildren != null) {
<add> for (int i = mNativeChildren.size() - 1; i >= 0; i--) {
<add> mNativeChildren.get(i).mNativeParent = null;
<add> }
<add> mNativeChildren.clear();
<add> }
<add> }
<add>
<add> @Override
<add> public final int getNativeChildCount() {
<add> return mNativeChildren == null ? 0 : mNativeChildren.size();
<add> }
<add>
<add> @Override
<add> public final int indexOfNativeChild(ReactShadowNodeImpl nativeChild) {
<add> Assertions.assertNotNull(mNativeChildren);
<add> return mNativeChildren.indexOf(nativeChild);
<add> }
<add>
<add> @Override
<add> public final @Nullable ReactShadowNodeImpl getNativeParent() {
<add> return mNativeParent;
<add> }
<add>
<add> /**
<add> * Sets whether this node only contributes to the layout of its children without doing any drawing
<add> * or functionality itself.
<add> */
<add> @Override
<add> public final void setIsLayoutOnly(boolean isLayoutOnly) {
<add> Assertions.assertCondition(getParent() == null, "Must remove from no opt parent first");
<add> Assertions.assertCondition(mNativeParent == null, "Must remove from native parent first");
<add> Assertions.assertCondition(getNativeChildCount() == 0, "Must remove all native children first");
<add> mIsLayoutOnly = isLayoutOnly;
<add> }
<add>
<add> @Override
<add> public final boolean isLayoutOnly() {
<add> return mIsLayoutOnly;
<add> }
<add>
<add> @Override
<add> public final int getTotalNativeChildren() {
<add> return mTotalNativeChildren;
<add> }
<add>
<add>
<add> @Override
<add> public boolean isDescendantOf(ReactShadowNodeImpl ancestorNode) {
<add> ReactShadowNodeImpl parentNode = getParent();
<add>
<add> boolean isDescendant = false;
<add>
<add> while (parentNode != null) {
<add> if (parentNode == ancestorNode) {
<add> isDescendant = true;
<add> break;
<add> } else {
<add> parentNode = parentNode.getParent();
<add> }
<add> }
<add>
<add> return isDescendant;
<add> }
<add>
<add> /**
<add> * Returns the offset within the native children owned by all layout-only nodes in the subtree
<add> * rooted at this node for the given child. Put another way, this returns the number of native
<add> * nodes (nodes not optimized out of the native tree) that are a) to the left (visited before by a
<add> * DFS) of the given child in the subtree rooted at this node and b) do not have a native parent
<add> * in this subtree (which means that the given child will be a sibling of theirs in the final
<add> * native hierarchy since they'll get attached to the same native parent).
<add> *
<add> * <p>Basically, a view might have children that have been optimized away by {@link
<add> * NativeViewHierarchyOptimizer}. Since those children will then add their native children to this
<add> * view, we now have ranges of native children that correspond to single unoptimized children. The
<add> * purpose of this method is to return the index within the native children that corresponds to
<add> * the **start** of the native children that belong to the given child. Also, note that all of the
<add> * children of a view might be optimized away, so this could return the same value for multiple
<add> * different children.
<add> *
<add> * <p>Example. Native children are represented by (N) where N is the no-opt child they came from.
<add> * If no children are optimized away it'd look like this: (0) (1) (2) (3) ... (n)
<add> *
<add> * <p>In case some children are optimized away, it might look like this: (0) (1) (1) (1) (3) (3)
<add> * (4)
<add> *
<add> * <p>In that case: getNativeOffsetForChild(Node 0) => 0 getNativeOffsetForChild(Node 1) => 1
<add> * getNativeOffsetForChild(Node 2) => 4 getNativeOffsetForChild(Node 3) => 4
<add> * getNativeOffsetForChild(Node 4) => 6
<add> */
<add> @Override
<add> public final int getNativeOffsetForChild(ReactShadowNodeImpl child) {
<add> int index = 0;
<add> boolean found = false;
<add> for (int i = 0; i < getChildCount(); i++) {
<add> ReactShadowNodeImpl current = getChildAt(i);
<add> if (child == current) {
<add> found = true;
<add> break;
<add> }
<add> index += (current.isLayoutOnly() ? current.getTotalNativeChildren() : 1);
<add> }
<add> if (!found) {
<add> throw new RuntimeException(
<add> "Child " + child.getReactTag() + " was not a child of " + mReactTag);
<add> }
<add> return index;
<add> }
<add>
<add> @Override
<add> public final float getLayoutX() {
<add> return mYogaNode.getLayoutX();
<add> }
<add>
<add> @Override
<add> public final float getLayoutY() {
<add> return mYogaNode.getLayoutY();
<add> }
<add>
<add> @Override
<add> public final float getLayoutWidth() {
<add> return mYogaNode.getLayoutWidth();
<add> }
<add>
<add> @Override
<add> public final float getLayoutHeight() {
<add> return mYogaNode.getLayoutHeight();
<add> }
<add>
<add> /** @return the x position of the corresponding view on the screen, rounded to pixels */
<add> @Override
<add> public int getScreenX() {
<add> return mScreenX;
<add> }
<add>
<add> /** @return the y position of the corresponding view on the screen, rounded to pixels */
<add> @Override
<add> public int getScreenY() {
<add> return mScreenY;
<add> }
<add>
<add> /** @return width corrected for rounding to pixels. */
<add> @Override
<add> public int getScreenWidth() {
<add> return mScreenWidth;
<add> }
<add>
<add> /** @return height corrected for rounding to pixels. */
<add> @Override
<add> public int getScreenHeight() {
<add> return mScreenHeight;
<add> }
<add>
<add> @Override
<add> public final YogaDirection getLayoutDirection() {
<add> return mYogaNode.getLayoutDirection();
<add> }
<add>
<add> @Override
<add> public void setLayoutDirection(YogaDirection direction) {
<add> mYogaNode.setDirection(direction);
<add> }
<add>
<add> @Override
<add> public final YogaValue getStyleWidth() {
<add> return mYogaNode.getWidth();
<add> }
<add>
<add> @Override
<add> public void setStyleWidth(float widthPx) {
<add> mYogaNode.setWidth(widthPx);
<add> }
<add>
<add> @Override
<add> public void setStyleWidthPercent(float percent) {
<add> mYogaNode.setWidthPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setStyleWidthAuto() {
<add> mYogaNode.setWidthAuto();
<add> }
<add>
<add> @Override
<add> public void setStyleMinWidth(float widthPx) {
<add> mYogaNode.setMinWidth(widthPx);
<add> }
<add>
<add> @Override
<add> public void setStyleMinWidthPercent(float percent) {
<add> mYogaNode.setMinWidthPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setStyleMaxWidth(float widthPx) {
<add> mYogaNode.setMaxWidth(widthPx);
<add> }
<add>
<add> @Override
<add> public void setStyleMaxWidthPercent(float percent) {
<add> mYogaNode.setMaxWidthPercent(percent);
<add> }
<add>
<add> @Override
<add> public final YogaValue getStyleHeight() {
<add> return mYogaNode.getHeight();
<add> }
<add>
<add> @Override
<add> public void setStyleHeight(float heightPx) {
<add> mYogaNode.setHeight(heightPx);
<add> }
<add>
<add> @Override
<add> public void setStyleHeightPercent(float percent) {
<add> mYogaNode.setHeightPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setStyleHeightAuto() {
<add> mYogaNode.setHeightAuto();
<add> }
<add>
<add> @Override
<add> public void setStyleMinHeight(float widthPx) {
<add> mYogaNode.setMinHeight(widthPx);
<add> }
<add>
<add> @Override
<add> public void setStyleMinHeightPercent(float percent) {
<add> mYogaNode.setMinHeightPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setStyleMaxHeight(float widthPx) {
<add> mYogaNode.setMaxHeight(widthPx);
<add> }
<add>
<add> @Override
<add> public void setStyleMaxHeightPercent(float percent) {
<add> mYogaNode.setMaxHeightPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setFlex(float flex) {
<add> mYogaNode.setFlex(flex);
<add> }
<add>
<add> @Override
<add> public void setFlexGrow(float flexGrow) {
<add> mYogaNode.setFlexGrow(flexGrow);
<add> }
<add>
<add> @Override
<add> public void setFlexShrink(float flexShrink) {
<add> mYogaNode.setFlexShrink(flexShrink);
<add> }
<add>
<add> @Override
<add> public void setFlexBasis(float flexBasis) {
<add> mYogaNode.setFlexBasis(flexBasis);
<add> }
<add>
<add> @Override
<add> public void setFlexBasisAuto() {
<add> mYogaNode.setFlexBasisAuto();
<add> }
<add>
<add> @Override
<add> public void setFlexBasisPercent(float percent) {
<add> mYogaNode.setFlexBasisPercent(percent);
<add> }
<add>
<add> @Override
<add> public void setStyleAspectRatio(float aspectRatio) {
<add> mYogaNode.setAspectRatio(aspectRatio);
<add> }
<add>
<add> @Override
<add> public void setFlexDirection(YogaFlexDirection flexDirection) {
<add> mYogaNode.setFlexDirection(flexDirection);
<add> }
<add>
<add> @Override
<add> public void setFlexWrap(YogaWrap wrap) {
<add> mYogaNode.setWrap(wrap);
<add> }
<add>
<add> @Override
<add> public void setAlignSelf(YogaAlign alignSelf) {
<add> mYogaNode.setAlignSelf(alignSelf);
<add> }
<add>
<add> @Override
<add> public void setAlignItems(YogaAlign alignItems) {
<add> mYogaNode.setAlignItems(alignItems);
<add> }
<add>
<add> @Override
<add> public void setAlignContent(YogaAlign alignContent) {
<add> mYogaNode.setAlignContent(alignContent);
<add> }
<add>
<add> @Override
<add> public void setJustifyContent(YogaJustify justifyContent) {
<add> mYogaNode.setJustifyContent(justifyContent);
<add> }
<add>
<add> @Override
<add> public void setOverflow(YogaOverflow overflow) {
<add> mYogaNode.setOverflow(overflow);
<add> }
<add>
<add> @Override
<add> public void setDisplay(YogaDisplay display) {
<add> mYogaNode.setDisplay(display);
<add> }
<add>
<add> @Override
<add> public void setMargin(int spacingType, float margin) {
<add> mYogaNode.setMargin(YogaEdge.fromInt(spacingType), margin);
<add> }
<add>
<add> @Override
<add> public void setMarginPercent(int spacingType, float percent) {
<add> mYogaNode.setMarginPercent(YogaEdge.fromInt(spacingType), percent);
<add> }
<add>
<add> @Override
<add> public void setMarginAuto(int spacingType) {
<add> mYogaNode.setMarginAuto(YogaEdge.fromInt(spacingType));
<add> }
<add>
<add> @Override
<add> public final float getPadding(int spacingType) {
<add> return mYogaNode.getLayoutPadding(YogaEdge.fromInt(spacingType));
<add> }
<add>
<add> @Override
<add> public final YogaValue getStylePadding(int spacingType) {
<add> return mYogaNode.getPadding(YogaEdge.fromInt(spacingType));
<add> }
<add>
<add> @Override
<add> public void setDefaultPadding(int spacingType, float padding) {
<add> mDefaultPadding.set(spacingType, padding);
<add> updatePadding();
<add> }
<add>
<add> @Override
<add> public void setPadding(int spacingType, float padding) {
<add> mPadding[spacingType] = padding;
<add> mPaddingIsPercent[spacingType] = false;
<add> updatePadding();
<add> }
<add>
<add> @Override
<add> public void setPaddingPercent(int spacingType, float percent) {
<add> mPadding[spacingType] = percent;
<add> mPaddingIsPercent[spacingType] = !YogaConstants.isUndefined(percent);
<add> updatePadding();
<add> }
<add>
<add> private void updatePadding() {
<add> for (int spacingType = Spacing.LEFT; spacingType <= Spacing.ALL; spacingType++) {
<add> if (spacingType == Spacing.LEFT ||
<add> spacingType == Spacing.RIGHT ||
<add> spacingType == Spacing.START ||
<add> spacingType == Spacing.END) {
<add> if (YogaConstants.isUndefined(mPadding[spacingType]) &&
<add> YogaConstants.isUndefined(mPadding[Spacing.HORIZONTAL]) &&
<add> YogaConstants.isUndefined(mPadding[Spacing.ALL])) {
<add> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<add> continue;
<add> }
<add> } else if (spacingType == Spacing.TOP || spacingType == Spacing.BOTTOM) {
<add> if (YogaConstants.isUndefined(mPadding[spacingType]) &&
<add> YogaConstants.isUndefined(mPadding[Spacing.VERTICAL]) &&
<add> YogaConstants.isUndefined(mPadding[Spacing.ALL])) {
<add> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<add> continue;
<add> }
<add> } else {
<add> if (YogaConstants.isUndefined(mPadding[spacingType])) {
<add> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mDefaultPadding.getRaw(spacingType));
<add> continue;
<add> }
<add> }
<add>
<add> if (mPaddingIsPercent[spacingType]) {
<add> mYogaNode.setPaddingPercent(YogaEdge.fromInt(spacingType), mPadding[spacingType]);
<add> } else {
<add> mYogaNode.setPadding(YogaEdge.fromInt(spacingType), mPadding[spacingType]);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void setBorder(int spacingType, float borderWidth) {
<add> mYogaNode.setBorder(YogaEdge.fromInt(spacingType), borderWidth);
<add> }
<add>
<add> @Override
<add> public void setPosition(int spacingType, float position) {
<add> mYogaNode.setPosition(YogaEdge.fromInt(spacingType), position);
<add> }
<add>
<add> @Override
<add> public void setPositionPercent(int spacingType, float percent) {
<add> mYogaNode.setPositionPercent(YogaEdge.fromInt(spacingType), percent);
<add> }
<add>
<add> @Override
<add> public void setPositionType(YogaPositionType positionType) {
<add> mYogaNode.setPositionType(positionType);
<add> }
<add>
<add> @Override
<add> public void setShouldNotifyOnLayout(boolean shouldNotifyOnLayout) {
<add> mShouldNotifyOnLayout = shouldNotifyOnLayout;
<add> }
<add>
<add> @Override
<add> public void setBaselineFunction(YogaBaselineFunction baselineFunction) {
<add> mYogaNode.setBaselineFunction(baselineFunction);
<add> }
<add>
<add> @Override
<add> public void setMeasureFunction(YogaMeasureFunction measureFunction) {
<add> if ((measureFunction == null ^ mYogaNode.isMeasureDefined()) &&
<add> getChildCount() != 0) {
<add> throw new RuntimeException(
<add> "Since a node with a measure function does not add any native yoga children, it's " +
<add> "not safe to transition to/from having a measure function unless a node has no children");
<add> }
<add> mYogaNode.setMeasureFunction(measureFunction);
<add> }
<add>
<add> @Override
<add> public boolean isMeasureDefined() {
<add> return mYogaNode.isMeasureDefined();
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> StringBuilder sb = new StringBuilder();
<add> toStringWithIndentation(sb, 0);
<add> return sb.toString();
<add> }
<add>
<add> private void toStringWithIndentation(StringBuilder result, int level) {
<add> // Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead.
<add> for (int i = 0; i < level; ++i) {
<add> result.append("__");
<add> }
<add>
<add> result
<add> .append(getClass().getSimpleName())
<add> .append(" ");
<add> if (mYogaNode != null) {
<add> result
<add> .append(getLayoutWidth())
<add> .append(",")
<add> .append(getLayoutHeight());
<add> } else {
<add> result.append("(virtual node)");
<add> }
<add> result.append("\n");
<add>
<add> if (getChildCount() == 0) {
<add> return;
<add> }
<add>
<add> for (int i = 0; i < getChildCount(); i++) {
<add> getChildAt(i).toStringWithIndentation(result, level + 1);
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> if (mYogaNode != null) {
<add> mYogaNode.reset();
<add> YogaNodePool.get().release(mYogaNode);
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java
<ide> protected UIImplementation(
<ide> }
<ide>
<ide> protected ReactShadowNode createRootShadowNode() {
<del> ReactShadowNode rootCSSNode = new ReactShadowNode();
<add> ReactShadowNode rootCSSNode = new ReactShadowNodeImpl();
<ide> I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
<ide> if (sharedI18nUtilInstance.isRTL(mReactContext)) {
<ide> rootCSSNode.setLayoutDirection(YogaDirection.RTL);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import javax.annotation.Nullable;
<del>
<del>import java.lang.reflect.Method;
<del>import java.util.Arrays;
<del>import java.util.HashMap;
<del>import java.util.Map;
<del>
<ide> import android.view.View;
<del>
<ide> import com.facebook.common.logging.FLog;
<ide> import com.facebook.react.bridge.Dynamic;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.annotations.ReactPropGroup;
<add>import java.lang.reflect.Method;
<add>import java.util.Arrays;
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * This class is responsible for holding view manager property setters and is used in a process of
<ide> public BoxedIntPropSetter(ReactPropGroup prop, Method setter, int index) {
<ide> */
<ide> /*package*/ static Map<String, PropSetter> getNativePropSettersForShadowNodeClass(
<ide> Class<? extends ReactShadowNode> cls) {
<del> if (cls == ReactShadowNode.class) {
<add> if (cls == null) {
<ide> return EMPTY_PROPS_MAP;
<ide> }
<ide> Map<String, PropSetter> props = CLASS_PROPS_CACHE.get(cls);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java
<ide>
<ide> package com.facebook.react.views.art;
<ide>
<del>import javax.annotation.Nullable;
<del>
<ide> import android.graphics.Canvas;
<ide> import android.graphics.Matrix;
<ide> import android.graphics.Paint;
<del>
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.uimanager.DisplayMetricsHolder;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<del>import com.facebook.react.uimanager.ReactShadowNode;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * Base class for ARTView virtual nodes: {@link ARTGroupShadowNode}, {@link ARTShapeShadowNode} and
<ide> * indirectly for {@link ARTTextShadowNode}.
<ide> */
<del>public abstract class ARTVirtualNode extends ReactShadowNode {
<add>public abstract class ARTVirtualNode extends ReactShadowNodeImpl {
<ide>
<ide> protected static final float MIN_OPACITY_FOR_DRAW = 0.01f;
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java
<ide> package com.facebook.react.views.modal;
<ide>
<ide> import android.graphics.Point;
<del>
<ide> import com.facebook.react.uimanager.LayoutShadowNode;
<del>import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide>
<ide> /**
<ide> * We implement the Modal by using an Android Dialog. That will fill the entire window of the
<ide> class ModalHostShadowNode extends LayoutShadowNode {
<ide>
<ide> /**
<ide> * We need to set the styleWidth and styleHeight of the one child (represented by the <View/>
<del> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<add> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<ide> */
<ide> @Override
<del> public void addChildAt(ReactShadowNode child, int i) {
<add> public void addChildAt(ReactShadowNodeImpl child, int i) {
<ide> super.addChildAt(child, i);
<ide> Point modalSize = ModalHostHelper.getModalHostSize(getThemedContext());
<ide> child.setStyleWidth(modalSize.x);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java
<ide>
<ide> import com.facebook.react.common.annotations.VisibleForTesting;
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<add>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import javax.annotation.Nullable;
<ide>
<ide> /**
<del> * {@link ReactShadowNode} class for pure raw text node
<del> * (aka {@code textContent} in terms of DOM).
<del> * Raw text node can only have simple string value without any attributes,
<del> * properties or state.
<add> * {@link ReactShadowNode} class for pure raw text node (aka {@code textContent} in terms of DOM).
<add> * Raw text node can only have simple string value without any attributes, properties or state.
<ide> */
<del>public class ReactRawTextShadowNode extends ReactShadowNode {
<add>public class ReactRawTextShadowNode extends ReactShadowNodeImpl {
<ide>
<ide> @VisibleForTesting public static final String PROP_TEXT = "text";
<ide>
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import javax.annotation.Nullable;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.reset;
<add>import static org.mockito.Mockito.verify;
<add>import static org.mockito.Mockito.verifyNoMoreInteractions;
<ide>
<add>import com.facebook.react.bridge.JavaOnlyMap;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.bridge.JavaOnlyMap;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.annotations.ReactPropGroup;
<del>
<add>import javax.annotation.Nullable;
<ide> import org.junit.Before;
<del>import org.junit.runner.RunWith;
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<add>import org.junit.runner.RunWith;
<ide> import org.powermock.core.classloader.annotations.PowerMockIgnore;
<ide> import org.powermock.modules.junit4.rule.PowerMockRule;
<ide> import org.robolectric.RobolectricTestRunner;
<ide>
<del>import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.reset;
<del>import static org.mockito.Mockito.verify;
<del>import static org.mockito.Mockito.verifyNoMoreInteractions;
<del>
<ide> /**
<ide> * Test {@link ReactProp} annotation for {@link ReactShadowNode}. More comprahensive test of this
<ide> * annotation can be found in {@link ReactPropAnnotationSetterTest} where we test all possible types
<ide> public static ReactStylesDiffMap buildStyles(Object... keysAndValues) {
<ide> return new ReactStylesDiffMap(JavaOnlyMap.of(keysAndValues));
<ide> }
<ide>
<del> private class ShadowViewUnderTest extends ReactShadowNode {
<add> private class ShadowViewUnderTest extends ReactShadowNodeImpl {
<ide>
<ide> private ViewManagerUpdatesReceiver mViewManagerUpdatesReceiver;
<ide>
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSpecTest.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import java.util.Map;
<del>
<ide> import android.view.View;
<del>
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.annotations.ReactPropGroup;
<del>
<del>import org.junit.Test;
<add>import java.util.Map;
<ide> import org.junit.Rule;
<add>import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide> import org.powermock.core.classloader.annotations.PowerMockIgnore;
<ide> import org.powermock.modules.junit4.rule.PowerMockRule;
<ide> public void updateExtraData(View root, Object extraData) {
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testMethodWithWrongNumberOfParams() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactProp(name = "prop")
<del> public void setterWithIncorrectNumberOfArgs(boolean value, int anotherValue) {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactProp(name = "prop")
<add> public void setterWithIncorrectNumberOfArgs(boolean value, int anotherValue) {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testMethodWithTooFewParams() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactProp(name = "prop")
<del> public void setterWithNoArgs() {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactProp(name = "prop")
<add> public void setterWithNoArgs() {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testUnsupportedValueType() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactProp(name = "prop")
<del> public void setterWithMap(Map value) {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactProp(name = "prop")
<add> public void setterWithMap(Map value) {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testGroupInvalidNumberOfParams() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactPropGroup(names = {"prop1", "prop2"})
<del> public void setterWithTooManyParams(int index, float value, boolean bool) {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactPropGroup(names = {"prop1", "prop2"})
<add> public void setterWithTooManyParams(int index, float value, boolean bool) {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testGroupTooFewParams() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactPropGroup(names = {"prop1", "prop2"})
<del> public void setterWithTooManyParams(int index) {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactPropGroup(names = {"prop1", "prop2"})
<add> public void setterWithTooManyParams(int index) {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide>
<ide> @Test(expected = RuntimeException.class)
<ide> public void testGroupNoIndexParam() {
<del> new BaseViewManager(new ReactShadowNode() {
<del> @ReactPropGroup(names = {"prop1", "prop2"})
<del> public void setterWithTooManyParams(float value, boolean bool) {
<del> }
<del> }.getClass()).getNativeProps();
<add> new BaseViewManager(
<add> new ReactShadowNodeImpl() {
<add> @ReactPropGroup(names = {"prop1", "prop2"})
<add> public void setterWithTooManyParams(float value, boolean bool) {}
<add> }.getClass())
<add> .getNativeProps();
<ide> }
<ide> } | 16 |
Mixed | Java | unify typeface logic (android) | 9d2fedc6e22ca1b45fbc2059971cd194de5d0170 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java
<ide> import android.graphics.Typeface;
<ide> import android.text.TextPaint;
<ide> import android.text.style.MetricAffectingSpan;
<del>import androidx.annotation.NonNull;
<ide> import androidx.annotation.Nullable;
<add>import com.facebook.infer.annotation.Nullsafe;
<ide>
<add>@Nullsafe(Nullsafe.Mode.LOCAL)
<ide> public class CustomStyleSpan extends MetricAffectingSpan implements ReactSpan {
<ide>
<ide> /**
<ide> public CustomStyleSpan(
<ide> int fontWeight,
<ide> @Nullable String fontFeatureSettings,
<ide> @Nullable String fontFamily,
<del> @NonNull AssetManager assetManager) {
<add> AssetManager assetManager) {
<ide> mStyle = fontStyle;
<ide> mWeight = fontWeight;
<ide> mFeatureSettings = fontFeatureSettings;
<ide> public void updateDrawState(TextPaint ds) {
<ide> }
<ide>
<ide> @Override
<del> public void updateMeasureState(@NonNull TextPaint paint) {
<add> public void updateMeasureState(TextPaint paint) {
<ide> apply(paint, mStyle, mWeight, mFeatureSettings, mFontFamily, mAssetManager);
<ide> }
<ide>
<del> /** Returns {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. */
<ide> public int getStyle() {
<del> return (mStyle == ReactTextShadowNode.UNSET ? 0 : mStyle);
<add> return mStyle == ReactBaseTextShadowNode.UNSET ? Typeface.NORMAL : mStyle;
<ide> }
<ide>
<del> /** Returns {@link Typeface#NORMAL} or {@link Typeface#BOLD}. */
<ide> public int getWeight() {
<del> return (mWeight == ReactTextShadowNode.UNSET ? 0 : mWeight);
<add> return mWeight == ReactBaseTextShadowNode.UNSET ? TypefaceStyle.NORMAL : mWeight;
<ide> }
<ide>
<del> /** Returns the font family set for this StyleSpan. */
<ide> public @Nullable String getFontFamily() {
<ide> return mFontFamily;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java
<ide> import android.content.Context;
<ide> import android.content.res.AssetManager;
<ide> import android.graphics.Typeface;
<del>import android.os.Build;
<ide> import android.util.SparseArray;
<del>import androidx.annotation.NonNull;
<ide> import androidx.annotation.Nullable;
<ide> import androidx.core.content.res.ResourcesCompat;
<add>import com.facebook.infer.annotation.Nullsafe;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<ide> /**
<del> * Class responsible to load and cache Typeface objects. It will first try to load typefaces inside
<del> * the assets/fonts folder and if it doesn't find the right Typeface in that folder will fall back
<del> * on the best matching system Typeface The supported custom fonts extensions are .ttf and .otf. For
<del> * each font family the bold, italic and bold_italic variants are supported. Given a "family" font
<del> * family the files in the assets/fonts folder need to be family.ttf(.otf) family_bold.ttf(.otf)
<del> * family_italic.ttf(.otf) and family_bold_italic.ttf(.otf)
<add> * Responsible for loading and caching Typeface objects.
<add> *
<add> * <p>This will first try to load a typeface from the assets/fonts folder. If one is not found in
<add> * that folder, this will fallback to the best matching system typeface.
<add> *
<add> * <p>Custom fonts support the extensions `.ttf` and `.otf` and the variants `bold`, `italic`, and
<add> * `bold_italic`. For example, given a font named "ExampleFontFamily", the following are supported:
<add> *
<add> * <ul>
<add> * <li>ExampleFontFamily.ttf (or .otf)
<add> * <li>ExampleFontFamily_bold.ttf (or .otf)
<add> * <li>ExampleFontFamily_italic.ttf (or .otf)
<add> * <li>ExampleFontFamily_bold_italic.ttf (or .otf)
<ide> */
<add>@Nullsafe(Nullsafe.Mode.LOCAL)
<ide> public class ReactFontManager {
<ide>
<add> // NOTE: Indices in `EXTENSIONS` correspond to the `TypeFace` style constants.
<ide> private static final String[] EXTENSIONS = {"", "_bold", "_italic", "_bold_italic"};
<ide> private static final String[] FILE_EXTENSIONS = {".ttf", ".otf"};
<ide> private static final String FONTS_ASSET_PATH = "fonts/";
<ide>
<ide> private static ReactFontManager sReactFontManagerInstance;
<ide>
<del> private final Map<String, FontFamily> mFontCache;
<add> private final Map<String, AssetFontFamily> mFontCache;
<ide> private final Map<String, Typeface> mCustomTypefaceCache;
<ide>
<ide> private ReactFontManager() {
<ide> public static ReactFontManager getInstance() {
<ide> return sReactFontManagerInstance;
<ide> }
<ide>
<del> public @Nullable Typeface getTypeface(
<del> String fontFamilyName, int style, AssetManager assetManager) {
<del> return getTypeface(fontFamilyName, style, 0, assetManager);
<add> public Typeface getTypeface(String fontFamilyName, int style, AssetManager assetManager) {
<add> return getTypeface(fontFamilyName, new TypefaceStyle(style), assetManager);
<ide> }
<ide>
<del> public @Nullable Typeface getTypeface(
<add> public Typeface getTypeface(
<add> String fontFamilyName, int weight, boolean italic, AssetManager assetManager) {
<add> return getTypeface(fontFamilyName, new TypefaceStyle(weight, italic), assetManager);
<add> }
<add>
<add> public Typeface getTypeface(
<ide> String fontFamilyName, int style, int weight, AssetManager assetManager) {
<add> return getTypeface(fontFamilyName, new TypefaceStyle(style, weight), assetManager);
<add> }
<add>
<add> public Typeface getTypeface(
<add> String fontFamilyName, TypefaceStyle typefaceStyle, AssetManager assetManager) {
<ide> if (mCustomTypefaceCache.containsKey(fontFamilyName)) {
<del> Typeface typeface = mCustomTypefaceCache.get(fontFamilyName);
<del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && weight >= 100 && weight <= 1000) {
<del> return Typeface.create(typeface, weight, (style & Typeface.ITALIC) != 0);
<del> }
<del> return Typeface.create(typeface, style);
<add> // Apply `typefaceStyle` because custom fonts configure variants using `app:fontStyle` and
<add> // `app:fontWeight` in their resource XML configuration file.
<add> return typefaceStyle.apply(mCustomTypefaceCache.get(fontFamilyName));
<ide> }
<ide>
<del> FontFamily fontFamily = mFontCache.get(fontFamilyName);
<del> if (fontFamily == null) {
<del> fontFamily = new FontFamily();
<del> mFontCache.put(fontFamilyName, fontFamily);
<add> AssetFontFamily assetFontFamily = mFontCache.get(fontFamilyName);
<add> if (assetFontFamily == null) {
<add> assetFontFamily = new AssetFontFamily();
<add> mFontCache.put(fontFamilyName, assetFontFamily);
<ide> }
<ide>
<del> Typeface typeface = fontFamily.getTypeface(style);
<del> if (typeface == null) {
<del> typeface = createTypeface(fontFamilyName, style, assetManager);
<del> if (typeface != null) {
<del> fontFamily.setTypeface(style, typeface);
<del> }
<del> }
<add> int style = typefaceStyle.getNearestStyle();
<ide>
<del> return typeface;
<add> Typeface assetTypeface = assetFontFamily.getTypefaceForStyle(style);
<add> if (assetTypeface == null) {
<add> assetTypeface = createAssetTypeface(fontFamilyName, style, assetManager);
<add> assetFontFamily.setTypefaceForStyle(style, assetTypeface);
<add> }
<add> // Do not apply `typefaceStyle` because asset font files already incorporate the style.
<add> return assetTypeface;
<ide> }
<ide>
<ide> /*
<ide> public static ReactFontManager getInstance() {
<ide> *
<ide> * ReactFontManager.getInstance().addCustomFont(this, "Srisakdi", R.font.srisakdi);
<ide> */
<del> public void addCustomFont(@NonNull Context context, @NonNull String fontFamily, int fontId) {
<add> public void addCustomFont(Context context, String fontFamily, int fontId) {
<ide> Typeface font = ResourcesCompat.getFont(context, fontId);
<ide> if (font != null) {
<ide> mCustomTypefaceCache.put(fontFamily, font);
<ide> public void addCustomFont(@NonNull Context context, @NonNull String fontFamily,
<ide> */
<ide> public void setTypeface(String fontFamilyName, int style, Typeface typeface) {
<ide> if (typeface != null) {
<del> FontFamily fontFamily = mFontCache.get(fontFamilyName);
<del> if (fontFamily == null) {
<del> fontFamily = new FontFamily();
<del> mFontCache.put(fontFamilyName, fontFamily);
<add> AssetFontFamily assetFontFamily = mFontCache.get(fontFamilyName);
<add> if (assetFontFamily == null) {
<add> assetFontFamily = new AssetFontFamily();
<add> mFontCache.put(fontFamilyName, assetFontFamily);
<ide> }
<del> fontFamily.setTypeface(style, typeface);
<add> assetFontFamily.setTypefaceForStyle(style, typeface);
<ide> }
<ide> }
<ide>
<del> private static @Nullable Typeface createTypeface(
<add> private static Typeface createAssetTypeface(
<ide> String fontFamilyName, int style, AssetManager assetManager) {
<ide> String extension = EXTENSIONS[style];
<ide> for (String fileExtension : FILE_EXTENSIONS) {
<ide> public void setTypeface(String fontFamilyName, int style, Typeface typeface) {
<ide> try {
<ide> return Typeface.createFromAsset(assetManager, fileName);
<ide> } catch (RuntimeException e) {
<del> // unfortunately Typeface.createFromAsset throws an exception instead of returning null
<del> // if the typeface doesn't exist
<add> // If the typeface asset does not exist, try another extension.
<add> continue;
<ide> }
<ide> }
<del>
<ide> return Typeface.create(fontFamilyName, style);
<ide> }
<ide>
<del> private static class FontFamily {
<add> /** Responsible for caching typefaces for each custom font family. */
<add> private static class AssetFontFamily {
<ide>
<ide> private SparseArray<Typeface> mTypefaceSparseArray;
<ide>
<del> private FontFamily() {
<add> private AssetFontFamily() {
<ide> mTypefaceSparseArray = new SparseArray<>(4);
<ide> }
<ide>
<del> public Typeface getTypeface(int style) {
<add> public @Nullable Typeface getTypefaceForStyle(int style) {
<ide> return mTypefaceSparseArray.get(style);
<ide> }
<ide>
<del> public void setTypeface(int style, Typeface typeface) {
<add> public void setTypefaceForStyle(int style, Typeface typeface) {
<ide> mTypefaceSparseArray.put(style, typeface);
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTypefaceUtils.java
<ide>
<ide> import android.content.res.AssetManager;
<ide> import android.graphics.Typeface;
<del>import android.os.Build;
<ide> import android.text.TextUtils;
<ide> import androidx.annotation.Nullable;
<del>import com.facebook.common.logging.FLog;
<add>import com.facebook.infer.annotation.Nullsafe;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>@Nullsafe(Nullsafe.Mode.LOCAL)
<ide> public class ReactTypefaceUtils {
<del> private static final String TAG = "ReactTypefaceUtils";
<del> public static final int UNSET = -1;
<ide>
<ide> public static int parseFontWeight(@Nullable String fontWeightString) {
<del> int fontWeightNumeric =
<del> fontWeightString != null ? parseNumericFontWeight(fontWeightString) : UNSET;
<del> int fontWeight = fontWeightNumeric != UNSET ? fontWeightNumeric : Typeface.NORMAL;
<del>
<del> if ("bold".equals(fontWeightString)) fontWeight = Typeface.BOLD;
<del> else if ("normal".equals(fontWeightString)) fontWeight = Typeface.NORMAL;
<del>
<del> return fontWeight;
<add> if (fontWeightString != null) {
<add> switch (fontWeightString) {
<add> case "100":
<add> return 100;
<add> case "200":
<add> return 200;
<add> case "300":
<add> return 300;
<add> case "normal":
<add> case "400":
<add> return 400;
<add> case "500":
<add> return 500;
<add> case "600":
<add> return 600;
<add> case "bold":
<add> case "700":
<add> return 700;
<add> case "800":
<add> return 800;
<add> case "900":
<add> return 900;
<add> }
<add> }
<add> return ReactBaseTextShadowNode.UNSET;
<ide> }
<ide>
<ide> public static int parseFontStyle(@Nullable String fontStyleString) {
<del> int fontStyle = UNSET;
<del> if ("italic".equals(fontStyleString)) {
<del> fontStyle = Typeface.ITALIC;
<del> } else if ("normal".equals(fontStyleString)) {
<del> fontStyle = Typeface.NORMAL;
<add> if (fontStyleString != null) {
<add> if ("italic".equals(fontStyleString)) {
<add> return Typeface.ITALIC;
<add> }
<add> if ("normal".equals(fontStyleString)) {
<add> return Typeface.NORMAL;
<add> }
<ide> }
<del>
<del> return fontStyle;
<add> return ReactBaseTextShadowNode.UNSET;
<ide> }
<ide>
<ide> public static @Nullable String parseFontVariant(@Nullable ReadableArray fontVariantArray) {
<ide> public static Typeface applyStyles(
<ide> @Nullable Typeface typeface,
<ide> int style,
<ide> int weight,
<del> @Nullable String family,
<add> @Nullable String fontFamilyName,
<ide> AssetManager assetManager) {
<del> int oldStyle;
<del> if (typeface == null) {
<del> oldStyle = Typeface.NORMAL;
<add> TypefaceStyle typefaceStyle = new TypefaceStyle(style, weight);
<add> if (fontFamilyName == null) {
<add> return typefaceStyle.apply(typeface == null ? Typeface.DEFAULT : typeface);
<ide> } else {
<del> oldStyle = typeface.getStyle();
<del> }
<del>
<del> int newStyle = oldStyle;
<del> boolean italic = false;
<del> if (weight == UNSET) weight = Typeface.NORMAL;
<del> if (style == Typeface.ITALIC) italic = true;
<del> boolean UNDER_SDK_28 = Build.VERSION.SDK_INT < Build.VERSION_CODES.P;
<del> boolean applyNumericValues = !(weight < (Typeface.BOLD_ITALIC + 1) || family != null);
<del> boolean numericBold = UNDER_SDK_28 && weight > 699 && applyNumericValues;
<del> boolean numericNormal = UNDER_SDK_28 && weight < 700 && applyNumericValues;
<del> if (weight == Typeface.BOLD) {
<del> newStyle = (newStyle == Typeface.ITALIC) ? Typeface.BOLD_ITALIC : Typeface.BOLD;
<del> typeface = Typeface.create(typeface, newStyle);
<add> return ReactFontManager.getInstance()
<add> .getTypeface(fontFamilyName, typefaceStyle, assetManager);
<ide> }
<del> if (weight == Typeface.NORMAL) {
<del> typeface = Typeface.create(typeface, Typeface.NORMAL);
<del> newStyle = Typeface.NORMAL;
<del> }
<del> if (style == Typeface.ITALIC) {
<del> newStyle = (newStyle == Typeface.BOLD) ? Typeface.BOLD_ITALIC : Typeface.ITALIC;
<del> typeface = Typeface.create(typeface, newStyle);
<del> }
<del> if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1 && weight > Typeface.BOLD_ITALIC) {
<del> typeface = Typeface.create(typeface, weight, italic);
<del> }
<del> if (family != null && UNDER_SDK_28 && weight > Typeface.BOLD_ITALIC) {
<del> FLog.d(
<del> TAG,
<del> "Support for numeric font weight numeric values with custom fonts under Android API 28 Pie is not yet supported in ReactNative.");
<del> }
<del> if (family != null) {
<del> typeface = ReactFontManager.getInstance().getTypeface(family, newStyle, weight, assetManager);
<del> }
<del> if (numericBold || numericNormal) {
<del> newStyle = numericBold ? Typeface.BOLD : Typeface.NORMAL;
<del> typeface = Typeface.create(typeface, newStyle);
<del> FLog.d(
<del> TAG,
<del> "Support for numeric font weight numeric values available only from Android API 28 Pie. Android device lower then API 28 will use normal or bold.");
<del> }
<del> return typeface;
<del> }
<del>
<del> /**
<del> * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise
<del> * return the weight.
<del> */
<del> private static int parseNumericFontWeight(String fontWeightString) {
<del> // This should be much faster than using regex to verify input and Integer.parseInt
<del> return fontWeightString.length() == 3
<del> && fontWeightString.endsWith("00")
<del> && fontWeightString.charAt(0) <= '9'
<del> && fontWeightString.charAt(0) >= '1'
<del> ? 100 * (fontWeightString.charAt(0) - '0')
<del> : UNSET;
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java
<ide>
<ide> package com.facebook.react.views.text;
<ide>
<del>import android.graphics.Typeface;
<ide> import android.os.Build;
<ide> import android.text.Layout;
<ide> import android.text.TextUtils;
<ide> public class TextAttributeProps {
<ide> protected @Nullable ReactAccessibilityDelegate.AccessibilityRole mAccessibilityRole = null;
<ide> protected boolean mIsAccessibilityRoleSet = false;
<ide>
<del> /**
<del> * mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. mFontWeight can be {@link
<del> * Typeface#NORMAL} or {@link Typeface#BOLD}.
<del> */
<ide> protected int mFontStyle = UNSET;
<del>
<ide> protected int mFontWeight = UNSET;
<ide> /**
<ide> * NB: If a font family is used that does not have a style in a certain Android version (ie.
<ide> private void setFontVariant(@Nullable ReadableMapBuffer fontVariant) {
<ide> mFontFeatureSettings = TextUtils.join(", ", features);
<ide> }
<ide>
<del> /**
<del> * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they
<del> * can both use
<del> */
<ide> private void setFontWeight(@Nullable String fontWeightString) {
<del> int fontWeightNumeric =
<del> fontWeightString != null ? parseNumericFontWeight(fontWeightString) : -1;
<del> int fontWeight = UNSET;
<del> if (fontWeightNumeric >= 500 || "bold".equals(fontWeightString)) {
<del> fontWeight = Typeface.BOLD;
<del> } else if ("normal".equals(fontWeightString)
<del> || (fontWeightNumeric != -1 && fontWeightNumeric < 500)) {
<del> fontWeight = Typeface.NORMAL;
<del> }
<del> if (fontWeight != mFontWeight) {
<del> mFontWeight = fontWeight;
<del> }
<add> mFontWeight = ReactTypefaceUtils.parseFontWeight(fontWeightString);
<ide> }
<ide>
<del> /**
<del> * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they
<del> * can both use
<del> */
<ide> private void setFontStyle(@Nullable String fontStyleString) {
<del> int fontStyle = UNSET;
<del> if ("italic".equals(fontStyleString)) {
<del> fontStyle = Typeface.ITALIC;
<del> } else if ("normal".equals(fontStyleString)) {
<del> fontStyle = Typeface.NORMAL;
<del> }
<del> if (fontStyle != mFontStyle) {
<del> mFontStyle = fontStyle;
<del> }
<add> mFontStyle = ReactTypefaceUtils.parseFontStyle(fontStyleString);
<ide> }
<ide>
<ide> private void setIncludeFontPadding(boolean includepad) {
<ide> public static int getTextBreakStrategy(@Nullable String textBreakStrategy) {
<ide> }
<ide> return androidTextBreakStrategy;
<ide> }
<del>
<del> /**
<del> * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise
<del> * return the weight.
<del> *
<del> * <p>This code is duplicated in ReactTextInputManager TODO: Factor into a common place they can
<del> * both use
<del> */
<del> private static int parseNumericFontWeight(String fontWeightString) {
<del> // This should be much faster than using regex to verify input and Integer.parseInt
<del> return fontWeightString.length() == 3
<del> && fontWeightString.endsWith("00")
<del> && fontWeightString.charAt(0) <= '9'
<del> && fontWeightString.charAt(0) >= '1'
<del> ? 100 * (fontWeightString.charAt(0) - '0')
<del> : -1;
<del> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TypefaceStyle.java
<add>/*
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.views.text;
<add>
<add>import android.graphics.Typeface;
<add>import android.os.Build;
<add>import com.facebook.infer.annotation.Nullsafe;
<add>
<add>/** Responsible for normalizing style and numeric weight for backward compatibility. */
<add>@Nullsafe(Nullsafe.Mode.LOCAL)
<add>class TypefaceStyle {
<add>
<add> public static final int BOLD = 700;
<add> public static final int NORMAL = 400;
<add>
<add> private static final int MIN_WEIGHT = 1;
<add> private static final int MAX_WEIGHT = 1000;
<add>
<add> private final boolean mItalic;
<add> private final int mWeight;
<add>
<add> public TypefaceStyle(int weight, boolean italic) {
<add> mItalic = italic;
<add> mWeight = weight == ReactBaseTextShadowNode.UNSET ? NORMAL : weight;
<add> }
<add>
<add> public TypefaceStyle(int style) {
<add> if (style == ReactBaseTextShadowNode.UNSET) {
<add> style = Typeface.NORMAL;
<add> }
<add>
<add> mItalic = (style & Typeface.ITALIC) != 0;
<add> mWeight = (style & Typeface.BOLD) != 0 ? BOLD : NORMAL;
<add> }
<add>
<add> /**
<add> * If `weight` is supplied, it will be combined with the italic bit from `style`. Otherwise, any
<add> * existing weight bit in `style` will be used.
<add> */
<add> public TypefaceStyle(int style, int weight) {
<add> if (style == ReactBaseTextShadowNode.UNSET) {
<add> style = Typeface.NORMAL;
<add> }
<add>
<add> mItalic = (style & Typeface.ITALIC) != 0;
<add> mWeight =
<add> weight == ReactBaseTextShadowNode.UNSET
<add> ? (style & Typeface.BOLD) != 0 ? BOLD : NORMAL
<add> : weight;
<add> }
<add>
<add> public int getNearestStyle() {
<add> if (mWeight < BOLD) {
<add> return mItalic ? Typeface.ITALIC : Typeface.NORMAL;
<add> } else {
<add> return mItalic ? Typeface.BOLD_ITALIC : Typeface.BOLD;
<add> }
<add> }
<add>
<add> public Typeface apply(Typeface typeface) {
<add> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
<add> return Typeface.create(typeface, getNearestStyle());
<add> } else {
<add> return Typeface.create(typeface, mWeight, mItalic);
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
<ide> public class ReactEditText extends AppCompatEditText
<ide> private TextAttributes mTextAttributes;
<ide> private boolean mTypefaceDirty = false;
<ide> private @Nullable String mFontFamily = null;
<del> private int mFontWeight = ReactTypefaceUtils.UNSET;
<del> private int mFontStyle = ReactTypefaceUtils.UNSET;
<add> private int mFontWeight = UNSET;
<add> private int mFontStyle = UNSET;
<ide> private boolean mAutoFocus = false;
<ide> private boolean mDidAttachToWindow = false;
<ide>
<ide><path>packages/rn-tester/js/examples/TextInput/TextInputExample.android.js
<ide> exports.examples = ([
<ide> );
<ide> },
<ide> },
<add> {
<add> title: 'Font Weight',
<add> render: function(): React.Node {
<add> return (
<add> <View>
<add> <TextInput
<add> defaultValue="Font Weight (default)"
<add> style={[styles.singleLine]}
<add> />
<add> {[
<add> 'normal',
<add> 'bold',
<add> '900',
<add> '800',
<add> '700',
<add> '600',
<add> '500',
<add> '400',
<add> '300',
<add> '200',
<add> '100',
<add> ].map(fontWeight => (
<add> <TextInput
<add> defaultValue={`Font Weight (${fontWeight})`}
<add> key={fontWeight}
<add> style={[styles.singleLine, {fontWeight}]}
<add> />
<add> ))}
<add> </View>
<add> );
<add> },
<add> },
<ide> {
<ide> title: 'Text input, themes and heights',
<ide> render: function(): React.Node { | 7 |
Text | Text | fix unusual line terminators [ci skip] | ef896892390adc3440b7a18cf03c0f6386b61a67 | <ide><path>guides/source/security.md
<ide> Intranet and Admin Security
<ide>
<ide> Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world.
<ide>
<del>In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.
<add>In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.
<ide>
<ide> **XSS** If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.
<ide>
<ide> Refer to the Injection section for countermeasures against XSS.
<ide>
<ide> A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/news/item/Symantec-reports-first-active-attack-on-a-DSL-router-735883.html). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for the user, but it also contained an image tag that resulted in an HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen.
<ide>
<del>Another example changed Google Adsense's e-mail address and password. If the victim was logged into Google Adsense, the administration interface for Google advertisement campaigns, an attacker could change the credentials of the victim.
<add>Another example changed Google Adsense's e-mail address and password. If the victim was logged into Google Adsense, the administration interface for Google advertisement campaigns, an attacker could change the credentials of the victim.
<ide>
<ide> Another popular attack is to spam your web application, your blog, or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.
<ide>
<ide> alert(eval('document.body.inne' + 'rHTML'));
<ide> The next problem was MySpace filtering the word `"javascript"`, so the author used `"java<NEWLINE>script"` to get around this:
<ide>
<ide> ```html
<del><div id="mycode" expr="alert('hah!')" style="background:url('java↵
<ide>script:eval(document.all.mycode.expr)')">
<add><div id="mycode" expr="alert('hah!')" style="background:url('java↵script:eval(document.all.mycode.expr)')">
<ide> ```
<ide>
<ide> Another problem for the worm's author was the [CSRF security tokens](#cross-site-request-forgery-csrf). Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.
<ide> If Header Injection was possible, Response Splitting might be, too. In HTTP, the
<ide> ```
<ide> HTTP/1.1 302 Found [First standard 302 response]
<ide> Date: Tue, 12 Apr 2005 22:09:07 GMT
<del>Location:
<ide>Content-Type: text/html
<add>Location:Content-Type: text/html
<ide>
<ide>
<ide> HTTP/1.1 200 OK [Second New response created by attacker begins] | 1 |
Ruby | Ruby | fix syntax error | 23cb26cfac0725ab979d026f52bf8f03d2a01309 | <ide><path>railties/lib/rails/generators/app_base.rb
<ide> def rails_gemfile_entry
<ide> if options.dev?
<ide> [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH),
<ide> GemfileEntry.github('arel', 'rails/arel'),
<del> GemfileEntry.github('rack', 'rack/rack')]
<add> GemfileEntry.github('rack', 'rack/rack'),
<ide> GemfileEntry.github('i18n', 'svenfuchs/i18n')]
<ide> elsif options.edge?
<ide> [GemfileEntry.github('rails', 'rails/rails'),
<ide> GemfileEntry.github('arel', 'rails/arel'),
<add> GemfileEntry.github('rack', 'rack/rack'),
<ide> GemfileEntry.github('i18n', 'svenfuchs/i18n')]
<ide> else
<ide> [GemfileEntry.version('rails', | 1 |
Ruby | Ruby | improve routing docs, mostly for #match | 277327bb7f389a140eb4ae7722d64d6cf45e06cf | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(set) #:nodoc:
<ide> #
<ide> # root :to => 'pages#main'
<ide> #
<del> # For options, see the +match+ method's documentation, as +root+ uses it internally.
<add> # For options, see +match+, as +root+ uses it internally.
<ide> #
<ide> # You should put the root route at the top of <tt>config/routes.rb</tt>,
<ide> # because this means it will be matched first. As this is the most popular route
<ide> def root(options = {})
<ide> match '/', options.reverse_merge(:as => :root)
<ide> end
<ide>
<del> # Matches a pattern to one or more urls. Any symbols in a pattern are
<del> # interpreted as url parameters:
<add> # Matches a url pattern to one or more routes. Any symbols in a pattern
<add> # are interpreted as url query parameters and thus available as +params+
<add> # in an action:
<ide> #
<del> # # sets parameters :controller, :action and :id
<add> # # sets :controller, :action and :id in params
<ide> # match ':controller/:action/:id'
<ide> #
<del> # Two of these symbols are special: <tt>:controller</tt> maps to the
<del> # controller name and <tt>:action</tt> to the action name within that
<del> # controller. Anything other than <tt>:controller</tt> or
<del> # <tt>:action</tt> will be available to the action as part of +params+.
<del> # If a pattern does not have :controller and :action symbols, then they
<del> # must be set in options or shorthand. For example:
<add> # Two of these symbols are special, +:controller+ maps to the controller
<add> # and +:action+ to the controller's action. A pattern can also map
<add> # wildcard segments (globs) to params:
<add> #
<add> # match 'songs/*category/:title' => 'songs#show'
<add> #
<add> # # 'songs/rock/classic/stairway-to-heaven' sets
<add> # # params[:category] = 'rock/classic'
<add> # # params[:title] = 'stairway-to-heaven'
<add> #
<add> # When a pattern points to an internal route, the route's +:action+ and
<add> # +:controller+ should be set in options or hash shorthand. Examples:
<ide> #
<ide> # match 'photos/:id' => 'photos#show'
<ide> # match 'photos/:id', :to => 'photos#show'
<ide> # match 'photos/:id', :controller => 'photos', :action => 'show'
<ide> #
<add> # A pattern can also point to a +Rack+ endpoint i.e. anything that
<add> # responds to +call+:
<add> #
<add> # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" }
<add> # match 'photos/:id' => PhotoRackApp
<add> # # Yes, controller actions are just rack endpoints
<add> # match 'photos/:id' => PhotosController.action(:show)
<add> #
<ide> # === Options
<ide> #
<add> # Any options not seen here are passed on as params with the url.
<add> #
<ide> # [:controller]
<ide> # The route's controller.
<ide> #
<ide> def root(options = {})
<ide> # match 'path' => 'c#a', :via => [:get, :post]
<ide> #
<ide> # [:to]
<del> # Shorthand for specifying :controller and :action.
<add> # Points to a +Rack+ endpoint. Can be an object that responds to
<add> # +call+ or a string representing a controller's action.
<ide> #
<del> # match 'path' => 'c#a', :to => 'controller#action'
<add> # match 'path', :to => 'controller#action'
<add> # match 'path', :to => lambda { [200, {}, "Success!"] }
<add> # match 'path', :to => RackApp
<ide> #
<ide> # [:on]
<ide> # Shorthand for wrapping routes in a specific RESTful context. Valid
<ide> def match(path, options=nil)
<ide> #
<ide> # mount(SomeRackApp => "some_route")
<ide> #
<add> # For options, see +match+, as +mount+ uses it internally.
<add> #
<ide> # All mounted applications come with routing helpers to access them.
<ide> # These are named after the class specified, so for the above example
<ide> # the helper is either +some_rack_app_path+ or +some_rack_app_url+. | 1 |
Text | Text | correct wrong spacing in readme | f72fe1f31aca235c7f675680832cc364efe4088e | <ide><path>model_cards/patrickvonplaten/bert2bert-cnn_dailymail-fp16/README.md
<ide> from transformers import BertTokenizer, EncoderDecoderModel
<ide> model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")
<ide> tokenizer = BertTokenizer.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")
<ide>
<del>article = """(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David B
<del>oren took it a step further, saying the university's affiliation with the fraternity is permanently done. The news is shocking, but it's not the first time SAE has faced controversy. SAE was founded March 9, 185
<del>6, at the University of Alabama, five years before the American Civil War, according to the fraternity website. When the war began, the group had fewer than 400 members, of which "369 went to war for the Confede
<del>rate States and seven for the Union Army," the website says. The fraternity now boasts more than 200,000 living alumni, along with about 15,000 undergraduates populating 219 chapters and 20 "colonies" seeking fu
<del>ll membership at universities. SAE has had to work hard to change recently after a string of member deaths, many blamed on the hazing of new recruits, SAE national President Bradley Cohen wrote in a message on t
<del>he fraternity's website. The fraternity's website lists more than 130 chapters cited or suspended for "health and safety incidents" since 2010. At least 30 of the incidents involved hazing, and dozens more invol
<del>ved alcohol. However, the list is missing numerous incidents from recent months. Among them, according to various media outlets: Yale University banned the SAEs from campus activities last month after members al
<del>legedly tried to interfere with a sexual misconduct investigation connected to an initiation rite. Stanford University in December suspended SAE housing privileges after finding sorority members attending a frat
<del>ernity function were subjected to graphic sexual content. And Johns Hopkins University in November suspended the fraternity for underage drinking. "The media has labeled us as the 'nation's deadliest fraternity,
<del>' " Cohen said. In 2011, for example, a student died while being coerced into excessive alcohol consumption, according to a lawsuit. SAE's previous insurer dumped the fraternity. "As a result, we are paying Lloy
<del>d's of London the highest insurance rates in the Greek-letter world," Cohen said. Universities have turned down SAE's attempts to open new chapters, and the fraternity had to close 12 in 18 months over hazing in
<del>cidents."""
<add>article = """(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David Boren took it a step further, saying the university's affiliation with the fraternity is permanently done. The news is shocking, but it's not the first time SAE has faced controversy. SAE was founded March 9, 1856, at the University of Alabama, five years before the American Civil War, according to the fraternity website. When the war began, the group had fewer than 400 members, of which "369 went to war for the Confederate States and seven for the Union Army," the website says. The fraternity now boasts more than 200,000 living alumni, along with about 15,000 undergraduates populating 219 chapters and 20 "colonies" seeking full membership at universities. SAE has had to work hard to change recently after a string of member deaths, many blamed on the hazing of new recruits, SAE national President Bradley Cohen wrote in a message on the fraternity's website. The fraternity's website lists more than 130 chapters cited or suspended for "health and safety incidents" since 2010. At least 30 of the incidents involved hazing, and dozens more involved alcohol. However, the list is missing numerous incidents from recent months. Among them, according to various media outlets: Yale University banned the SAEs from campus activities last month after members allegedly tried to interfere with a sexual misconduct investigation connected to an initiation rite. Stanford University in December suspended SAE housing privileges after finding sorority members attending a fraternity function were subjected to graphic sexual content. And Johns Hopkins University in November suspended the fraternity for underage drinking. "The media has labeled us as the 'nation's deadliest fraternity,' " Cohen said. In 2011, for example, a student died while being coerced into excessive alcohol consumption, according to a lawsuit. SAE's previous insurer dumped the fraternity. "As a result, we are paying Lloyd's of London the highest insurance rates in the Greek-letter world," Cohen said. Universities have turned down SAE's attempts to open new chapters, and the fraternity had to close 12 in 18 months over hazing incidents."""
<ide>
<ide> input_ids = tokenizer(article, return_tensors="pt").input_ids
<ide> output_ids = model.generate(input_ids) | 1 |
PHP | PHP | remove function that is no longer used | 0f2b3be9b8753ba2813595f9191aa8d8c31886b1 | <ide><path>src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php
<ide> protected function loadRoutes()
<ide> $this->app->call([$this, 'map']);
<ide> }
<ide>
<del> /**
<del> * Load the standard routes file for the application.
<del> *
<del> * @param string $path
<del> * @return mixed
<del> */
<del> protected function loadRoutesFrom($path)
<del> {
<del> $router = $this->app->make(Router::class);
<del>
<del> if (is_null($this->namespace)) {
<del> return require $path;
<del> }
<del>
<del> $router->group(['namespace' => $this->namespace], function (Router $router) use ($path) {
<del> require $path;
<del> });
<del> }
<del>
<ide> /**
<ide> * Register the service provider.
<ide> * | 1 |
Python | Python | fix length of iterabledatasetshard and add test | 63cc5bda6028d64cb5399d4c0f7d2946bebb663b | <ide><path>src/transformers/trainer_pt_utils.py
<ide> def __iter__(self):
<ide> def __len__(self):
<ide> # Will raise an error if the underlying dataset is not sized.
<ide> if self.drop_last:
<del> return len(self.dataset) // self.num_processes
<add> return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
<ide> else:
<del> return math.ceil(len(self.dataset) / self.num_processes)
<add> return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
<ide>
<ide>
<ide> # In order to keep `trainer.py` compact and easy to understand, place any secondary PT Trainer
<ide><path>tests/test_trainer_utils.py
<ide> def test_iterable_dataset_shard(self):
<ide> self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=3, epoch=42)
<ide> self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=3, epoch=42)
<ide>
<add> def test_iterable_dataset_shard_with_length(self):
<add> sampler_shards = [
<add> IterableDatasetShard(list(range(100)), batch_size=4, drop_last=True, num_processes=2, process_index=i)
<add> for i in range(2)
<add> ]
<add>
<add> # Build expected shards: each process will have batches of size 4 until there is not enough elements to
<add> # form two full batches (so we stop at 96 = (100 // (4 * 2)) * 4)
<add> expected_shards = [[], []]
<add> current_shard = 0
<add> for i in range(0, 96, 4):
<add> expected_shards[current_shard].extend(list(range(i, i + 4)))
<add> current_shard = 1 - current_shard
<add>
<add> self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards)
<add> self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards])
<add>
<add> sampler_shards = [
<add> IterableDatasetShard(list(range(100)), batch_size=4, drop_last=False, num_processes=2, process_index=i)
<add> for i in range(2)
<add> ]
<add> # When drop_last=False, we get two last full batches by looping back to the beginning.
<add> expected_shards[0].extend(list(range(96, 100)))
<add> expected_shards[1].extend(list(range(0, 4)))
<add>
<add> self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards)
<add> self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards])
<add>
<ide> def check_shard_sampler(self, dataset, batch_size, drop_last, num_processes=2):
<ide> shards = [
<ide> ShardSampler(
<ide><path>utils/tests_fetcher.py
<ide> def create_reverse_dependency_map():
<ide> "test_trainer_distributed.py",
<ide> "test_trainer_tpu.py",
<ide> ],
<add> "train_pt_utils.py": "test_trainer_utils.py",
<ide> "utils/versions.py": "test_versions_utils.py",
<ide> }
<ide> | 3 |
Text | Text | remove semi-colons after class definition | 8174a0dc086268fb092f65f965fc769b08bd938a | <ide><path>docs/HeightAndWidth.md
<ide> class FixedDimensionsBasics extends Component {
<ide> </View>
<ide> );
<ide> }
<del>};
<add>}
<ide>
<ide> AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
<ide> ```
<ide> class FlexDimensionsBasics extends Component {
<ide> </View>
<ide> );
<ide> }
<del>};
<add>}
<ide>
<ide> AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);
<ide> ``` | 1 |
Go | Go | update the comment about mappingwithequals | 2cdc9c42eb138bcaffb1cbd4172bd18b69446394 | <ide><path>cli/compose/types/types.go
<ide> type StringList []string
<ide> type StringOrNumberList []string
<ide>
<ide> // MappingWithEquals is a mapping type that can be converted from a list of
<del>// key=value strings
<add>// key[=value] strings.
<add>// For the key with an empty value (`key=`), the mapped value is set to a pointer to `""`.
<add>// For the key without value (`key`), the mapped value is set to nil.
<ide> type MappingWithEquals map[string]*string
<ide>
<ide> // Labels is a mapping type for labels | 1 |
Python | Python | fix pickle tests | e619f452877c54c2801415abaf0f93ff3889adb4 | <ide><path>spacy/tests/test_pickles.py
<ide> from __future__ import unicode_literals
<ide>
<ide> import pytest
<del>import dill as pickle
<ide> import numpy
<add>import srsly
<ide> from spacy.strings import StringStore
<ide> from spacy.vocab import Vocab
<ide> from spacy.attrs import NORM
<ide> def test_pickle_string_store(text1, text2):
<ide> stringstore = StringStore()
<ide> store1 = stringstore[text1]
<ide> store2 = stringstore[text2]
<del> data = pickle.dumps(stringstore, protocol=-1)
<del> unpickled = pickle.loads(data)
<add> data = srsly.pickle_dumps(stringstore, protocol=-1)
<add> unpickled = srsly.pickle_loads(data)
<ide> assert unpickled[text1] == store1
<ide> assert unpickled[text2] == store2
<ide> assert len(stringstore) == len(unpickled) | 1 |
PHP | PHP | fix error when generating xml | 5d6a6fa203eeaf32d87c77276f38fbb3451561a0 | <ide><path>lib/Cake/Test/Case/Utility/XmlTest.php
<ide> public function testFromArrayFail($value) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Test that there are not unterminated errors when building xml
<add> *
<add> * @return void
<add> */
<add> public function testFromArrayUnterminatedError() {
<add> $data = array(
<add> 'product_ID' => 'GENERT-DL',
<add> 'deeplink' => 'http://example.com/deep',
<add> 'image_URL' => 'http://example.com/image',
<add> 'thumbnail_image_URL' => 'http://example.com/thumb',
<add> 'brand' => 'Malte Lange & Co',
<add> 'availability' => 'in stock',
<add> 'authors' =>array(
<add> 'author' => array('Malte Lange & Co')
<add> )
<add> );
<add> $xml = Xml::fromArray(array('products' => $data), 'tags');
<add> $expected = <<<XML
<add><?xml version="1.0" encoding="UTF-8"?>
<add><products>
<add> <product_ID>GENERT-DL</product_ID>
<add> <deeplink>http://example.com/deep</deeplink>
<add> <image_URL>http://example.com/image</image_URL>
<add> <thumbnail_image_URL>http://example.com/thumb</thumbnail_image_URL>
<add> <brand>Malte Lange & Co</brand>
<add> <availability>in stock</availability>
<add> <authors>
<add> <author>Malte Lange & Co</author>
<add> </authors>
<add></products>
<add>XML;
<add> $this->assertXmlStringEqualsXmlString($expected, $xml->asXML());
<add> }
<add>
<ide> /**
<ide> * testToArray method
<ide> *
<ide><path>lib/Cake/Utility/Xml.php
<ide> protected static function _createChild($data) {
<ide> $childValue = (string)$value;
<ide> }
<ide>
<add> $child = $dom->createElement($key);
<ide> if ($childValue) {
<del> $child = $dom->createElement($key, $childValue);
<del> } else {
<del> $child = $dom->createElement($key);
<add> $child->appendChild($dom->createTextNode($childValue));
<ide> }
<ide> if ($childNS) {
<ide> $child->setAttribute('xmlns', $childNS); | 2 |
Text | Text | add a code of conduct | f1220c5fe2309353a7c37dc00c8cbcb5ed5b568d | <ide><path>CODE_OF_CONDUCT.md
<add>
<add># Contributor Covenant Code of Conduct
<add>
<add>## Our Pledge
<add>
<add>We as members, contributors, and leaders pledge to make participation in our
<add>community a harassment-free experience for everyone, regardless of age, body
<add>size, visible or invisible disability, ethnicity, sex characteristics, gender
<add>identity and expression, level of experience, education, socio-economic status,
<add>nationality, personal appearance, race, religion, or sexual identity
<add>and orientation.
<add>
<add>We pledge to act and interact in ways that contribute to an open, welcoming,
<add>diverse, inclusive, and healthy community.
<add>
<add>## Our Standards
<add>
<add>Examples of behavior that contributes to a positive environment for our
<add>community include:
<add>
<add>* Demonstrating empathy and kindness toward other people
<add>* Being respectful of differing opinions, viewpoints, and experiences
<add>* Giving and gracefully accepting constructive feedback
<add>* Accepting responsibility and apologizing to those affected by our mistakes,
<add> and learning from the experience
<add>* Focusing on what is best not just for us as individuals, but for the
<add> overall community
<add>
<add>Examples of unacceptable behavior include:
<add>
<add>* The use of sexualized language or imagery, and sexual attention or
<add> advances of any kind
<add>* Trolling, insulting or derogatory comments, and personal or political attacks
<add>* Public or private harassment
<add>* Publishing others' private information, such as a physical or email
<add> address, without their explicit permission
<add>* Other conduct which could reasonably be considered inappropriate in a
<add> professional setting
<add>
<add>## Enforcement Responsibilities
<add>
<add>Community leaders are responsible for clarifying and enforcing our standards of
<add>acceptable behavior and will take appropriate and fair corrective action in
<add>response to any behavior that they deem inappropriate, threatening, offensive,
<add>or harmful.
<add>
<add>Community leaders have the right and responsibility to remove, edit, or reject
<add>comments, commits, code, wiki edits, issues, and other contributions that are
<add>not aligned to this Code of Conduct, and will communicate reasons for moderation
<add>decisions when appropriate.
<add>
<add>## Scope
<add>
<add>This Code of Conduct applies within all community spaces, and also applies when
<add>an individual is officially representing the community in public spaces.
<add>Examples of representing our community include using an official e-mail address,
<add>posting via an official social media account, or acting as an appointed
<add>representative at an online or offline event.
<add>
<add>## Enforcement
<add>
<add>Instances of abusive, harassing, or otherwise unacceptable behavior may be
<add>reported to the community leaders responsible for enforcement at
<add>[email protected].
<add>All complaints will be reviewed and investigated promptly and fairly.
<add>
<add>All community leaders are obligated to respect the privacy and security of the
<add>reporter of any incident.
<add>
<add>## Enforcement Guidelines
<add>
<add>Community leaders will follow these Community Impact Guidelines in determining
<add>the consequences for any action they deem in violation of this Code of Conduct:
<add>
<add>### 1. Correction
<add>
<add>**Community Impact**: Use of inappropriate language or other behavior deemed
<add>unprofessional or unwelcome in the community.
<add>
<add>**Consequence**: A private, written warning from community leaders, providing
<add>clarity around the nature of the violation and an explanation of why the
<add>behavior was inappropriate. A public apology may be requested.
<add>
<add>### 2. Warning
<add>
<add>**Community Impact**: A violation through a single incident or series
<add>of actions.
<add>
<add>**Consequence**: A warning with consequences for continued behavior. No
<add>interaction with the people involved, including unsolicited interaction with
<add>those enforcing the Code of Conduct, for a specified period of time. This
<add>includes avoiding interactions in community spaces as well as external channels
<add>like social media. Violating these terms may lead to a temporary or
<add>permanent ban.
<add>
<add>### 3. Temporary Ban
<add>
<add>**Community Impact**: A serious violation of community standards, including
<add>sustained inappropriate behavior.
<add>
<add>**Consequence**: A temporary ban from any sort of interaction or public
<add>communication with the community for a specified period of time. No public or
<add>private interaction with the people involved, including unsolicited interaction
<add>with those enforcing the Code of Conduct, is allowed during this period.
<add>Violating these terms may lead to a permanent ban.
<add>
<add>### 4. Permanent Ban
<add>
<add>**Community Impact**: Demonstrating a pattern of violation of community
<add>standards, including sustained inappropriate behavior, harassment of an
<add>individual, or aggression toward or disparagement of classes of individuals.
<add>
<add>**Consequence**: A permanent ban from any sort of public interaction within
<add>the community.
<add>
<add>## Attribution
<add>
<add>This Code of Conduct is adapted from the [Contributor Covenant][homepage],
<add>version 2.0, available at
<add>https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
<add>
<add>Community Impact Guidelines were inspired by [Mozilla's code of conduct
<add>enforcement ladder](https://github.com/mozilla/diversity).
<add>
<add>[homepage]: https://www.contributor-covenant.org
<add>
<add>For answers to common questions about this code of conduct, see the FAQ at
<add>https://www.contributor-covenant.org/faq. Translations are available at
<add>https://www.contributor-covenant.org/translations.
<ide><path>CONTRIBUTING.md
<ide> It also helps us if you spread the word: reference the library from blog posts
<ide> on the awesome projects it made possible, shout out on Twitter every time it has
<ide> helped you, or simply star the repo to say "thank you".
<ide>
<add>Whichever way you choose to contribute, please be mindful to respect our
<add>[code of conduct](https://github.com/huggingface/transformers/blob/master/CODE_OF_CONDUCT.md).
<add>
<ide> ## You can contribute in so many ways!
<ide>
<ide> There are 4 ways you can contribute to transformers:
<ide><path>README.md
<ide> <a href="https://github.com/huggingface/transformers/releases">
<ide> <img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg">
<ide> </a>
<add> <a href="https://github.com/huggingface/transformers/blob/master/CODE_OF_CONDUCT.md">
<add> <img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg">
<add> </a>
<ide> </p>
<ide>
<ide> <h3 align="center"> | 3 |
Ruby | Ruby | use canonical_name to canonicalize aliases | ccc62a0cad3816389db805143f39013218b57bce | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search_formulae rx
<ide> results = (Formula.names+aliases).grep(rx).sort
<ide>
<ide> # Filter out aliases when the full name was also found
<del> results.reject do |alias_name|
<del> if aliases.include? alias_name
<del> resolved_name = (HOMEBREW_REPOSITORY+"Library/Aliases"+alias_name).readlink.basename('.rb').to_s
<del> results.include? resolved_name
<del> end
<add> results.reject do |name|
<add> canonical_name = Formulary.canonical_name(name)
<add> aliases.include?(name) && results.include?(canonical_name)
<ide> end
<ide> end
<ide> end | 1 |
Java | Java | fix checkstyle errors | 9990bd2ea84560c64b44900754ddfd35d77de763 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/KotlinSerializationJsonDecoder.java
<ide> public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType ele
<ide>
<ide> @Override
<ide> public Mono<Object> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
<del> return stringDecoder
<add> return this.stringDecoder
<ide> .decodeToMono(inputStream, elementType, mimeType, hints)
<ide> .map(jsonText -> this.json.decodeFromString(serializer(elementType.getType()), jsonText));
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/KotlinSerializationJsonEncoder.java
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> @Override
<ide> public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType, MimeType mimeType, Map<String, Object> hints) {
<ide> String json = this.json.encodeToString(serializer(valueType.getType()), value);
<del> return charSequenceEncoder.encodeValue(json, bufferFactory, valueType, mimeType, null);
<add> return this.charSequenceEncoder.encodeValue(json, bufferFactory, valueType, mimeType, null);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | remove obsolete completer variable | ee176f1205ce6eba8848779d793ad40c8236fbfa | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> enumerable: true
<ide> });
<ide>
<del> // Figure out which "complete" function to use.
<del> self.completer = (typeof options.completer === 'function') ?
<del> options.completer : completer;
<del>
<ide> function completer(text, cb) {
<ide> complete.call(self, text, self.editorMode ?
<ide> self.completeOnEditorMode(cb) : cb);
<ide> function REPLServer(prompt,
<ide> Interface.call(this, {
<ide> input: options.input,
<ide> output: options.output,
<del> completer: self.completer,
<add> completer: options.completer || completer,
<ide> terminal: options.terminal,
<ide> historySize: options.historySize,
<ide> prompt | 1 |
Python | Python | make test less flakey | 2f7e9f390d26b0f2bb335b9767c762744b04783d | <ide><path>spacy/tests/regression/test_issue781.py
<ide> @pytest.mark.parametrize('word,lemmas', [("chromosomes", ["chromosome"]), ("endosomes", ["endosome"]), ("colocalizes", ["colocaliz", "colocalize"])])
<ide> def test_issue781(EN, word, lemmas):
<ide> lemmatizer = EN.Defaults.create_lemmatizer()
<del> assert lemmatizer(word, 'noun', morphology={'number': 'plur'}) == sorted(lemmas)
<add> assert sorted(lemmatizer(word, 'noun', morphology={'number': 'plur'})) == sorted(lemmas) | 1 |
Ruby | Ruby | expose uses_from_macos list | 9bd77b18197ecf5e3b4d048fb2452d7be474ee13 | <ide><path>Library/Homebrew/extend/os/mac/software_spec.rb
<ide> class SoftwareSpec
<ide> undef uses_from_macos
<ide>
<ide> def uses_from_macos(deps, **args)
<add> @uses_from_macos_elements ||= []
<add>
<ide> if deps.is_a?(Hash)
<ide> args = deps
<ide> deps = Hash[*args.shift]
<ide> end
<ide>
<del> depends_on(deps) if add_mac_dependency?(args)
<add> if add_mac_dependency?(args)
<add> depends_on(deps)
<add> else
<add> @uses_from_macos_elements << deps
<add> end
<ide> end
<ide>
<ide> private
<ide><path>Library/Homebrew/formula.rb
<ide> def aliases
<ide> # The {Dependency}s for the currently active {SoftwareSpec}.
<ide> delegate deps: :active_spec
<ide>
<add> # Dependencies provided by macOS for the currently active {SoftwareSpec}.
<add> delegate uses_from_macos_elements: :active_spec
<add>
<ide> # The {Requirement}s for the currently active {SoftwareSpec}.
<ide> delegate requirements: :active_spec
<ide>
<ide> def missing_dependencies(hide: nil)
<ide> # @private
<ide> def to_hash
<ide> dependencies = deps
<add> uses_from_macos = uses_from_macos_elements || []
<ide>
<ide> hsh = {
<ide> "name" => name,
<ide> def to_hash
<ide> "optional_dependencies" => dependencies.select(&:optional?)
<ide> .map(&:name)
<ide> .uniq,
<add> "uses_from_macos" => uses_from_macos.uniq,
<ide> "requirements" => [],
<ide> "conflicts_with" => conflicts.map(&:name),
<ide> "caveats" => caveats&.gsub(HOMEBREW_PREFIX, "$(brew --prefix)"),
<ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide> attr_reader :dependency_collector
<ide> attr_reader :bottle_specification
<ide> attr_reader :compiler_failures
<add> attr_reader :uses_from_macos_elements
<ide>
<ide> def_delegators :@resource, :stage, :fetch, :verify_download_integrity, :source_modified_time
<ide> def_delegators :@resource, :download_name, :cached_download, :clear_cache | 3 |
Javascript | Javascript | remove mozopaque for driver | 95dd33d51a8b98d6bb0e8bd4944bc5b9873ba732 | <ide><path>test/driver.js
<ide> function load() {
<ide> var delay = params.delay || 0;
<ide>
<ide> canvas = document.createElement('canvas');
<del> canvas.mozOpaque = true;
<ide> stdout = document.getElementById('stdout');
<ide>
<ide> info('User Agent: ' + navigator.userAgent); | 1 |
Javascript | Javascript | fix nits in test-fs-mkdir-rmdir.js | 50b35460e34afcdc73d82cd5f29edf7f961771b8 | <ide><path>test/parallel/test-fs-mkdir-rmdir.js
<ide> fs.rmdirSync(d);
<ide> assert(!common.fileExists(d));
<ide>
<ide> // Similarly test the Async version
<del>fs.mkdir(d, 0o666, function(err) {
<add>fs.mkdir(d, 0o666, common.mustCall(function(err) {
<ide> assert.ifError(err);
<ide>
<del> fs.mkdir(d, 0o666, function(err) {
<del> assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message');
<del> assert.strictEqual(err.code, 'EEXIST', 'got EEXIST code');
<del> assert.strictEqual(err.path, d, 'got proper path for EEXIST');
<add> fs.mkdir(d, 0o666, common.mustCall(function(err) {
<add> assert.ok(err, 'got no error');
<add> assert.ok(/^EEXIST/.test(err.message), 'got no EEXIST message');
<add> assert.strictEqual(err.code, 'EEXIST', 'got no EEXIST code');
<add> assert.strictEqual(err.path, d, 'got no proper path for EEXIST');
<ide>
<ide> fs.rmdir(d, assert.ifError);
<del> });
<del>});
<add> }));
<add>})); | 1 |
Javascript | Javascript | add more info on `debuginfoenabled()` | 233a93f6e01f7f06d17cdea8a7b2a7098803639d | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * binding information and a reference to the current scope on to DOM elements.
<ide> * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
<ide> * * `ng-binding` CSS class
<add> * * `ng-scope` and `ng-isolated-scope` CSS classes
<ide> * * `$binding` data property containing an array of the binding expressions
<add> * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return
<add> * the element's scope.
<add> * * Placeholder comments will contain information about what directive and binding caused the placeholder.
<add> * E.g. `<!-- ngIf: shouldShow() -->`.
<ide> *
<ide> * You may want to disable this in production for a significant performance boost. See
<ide> * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. | 1 |
Python | Python | fix roformer config doc | e2c1dd09667af5a535689c371b4658c36681131f | <ide><path>src/transformers/models/roformer/configuration_roformer.py
<ide> class RoFormerConfig(PretrainedConfig):
<ide> gradient_checkpointing (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> If :obj:`True`, use gradient checkpointing to save memory at the expense of slower backward pass.
<ide>
<del> Example::
<add> Example::
<ide>
<ide> >>> from transformers import RoFormerModel, RoFormerConfig
<ide> | 1 |
Text | Text | correct typos and expressions | b4f2fa6fbc7477324ff0f83b1f440e1df6e72b04 | <ide><path>guide/spanish/swift/index.md
<ide> Swift es un lenguaje de programación de [código abierto](https://en.wikipedia.
<ide>
<ide> > Swift es un lenguaje de programación potente e intuitivo para macOS, iOS, watchOS y tvOS. Escribir código Swift es interactivo y divertido, la sintaxis es concisa pero expresiva, y Swift incluye características modernas que encantan a los desarrolladores. El código Swift es seguro por diseño, pero también produce un software que funciona a la velocidad de la luz. 1
<ide>
<del>¿Quieres probar Swift en este momento? [Repl.it](https://repl.it/languages/swift) ofrece un bucle de lectura, evaluación y impresión en línea para Swift. No tendrás acceso a UIKit u otras API que se usan comúnmente, ¡pero dale una oportunidad!
<add>¿Quieres probar Swift en este momento? [Repl.it](https://repl.it/languages/swift) ofrece un bucle de lectura, evaluación e impresión en línea para Swift. No tendrás acceso a UIKit u otras APIs que se usan comúnmente, ¡pero dale una oportunidad!
<ide>
<ide> # Lo esencial
<ide>
<del>Para declarar una variable en Swift, simplemente use var seguido del nombre de su variable.
<add>Para declarar una variable en Swift, simplemente usa var seguido del nombre de tu variable.
<ide>
<ide> ```Swift
<ide> var x = 6
<ide> var x = 6
<ide> x = 3
<ide> ```
<ide>
<del>Las constantes son similares a las variables, pero no pueden cambiar de valor después de la creación.
<add>Las constantes son similares a las variables, pero no pueden cambiar de valor después de haber sido creadas.
<ide>
<ide> ```Swift
<ide> let x = 6
<ide> let name = "Bob"
<ide> let boole = true
<ide> ```
<ide>
<del>Para imprimir cualquier cosa en la salida estándar, simplemente use print () y coloque su salida entre paréntesis.
<add>Para imprimir cualquier cosa en la salida estándar, simplemente usa print() y coloca su salida entre paréntesis.
<ide>
<ide> ```Swift
<ide> let x = "World"
<ide> let x = "World"
<ide>
<ide> # Versión
<ide>
<del>La última versión es [Swift 4.2](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/RevisionHistory.html) , lanzada el 17 de septiembre de 2018. Swift está en constante evolución y puede esperar más cambios en el futuro. Se recomienda utilizar la última versión de Swift al iniciar un nuevo proyecto.
<add>La última versión es [Swift 4.2](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/RevisionHistory.html) , lanzada el 17 de septiembre de 2018. Swift está en constante evolución y puedes esperar más cambios en el futuro. Se recomienda utilizar la última versión de Swift al iniciar un nuevo proyecto.
<ide>
<ide> # Documentación
<ide>
<del>Swift está muy documentado. Tenga en cuenta que la codificación de Swift no solo implica Usando el lenguaje, pero también muchas APIs. La mejor manera de aprender Swift es hacer un Proyecto o aplicación, no importa lo pequeño que sea!
<add>Swift está muy documentado. Ten en cuenta que codificar en Swift no solo implica usar el lenguaje, sino también muchas APIs. La mejor manera de aprender Swift es hacer un Proyecto o aplicación, no importa lo pequeño que sea!
<ide>
<ide> * [Código fuente](https://github.com/apple/swift)
<ide>
<ide> * [Desarrollo de aplicaciones iOS (Swift)](https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) : ¿Quieres hacer aplicaciones iOS? Este es un gran lugar para empezar.
<ide>
<del>* [Guía de idiomas](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) : tiene una descripción general de casi todas las funciones de Swift. Si se confunde al leer el código de otra persona, este documento puede ayudarlo.
<add>* [Guía de idiomas](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) : Tiene una descripción general de casi todas las características de Swift. Si te confundes al leer el código de otra persona, este documento puede ayudarte.
<ide>
<ide>
<del># ¿Querer aprender más?
<add># ¿Quieres aprender más?
<ide>
<del>* [RayWenderlich.com](https://www.raywenderlich.com/) : tiene muchos tutoriales excelentes para el desarrollo de Swift y iOS.
<del>* [Hackear con Swift](https://www.hackingwithswift.com/read) : un tutorial completo de Swift, que te lleva de principiante a avanzado usando proyectos prácticos.
<add>* [RayWenderlich.com](https://www.raywenderlich.com/) : Tiene muchos tutoriales excelentes para el desarrollo de Swift y iOS.
<add>* [Hackear con Swift](https://www.hackingwithswift.com/read) : Un tutorial completo de Swift, que te lleva de principiante a avanzado usando proyectos prácticos.
<ide>
<ide> ### Fuentes
<ide>
<del>1. "Swift 4: el potente lenguaje de programación que también es fácil de aprender". Apple, [developer.apple.com/swift](https://developer.apple.com/swift/) , consultado el 31 de octubre de 2017.
<ide>\ No newline at end of file
<add>1. "Swift 4: El potente lenguaje de programación que también es fácil de aprender". Apple, [developer.apple.com/swift](https://developer.apple.com/swift/) , consultado el 31 de octubre de 2017. | 1 |
Javascript | Javascript | make hot loading work on oss | bba35f0415fa6868e4ce6744e4d044d60cb8a041 | <ide><path>local-cli/server/runServer.js
<ide> */
<ide> 'use strict';
<ide>
<add>const attachHMRServer = require('./util/attachHMRServer');
<ide> const connect = require('connect');
<ide> const cpuProfilerMiddleware = require('./middleware/cpuProfilerMiddleware');
<ide> const getDevToolsMiddleware = require('./middleware/getDevToolsMiddleware');
<ide> const webSocketProxy = require('./util/webSocketProxy.js');
<ide>
<ide> function runServer(args, config, readyCallback) {
<ide> var wsProxy = null;
<add> const packagerServer = getPackagerServer(args, config);
<ide> const app = connect()
<ide> .use(loadRawBodyMiddleware)
<ide> .use(connect.compress())
<ide> function runServer(args, config, readyCallback) {
<ide> .use(cpuProfilerMiddleware)
<ide> // Temporarily disable flow check until it's more stable
<ide> //.use(getFlowTypeCheckMiddleware(args))
<del> .use(getAppMiddleware(args, config));
<add> .use(packagerServer.processRequest.bind(packagerServer));
<ide>
<ide> args.projectRoots.forEach(root => app.use(connect.static(root)));
<ide>
<ide> function runServer(args, config, readyCallback) {
<ide> args.port,
<ide> '::',
<ide> function() {
<add> attachHMRServer({
<add> httpServer: serverInstance,
<add> path: '/hot',
<add> packagerServer,
<add> });
<add>
<ide> wsProxy = webSocketProxy.attachToServer(serverInstance, '/debugger-proxy');
<ide> webSocketProxy.attachToServer(serverInstance, '/devtools');
<ide> readyCallback();
<ide> function runServer(args, config, readyCallback) {
<ide> serverInstance.timeout = 0;
<ide> }
<ide>
<del>function getAppMiddleware(args, config) {
<add>function getPackagerServer(args, config) {
<ide> let transformerPath = args.transformer;
<ide> if (!isAbsolutePath(transformerPath)) {
<ide> transformerPath = path.resolve(process.cwd(), transformerPath);
<ide> }
<ide>
<del> return ReactPackager.middleware({
<add> return ReactPackager.createServer({
<ide> nonPersistent: args.nonPersistent,
<ide> projectRoots: args.projectRoots,
<ide> blacklistRE: config.getBlacklistRE(),
<ide><path>packager/react-packager/src/JSTransformer/resolvePlugins.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>/**
<add> * Manually resolve all default Babel plugins.
<add> * `babel.transform` will attempt to resolve all base plugins relative to
<add> * the file it's compiling. This makes sure that we're using the plugins
<add> * installed in the react-native package.
<add> */
<add>function resolvePlugins(plugins) {
<add> return plugins.map(function(plugin) {
<add> // Normalise plugin to an array.
<add> if (!Array.isArray(plugin)) {
<add> plugin = [plugin];
<add> }
<add> // Only resolve the plugin if it's a string reference.
<add> if (typeof plugin[0] === 'string') {
<add> plugin[0] = require('babel-plugin-' + plugin[0]);
<add> plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0];
<add> }
<add> return plugin;
<add> });
<add>}
<add>
<add>module.exports = resolvePlugins;
<ide><path>packager/react-packager/src/JSTransformer/worker.js
<ide> 'use strict';
<ide>
<ide> var babel = require('babel-core');
<add>var resolvePlugins = require('./resolvePlugins');
<ide> var Transforms = require('../transforms');
<ide>
<ide> // Runs internal transforms on the given sourceCode. Note that internal
<ide> // transforms should be run after the external ones to ensure that they run on
<ide> // Javascript code
<ide> function internalTransforms(sourceCode, filename, options) {
<del> var plugins = Transforms.getAll(options);
<add> var plugins = resolvePlugins(Transforms.getAll(options));
<ide> if (plugins.length === 0) {
<ide> return {
<ide> code: sourceCode,
<ide><path>packager/transformer.js
<ide> const inlineRequires = require('fbjs-scripts/babel-6/inline-requires');
<ide> const json5 = require('json5');
<ide> const path = require('path');
<ide> const ReactPackager = require('./react-packager');
<add>const resolvePlugins = require('./react-packager/src/JSTransformer/resolvePlugins');
<ide>
<ide> const babelRC =
<ide> json5.parse(
<ide> function transform(src, filename, options) {
<ide> if (options.inlineRequires) {
<ide> extraPlugins.push(inlineRequires);
<ide> }
<del> config.plugins = extraPlugins.concat(config.plugins);
<del>
<del> // Manually resolve all default Babel plugins. babel.transform will attempt to resolve
<del> // all base plugins relative to the file it's compiling. This makes sure that we're
<del> // using the plugins installed in the react-native package.
<del> config.plugins = config.plugins.map(function(plugin) {
<del> // Normalise plugin to an array.
<del> if (!Array.isArray(plugin)) {
<del> plugin = [plugin];
<del> }
<del> // Only resolve the plugin if it's a string reference.
<del> if (typeof plugin[0] === 'string') {
<del> plugin[0] = require(`babel-plugin-${plugin[0]}`);
<del> plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0];
<del> }
<del> return plugin;
<del> });
<add> config.plugins = resolvePlugins(extraPlugins.concat(config.plugins));
<ide>
<ide> const result = babel.transform(src, Object.assign({}, babelRC, config));
<ide> | 4 |
Ruby | Ruby | remove unused method | 8a5e217b47531764986f9d806fbf1464431684ae | <ide><path>activemodel/lib/active_model/errors.rb
<ide> def add_from_legacy_details_hash(details)
<ide> }
<ide> }
<ide> end
<del>
<del> def deprecation_rename_warning(old_method_name, new_method_name)
<del> ActiveSupport::Deprecation.warn("ActiveModel::Errors##{old_method_name} is deprecated. Please call ##{new_method_name} instead.")
<del> end
<ide> end
<ide>
<ide> class DeprecationHandlingMessageHash < SimpleDelegator # :nodoc: | 1 |
Text | Text | add new method | f6d8d01ed3c837df33960006076c41dd22b56b0a | <ide><path>guide/chinese/javascript/tutorials/add-new-properties-to-a-javascript-object/index.md
<ide> myObject['bark'] = "woof-woof";
<ide> var dynamicProperty = "bark";
<ide> myObject[dynamicProperty] = "woof-woof";
<ide>
<del>```
<ide>\ No newline at end of file
<add>```
<add>
<add>使用`Object.defineProperty(o, prop, descriptor)`方法
<add>```javascript
<add>Object.defineProperty(myObject, 'bark', {
<add> enumerable: false, // 当且仅当该属性的enumerable为true时,该属性才能够出现在对象的枚举属性中。默认为 false。
<add> configurable: false, // 当且仅当该属性的 configurable 为 true 时,该属性描述符才能够被改变,同时该属性也能从对应的对象上被删除。默认为 false。
<add> writable: false, // 当且仅当该属性的writable为true时,value才能被赋值运算符改变。默认为 false。
<add> value: "woof-woof" // 该属性对应的值。可以是任何有效的 JavaScript 值(数值,对象,函数等)。默认为 undefined。
<add>})
<add>``` | 1 |
PHP | PHP | use cookieinterface instead for typehint | 9f6bdbb403e1b866259e1007daafff9e4515cd1d | <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide>
<ide> use ArrayAccess;
<ide> use Cake\Http\Cookie\Cookie;
<add>use Cake\Http\Cookie\CookieInterface;
<ide> use Cake\Http\Exception\InvalidCsrfTokenException;
<ide> use Cake\Http\Response;
<ide> use Cake\Utility\Hash;
<ide> protected function _validateToken(ServerRequestInterface $request): void
<ide> *
<ide> * @param string $value Cookie value
<ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request object.
<del> * @return \Cake\Http\Cookie\Cookie
<add> * @return \Cake\Http\Cookie\CookieInterface
<ide> */
<del> protected function _createCookie(string $value, ServerRequestInterface $request): Cookie
<add> protected function _createCookie(string $value, ServerRequestInterface $request): CookieInterface
<ide> {
<ide> $cookie = Cookie::create(
<ide> $this->_config['cookieName'], | 1 |
Javascript | Javascript | fix buffer.slice(0, 0) | 4f32a59307b15ce5c3b9d543b16ed90470b1132e | <ide><path>lib/buffer.js
<ide> Buffer.prototype.copy = function copy (target, target_start, start, end) {
<ide>
<ide> // slice(start, end)
<ide> Buffer.prototype.slice = function (start, end) {
<del> if (!end) end = this.length;
<add> if (end === undefined) end = this.length;
<ide> if (end > this.length) throw new Error("oob");
<ide> if (start > end) throw new Error("oob");
<ide>
<ide><path>test/simple/test-buffer.js
<ide> assert.equal(14, Buffer.byteLength("Il était tué"));
<ide> assert.equal(14, Buffer.byteLength("Il était tué", "utf8"));
<ide> assert.equal(12, Buffer.byteLength("Il était tué", "ascii"));
<ide> assert.equal(12, Buffer.byteLength("Il était tué", "binary"));
<add>
<add>
<add>// slice(0,0).length === 0
<add>assert.equal(0, Buffer('hello').slice(0, 0).length) | 2 |
Python | Python | replace dynamic squeeze with reshape to 1d | ce7d80652ca4b4d95532dd55b7cff913c5f1c646 | <ide><path>official/nlp/bert/run_classifier.py
<ide> def get_loss_fn(num_classes):
<ide>
<ide> def classification_loss_fn(labels, logits):
<ide> """Classification loss."""
<del> labels = tf.squeeze(labels)
<add> labels = tf.reshape(labels, [-1])
<ide> log_probs = tf.nn.log_softmax(logits, axis=-1)
<ide> one_hot_labels = tf.one_hot(
<ide> tf.cast(labels, dtype=tf.int32), depth=num_classes, dtype=tf.float32) | 1 |
Java | Java | add doc & tests to jaxb2xmlencoder for collections | 1c628293a2eda10ab07d77f4d2ae832d134c578c | <ide><path>spring-web/src/main/java/org/springframework/http/codec/xml/Jaxb2XmlEncoder.java
<ide> import org.springframework.util.MimeTypeUtils;
<ide>
<ide> /**
<del> * Encode from {@code Object} stream to a byte stream containing XML elements.
<add> * Encode from single value to a byte stream containing XML elements.
<add> *
<add> * <p>{@link javax.xml.bind.annotation.XmlElements @XmlElements} and
<add> * {@link javax.xml.bind.annotation.XmlElement @XmlElement} can be used to specify how
<add> * collections should be marshalled.
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @author Arjen Poutsma
<ide><path>spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 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> package org.springframework.http.codec.xml;
<ide>
<ide> import java.nio.charset.StandardCharsets;
<add>import java.util.Arrays;
<ide> import java.util.Collections;
<add>import java.util.List;
<ide>
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<ide> import reactor.test.StepVerifier;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
<ide>
<add>import javax.xml.bind.annotation.XmlElement;
<add>import javax.xml.bind.annotation.XmlElements;
<add>import javax.xml.bind.annotation.XmlRootElement;
<add>
<ide> /**
<ide> * @author Sebastien Deleuze
<ide> * @author Arjen Poutsma
<ide> public void canEncode() {
<ide> }
<ide>
<ide> @Test
<del> public void encode() throws Exception {
<del> Flux<Pojo> source = Flux.just(new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar"));
<add> public void encode() {
<add> Mono<Pojo> source = Mono.just(new Pojo("foofoo", "barbar"));
<ide> Flux<DataBuffer> output = this.encoder.encode(source, this.bufferFactory,
<ide> ResolvableType.forClass(Pojo.class),
<ide> MediaType.APPLICATION_XML, Collections.emptyMap());
<ide> public void encode() throws Exception {
<ide> DataBufferUtils.release(dataBuffer);
<ide> }
<ide> })
<del> .expectComplete()
<del> .verify();
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void encodeElementsWithCommonType() {
<add> Mono<Container> source = Mono.just(new Container());
<add> Flux<DataBuffer> output = this.encoder.encode(source, this.bufferFactory,
<add> ResolvableType.forClass(Pojo.class),
<add> MediaType.APPLICATION_XML, Collections.emptyMap());
<add>
<add> StepVerifier.create(output)
<add> .consumeNextWith(dataBuffer -> {
<add> try {
<add> String s = DataBufferTestUtils
<add> .dumpString(dataBuffer, StandardCharsets.UTF_8);
<add> assertThat(s, isSimilarTo("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" +
<add> "<container><foo><name>name1</name></foo><bar><title>title1</title></bar></container>"));
<add> }
<add> finally {
<add> DataBufferUtils.release(dataBuffer);
<add> }
<add> })
<add> .verifyComplete();
<add> }
<add>
<add>
<add> public static class Model {}
<add>
<add> public static class Foo extends Model {
<add>
<add> private String name;
<add>
<add> public Foo(String name) {
<add> this.name = name;
<add> }
<add>
<add> public String getName() {
<add> return this.name;
<add> }
<add>
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add> }
<add>
<add> public static class Bar extends Model {
<add>
<add> private String title;
<add>
<add> public Bar(String title) {
<add> this.title = title;
<add> }
<add>
<add> public String getTitle() {
<add> return title;
<add> }
<add>
<add> public void setTitle(String title) {
<add> this.title = title;
<add> }
<add> }
<add>
<add> @XmlRootElement
<add> public static class Container {
<add>
<add> @XmlElements({
<add> @XmlElement(name="foo", type=Foo.class),
<add> @XmlElement(name="bar", type=Bar.class)
<add> })
<add> public List<Model> getElements() {
<add> return Arrays.asList(new Foo("name1"), new Bar("title1"));
<add> }
<ide> }
<ide>
<ide> } | 2 |
Go | Go | add support for ipv6 addresses in --dns parameters | 899e9e74165b567c157756d56c47d33fac82c05a | <ide><path>docker/docker.go
<ide> func main() {
<ide> flRoot = flag.String([]string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
<ide> flSocketGroup = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
<ide> flEnableCors = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
<del> flDns = opts.NewListOpts(opts.ValidateIp4Address)
<add> flDns = opts.NewListOpts(opts.ValidateIpAddress)
<ide> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch)
<ide> flEnableIptables = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
<ide> flEnableIpForward = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
<ide><path>opts/opts.go
<ide> package opts
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/utils"
<add> "net"
<ide> "os"
<ide> "path/filepath"
<ide> "regexp"
<ide> func ValidateEnv(val string) (string, error) {
<ide> return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil
<ide> }
<ide>
<del>func ValidateIp4Address(val string) (string, error) {
<del> re := regexp.MustCompile(`^(([0-9]+\.){3}([0-9]+))\s*$`)
<del> var ns = re.FindSubmatch([]byte(val))
<del> if len(ns) > 0 {
<del> return string(ns[1]), nil
<add>func ValidateIpAddress(val string) (string, error) {
<add> var ip = net.ParseIP(strings.TrimSpace(val))
<add> if ip != nil {
<add> return ip.String(), nil
<ide> }
<del> return "", fmt.Errorf("%s is not an ip4 address", val)
<add> return "", fmt.Errorf("%s is not an ip address", val)
<ide> }
<ide>
<ide> // Validates domain for resolvconf search configuration.
<ide><path>opts/opts_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestValidateIP4(t *testing.T) {
<del> if ret, err := ValidateIp4Address(`1.2.3.4`); err != nil || ret == "" {
<del> t.Fatalf("ValidateIp4Address(`1.2.3.4`) got %s %s", ret, err)
<add> if ret, err := ValidateIpAddress(`1.2.3.4`); err != nil || ret == "" {
<add> t.Fatalf("ValidateIpAddress(`1.2.3.4`) got %s %s", ret, err)
<ide> }
<ide>
<del> if ret, err := ValidateIp4Address(`127.0.0.1`); err != nil || ret == "" {
<del> t.Fatalf("ValidateIp4Address(`127.0.0.1`) got %s %s", ret, err)
<add> if ret, err := ValidateIpAddress(`127.0.0.1`); err != nil || ret == "" {
<add> t.Fatalf("ValidateIpAddress(`127.0.0.1`) got %s %s", ret, err)
<ide> }
<ide>
<del> if ret, err := ValidateIp4Address(`127`); err == nil || ret != "" {
<del> t.Fatalf("ValidateIp4Address(`127`) got %s %s", ret, err)
<add> if ret, err := ValidateIpAddress(`::1`); err != nil || ret == "" {
<add> t.Fatalf("ValidateIpAddress(`::1`) got %s %s", ret, err)
<ide> }
<ide>
<del> if ret, err := ValidateIp4Address(`random invalid string`); err == nil || ret != "" {
<del> t.Fatalf("ValidateIp4Address(`random invalid string`) got %s %s", ret, err)
<add> if ret, err := ValidateIpAddress(`127`); err == nil || ret != "" {
<add> t.Fatalf("ValidateIpAddress(`127`) got %s %s", ret, err)
<add> }
<add>
<add> if ret, err := ValidateIpAddress(`random invalid string`); err == nil || ret != "" {
<add> t.Fatalf("ValidateIpAddress(`random invalid string`) got %s %s", ret, err)
<ide> }
<ide>
<ide> } | 3 |
Text | Text | translate 10.9-perf.md to japanese | 2392217f32e839b385a654f70fe8c72e56634303 | <ide><path>docs/docs/10.9-perf.ja-JP.md
<add>---
<add>id: perf
<add>title: パフォーマンスツール
<add>permalink: perf-ja-JP.html
<add>prev: pure-render-mixin-ja-JP.html
<add>next: advanced-performance-ja-JP.html
<add>---
<add>
<add>Reactは普通、従来の枠を超えてとても速いです。しかし、アプリケーションにおいて、少しでもパフォーマンスを上げようという状況では、Reactの差分を取るアルゴリズムを最大限活用するヒントが得られる、[shouldComponentUpdate](/react/docs/component-specs-ja-JP.html#updating-shouldcomponentupdate)のフックを提供します。
<add>
<add>アプリケーション全体のパフォーマンスについての要約を得ることに加えて、ReactPerfはそれらのフックを実際にはどこに配置する必要があるか教えてくれるプロファイリングツールでもあります。
<add>
<add>> 注意:
<add>> Reactの開発版のビルドは与えられた外部ロジックのためにプロダクション版のビルドよりも遅くなります。例えば、Reactのフレンドリーコンソールの警告(プロダクション版のビルドにおいては警告が出ません)のように。それゆえ、プロファイラは *比較的* コストがかかっている箇所のみを指し示します。
<add>
<add>## 一般的なAPI
<add>
<add>ここに記述されている `Perf` オブジェクトは `react-with-addons.js` を開発版でビルドしたものを使用する際に `React.addons.Perf` として表されます。
<add>
<add>### `Perf.start()` と `Perf.stop()`
<add>測定の開始/終了です。その間のReactの操作は以下のような分析のために記録されます。あまり時間を使わない操作は無視されます。
<add>
<add>### `Perf.printInclusive(measurements)`
<add>かかった全ての時間を出力します。引数が渡されなかった場合は、デフォルトで最後の測定から全ての測定が行われます。これは以下のように、コンソールに綺麗にフォーマットされたテーブルを出力します。
<add>
<add>
<add>
<add>### `Perf.printExclusive(measurements)`
<add>「占有」時間はコンポーネントをマウントするのにかかった時間を含みません。プロパティの処理、 `getInitialState` , `componentWillMount` や `componentDidMount` の呼び出しなどは含みます。
<add>
<add>
<add>
<add>### `Perf.printWasted(measurements)`
<add>
<add>**プロファイラの最も有用な箇所です**。
<add>
<add>「無駄な」時間はコンポーネントが実際には何もレンダリングしていないのにかかっている時間です。例えば、同じものをレンダリングしたので、DOMが触られなかったような場合です。
<add>
<add>
<add>
<add>### `Perf.printDOM(measurements)`
<add>以下のような、DOMの操作を出力します。例えば、"set innerHTML"や"remove"といったものです。
<add>
<add>
<add>
<add>## 先進的なAPI
<add>
<add>上記の出力メソッドは結果をプリティプリントするのに `Perf.getLastMeasurements()` を使用しています。
<add>
<add>### `Perf.getLastMeasurements()`
<add>最後の開始と終了のセッションから測定の配列を取得します。配列は以下のようなオブジェクトを含みます。
<add>
<add>```js
<add>{
<add> // "inclusive"と"exclusive"の期間は以下で説明されています
<add> "exclusive": {},
<add> // '.0.0' はノードのReact ID
<add> "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346},
<add> "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559},
<add> // インスタンスの数
<add> "counts": {".0": 1, ".0.0": 1},
<add> // 触ったDOM
<add> "writes": {},
<add> // 追加のデバッグ情報
<add> "displayNames": {
<add> ".0": {"current": "App", "owner": "<root>"},
<add> ".0.0": {"current": "Box", "owner": "App"}
<add> },
<add> "totalTime": 0.48499999684281647
<add>}
<add>``` | 1 |
Python | Python | remove accidental comment | bdf7e5de92d76ff6dd7cee317ffa43bed8c5d233 | <ide><path>src/transformers/generation_tf_utils.py
<ide> def generate(
<ide>
<ide> tokenizer = AutoTokenizer.from_pretrained('gpt2') # Initialize tokenizer
<ide> model = TFAutoModelWithLMHead.from_pretrained('gpt2') # Download model and configuration from S3 and cache.
<del> input_context = 'My cute dog' # "Legal" is one of the control codes for ctrl
<add> input_context = 'My cute dog'
<ide> bad_words_ids = [tokenizer.encode(bad_word, add_prefix_space=True) for bad_word in ['idiot', 'stupid', 'shut up']]
<ide> input_ids = tokenizer.encode(input_context, return_tensors='tf') # encode input context
<ide> outputs = model.generate(input_ids=input_ids, max_length=100, do_sample=True, bad_words_ids=bad_words_ids) # generate sequences without allowing bad_words to be generated | 1 |
Python | Python | add missing tags to verbs (resolves #948) | 808cd6cf7f184e20d9b8e42364f7e10f045028dc | <ide><path>spacy/en/tokenizer_exceptions.py
<ide> {ORTH: "does", LEMMA: "do"},
<ide> {ORTH: "did", LEMMA: "do", TAG: "VBD"},
<ide> {ORTH: "had", LEMMA: "have", TAG: "VBD"},
<del> {ORTH: "may"},
<del> {ORTH: "might"},
<del> {ORTH: "must"},
<add> {ORTH: "may", TAG: "MD"},
<add> {ORTH: "might", TAG: "MD"},
<add> {ORTH: "must", TAG: "MD"},
<ide> {ORTH: "need"},
<ide> {ORTH: "ought"},
<del> {ORTH: "sha", LEMMA: "shall"},
<del> {ORTH: "should"},
<del> {ORTH: "wo", LEMMA: "will"},
<del> {ORTH: "would"}
<add> {ORTH: "sha", LEMMA: "shall", TAG: "MD"},
<add> {ORTH: "should", TAG: "MD"},
<add> {ORTH: "wo", LEMMA: "will", TAG: "MD"},
<add> {ORTH: "would", TAG: "MD"}
<ide> ]:
<ide> verb_data_tc = dict(verb_data)
<ide> verb_data_tc[ORTH] = verb_data_tc[ORTH].title() | 1 |
Ruby | Ruby | use source_path instead of homebrew_library | 1d8e59b31f060b6d60a98d888263d2be783637ce | <ide><path>Library/Homebrew/dev-cmd/man.rb
<ide> def regenerate_man_pages
<ide> convert_man_page(markup, TARGET_DOC_PATH/"brew.1.html")
<ide> convert_man_page(markup, TARGET_MAN_PATH/"brew.1")
<ide>
<del> cask_markup = (HOMEBREW_LIBRARY/"Homebrew/manpages/brew-cask.1.md").read
<add> cask_markup = (SOURCE_PATH/"brew-cask.1.md").read
<ide> convert_man_page(cask_markup, TARGET_MAN_PATH/"brew-cask.1")
<ide> end
<ide> | 1 |
Javascript | Javascript | display actual reactdom api name in root type | 3ee7a004e59cc7d71e4d3fc698777b381f4ec719 | <ide><path>packages/react-devtools-shared/src/__tests__/inspectedElement-test.js
<ide> describe('InspectedElement', () => {
<ide> "a": 1,
<ide> "b": "abc",
<ide> },
<add> "rootType": "render()",
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElement', () => {
<ide> "a": 1,
<ide> "b": "abc",
<ide> },
<add> "rootType": "render()",
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElement', () => {
<ide> "id": 2,
<ide> "owners": null,
<ide> "props": Object {},
<add> "rootType": "render()",
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElement', () => {
<ide> "id": 2,
<ide> "owners": null,
<ide> "props": Object {},
<add> "rootType": "render()",
<ide> "state": null,
<ide> }
<ide> `);
<ide> });
<ide>
<add> it('should display the root type for ReactDOM.hydrate', async () => {
<add> const Example = () => <div />;
<add>
<add> await utils.actAsync(() => {
<add> const container = document.createElement('div');
<add> container.innerHTML = '<div></div>';
<add> withErrorsOrWarningsIgnored(
<add> ['ReactDOM.hydrate is no longer supported in React 18'],
<add> () => {
<add> ReactDOM.hydrate(<Example />, container);
<add> },
<add> );
<add> }, false);
<add>
<add> const inspectedElement = await inspectElementAtIndex(0);
<add> expect(inspectedElement.rootType).toMatchInlineSnapshot(`"hydrate()"`);
<add> });
<add>
<add> it('should display the root type for ReactDOM.render', async () => {
<add> const Example = () => <div />;
<add>
<add> await utils.actAsync(() => {
<add> const container = document.createElement('div');
<add> legacyRender(<Example />, container);
<add> }, false);
<add>
<add> const inspectedElement = await inspectElementAtIndex(0);
<add> expect(inspectedElement.rootType).toMatchInlineSnapshot(`"render()"`);
<add> });
<add>
<add> it('should display the root type for ReactDOM.hydrateRoot', async () => {
<add> const Example = () => <div />;
<add>
<add> await utils.actAsync(() => {
<add> const container = document.createElement('div');
<add> container.innerHTML = '<div></div>';
<add> ReactDOM.hydrateRoot(container).render(<Example />);
<add> }, false);
<add>
<add> const inspectedElement = await inspectElementAtIndex(0);
<add> expect(inspectedElement.rootType).toMatchInlineSnapshot(`"hydrateRoot()"`);
<add> });
<add>
<add> it('should display the root type for ReactDOM.createRoot', async () => {
<add> const Example = () => <div />;
<add>
<add> await utils.actAsync(() => {
<add> const container = document.createElement('div');
<add> ReactDOM.createRoot(container).render(<Example />);
<add> }, false);
<add>
<add> const inspectedElement = await inspectElementAtIndex(0);
<add> expect(inspectedElement.rootType).toMatchInlineSnapshot(`"createRoot()"`);
<add> });
<add>
<ide> describe('$r', () => {
<ide> it('should support function components', async () => {
<ide> const Example = () => {
<ide><path>packages/react-devtools-shared/src/__tests__/inspectedElementSerializer.js
<ide> export function print(inspectedElement, serialize, indent) {
<ide> id: inspectedElement.id,
<ide> owners: inspectedElement.owners,
<ide> props: inspectedElement.props,
<add> rootType: inspectedElement.rootType,
<ide> state: inspectedElement.state,
<ide> });
<ide> }
<ide><path>packages/react-devtools-shared/src/__tests__/legacy/inspectElement-test.js
<ide> describe('InspectedElementContext', () => {
<ide> "a": 1,
<ide> "b": "abc",
<ide> },
<add> "rootType": null,
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElementContext', () => {
<ide> "value_null": null,
<ide> "value_undefined": undefined,
<ide> },
<add> "rootType": null,
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElementContext', () => {
<ide> "preview_long": Generator,
<ide> },
<ide> },
<add> "rootType": null,
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElementContext', () => {
<ide> "number": 42,
<ide> },
<ide> },
<add> "rootType": null,
<ide> "state": null,
<ide> }
<ide> `);
<ide> describe('InspectedElementContext', () => {
<ide> "enumerableStringBase": 1,
<ide> },
<ide> },
<add> "rootType": null,
<ide> "state": null,
<ide> }
<ide> `);
<ide><path>packages/react-reconciler/src/ReactFiberRoot.new.js
<ide> function FiberRootNode(containerInfo, tag, hydrate) {
<ide> if (__DEV__) {
<ide> switch (tag) {
<ide> case ConcurrentRoot:
<del> this._debugRootType = 'createRoot()';
<add> this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
<ide> break;
<ide> case LegacyRoot:
<del> this._debugRootType = 'createLegacyRoot()';
<add> this._debugRootType = hydrate ? 'hydrate()' : 'render()';
<ide> break;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberRoot.old.js
<ide> function FiberRootNode(containerInfo, tag, hydrate) {
<ide> if (__DEV__) {
<ide> switch (tag) {
<ide> case ConcurrentRoot:
<del> this._debugRootType = 'createRoot()';
<add> this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
<ide> break;
<ide> case LegacyRoot:
<del> this._debugRootType = 'createLegacyRoot()';
<add> this._debugRootType = hydrate ? 'hydrate()' : 'render()';
<ide> break;
<ide> }
<ide> } | 5 |
Javascript | Javascript | enforce child outlets to be fragments. | 81884e31f9a6007719a42ba71e84cf2c1cce41ef | <ide><path>packages/ember-glimmer/lib/syntax/outlet.js
<ide> class OutletComponentDefinition extends AbstractOutletComponentDefinition {
<ide> }
<ide>
<ide> compile(builder) {
<del> builder.fromLayout(this.template.asLayout());
<add> builder.wrapLayout(this.template.asLayout());
<ide> }
<ide> }
<ide>
<ide><path>packages/ember-glimmer/lib/views/outlet.js
<ide> export default class OutletView {
<ide> setOutletState(state) {
<ide> this.outletState = state;
<ide> this._tag.dirty();
<del> this.rerender(); // FIXME
<ide> }
<ide>
<ide> toReference() {
<ide><path>packages/ember-glimmer/tests/integration/application/rendering-test.js
<ide> moduleFor('Application test: rendering', class extends ApplicationTest {
<ide> });
<ide> }
<ide>
<add> // Regression test, glimmer child outlets tried to assume the first element.
<add> // but the if put-args clobbered the args used by did-create-element.
<add> // I wish there was a way to assert that the OutletComponentManager did not
<add> // receive a didCreateElement.
<add> ['@test a child outlet is always a fragment']() {
<add> this.registerTemplate('application', '{{outlet}}');
<add> this.registerTemplate('index', '{{#if true}}1{{/if}}<div>2</div>');
<add> return this.visit('/').then(() => {
<add> this.assertComponentElement(this.firstChild, { content: '1<div>2</div>' });
<add> });
<add> }
<ide> }); | 3 |
Mixed | Javascript | remove the comparrison doc page | 39140cca2e36333abb7ab4309a6b4ee2c52e4d95 | <ide><path>docs/docs/notes/comparison.md
<del>---
<del>title: Comparison with Other Libraries
<del>---
<del>
<del>Library Features
<del>
<del>| Feature | Chart.js | D3 | HighCharts | Chartist |
<del>| ------- | -------- | --- | ---------- | -------- |
<del>| Completely Free | ✓ | ✓ | | ✓ |
<del>| Canvas | ✓ | | | |
<del>| SVG | | ✓ | ✓ | ✓ |
<del>| Built-in Charts | ✓ | | ✓ | ✓ |
<del>| 8+ Chart Types | ✓ | ✓ | ✓ | |
<del>| Extendable to Custom Charts | ✓ | ✓ | | |
<del>| Supports Modern Browsers | ✓ | ✓ | ✓ | ✓ |
<del>| Extensive Documentation | ✓ | ✓ | ✓ | ✓ |
<del>| Open Source | ✓ | ✓ | | ✓ |
<del>
<del>Built in Chart Types
<del>
<del>| Type | Chart.js | HighCharts | Chartist |
<del>| ---- | -------- | ---------- | -------- |
<del>| Combined Types | ✓ | ✓ | |
<del>| Line | ✓ | ✓ | ✓ |
<del>| Bar | ✓ | ✓ | ✓ |
<del>| Horizontal Bar | ✓ | ✓ | ✓ |
<del>| Pie/Doughnut | ✓ | ✓ | ✓ |
<del>| Polar Area | ✓ | ✓ | |
<del>| Radar | ✓ | | |
<del>| Scatter | ✓ | ✓ | ✓ |
<del>| Bubble | ✓ | | |
<del>| Gauges | | ✓ | |
<del>| Maps (Heat/Tree/etc.) | | ✓ | |
<ide><path>docs/sidebars.js
<ide> module.exports = {
<ide> 'developers/publishing'
<ide> ],
<ide> 'Additional Notes': [
<del> 'notes/comparison',
<ide> {
<ide> type: 'link',
<ide> label: 'Extensions', | 2 |
Javascript | Javascript | add missing iscanvastexture property | 54fdf6304b789b575b341f2008adcf31b96ab468 | <ide><path>src/textures/CanvasTexture.js
<ide> function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, for
<ide>
<ide> CanvasTexture.prototype = Object.create( Texture.prototype );
<ide> CanvasTexture.prototype.constructor = CanvasTexture;
<del>
<add>CanvasTexture.prototype.isCanvasTexture = true;
<ide>
<ide> export { CanvasTexture }; | 1 |
Python | Python | clarify use of unk_token in tokenizer docstrings | 99b9affa02a6ef02c765c541a5c6f3dcff592bae | <ide><path>src/transformers/tokenization_utils.py
<ide> def tokenize(self, text: TextInput, **kwargs) -> List[str]:
<ide> """
<ide> Converts a string in a sequence of tokens, using the tokenizer.
<ide>
<del> Note that, unlike Fast tokenizers (instances of PreTrainedTokenizerFast), this method won't replace the unknown
<del> tokens with the `unk_token` yet (this is done in the `encode()` method)
<del>
<ide> Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
<ide> (BPE/SentencePieces/WordPieces). Takes care of added tokens.
<ide>
<ide><path>src/transformers/tokenization_utils_base.py
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] =
<ide>
<ide> def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
<ide> """
<del> Converts a string in a sequence of tokens, using the backend Rust tokenizer.
<del>
<del> Note that this method behave differently between fast and slow tokenizers:
<del>
<del> - in fast tokenizers (instances of :class:`~transformers.PreTrainedTokenizerFast`), this method will
<del> replace the unknown tokens with the :obj:`unk_token`,
<del> - in slow tokenizers (instances of :class:`~transformers.PreTrainedTokenizer`), this method keep unknown
<del> tokens unchanged.
<add> Converts a string in a sequence of tokens, replacing unknown tokens with the :obj:`unk_token`.
<ide>
<ide> Args:
<ide> text (:obj:`str`): | 2 |
Text | Text | modify the return value of request.write() | 766eea6ca48d5ca5cd2e9a1442a9dd6fc4932d9d | <ide><path>doc/api/http.md
<ide> Defaults to `'utf8'`.
<ide> The `callback` argument is optional and will be called when this chunk of data
<ide> is flushed.
<ide>
<del>Returns `request`.
<add>Returns `true` if the entire data was flushed successfully to the kernel
<add>buffer. Returns `false` if all or part of the data was queued in user memory.
<add>`'drain'` will be emitted when the buffer is free again.
<ide>
<ide> ## Class: http.Server
<ide> <!-- YAML | 1 |
Ruby | Ruby | remove /cask/ from readall file filter | 99bccaae13b38eeb58c234e48386b2898845f2a1 | <ide><path>Library/Homebrew/cmd/readall.rb
<ide> module Homebrew
<ide> def readall
<ide> if ARGV.include?("--syntax")
<ide> scan_files = "#{HOMEBREW_LIBRARY}/Homebrew/**/*.rb"
<del> ruby_files = Dir.glob(scan_files).reject{|file| file =~ /vendor|cask/ }
<add> ruby_files = Dir.glob(scan_files).reject{|file| file.include? '/vendor/' }
<ide>
<ide> Homebrew.failed = true unless Readall.valid_ruby_syntax?(ruby_files)
<ide> end | 1 |
Java | Java | resolve android crash on display modal | 15656342a8401eb599090da7962928dd48d7d890 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java
<ide> public void addView(View child, int index) {
<ide>
<ide> @Override
<ide> public int getChildCount() {
<del> return mHostView.getChildCount();
<add> // This method may be called by the parent constructor
<add> // before mHostView is initialized.
<add> return mHostView == null ? 0 : mHostView.getChildCount();
<ide> }
<ide>
<ide> @Override | 1 |
Text | Text | fix small typos | f2a3eb987e1fc2c85320fc3849c67811f5736b50 | <ide><path>README.md
<ide> python ./examples/run_glue.py \
<ide> --warmup_steps=120
<ide> ```
<ide>
<del>On this machine we thus have a batch size of 32, please increase `gradient_accumulation_steps` to reach the same batch size if you have a smaller machine. These hyper-parameters should results in a Pearson correlation coefficient of `+0.917` on the development set.
<add>On this machine we thus have a batch size of 32, please increase `gradient_accumulation_steps` to reach the same batch size if you have a smaller machine. These hyper-parameters should result in a Pearson correlation coefficient of `+0.917` on the development set.
<ide>
<ide> #### Fine-tuning Bert model on the MRPC classification task
<ide>
<ide> This is the model provided as `bert-large-uncased-whole-word-masking-finetuned-s
<ide> ### `run_generation.py`: Text generation with GPT, GPT-2, Transformer-XL and XLNet
<ide>
<ide> A conditional generation script is also included to generate text from a prompt.
<del>The generation script include the [tricks](https://github.com/rusiaaman/XLNet-gen#methodology) proposed by by Aman Rusia to get high quality generation with memory models like Transformer-XL and XLNet (include a predefined text to make short inputs longer).
<add>The generation script includes the [tricks](https://github.com/rusiaaman/XLNet-gen#methodology) proposed by by Aman Rusia to get high quality generation with memory models like Transformer-XL and XLNet (include a predefined text to make short inputs longer).
<ide>
<ide> Here is how to run the script with the small version of OpenAI GPT-2 model:
<ide> | 1 |
Python | Python | add openai gpt | eed51c5bdf0d26159127f82f0fe95265b076e1af | <ide><path>pytorch_pretrained_bert/__init__.py
<del>__version__ = "0.4.0"
<add>__version__ = "0.5.0"
<ide> from .tokenization import BertTokenizer, BasicTokenizer, WordpieceTokenizer
<add>from .tokenization_openai import OpenAIGPTTokenizer
<ide> from .modeling import (BertConfig, BertModel, BertForPreTraining,
<ide> BertForMaskedLM, BertForNextSentencePrediction,
<ide> BertForSequenceClassification, BertForMultipleChoice,
<ide> BertForTokenClassification, BertForQuestionAnswering)
<add>from .modeling_openai import OpenAIGPTConfig, OpenAIGPTModel, OpenAIGPTDoubleHeadsModel
<ide> from .optimization import BertAdam
<add>from .optimization_openai import OpenAIAdam
<ide> from .file_utils import PYTORCH_PRETRAINED_BERT_CACHE
<ide><path>pytorch_pretrained_bert/__main__.py
<ide> # coding: utf8
<ide> def main():
<ide> import sys
<del> try:
<del> from .convert_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
<del> except ModuleNotFoundError:
<del> print("pytorch_pretrained_bert can only be used from the commandline to convert TensorFlow models in PyTorch, "
<del> "In that case, it requires TensorFlow to be installed. Please see "
<del> "https://www.tensorflow.org/install/ for installation instructions.")
<del> raise
<del>
<del> if len(sys.argv) != 5:
<del> # pylint: disable=line-too-long
<del> print("Should be used as `pytorch_pretrained_bert convert_tf_checkpoint_to_pytorch TF_CHECKPOINT TF_CONFIG PYTORCH_DUMP_OUTPUT`")
<add> if (len(sys.argv) != 4 and len(sys.argv) != 5) or sys.argv[1] not in [
<add> "convert_tf_checkpoint_to_pytorch",
<add> "convert_openai_checkpoint"
<add> ]:
<add> print("Should be used as `pytorch_pretrained_bert convert_tf_checkpoint_to_pytorch TF_CHECKPOINT TF_CONFIG PYTORCH_DUMP_OUTPUT` \n or `pytorch_pretrained_bert convert_openai_checkpoint OPENAI_GPT_CHECKPOINT_FOLDER_PATH PYTORCH_DUMP_OUTPUT [OPENAI_GPT_CONFIG]`")
<ide> else:
<del> PYTORCH_DUMP_OUTPUT = sys.argv.pop()
<del> TF_CONFIG = sys.argv.pop()
<del> TF_CHECKPOINT = sys.argv.pop()
<del> convert_tf_checkpoint_to_pytorch(TF_CHECKPOINT, TF_CONFIG, PYTORCH_DUMP_OUTPUT)
<add> if sys.argv[1] == "convert_tf_checkpoint_to_pytorch":
<add> try:
<add> from .convert_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
<add> except ModuleNotFoundError:
<add> print("pytorch_pretrained_bert can only be used from the commandline to convert TensorFlow models in PyTorch, "
<add> "In that case, it requires TensorFlow to be installed. Please see "
<add> "https://www.tensorflow.org/install/ for installation instructions.")
<add> raise
<add>
<add> if len(sys.argv) != 5:
<add> # pylint: disable=line-too-long
<add> print("Should be used as `pytorch_pretrained_bert convert_tf_checkpoint_to_pytorch TF_CHECKPOINT TF_CONFIG PYTORCH_DUMP_OUTPUT`")
<add> else:
<add> PYTORCH_DUMP_OUTPUT = sys.argv.pop()
<add> TF_CONFIG = sys.argv.pop()
<add> TF_CHECKPOINT = sys.argv.pop()
<add> convert_tf_checkpoint_to_pytorch(TF_CHECKPOINT, TF_CONFIG, PYTORCH_DUMP_OUTPUT)
<add> else:
<add> from .convert_openai_checkpoint_to_pytorch import convert_openai_checkpoint_to_pytorch
<add> OPENAI_GPT_CHECKPOINT_FOLDER_PATH = sys.argv[2]
<add> PYTORCH_DUMP_OUTPUT = sys.argv[3]
<add> if len(sys.argv) == 5:
<add> OPENAI_GPT_CONFIG = sys.argv[4]
<add> else:
<add> OPENAI_GPT_CONFIG = ""
<add> convert_openai_checkpoint_to_pytorch(OPENAI_GPT_CHECKPOINT_FOLDER_PATH,
<add> OPENAI_GPT_CONFIG,
<add> PYTORCH_DUMP_OUTPUT)
<ide>
<ide> if __name__ == '__main__':
<ide> main()
<ide><path>pytorch_pretrained_bert/convert_openai_checkpoint_to_pytorch.py
<ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<del>"""Convert BERT checkpoint."""
<add>"""Convert OpenAI GPT checkpoint."""
<ide>
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import os
<ide> import re
<add>import json
<ide> import argparse
<ide> import tensorflow as tf
<ide> import torch
<ide> import numpy as np
<ide>
<del>from .modeling import BertConfig, BertForPreTraining
<add>from .modeling_openai import OpenAIGPTConfig, OpenAIGPTModel, CONFIG_NAME, WEIGHTS_NAME
<ide>
<ide>
<del>def convert_openai_checkpoint_to_pytorch(open_checkpoint_folder_path, openai_config_file, pytorch_dump_path):
<del>def load_openai_pretrained_model(model, n_ctx=-1, n_special=-1, n_transfer=12, n_embd=768, path='./model/',
<del> path_names='./'):
<add>def convert_openai_checkpoint_to_pytorch(openai_checkpoint_folder_path, openai_config_file, pytorch_dump_folder_path):
<ide> # Load weights from TF model
<ide> print("Loading weights...")
<del> names = json.load(open(path_names + 'parameters_names.json'))
<del> shapes = json.load(open(path + 'params_shapes.json'))
<add> names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", encoding='utf-8'))
<add> shapes = json.load(open(openai_checkpoint_folder_path + '/params_shapes.json', "r", encoding='utf-8'))
<ide> offsets = np.cumsum([np.prod(shape) for shape in shapes])
<del> init_params = [np.load(path + 'params_{}.npy'.format(n)) for n in range(10)]
<add> init_params = [np.load(openai_checkpoint_folder_path + '/params_{}.npy'.format(n)) for n in range(10)]
<ide> init_params = np.split(np.concatenate(init_params, 0), offsets)[:-1]
<ide> init_params = [param.reshape(shape) for param, shape in zip(init_params, shapes)]
<del> if n_ctx > 0:
<del> init_params[0] = init_params[0][:n_ctx]
<del> if n_special > 0:
<del> init_params[0] = np.concatenate(
<del> [init_params[1],
<del> (np.random.randn(n_special, n_embd) * 0.02).astype(np.float32),
<del> init_params[0]
<del> ], 0)
<del> else:
<del> init_params[0] = np.concatenate(
<del> [init_params[1],
<del> init_params[0]
<del> ], 0)
<add> # if n_ctx > 0:
<add> # init_params[0] = init_params[0][:n_ctx]
<add> # if n_special > 0:
<add> # init_params[0] = np.concatenate(
<add> # [init_params[1],
<add> # (np.random.randn(n_special, n_embd) * 0.02).astype(np.float32),
<add> # init_params[0]
<add> # ], 0)
<add> # else:
<add> # init_params[0] = np.concatenate(
<add> # [init_params[1],
<add> # init_params[0]
<add> # ], 0)
<add> # del init_params[1]
<add> # if n_transfer == -1:
<add> # n_transfer = 0
<add> # else:
<add> # n_transfer = 1 + n_transfer * 12
<add>
<add> init_params[0] = np.concatenate([init_params[1], init_params[0]], 0)
<ide> del init_params[1]
<del> if n_transfer == -1:
<del> n_transfer = 0
<del> else:
<del> n_transfer = 1 + n_transfer * 12
<ide> init_params = [arr.squeeze() for arr in init_params]
<ide>
<add> # Construct model
<add> if openai_config_file == "":
<add> config = OpenAIGPTConfig()
<add> else:
<add> config = OpenAIGPTConfig(openai_config_file)
<add> model = OpenAIGPTModel(config)
<ide> try:
<ide> assert model.embed.weight.shape == init_params[0].shape
<ide> except AssertionError as e:
<ide> e.args += (model.embed.weight.shape, init_params[0].shape)
<ide> raise
<ide>
<ide> model.embed.weight.data = torch.from_numpy(init_params[0])
<add> names.pop(0)
<add> init_params.pop(0)
<ide>
<del> for name, ip in zip(names[1:n_transfer], init_params[1:n_transfer]):
<add> for name, array in zip(names, init_params): # names[1:n_transfer], init_params[1:n_transfer]):
<ide> name = name[6:] # skip "model/"
<ide> assert name[-2:] == ":0"
<ide> name = name[:-2]
<ide> def load_openai_pretrained_model(model, n_ctx=-1, n_special=-1, n_transfer=12, n
<ide> l = re.split(r'(\d+)', m_name)
<ide> else:
<ide> l = [m_name]
<del> pointer = getattr(pointer, l[0])
<del> if len(l) >= 2:
<del> num = int(l[1])
<del> pointer = pointer[num]
<del> try:
<del> assert pointer.shape == ip.shape
<del> except AssertionError as e:
<del> e.args += (pointer.shape, ip.shape)
<del> raise
<del> pointer.data = torch.from_numpy(ip)
<del>
<del>def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path):
<del> config_path = os.path.abspath(bert_config_file)
<del> tf_path = os.path.abspath(tf_checkpoint_path)
<del> print("Converting TensorFlow checkpoint from {} with config at {}".format(tf_path, config_path))
<del> # Load weights from TF model
<del> init_vars = tf.train.list_variables(tf_path)
<del> names = []
<del> arrays = []
<del> for name, shape in init_vars:
<del> print("Loading TF weight {} with shape {}".format(name, shape))
<del> array = tf.train.load_variable(tf_path, name)
<del> names.append(name)
<del> arrays.append(array)
<del>
<del> # Initialise PyTorch model
<del> config = BertConfig.from_json_file(bert_config_file)
<del> print("Building PyTorch model from configuration: {}".format(str(config)))
<del> model = BertForPreTraining(config)
<del>
<del> for name, array in zip(names, arrays):
<del> name = name.split('/')
<del> # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
<del> # which are not required for using pretrained model
<del> if any(n in ["adam_v", "adam_m"] for n in name):
<del> print("Skipping {}".format("/".join(name)))
<del> continue
<del> pointer = model
<del> for m_name in name:
<del> if re.fullmatch(r'[A-Za-z]+_\d+', m_name):
<del> l = re.split(r'_(\d+)', m_name)
<del> else:
<del> l = [m_name]
<del> if l[0] == 'kernel' or l[0] == 'gamma':
<add> if l[0] == 'g':
<ide> pointer = getattr(pointer, 'weight')
<del> elif l[0] == 'output_bias' or l[0] == 'beta':
<add> elif l[0] == 'b':
<ide> pointer = getattr(pointer, 'bias')
<del> elif l[0] == 'output_weights':
<add> elif l[0] == 'w':
<ide> pointer = getattr(pointer, 'weight')
<ide> else:
<ide> pointer = getattr(pointer, l[0])
<ide> if len(l) >= 2:
<ide> num = int(l[1])
<ide> pointer = pointer[num]
<del> if m_name[-11:] == '_embeddings':
<del> pointer = getattr(pointer, 'weight')
<del> elif m_name == 'kernel':
<del> array = np.transpose(array)
<add> try:
<add> assert pointer.shape == array.shape
<add> except AssertionError as e:
<add> e.args += (pointer.shape, array.shape)
<add> raise
<ide> try:
<ide> assert pointer.shape == array.shape
<ide> except AssertionError as e:
<ide> def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytor
<ide> pointer.data = torch.from_numpy(array)
<ide>
<ide> # Save pytorch-model
<del> print("Save PyTorch model to {}".format(pytorch_dump_path))
<del> torch.save(model.state_dict(), pytorch_dump_path)
<del>
<add> pytorch_weights_dump_path = pytorch_dump_folder_path + '/' + WEIGHTS_NAME
<add> pytorch_config_dump_path = pytorch_dump_folder_path + '/' + CONFIG_NAME
<add> print("Save PyTorch model to {}".format(pytorch_weights_dump_path))
<add> torch.save(model.state_dict(), pytorch_weights_dump_path)
<add> print("Save configuration file to {}".format(pytorch_config_dump_path))
<add> with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
<add> f.write(config.to_json_string())
<ide>
<ide> if __name__ == "__main__":
<ide> parser = argparse.ArgumentParser()
<ide> ## Required parameters
<del> parser.add_argument("--tf_checkpoint_path",
<add> parser.add_argument("--openai_checkpoint_folder_path",
<ide> default = None,
<ide> type = str,
<ide> required = True,
<ide> help = "Path the TensorFlow checkpoint path.")
<del> parser.add_argument("--bert_config_file",
<del> default = None,
<del> type = str,
<del> required = True,
<del> help = "The config json file corresponding to the pre-trained BERT model. \n"
<del> "This specifies the model architecture.")
<del> parser.add_argument("--pytorch_dump_path",
<add> parser.add_argument("--pytorch_dump_folder_path",
<ide> default = None,
<ide> type = str,
<ide> required = True,
<ide> help = "Path to the output PyTorch model.")
<add> parser.add_argument("--openai_config_file",
<add> default = "",
<add> type = str,
<add> help = "An optional config json file corresponding to the pre-trained OpenAI model. \n"
<add> "This specifies the model architecture.")
<ide> args = parser.parse_args()
<del> convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path,
<del> args.bert_config_file,
<del> args.pytorch_dump_path)
<add> convert_openai_checkpoint_to_pytorch(args.openai_checkpoint_folder_path,
<add> args.pytorch_dump_folder_path,
<add> args.openai_config_file)
<ide><path>pytorch_pretrained_bert/modeling.py
<ide> def forward(self, sequence_output, pooled_output):
<ide> return prediction_scores, seq_relationship_score
<ide>
<ide>
<del>class PreTrainedModel(nn.Module):
<add>class BertPreTrainedModel(nn.Module):
<ide> """ An abstract class to handle weights initialization and
<ide> a simple interface for dowloading and loading pretrained models.
<ide> """
<ide> def __init__(self, config, *inputs, **kwargs):
<del> super(PreTrainedModel, self).__init__()
<add> super(BertPreTrainedModel, self).__init__()
<ide> if not isinstance(config, BertConfig):
<ide> raise ValueError(
<ide> "Parameter config in `{}(config)` should be an instance of class `BertConfig`. "
<ide> def init_bert_weights(self, module):
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name, state_dict=None, cache_dir=None, *inputs, **kwargs):
<ide> """
<del> Instantiate a PreTrainedModel from a pre-trained model file or a pytorch state dict.
<add> Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.
<ide> Download and cache the pre-trained model file if needed.
<ide>
<ide> Params:
<ide> def load(module, prefix=''):
<ide> if len(unexpected_keys) > 0:
<ide> logger.info("Weights from pretrained model not used in {}: {}".format(
<ide> model.__class__.__name__, unexpected_keys))
<add> if len(error_msgs) > 0:
<add> raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
<add> self.__class__.__name__, "\n\t".join(error_msgs)))
<ide> if tempdir:
<ide> # Clean up temp dir
<ide> shutil.rmtree(tempdir)
<ide> return model
<ide>
<ide>
<del>class BertModel(PreTrainedModel):
<add>class BertModel(BertPreTrainedModel):
<ide> """BERT model ("Bidirectional Embedding Representations from a Transformer").
<ide>
<ide> Params:
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_al
<ide> return encoded_layers, pooled_output
<ide>
<ide>
<del>class BertForPreTraining(PreTrainedModel):
<add>class BertForPreTraining(BertPreTrainedModel):
<ide> """BERT model with pre-training heads.
<ide> This module comprises the BERT model followed by the two pre-training heads:
<ide> - the masked language modeling head, and
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm
<ide> return prediction_scores, seq_relationship_score
<ide>
<ide>
<del>class BertForMaskedLM(PreTrainedModel):
<add>class BertForMaskedLM(BertPreTrainedModel):
<ide> """BERT model with the masked language modeling head.
<ide> This module comprises the BERT model followed by the masked language modeling head.
<ide>
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm
<ide> return prediction_scores
<ide>
<ide>
<del>class BertForNextSentencePrediction(PreTrainedModel):
<add>class BertForNextSentencePrediction(BertPreTrainedModel):
<ide> """BERT model with next sentence prediction head.
<ide> This module comprises the BERT model followed by the next sentence classification head.
<ide>
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, next_sent
<ide> return seq_relationship_score
<ide>
<ide>
<del>class BertForSequenceClassification(PreTrainedModel):
<add>class BertForSequenceClassification(BertPreTrainedModel):
<ide> """BERT model for classification.
<ide> This module is composed of the BERT model with a linear layer on top of
<ide> the pooled output.
<ide> class BertForSequenceClassification(PreTrainedModel):
<ide> logits = model(input_ids, token_type_ids, input_mask)
<ide> ```
<ide> """
<del> def __init__(self, config, num_labels=2):
<add> def __init__(self, config, num_labels):
<ide> super(BertForSequenceClassification, self).__init__(config)
<ide> self.num_labels = num_labels
<ide> self.bert = BertModel(config)
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No
<ide> return logits
<ide>
<ide>
<del>class BertForMultipleChoice(PreTrainedModel):
<add>class BertForMultipleChoice(BertPreTrainedModel):
<ide> """BERT model for multiple choice tasks.
<ide> This module is composed of the BERT model with a linear layer on top of
<ide> the pooled output.
<ide> class BertForMultipleChoice(PreTrainedModel):
<ide> logits = model(input_ids, token_type_ids, input_mask)
<ide> ```
<ide> """
<del> def __init__(self, config, num_choices=2):
<add> def __init__(self, config, num_choices):
<ide> super(BertForMultipleChoice, self).__init__(config)
<ide> self.num_choices = num_choices
<ide> self.bert = BertModel(config)
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No
<ide> return reshaped_logits
<ide>
<ide>
<del>class BertForTokenClassification(PreTrainedModel):
<add>class BertForTokenClassification(BertPreTrainedModel):
<ide> """BERT model for token-level classification.
<ide> This module is composed of the BERT model with a linear layer on top of
<ide> the full hidden state of the last layer.
<ide> class BertForTokenClassification(PreTrainedModel):
<ide> logits = model(input_ids, token_type_ids, input_mask)
<ide> ```
<ide> """
<del> def __init__(self, config, num_labels=2):
<add> def __init__(self, config, num_labels):
<ide> super(BertForTokenClassification, self).__init__(config)
<ide> self.num_labels = num_labels
<ide> self.bert = BertModel(config)
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No
<ide> return logits
<ide>
<ide>
<del>class BertForQuestionAnswering(PreTrainedModel):
<add>class BertForQuestionAnswering(BertPreTrainedModel):
<ide> """BERT model for Question Answering (span extraction).
<ide> This module is composed of the BERT model with a linear layer on top of
<ide> the sequence output that computes start_logits and end_logits
<ide><path>pytorch_pretrained_bert/modeling_openai.py
<add>import os
<ide> import copy
<ide> import json
<ide> import math
<del>import re
<add>import logging
<add>import tarfile
<add>import tempfile
<add>import shutil
<ide> import collections
<ide>
<del>import numpy as np
<ide> import torch
<ide> import torch.nn as nn
<add>from torch.nn import CrossEntropyLoss
<ide> from torch.nn.parameter import Parameter
<ide>
<ide> from .modeling import BertLayerNorm as LayerNorm
<add>from .file_utils import cached_path
<ide>
<add>logger = logging.getLogger(__name__)
<add>
<add>PRETRAINED_MODEL_ARCHIVE_MAP = {
<add> 'openai-gpt': "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt.tar.gz",
<add>}
<add>CONFIG_NAME = 'openai_gpt_config.json'
<add>WEIGHTS_NAME = 'pytorch_model.bin'
<ide>
<ide> def gelu(x):
<ide> return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
<ide> def swish(x):
<ide> 'gelu': gelu
<ide> }
<ide>
<add>class OpenAIGPTConfig(object):
<add> """Configuration class to store the configuration of a `OpenAIGPTModel`.
<add> """
<add> def __init__(self,
<add> vocab_size_or_config_json_file=40478,
<add> n_special=0,
<add> n_ctx=512,
<add> n_embd=768,
<add> n_layer=12,
<add> n_head=12,
<add> intermediate_size=3072,
<add> afn="gelu",
<add> resid_pdrop=0.1,
<add> embd_pdrop=0.1,
<add> attn_pdrop=0.1,
<add> type_vocab_size=2,
<add> initializer_range=0.02):
<add> """Constructs OpenAIGPTConfig.
<add>
<add> Args:
<add> vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `OpenAIGPTModel` or a configuration json file.
<add> n_special: The number of special tokens to learn during fine-tuning ('[SEP]', '[CLF]', ...)
<add> n_ctx: Number of positional embeddings.
<add> n_embd: Dimensionality of the embeddings and hidden states.
<add> n_layer: Number of hidden layers in the Transformer encoder.
<add> n_head: Number of attention heads for each attention layer in
<add> the Transformer encoder.
<add> intermediate_size: The size of the "intermediate" (i.e., feed-forward)
<add> layer in the Transformer encoder.
<add> afn: The non-linear activation function (function or string) in the
<add> encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
<add> resid_pdrop: The dropout probabilitiy for all fully connected
<add> layers in the embeddings, encoder, and pooler.
<add> attn_pdrop: The dropout ratio for the attention
<add> probabilities.
<add> embd_pdrop: The dropout ratio for the embeddings.
<add> type_vocab_size: The vocabulary size of the `token_type_ids` passed into
<add> `OpenAIGPTModel`.
<add> initializer_range: The sttdev of the truncated_normal_initializer for
<add> initializing all weight matrices.
<add> """
<add> if isinstance(vocab_size_or_config_json_file, str):
<add> with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
<add> json_config = json.loads(reader.read())
<add> for key, value in json_config.items():
<add> self.__dict__[key] = value
<add> elif isinstance(vocab_size_or_config_json_file, int):
<add> self.vocab_size = vocab_size_or_config_json_file
<add> self.n_special = n_special
<add> self.n_ctx = n_ctx
<add> self.n_embd = n_embd
<add> self.n_layer = n_layer
<add> self.n_head = n_head
<add> self.afn = afn
<add> self.intermediate_size = intermediate_size
<add> self.resid_pdrop = resid_pdrop
<add> self.embd_pdrop = embd_pdrop
<add> self.attn_pdrop = attn_pdrop
<add> self.type_vocab_size = type_vocab_size
<add> self.initializer_range = initializer_range
<add> else:
<add> raise ValueError("First argument must be either a vocabulary size (int)"
<add> "or the path to a pretrained model config file (str)")
<add>
<add> @property
<add> def total_num_embeddings(self):
<add> return self.vocab_size + self.n_special + self.n_ctx
<add>
<add> @classmethod
<add> def from_dict(cls, json_object):
<add> """Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters."""
<add> config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1)
<add> for key, value in json_object.items():
<add> config.__dict__[key] = value
<add> return config
<add>
<add> @classmethod
<add> def from_json_file(cls, json_file):
<add> """Constructs a `OpenAIGPTConfig` from a json file of parameters."""
<add> with open(json_file, "r", encoding='utf-8') as reader:
<add> text = reader.read()
<add> return cls.from_dict(json.loads(text))
<add>
<add> def __repr__(self):
<add> return str(self.to_json_string())
<add>
<add> def to_dict(self):
<add> """Serializes this instance to a Python dictionary."""
<add> output = copy.deepcopy(self.__dict__)
<add> return output
<add>
<add> def to_json_string(self):
<add> """Serializes this instance to a JSON string."""
<add> return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
<add>
<add>class OpenAIGPTPreTrainedModel(nn.Module):
<add> """ An abstract class to handle weights initialization and
<add> a simple interface for dowloading and loading pretrained models.
<add> """
<add> def __init__(self, config, *inputs, **kwargs):
<add> super(OpenAIGPTPreTrainedModel, self).__init__()
<add> if not isinstance(config, OpenAIGPTConfig):
<add> raise ValueError(
<add> "Parameter config in `{}(config)` should be an instance of class `OpenAIGPTConfig`. "
<add> "To create a model from a Google pretrained model use "
<add> "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
<add> self.__class__.__name__, self.__class__.__name__
<add> ))
<add> self.config = config
<add>
<add> def init_weights(self, module):
<add> """ Initialize the weights.
<add> """
<add> if isinstance(module, (nn.Linear, nn.Embedding)):
<add> # Slightly different from the TF version which uses truncated_normal for initialization
<add> # cf https://github.com/pytorch/pytorch/pull/5617
<add> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
<add> elif isinstance(module, LayerNorm):
<add> module.bias.data.zero_()
<add> module.weight.data.fill_(1.0)
<add> if isinstance(module, nn.Linear) and module.bias is not None:
<add> module.bias.data.zero_()
<add>
<add> def post_loading(self):
<add> pass
<add>
<add> @classmethod
<add> def from_pretrained(cls, pretrained_model_name, state_dict=None, cache_dir=None, *inputs, **kwargs):
<add> """
<add> Instantiate a OpenAIGPTPreTrainedModel from a pre-trained model file or a pytorch state dict.
<add> Download and cache the pre-trained model file if needed.
<add>
<add> Params:
<add> pretrained_model_name: either:
<add> - a str with the name of a pre-trained model to load selected in the list of:
<add> . `openai-gpt`
<add> - a path or url to a pretrained model archive containing:
<add> . `openai_gpt_config.json` a configuration file for the model
<add> . `pytorch_model.bin` a PyTorch dump of a OpenAIGPTModel instance
<add> cache_dir: an optional path to a folder in which the pre-trained models will be cached.
<add> state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models
<add> *inputs, **kwargs: additional input for the specific Bert class
<add> (ex: num_labels for BertForSequenceClassification)
<add> """
<add> if pretrained_model_name in PRETRAINED_MODEL_ARCHIVE_MAP:
<add> archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name]
<add> else:
<add> archive_file = pretrained_model_name
<add> # redirect to the cache, if necessary
<add> try:
<add> resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)
<add> except FileNotFoundError:
<add> logger.error(
<add> "Model name '{}' was not found in model name list ({}). "
<add> "We assumed '{}' was a path or url but couldn't find any file "
<add> "associated to this path or url.".format(
<add> pretrained_model_name,
<add> ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),
<add> archive_file))
<add> return None
<add> if resolved_archive_file == archive_file:
<add> logger.info("loading archive file {}".format(archive_file))
<add> else:
<add> logger.info("loading archive file {} from cache at {}".format(
<add> archive_file, resolved_archive_file))
<add> tempdir = None
<add> if os.path.isdir(resolved_archive_file):
<add> serialization_dir = resolved_archive_file
<add> else:
<add> # Extract archive to temp dir
<add> tempdir = tempfile.mkdtemp()
<add> logger.info("extracting archive file {} to temp dir {}".format(
<add> resolved_archive_file, tempdir))
<add> with tarfile.open(resolved_archive_file, 'r:gz') as archive:
<add> archive.extractall(tempdir)
<add> serialization_dir = tempdir
<add> # Load config
<add> config_file = os.path.join(serialization_dir, CONFIG_NAME)
<add> config = OpenAIGPTConfig.from_json_file(config_file)
<add> logger.info("Model config {}".format(config))
<add> # Instantiate model.
<add> model = cls(config, *inputs, **kwargs)
<add> if state_dict is None:
<add> weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)
<add> state_dict = torch.load(weights_path)
<add>
<add> old_keys = []
<add> new_keys = []
<add> for key in state_dict.keys():
<add> new_key = None
<add> if 'gamma' in key:
<add> new_key = key.replace('gamma', 'weight')
<add> if 'beta' in key:
<add> new_key = key.replace('beta', 'bias')
<add> if new_key:
<add> old_keys.append(key)
<add> new_keys.append(new_key)
<add> for old_key, new_key in zip(old_keys, new_keys):
<add> state_dict[new_key] = state_dict.pop(old_key)
<add>
<add> missing_keys = []
<add> unexpected_keys = []
<add> error_msgs = []
<add> # copy state_dict so _load_from_state_dict can modify it
<add> metadata = getattr(state_dict, '_metadata', None)
<add> state_dict = state_dict.copy()
<add> if metadata is not None:
<add> state_dict._metadata = metadata
<add>
<add> def load(module, prefix=''):
<add> local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
<add> module._load_from_state_dict(
<add> state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)
<add> for name, child in module._modules.items():
<add> if child is not None:
<add> load(child, prefix + name + '.')
<add> load(model.transformer if hasattr(model, 'transformer') else model, prefix='')
<add> if len(missing_keys) > 0:
<add> logger.info("Weights of {} not initialized from pretrained model: {}".format(
<add> model.__class__.__name__, missing_keys))
<add> if len(unexpected_keys) > 0:
<add> logger.info("Weights from pretrained model not used in {}: {}".format(
<add> model.__class__.__name__, unexpected_keys))
<add> if len(error_msgs) > 0:
<add> raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
<add> self.__class__.__name__, "\n\t".join(error_msgs)))
<add> model.post_loading()
<add> if tempdir:
<add> # Clean up temp dir
<add> shutil.rmtree(tempdir)
<add> return model
<ide>
<ide> class Conv1D(nn.Module):
<ide> def __init__(self, nf, rf, nx):
<ide> def __init__(self, nf, rf, nx):
<ide> if rf == 1: # faster 1x1 conv
<ide> w = torch.empty(nx, nf)
<ide> nn.init.normal_(w, std=0.02)
<del> self.w = Parameter(w)
<del> self.b = Parameter(torch.zeros(nf))
<add> self.weight = Parameter(w)
<add> self.bias = Parameter(torch.zeros(nf))
<ide> else: # was used to train LM
<ide> raise NotImplementedError
<ide>
<ide> def forward(self, x):
<ide> if self.rf == 1:
<ide> size_out = x.size()[:-1] + (self.nf,)
<del> x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w)
<add> x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
<ide> x = x.view(*size_out)
<ide> else:
<ide> raise NotImplementedError
<ide> def forward(self, x):
<ide> return h
<ide>
<ide>
<del>class TransformerModel(nn.Module):
<del> """ Transformer model """
<del>
<del> def __init__(self, cfg, vocab=40990, n_ctx=512):
<del> super(TransformerModel, self).__init__()
<del> self.vocab = vocab
<del> self.embed = nn.Embedding(vocab, cfg.n_embd)
<del> self.drop = nn.Dropout(cfg.embd_pdrop)
<del> block = Block(n_ctx, cfg, scale=True)
<del> self.h = nn.ModuleList([copy.deepcopy(block) for _ in range(cfg.n_layer)])
<del>
<del> nn.init.normal_(self.embed.weight, std=0.02)
<del>
<del> def forward(self, x):
<del> x = x.view(-1, x.size(-2), x.size(-1))
<del> e = self.embed(x)
<del> # Add the position information to the input embeddings
<del> h = e.sum(dim=2)
<del> for block in self.h:
<del> h = block(h)
<del> return h
<del>
<del>
<del>class LMHead(nn.Module):
<add>class OpenAIGPTLMHead(nn.Module):
<ide> """ Language Model Head for the transformer """
<ide>
<del> def __init__(self, model, cfg):
<del> super(LMHead, self).__init__()
<add> def __init__(self, model_embeddings_weights, cfg):
<add> super(OpenAIGPTLMHead, self).__init__()
<ide> self.n_embd = cfg.n_embd
<del> embed_shape = model.embed.weight.shape
<add> self.set_embeddings_weights(model_embeddings_weights)
<add>
<add> def set_embeddings_weights(self, model_embeddings_weights):
<add> embed_shape = model_embeddings_weights.shape
<ide> self.decoder = nn.Linear(embed_shape[1], embed_shape[0], bias=False)
<del> self.decoder.weight = model.embed.weight # Tied weights
<add> self.decoder.weight = model_embeddings_weights # Tied weights
<ide>
<ide> def forward(self, h):
<ide> # Truncated Language modeling logits (we remove the last token)
<ide> def forward(self, h):
<ide> return lm_logits
<ide>
<ide>
<del>class MultipleChoiceHead(nn.Module):
<add>class OpenAIGPTClfHead(nn.Module):
<ide> """ Classifier Head for the transformer """
<ide>
<ide> def __init__(self, clf_token, cfg):
<del> super(MultipleChoiceHead, self).__init__()
<add> super(OpenAIGPTClfHead, self).__init__()
<ide> self.n_embd = cfg.n_embd
<ide> self.clf_token = clf_token
<del> self.dropout = nn.Dropout2d(cfg.clf_pdrop) # To reproduce the noise_shape parameter of TF implementation
<add> self.dropout = nn.Dropout2d(cfg.resid_pdrop) # To reproduce the noise_shape parameter of TF implementation
<ide> self.linear = nn.Linear(cfg.n_embd, 1)
<ide>
<ide> nn.init.normal_(self.linear.weight, std = 0.02)
<ide> def forward(self, h, x):
<ide> return clf_logits.view(-1, x.size(1))
<ide>
<ide>
<del>class ClfHead(nn.Module):
<del> """Classification Head for the transformer
<add>class OpenAIGPTModel(OpenAIGPTPreTrainedModel):
<add> """ OpenAI GPT model """
<ide>
<del> TODO: test this class."""
<del> def __init__(self, clf_token, cfg, n_class):
<del> super(ClfHead, self).__init__()
<del> self.n_embd = cfg.n_embd
<del> self.clf_token = clf_token
<del> self.dropout = nn.Dropout(cfg.clf_pdrop)
<del> self.linear = nn.Linear(cfg.n_embd, n_class)
<add> def __init__(self, cfg):
<add> super(OpenAIGPTModel, self).__init__(cfg)
<add> total_embeddings_size = cfg.vocab_size + cfg.n_special + cfg.n_ctx
<add> self.embed = nn.Embedding(total_embeddings_size, cfg.n_embd)
<add> self.drop = nn.Dropout(cfg.embd_pdrop)
<add> block = Block(cfg.n_ctx, cfg, scale=True)
<add> self.h = nn.ModuleList([copy.deepcopy(block) for _ in range(cfg.n_layer)])
<ide>
<del> nn.init.normal_(self.linear.weight, std = 0.02)
<del> nn.init.normal_(self.linear.bias, 0)
<add> self.apply(self.init_weights)
<add> # nn.init.normal_(self.embed.weight, std=0.02)
<add>
<add> def set_num_special_tokens(self, num_special_tokens):
<add> # Update config
<add> self.config.n_special = num_special_tokens
<add> # # Build new embeddings and initialize
<add> old_embed = self.embed
<add> self.embed = nn.Embedding(self.config.total_num_embeddings, self.config.n_embd)
<add> # Initialize all new embeddings (in particular the special tokens)
<add> self.init_weights(self.embed)
<add> # Copy word and positional embeddings from the previous weights
<add> self.embed.weight.data[:self.config.vocab_size, :] = old_embed.weight.data[:self.config.vocab_size, :]
<add> self.embed.weight.data[-self.config.n_ctx:, :] = old_embed.weight.data[-self.config.n_ctx:, :]
<ide>
<del> def forward(self, h, x):
<del> clf_h = h.view(-1, self.n_embd)
<del> flat = x[..., 0].contiguous().view(-1)
<del> clf_h = clf_h[flat == self.clf_token, :]
<del> clf_h = self.dropout(clf_h)
<del> clf_logits = self.linear(clf_h)
<del>
<del> return clf_logits
<add> def forward(self, x):
<add> x = x.view(-1, x.size(-2), x.size(-1))
<add> e = self.embed(x)
<add> # Add the position information to the input embeddings
<add> h = e.sum(dim=2)
<add> for block in self.h:
<add> h = block(h)
<add> return h
<ide>
<del>class SimilarityHead(nn.Module):
<del> """ Similarity Head for the transformer
<ide>
<del> TODO: test this class."""
<del> def __init__(self, clf_token, cfg):
<del> super(SimilarityHead, self).__init__()
<del> self.n_embd = cfg.n_embd
<del> self.clf_token = clf_token
<del> self.dropout = nn.Dropout(cfg.clf_pdrop)
<del> self.linear = nn.Linear(cfg.n_embd, 1)
<add>class OpenAIGPTDoubleHeadsModel(OpenAIGPTPreTrainedModel):
<add> """ OpenAI GPT model with language model and classification heads """
<add> def __init__(self, cfg, clf_token='[CLS]'):
<add> super(OpenAIGPTDoubleHeadsModel, self).__init__(cfg)
<add> self.transformer = OpenAIGPTModel(cfg)
<add> self.lm_head = OpenAIGPTLMHead(self.transformer.embed.weight, cfg)
<add> self.clf_head = OpenAIGPTClfHead(clf_token, cfg)
<add> self.apply(self.init_weights)
<ide>
<del> nn.init.normal_(self.linear.weight, std = 0.02)
<del> nn.init.normal_(self.linear.bias, 0)
<add> def post_loading(self):
<add> " Set the number of special tokens to 1 (for the [CLS] token) "
<add> self.set_num_special_tokens(1)
<ide>
<del> def forward(self, h, x):
<del> sim_h = h.view(-1, self.n_embd)
<del> flat = x[..., 0].contiguous().view(-1)
<del> sim_h = sim_h[flat == self.clf_token, :]
<del> sim_h = self.dropout(sim_h)
<del> sim_h = sim_h.sum(dim = 1)
<del> sim_logits = self.linear(sim_h)
<del>
<del> return sim_logits
<del>
<del>class DoubleHeadModel(nn.Module):
<del> """ Transformer with language model and task specific heads """
<del> def __init__(self, cfg, clf_token, task_head_type, vocab=40990, n_ctx=512):
<del> super(DoubleHeadModel, self).__init__()
<del> self.transformer = TransformerModel(cfg, vocab=vocab, n_ctx=n_ctx)
<del> self.lm_head = LMHead(self.transformer, cfg)
<del> if isinstance(task_head_type, str):
<del> if task_head_type == 'multiple_choice':
<del> self.task_head = MultipleChoiceHead(clf_token, cfg)
<del> elif task_head_type == 'similarity':
<del> self.task_head = SimilarityHead(clf_token, cfg)
<del> elif task_head_type == 'inference':
<del> # the three classes correspond to entailment, contradiction and neutral.
<del> self.task_head = ClfHead(clf_token, cfg, 3)
<del> else:
<del> raise ValueError("task_head_type is expected to be 'multiple_choice' "
<del> "'similarity', 'inference' or ('classification', n_class) "
<del> f"got {task_head_type}.")
<del> elif isinstance(task_head_type, collections.abc.Sequence) and len(task_head_type) == 2 and \
<del> task_head_type[0] == 'classification':
<del> n_class = task_head_type[1]
<del> self.task_head = ClfHead(clf_token, cfg, n_class)
<del> else:
<del> raise ValueError("task_head_type is expected to be 'multiple_choice' "
<del> "'similarity', 'inference' or ('classification', n_class) "
<del> f"got {task_head_type}.")
<add> def set_num_special_tokens(self, num_special_tokens):
<add> " Update input and output embeddings with new embedding matrice "
<add> self.transformer.set_num_special_tokens(num_special_tokens)
<add> self.lm_head.set_embeddings_weights(self.transformer.embed.weight)
<ide>
<del> def forward(self, x):
<add> def forward(self, x, lm_labels=None, clf_labels=None):
<ide> h = self.transformer(x)
<ide> lm_logits = self.lm_head(h)
<del> task_logits = self.task_head(h, x)
<del>
<del> return lm_logits, task_logits
<del>
<del>
<del>class dotdict(dict):
<del> """dot.notation access to dictionary attributes"""
<del> __getattr__ = dict.get
<del> __setattr__ = dict.__setitem__
<del> __delattr__ = dict.__delitem__
<del>
<del>
<del>DEFAULT_CONFIG = dotdict({
<del> 'n_embd': 768,
<del> 'n_head': 12,
<del> 'n_layer': 12,
<del> 'embd_pdrop': 0.1,
<del> 'attn_pdrop': 0.1,
<del> 'resid_pdrop': 0.1,
<del> 'afn': 'gelu',
<del> 'clf_pdrop': 0.1})
<add> clf_logits = self.clf_head(h, x)
<add> losses = []
<add> if lm_labels is not None:
<add> loss_fct = CrossEntropyLoss()
<add> losses.append(loss_fct(lm_logits, lm_labels))
<add> if clf_labels is not None:
<add> loss_fct = CrossEntropyLoss()
<add> losses.append(loss_fct(clf_logits, clf_labels))
<add> if losses:
<add> return losses
<add> return lm_logits, clf_logits
<ide><path>pytorch_pretrained_bert/optimization_openai.py
<add># coding=utf-8
<add># Copyright 2018 The Open AI Team Authors and The HugginFace Inc. team.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>"""PyTorch optimization for OpenAI GPT model."""
<add>
<ide> import math
<ide> import torch
<ide> from torch.optim import Optimizer
<add>from torch.optim.optimizer import required
<ide> from torch.nn.utils import clip_grad_norm_
<ide>
<ide> def warmup_cosine(x, warmup=0.002):
<ide> def warmup_linear(x, warmup=0.002):
<ide> class OpenAIAdam(Optimizer):
<ide> """Implements Open AI version of Adam algorithm with weight decay fix.
<ide> """
<del> def __init__(self, params, lr, schedule, warmup, t_total,
<del> b1=0.9, b2=0.999, e=1e-8, l2=0,
<add> def __init__(self, params, lr=required, schedule='warmup_linear', warmup=-1, t_total=-1,
<add> b1=0.9, b2=0.999, e=1e-8, weight_decay=0,
<ide> vector_l2=False, max_grad_norm=-1, **kwargs):
<del> if not 0.0 <= lr:
<del> raise ValueError("Invalid learning rate: {}".format(lr))
<add> if lr is not required and lr < 0.0:
<add> raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
<ide> if schedule not in SCHEDULES:
<ide> raise ValueError("Invalid schedule parameter: {}".format(schedule))
<del> if not 0 <= warmup:
<del> raise ValueError("Invalid warmup: {}".format(warmup))
<add> if not 0.0 <= warmup < 1.0 and not warmup == -1:
<add> raise ValueError("Invalid warmup: {} - should be in [0.0, 1.0[ or -1".format(warmup))
<ide> if not 0.0 <= b1 < 1.0:
<ide> raise ValueError("Invalid b1 parameter: {}".format(b1))
<ide> if not 0.0 <= b2 < 1.0:
<ide> raise ValueError("Invalid b2 parameter: {}".format(b2))
<del> if not 0.0 <= e:
<add> if not e >= 0.0:
<ide> raise ValueError("Invalid epsilon value: {}".format(e))
<ide> defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total,
<del> b1=b1, b2=b2, e=e, l2=l2, vector_l2=vector_l2,
<add> b1=b1, b2=b2, e=e, weight_decay=weight_decay, vector_l2=vector_l2,
<ide> max_grad_norm=max_grad_norm)
<ide> super(OpenAIAdam, self).__init__(params, defaults)
<ide>
<add> def get_lr(self):
<add> lr = []
<add> for group in self.param_groups:
<add> for p in group['params']:
<add> state = self.state[p]
<add> if len(state) == 0:
<add> return [0]
<add> if group['t_total'] != -1:
<add> schedule_fct = SCHEDULES[group['schedule']]
<add> lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])
<add> else:
<add> lr_scheduled = group['lr']
<add> lr.append(lr_scheduled)
<add> return lr
<add>
<ide> def step(self, closure=None):
<ide> """Performs a single optimization step.
<ide>
<ide> def step(self, closure=None):
<ide> bias_correction1 = 1 - beta1 ** state['step']
<ide> bias_correction2 = 1 - beta2 ** state['step']
<ide>
<del> schedule_fct = SCHEDULES[group['schedule']]
<del> lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])
<add> if group['t_total'] != -1:
<add> schedule_fct = SCHEDULES[group['schedule']]
<add> lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])
<add> else:
<add> lr_scheduled = group['lr']
<add>
<ide> step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1
<ide>
<ide> p.data.addcdiv_(-step_size, exp_avg, denom)
<ide>
<ide> # Add weight decay at the end (fixed version)
<del> if (len(p.size()) > 1 or group['vector_l2']) and group['l2'] > 0:
<del> p.data.add_(-lr_scheduled * group['l2'], p.data)
<add> if (len(p.size()) > 1 or group['vector_l2']) and group['weight_decay'] > 0:
<add> p.data.add_(-lr_scheduled * group['weight_decay'], p.data)
<ide>
<ide> return loss
<ide><path>pytorch_pretrained_bert/tokenization_openai.py
<add># coding=utf-8
<add># Copyright 2018 The Open AI Team Authors and The HugginFace Inc. team.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>"""Tokenization classes for OpenAI GPT."""
<add>import os
<ide> import re
<del>import ftfy
<ide> import json
<del>import spacy
<del>
<ide> from tqdm import tqdm
<add>import logging
<add>
<add>from .file_utils import cached_path
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>PRETRAINED_VOCAB_ARCHIVE_MAP = {
<add> 'openai-gpt': "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-vocab.json",
<add>}
<add>PRETRAINED_MERGES_ARCHIVE_MAP = {
<add> 'openai-gpt': "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-merges.txt",
<add>}
<add>PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP = {
<add> 'openai-gpt': 512,
<add>}
<add>VOCAB_NAME = 'vocab.json'
<add>MERGES_NAME = 'merges.txt'
<ide>
<ide> def get_pairs(word):
<ide> """
<ide> def text_standardize(text):
<ide> text = re.sub(r'[^\S\n]+', ' ', text)
<ide> return text.strip()
<ide>
<del>class TextEncoder(object):
<add>class OpenAIGPTTokenizer(object):
<ide> """
<ide> mostly a wrapper for a public python bpe tokenizer
<ide> """
<add> @classmethod
<add> def from_pretrained(cls, pretrained_model_name, cache_dir=None, *inputs, **kwargs):
<add> """
<add> Instantiate a PreTrainedBertModel from a pre-trained model file.
<add> Download and cache the pre-trained model file if needed.
<add> """
<add> if pretrained_model_name in PRETRAINED_VOCAB_ARCHIVE_MAP:
<add> vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name]
<add> merges_file = PRETRAINED_MERGES_ARCHIVE_MAP[pretrained_model_name]
<add> else:
<add> vocab_file = pretrained_model_name
<add> if os.path.isdir(vocab_file):
<add> vocab_file = os.path.join(vocab_file, VOCAB_NAME)
<add> merges_file = os.path.join(vocab_file, MERGES_NAME)
<add> # redirect to the cache, if necessary
<add> try:
<add> resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir)
<add> resolved_merges_file = cached_path(merges_file, cache_dir=cache_dir)
<add> except FileNotFoundError:
<add> logger.error(
<add> "Model name '{}' was not found in model name list ({}). "
<add> "We assumed '{}' was a path or url but couldn't find any file "
<add> "associated to this path or url.".format(
<add> pretrained_model_name,
<add> ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()),
<add> vocab_file))
<add> return None
<add> if resolved_vocab_file == vocab_file and resolved_merges_file == merges_file:
<add> logger.info("loading vocabulary file {}".format(vocab_file))
<add> logger.info("loading merges file {}".format(merges_file))
<add> else:
<add> logger.info("loading vocabulary file {} from cache at {}".format(
<add> vocab_file, resolved_vocab_file))
<add> logger.info("loading merges file {} from cache at {}".format(
<add> merges_file, resolved_merges_file))
<add> if pretrained_model_name in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP:
<add> # if we're using a pretrained model, ensure the tokenizer wont index sequences longer
<add> # than the number of positional embeddings
<add> max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name]
<add> kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)
<add> # Instantiate tokenizer.
<add> tokenizer = cls(resolved_vocab_file, resolved_merges_file, *inputs, **kwargs)
<add> return tokenizer
<add>
<add> def __init__(self, vocab_file, merges_file):
<add> try:
<add> import ftfy
<add> import spacy
<add> except ImportError:
<add> raise ImportError("Please install ftfy and spacy to use OpenAI GPT tokenizer.")
<ide>
<del> def __init__(self, encoder_path, bpe_path):
<ide> self.nlp = spacy.load('en', disable=['parser', 'tagger', 'ner', 'textcat'])
<del> self.encoder = json.load(open(encoder_path))
<add> self.encoder = json.load(open(vocab_file))
<ide> self.decoder = {v:k for k,v in self.encoder.items()}
<del> merges = open(bpe_path, encoding='utf-8').read().split('\n')[1:-1]
<add> merges = open(merges_file, encoding='utf-8').read().split('\n')[1:-1]
<ide> merges = [tuple(merge.split()) for merge in merges]
<ide> self.bpe_ranks = dict(zip(merges, range(len(merges))))
<ide> self.cache = {}
<ide> def bpe(self, token):
<ide> self.cache[token] = word
<ide> return word
<ide>
<del> def encode(self, texts, verbose=True):
<add> def tokenize(self, texts, verbose=True):
<ide> texts_tokens = []
<ide> if verbose:
<ide> for text in tqdm(texts, ncols=80, leave=False):
<ide><path>setup.py
<ide>
<ide> setup(
<ide> name="pytorch_pretrained_bert",
<del> version="0.4.0",
<del> author="Thomas Wolf, Victor Sanh, Tim Rault, Google AI Language Team Authors",
<add> version="0.5.0",
<add> author="Thomas Wolf, Victor Sanh, Tim Rault, Google AI Language Team Authors, Open AI team Authors",
<ide> author_email="[email protected]",
<ide> description="PyTorch version of Google AI BERT model with script to load Google pre-trained models",
<ide> long_description=open("README.md", "r", encoding='utf-8').read(),
<ide> 'tqdm'],
<ide> entry_points={
<ide> 'console_scripts': [
<del> "pytorch_pretrained_bert=pytorch_pretrained_bert.__main__:main"
<add> "pytorch_pretrained_bert=pytorch_pretrained_bert.__main__:main",
<ide> ]
<ide> },
<ide> python_requires='>=3.5.0', | 8 |
PHP | PHP | convert rule object to string once | 05e4e9e43857adacffd87f4066a10b2ceccae774 | <ide><path>src/Illuminate/Validation/ValidationRuleParser.php
<ide> protected function explodeExplicitRule($rule)
<ide> if (is_string($rule)) {
<ide> return explode('|', $rule);
<ide> } elseif (is_object($rule)) {
<del> return [$rule];
<add> return [strval($rule)];
<ide> } else {
<del> return $rule;
<add> return array_map('strval', $rule);
<ide> }
<ide> }
<ide> | 1 |
Java | Java | fix crash when removing root nodes | 39b68903463062f69c9120fab7e79fa2735b0b07 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> public synchronized void manageChildren(
<ide> tagsToDelete));
<ide> }
<ide> if (indexToRemove >= viewManager.getChildCount(viewToManage)) {
<add> if (mRootTags.get(tag) && viewManager.getChildCount(viewToManage) == 0) {
<add> // This root node has already been removed (likely due to a threading issue caused by
<add> // async js execution). Ignore this root removal.
<add> return;
<add> }
<ide> throw new IllegalViewOperationException(
<ide> "Trying to remove a view index above child " +
<ide> "count " + indexToRemove + " view tag: " + tag + "\n detail: " + | 1 |
PHP | PHP | make exceptions raised by plugincollection better | 7be7aa393c3fb4693180351ceeb86288a3869f7f | <ide><path>src/Core/PluginCollection.php
<ide> namespace Cake\Core;
<ide>
<ide> use ArrayIterator;
<add>use Cake\Core\Exception\MissingPluginException;
<ide> use Countable;
<ide> use InvalidArgumentException;
<ide> use IteratorAggregate;
<ide> public function has($name)
<ide> *
<ide> * @param string $name The plugin to get.
<ide> * @return \Cake\Core\PluginInterface The plugin.
<del> * @throws \InvalidArgumentException when unknown plugins are fetched.
<add> * @throws \Cake\Core\Exception\MissingPluginException when unknown plugins are fetched.
<ide> */
<ide> public function get($name)
<ide> {
<ide> if (!$this->has($name)) {
<del> throw new InvalidArgumentException("`$name` is not a loaded plugin.");
<add> throw new MissingPluginException(['plugin' => $name]);
<ide> }
<ide>
<ide> return $this->plugins[$name];
<ide><path>tests/TestCase/Core/PluginCollectionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Core;
<ide>
<add>use Cake\Core\Exception\MissingPluginException;
<ide> use Cake\Core\PluginCollection;
<ide> use Cake\Core\PluginInterface;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testGet()
<ide>
<ide> public function testGetInvalid()
<ide> {
<del> $this->expectException(InvalidArgumentException::class);
<add> $this->expectException(MissingPluginException::class);
<ide>
<ide> $plugins = new PluginCollection();
<ide> $plugins->get('Invalid'); | 2 |
Go | Go | add disable flag for plugin install | 22e781e8e3ae1d1ab62ddcda983cabfde2e08ad4 | <ide><path>api/client/plugin/install.go
<ide> import (
<ide> type pluginOptions struct {
<ide> name string
<ide> grantPerms bool
<add> disable bool
<ide> }
<ide>
<ide> func newInstallCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> func newInstallCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide>
<ide> flags := cmd.Flags()
<ide> flags.BoolVar(&options.grantPerms, "grant-all-permissions", true, "grant all permissions necessary to run the plugin")
<add> flags.BoolVar(&options.disable, "disable", false, "do not enable the plugin on install")
<ide>
<ide> return cmd
<ide> }
<ide> func runInstall(dockerCli *client.DockerCli, opts pluginOptions) error {
<ide>
<ide> requestPrivilege := dockerCli.RegistryAuthenticationPrivilegedFunc(repoInfo.Index, "plugin install")
<ide>
<del> // TODO: pass acceptAllPermissions and noEnable flag
<ide> options := types.PluginInstallOptions{
<ide> RegistryAuth: encodedAuth,
<del> Disabled: false,
<add> Disabled: opts.disable,
<ide> AcceptAllPermissions: opts.grantPerms,
<ide> AcceptPermissionsFunc: acceptPrivileges(dockerCli, opts.name),
<ide> PrivilegeFunc: requestPrivilege,
<ide><path>integration-cli/docker_cli_plugins_test.go
<ide> func (s *DockerSuite) TestPluginBasicOps(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, nameWithTag)
<ide> }
<add>
<add>func (s *DockerSuite) TestPluginInstallDisable(c *check.C) {
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> name := "tiborvass/no-remove"
<add> tag := "latest"
<add> nameWithTag := name + ":" + tag
<add>
<add> _, _, err := dockerCmdWithError("plugin", "install", name, "--disable")
<add> c.Assert(err, checker.IsNil)
<add>
<add> out, _, err := dockerCmdWithError("plugin", "ls")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(out, checker.Contains, "false")
<add>
<add> out, _, err = dockerCmdWithError("plugin", "remove", nameWithTag)
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(out, checker.Contains, nameWithTag)
<add>} | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.