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
Ruby
Ruby
allow sass-rails greater than 5.x in new apps
2e4c65e3afb18fc9a84d4d3ae893209efce27592
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def rails_version_specifier(gem_version = Rails.gem_version) <ide> def assets_gemfile_entry <ide> return [] if options[:skip_sprockets] <ide> <del> GemfileEntry.version("sass-rails", "~> 5.0", "Use SCSS for stylesheets") <add> GemfileEntry.version("sass-rails", "~> 5", "Use SCSS for stylesheets") <ide> end <ide> <ide> def webpacker_gemfile_entry
1
PHP
PHP
display offending model and column
a02fd82db2a25b67c6a65d16ce3c8dbcf7ac8e95
<ide><path>lib/Cake/Model/CakeSchema.php <ide> protected function _columns(&$Obj) { <ide> $value['key'] = 'primary'; <ide> } <ide> if (!isset($db->columns[$value['type']])) { <del> trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s does not exist in DBO', $value['type']), E_USER_NOTICE); <add> trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s for %s.%s does not exist in DBO', $value['type'], $Obj->name, $name), E_USER_NOTICE); <ide> continue; <ide> } else { <ide> $defaultCol = $db->columns[$value['type']];
1
Javascript
Javascript
fix inaccurate comments in matrix4
c11662b22ffb2babba1754854f0449f956411188
<ide><path>src/math/Matrix4.js <ide> Object.assign( Matrix4.prototype, { <ide> <ide> } <ide> <del> // last column <add> // bottom row <ide> te[ 3 ] = 0; <ide> te[ 7 ] = 0; <ide> te[ 11 ] = 0; <ide> <del> // bottom row <add> // last column <ide> te[ 12 ] = 0; <ide> te[ 13 ] = 0; <ide> te[ 14 ] = 0; <ide> Object.assign( Matrix4.prototype, { <ide> te[ 6 ] = ( yz + wx ) * sy; <ide> te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; <ide> <del> // last column <add> // bottom row <ide> te[ 3 ] = 0; <ide> te[ 7 ] = 0; <ide> te[ 11 ] = 0; <ide> <del> // bottom row <add> // last column <ide> te[ 12 ] = position.x; <ide> te[ 13 ] = position.y; <ide> te[ 14 ] = position.z;
1
Javascript
Javascript
remove https redirect
00c3a97fa0db5ec1bc89d19f6568dea3a699b245
<ide><path>server/boot/redirectHttps.js <del>var path = require('path'); <del>var loopback = require('loopback'); <del>var express = require('express'); <del> <del>var port = 1337; <del> <del>// this will listen to traffic on port 1337 <del>// The purpose is to redirect any user who is direct to https <del>// instead of http by mistake. Our nginx proxy server will listen <del>// for https traffic and serve from this port on this server. <del>// the view being send will have a short timeout and a redirect <del>module.exports = function(loopbackApp) { <del> var app = express(); <del> app.set('view engine', 'jade'); <del> // views in ../views' <del> app.set('views', path.join(__dirname, '..')); <del> <del> // server static files <del> app.use(loopback.static(path.join( <del> __dirname, <del> '../', <del> '../public' <del> ))); <del> <del> // all traffic will be redirected on page load; <del> app.use(function(req, res) { <del> return res.render('views/redirect-https'); <del> }); <del> <del> loopbackApp.once('started', function() { <del> app.listen(port, function() { <del> console.log('https redirect listening on port %s', port); <del> }); <del> }); <del>};
1
Text
Text
add link to 16 pos tags model
c2cf19294359b7b3afbc8ac9cbc6d6dbed53ab11
<ide><path>model_cards/mrm8488/bert-spanish-cased-finetuned-pos/README.md <ide> I preprocessed the dataset and splitted it as train / dev (80/20) <ide> <ide> - [Fine-tune on NER script provided by Huggingface](https://github.com/huggingface/transformers/blob/master/examples/run_ner.py) <ide> <del>- Labels covered: <add>- **60** Labels covered: <ide> <ide> ``` <ide> AO, AQ, CC, CS, DA, DD, DE, DI, DN, DP, DT, Faa, Fat, Fc, Fd, Fe, Fg, Fh, Fia, Fit, Fp, Fpa, Fpt, Fs, Ft, Fx, Fz, I, NC, NP, P0, PD, PI, PN, PP, PR, PT, PX, RG, RN, SP, VAI, VAM, VAN, VAP, VAS, VMG, VMI, VMM, VMN, VMP, VMS, VSG, VSI, VSM, VSN, VSP, VSS, Y and Z <ide> nlp_pos(text) <ide> ``` <ide> ![model in action](https://media.giphy.com/media/jVC9m1cNrdIWuAAtjy/giphy.gif) <ide> <add>16 POS tags version also available [here](https://huggingface.co/mrm8488/bert-spanish-cased-finetuned-pos-16-tags) <add> <ide> <ide> > Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <ide>
1
Text
Text
remove a dead link and an archived example
91aafd8c3fb14f5a1ab689c1fb30270483bed6a3
<ide><path>docs/faq/Miscellaneous.md <ide> <ide> Yes, lots of them! To name just a few: <ide> <del>- [Twitter's mobile site](https://twitter.com/necolas/status/727538799966715904) <add>- [Twitter's mobile site](https://mobile.twitter.com/) <ide> - [Wordpress's new admin page](https://github.com/Automattic/wp-calypso) <del>- [Firefox's new debugger](https://github.com/jlongster/debugger.html) <del>- [Mozilla's experimental browser testbed](https://github.com/mozilla/tofino) <add>- [Firefox's new debugger](https://github.com/devtools-html/debugger.html) <ide> - [The HyperTerm terminal application](https://github.com/zeit/hyperterm) <ide> <ide> And many, many more! The Redux Addons Catalog has **[a list of Redux-based applications and examples](https://github.com/markerikson/redux-ecosystem-links/blob/master/apps-and-examples.md)** that points to a variety of actual applications, large and small.
1
Mixed
Text
fix some minor typos [ci skip]
82de1eda7c8a8f11b65d8edf70c4af7ce08507ec
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Adam Williams*, *Yves Senn* <ide> <del>* Fix bug where `has_one` associaton record update result in crash, when replaced with itself. <add>* Fix bug where `has_one` association record update result in crash, when replaced with itself. <ide> <ide> Fixes #12834. <ide> <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def test_do_not_call_callbacks_for_delete_all <ide> car = Car.create(:name => 'honda') <ide> car.funky_bulbs.create! <ide> assert_nothing_raised { car.reload.funky_bulbs.delete_all } <del> assert_equal 0, Bulb.count, "bulbs should have been deleted using :delete_all strategey" <add> assert_equal 0, Bulb.count, "bulbs should have been deleted using :delete_all strategy" <ide> end <ide> <ide> def test_building_the_associated_object_with_implicit_sti_base_class
2
Mixed
Python
unlock inceptionresnetv2 for cntk
71a791cb71ef7080ea150152633a90e7821070af
<ide><path>docs/templates/applications.md <ide> keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=True, weigh <ide> <ide> Inception-ResNet V2 model, with weights pre-trained on ImageNet. <ide> <del>This model is available for both the Theano and TensorFlow backend (but not CNTK), and can be built both <add>This model is available for Theano, TensorFlow and CNTK backends, and can be built both <ide> with `'channels_first'` data format (channels, height, width) or `'channels_last'` data format (height, width, channels). <ide> <ide> The default input size for this model is 299x299. <ide><path>keras/applications/inception_resnet_v2.py <ide> def InceptionResNetV2(include_top=True, <ide> set `"image_data_format": "channels_last"` in your Keras config <ide> at `~/.keras/keras.json`. <ide> <del> The model and the weights are compatible with both TensorFlow and Theano <del> backends (but not CNTK). The data format convention used by the model is <add> The model and the weights are compatible with TensorFlow, Theano and <add> CNTK backends. The data format convention used by the model is <ide> the one specified in your Keras config file. <ide> <ide> Note that the default input image size for this model is 299x299, instead <ide> def InceptionResNetV2(include_top=True, <ide> # Raises <ide> ValueError: in case of invalid argument for `weights`, <ide> or invalid input shape. <del> RuntimeError: If attempting to run this model with an unsupported backend. <ide> """ <del> if K.backend() in {'cntk'}: <del> raise RuntimeError(K.backend() + ' backend is currently unsupported for this model.') <del> <ide> if weights not in {'imagenet', None}: <ide> raise ValueError('The `weights` argument should be either ' <ide> '`None` (random initialization) or `imagenet` ' <ide><path>tests/keras/applications/applications_test.py <ide> import pytest <add>from multiprocessing import Process, Queue <ide> from keras.utils.test_utils import keras_test <ide> from keras.utils.test_utils import layer_test <ide> from keras.utils.generic_utils import CustomObjectScope <ide> def test_inceptionv3_variable_input_channels(): <ide> <ide> <ide> @keras_test <del>@pytest.mark.skipif((K.backend() == 'cntk'), <del> reason='InceptionResNetV2 is not supported on CNTK') <ide> def test_inceptionresnetv2(): <del> model = applications.InceptionResNetV2(weights=None) <del> assert model.output_shape == (None, 1000) <add> # Create model in a subprocess so that the memory consumed by InceptionResNetV2 will be <add> # released back to the system after this test (to deal with OOM error on CNTK backend) <add> # TODO: remove the use of multiprocessing from these tests once a memory clearing mechanism <add> # is implemented in the CNTK backend <add> def target(queue): <add> model = applications.InceptionResNetV2(weights=None) <add> queue.put(model.output_shape) <add> queue = Queue() <add> p = Process(target=target, args=(queue,)) <add> p.start() <add> p.join() <add> <add> # The error in a subprocess won't propagate to the main process, so we check if the model <add> # is successfully created by checking if the output shape has been put into the queue <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, 1000) <ide> <ide> <ide> @keras_test <del>@pytest.mark.skipif((K.backend() == 'cntk'), <del> reason='InceptionResNetV2 is not supported on CNTK') <ide> def test_inceptionresnetv2_notop(): <add> def target(queue): <add> model = applications.InceptionResNetV2(weights=None, include_top=False) <add> queue.put(model.output_shape) <add> <ide> global_image_data_format = K.image_data_format() <add> queue = Queue() <ide> <ide> K.set_image_data_format('channels_first') <del> model = applications.InceptionResNetV2(weights=None, include_top=False) <del> assert model.output_shape == (None, 1536, None, None) <add> p = Process(target=target, args=(queue,)) <add> p.start() <add> p.join() <add> K.set_image_data_format(global_image_data_format) <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, 1536, None, None) <ide> <ide> K.set_image_data_format('channels_last') <del> model = applications.InceptionResNetV2(weights=None, include_top=False) <del> assert model.output_shape == (None, None, None, 1536) <del> <add> p = Process(target=target, args=(queue,)) <add> p.start() <add> p.join() <ide> K.set_image_data_format(global_image_data_format) <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, None, None, 1536) <ide> <ide> <ide> @keras_test <del>@pytest.mark.skipif((K.backend() == 'cntk'), <del> reason='InceptionResNetV2 is not supported on CNTK') <ide> def test_inceptionresnetv2_pooling(): <del> model = applications.InceptionResNetV2(weights=None, include_top=False, pooling='avg') <del> assert model.output_shape == (None, 1536) <add> def target(queue): <add> model = applications.InceptionResNetV2(weights=None, include_top=False, pooling='avg') <add> queue.put(model.output_shape) <add> queue = Queue() <add> p = Process(target=target, args=(queue,)) <add> p.start() <add> p.join() <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, 1536) <ide> <ide> <ide> @keras_test <del>@pytest.mark.skipif((K.backend() == 'cntk'), <del> reason='InceptionResNetV2 is not supported on CNTK') <ide> def test_inceptionresnetv2_variable_input_channels(): <del> global_image_data_format = K.image_data_format() <del> <del> K.set_image_data_format('channels_first') <del> input_shape = (1, None, None) <del> model = applications.InceptionResNetV2(weights=None, include_top=False, input_shape=input_shape) <del> assert model.output_shape == (None, 1536, None, None) <del> input_shape = (4, None, None) <del> model = applications.InceptionResNetV2(weights=None, include_top=False, input_shape=input_shape) <del> assert model.output_shape == (None, 1536, None, None) <del> <del> K.set_image_data_format('channels_last') <del> input_shape = (None, None, 1) <del> model = applications.InceptionResNetV2(weights=None, include_top=False, input_shape=input_shape) <del> assert model.output_shape == (None, None, None, 1536) <del> input_shape = (None, None, 4) <del> model = applications.InceptionResNetV2(weights=None, include_top=False, input_shape=input_shape) <del> assert model.output_shape == (None, None, None, 1536) <del> <del> K.set_image_data_format(global_image_data_format) <add> def target(queue, input_shape): <add> model = applications.InceptionResNetV2(weights=None, include_top=False, input_shape=input_shape) <add> queue.put(model.output_shape) <add> <add> queue = Queue() <add> p = Process(target=target, args=(queue, (None, None, 1))) <add> p.start() <add> p.join() <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, None, None, 1536) <add> <add> p = Process(target=target, args=(queue, (None, None, 4))) <add> p.start() <add> p.join() <add> assert not queue.empty(), 'Model creation failed.' <add> model_output_shape = queue.get_nowait() <add> assert model_output_shape == (None, None, None, 1536) <ide> <ide> <ide> @keras_test
3
Text
Text
add link to coding rules
b3acddea37aca9f8e3f881100b5af657194d262a
<ide><path>CONTRIBUTING.md <ide> Before you submit your pull request consider the following guidelines: <ide> ``` <ide> <ide> * Create your patch, including appropriate test cases. <del>* Follow our Coding Rules <add>* Follow our [Coding Rules](#coding-rules) <ide> * Commit your changes and create a descriptive commit message (the <ide> commit message is used to generate release notes, please check out our <ide> [commit message conventions](#commit-message-format) and our commit message presubmit hook <ide> You can find out more detailed information about contributing in the <ide> [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# <ide> [github-pr-helper]: https://chrome.google.com/webstore/detail/github-pr-helper/mokbklfnaddkkbolfldepnkfmanfhpen <ide> <del> <ide> [![Analytics](https://ga-beacon.appspot.com/UA-8594346-11/angular.js/CONTRIBUTING.md?pixel)](https://github.com/igrigorik/ga-beacon)
1
Ruby
Ruby
convert `references` to kwargs
a9c0c46263dcafcf01944246e31cbe5650ee605e
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> def timestamps(*args) <ide> # t.belongs_to(:supplier, polymorphic: true) <ide> # <ide> # See SchemaStatements#add_reference <del> def references(*args) <del> options = args.extract_options! <del> polymorphic = options.delete(:polymorphic) <del> index_options = options.delete(:index) <del> type = options.delete(:type) || :integer <add> def references( <add> *args, <add> polymorphic: false, <add> index: false, <add> type: :integer, <add> **options <add> ) <add> polymorphic_options = polymorphic.is_a?(Hash) ? polymorphic : options <add> index_options = index.is_a?(Hash) ? index : {} <ide> args.each do |col| <ide> column("#{col}_id", type, options) <del> column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic <del> index(polymorphic ? %w(type id).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options <add> <add> if polymorphic <add> column("#{col}_type", :string, polymorphic_options) <add> end <add> <add> if index <add> self.index(polymorphic ? %w(type id).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options) <add> end <ide> end <ide> end <ide> alias :belongs_to :references
1
Javascript
Javascript
use module.rules instead of module.loaders
645867ed7e93b41e789ab10b67bc743091cf46e2
<ide><path>examples/code-splitted-css-bundle/webpack.config.js <ide> var ExtractTextPlugin = require("extract-text-webpack-plugin"); <ide> module.exports = { <ide> module: { <del> loaders: [ <add> rules: [ <ide> { <ide> test: /\.css$/, <ide> use: ExtractTextPlugin.extract({ <ide><path>examples/coffee-script/webpack.config.js <ide> module.exports = { <ide> module: { <del> loaders: [ <add> rules: [ <ide> { test: /\.coffee$/, loader: "coffee-loader" } <ide> ] <ide> }, <ide><path>examples/css-bundle/webpack.config.js <ide> var ExtractTextPlugin = require("extract-text-webpack-plugin"); <ide> module.exports = { <ide> module: { <del> loaders: [ <add> rules: [ <ide> { <ide> test: /\.css$/, <ide> use: ExtractTextPlugin.extract({ <ide><path>examples/loader/webpack.config.js <ide> module.exports = { <ide> module: { <del> loaders: [ <add> rules: [ <ide> { test: /\.css$/, loader: "css-loader" } <ide> ] <ide> } <ide><path>examples/multiple-entry-points-commons-chunk-css-bundle/webpack.config.js <ide> module.exports = { <ide> filename: "[name].js" <ide> }, <ide> module: { <del> loaders: [ <add> rules: [ <ide> { <ide> test: /\.css$/, <ide> use: ExtractTextPlugin.extract({ <ide><path>test/configCases/extract-text/issue-14/webpack.config.js <ide> module.exports = { <ide> __filename: false <ide> }, <ide> module: { <del> loaders: [ <add> rules: [ <ide> { <ide> test: /\.css$/, <ide> loader: ETP.extract("css-loader") <ide><path>test/configCases/target/webworker/webpack.config.js <ide> module.exports = { <ide> hints: false <ide> }, <ide> module: { <del> loaders: [ <add> rules: [ <ide> { test: /\.json$/, loader: "json-loader" } <ide> ] <ide> }, <ide><path>test/statsCases/exclude-with-loader/webpack.config.js <ide> module.exports = { <ide> ] <ide> }, <ide> module: { <del> loaders: [{ <add> rules: [{ <ide> test: /\.txt/, <ide> loader: "raw-loader" <ide> }] <ide><path>test/statsCases/separate-css-bundle/webpack.config.js <ide> var path = require("path"); <ide> var ExtractTextPlugin = require("extract-text-webpack-plugin"); <ide> <ide> var moduleConfig = { <del> loaders: [ <add> rules: [ <ide> { <ide> test: /\.css$/, <ide> use: ExtractTextPlugin.extract({
9
Go
Go
add support for 20.10 cli
601707a655071e4ab2d3c7ee3f7f868af1774321
<ide><path>integration-cli/cli/cli.go <ide> type CmdOperator func(*icmd.Cmd) func() <ide> <ide> // DockerCmd executes the specified docker command and expect a success <ide> func DockerCmd(t testing.TB, args ...string) *icmd.Result { <add> t.Helper() <ide> return Docker(Args(args...)).Assert(t, icmd.Success) <ide> } <ide> <ide><path>integration-cli/docker_cli_push_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/types/versions" <ide> "github.com/docker/docker/integration-cli/cli/build" <ide> "gotest.tools/v3/assert" <ide> "gotest.tools/v3/icmd" <ide> func testPushMultipleTags(c *testing.T) { <ide> // tag the image and upload it to the private registry <ide> dockerCmd(c, "tag", "busybox", repoTag1) <ide> dockerCmd(c, "tag", "busybox", repoTag2) <del> dockerCmd(c, "push", repoName) <add> <add> args := []string{"push"} <add> if versions.GreaterThanOrEqualTo(DockerCLIVersion(c), "20.10.0") { <add> // 20.10 CLI removed implicit push all tags and requires the "--all" flag <add> args = append(args, "--all-tags") <add> } <add> args = append(args, repoName) <add> <add> dockerCmd(c, args...) <ide> <ide> imageAlreadyExists := ": Image already exists" <ide> <ide><path>integration-cli/docker_utils_test.go <ide> func dockerCmdWithError(args ...string) (string, int, error) { <ide> <ide> // Deprecated: use cli.Docker or cli.DockerCmd <ide> func dockerCmd(c testing.TB, args ...string) (string, int) { <add> c.Helper() <ide> result := cli.DockerCmd(c, args...) <ide> return result.Combined(), result.ExitCode <ide> } <ide><path>integration-cli/requirements_test.go <ide> func TODOBuildkit() bool { <ide> return os.Getenv("DOCKER_BUILDKIT") == "" <ide> } <ide> <add>func DockerCLIVersion(t testing.TB) string { <add> out, _ := dockerCmd(t, "--version") <add> version := strings.Fields(out) <add> if len(version) < 3 { <add> t.Fatal("unknown version output", version) <add> } <add> return version[2] <add>} <add> <ide> // testRequires checks if the environment satisfies the requirements <ide> // for the test to run or skips the tests. <ide> func testRequires(t *testing.T, requirements ...requirement.Test) {
4
Python
Python
dump version info and exit
030616c9b50dcb891b6075af832cacb55269b686
<ide><path>celery/bin/celeryd.py <ide> <ide> TASK_LIST_FMT = """ . tasks ->\n%s""" <ide> <add> <add>def dump_version(*args): <add> print("celeryd v%s" % celery.__version__) <add> sys.exit(0) <add> <add> <ide> OPTION_LIST = ( <ide> optparse.make_option('-c', '--concurrency', <ide> default=conf.CELERYD_CONCURRENCY, <ide> action="store", dest="concurrency", type="int", <ide> help="Number of child processes processing the queue."), <add> optparse.make_option('-V', '--version', <add> action="callback", callback=dump_version, <add> help="Show version information and exit."), <ide> optparse.make_option('--discard', default=False, <ide> action="store_true", dest="discard", <ide> help="Discard all waiting tasks before the server is started. "
1
Text
Text
fix links in readme
f26ce6992e683a49799515e86086cf66599e2762
<ide><path>README.md <ide> A command-line interface is provided to convert a TensorFlow checkpoint in a PyT <ide> <ide> ### BERT <ide> <del>You can convert any TensorFlow checkpoint for BERT (in particular [the pre-trained models released by Google](https://github.com/google-research/bert#pre-trained-models)) in a PyTorch save file by using the [`./pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py`](convert_tf_checkpoint_to_pytorch.py) script. <add>You can convert any TensorFlow checkpoint for BERT (in particular [the pre-trained models released by Google](https://github.com/google-research/bert#pre-trained-models)) in a PyTorch save file by using the [`convert_tf_checkpoint_to_pytorch.py`](./pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py ) script. <ide> <del>This CLI takes as input a TensorFlow checkpoint (three files starting with `bert_model.ckpt`) and the associated configuration file (`bert_config.json`), and creates a PyTorch model for this configuration, loads the weights from the TensorFlow checkpoint in the PyTorch model and saves the resulting model in a standard PyTorch save file that can be imported using `torch.load()` (see examples in [`extract_features.py`](./examples/extract_features.py), [`run_classifier.py`](./examples/run_classifier.py) and [`run_squad.py`]((./examples/run_squad.py))). <add>This CLI takes as input a TensorFlow checkpoint (three files starting with `bert_model.ckpt`) and the associated configuration file (`bert_config.json`), and creates a PyTorch model for this configuration, loads the weights from the TensorFlow checkpoint in the PyTorch model and saves the resulting model in a standard PyTorch save file that can be imported using `torch.load()` (see examples in [`extract_features.py`](./examples/extract_features.py), [`run_classifier.py`](./examples/run_classifier.py) and [`run_squad.py`](./examples/run_squad.py)). <ide> <ide> You only need to run this conversion script **once** to get a PyTorch model. You can then disregard the TensorFlow checkpoint (the three files starting with `bert_model.ckpt`) but be sure to keep the configuration file (`bert_config.json`) and the vocabulary file (`vocab.txt`) as these are needed for the PyTorch model too. <ide>
1
Go
Go
fix validation for "condition" parameter
0bce64f08d72147b0572f96ac678620d289b4499
<ide><path>api/server/router/container/container_routes.go <ide> func (s *containerRouter) postContainersWait(ctx context.Context, w http.Respons <ide> } <ide> if v := r.Form.Get("condition"); v != "" { <ide> switch container.WaitCondition(v) { <add> case container.WaitConditionNotRunning: <add> waitCondition = containerpkg.WaitConditionNotRunning <ide> case container.WaitConditionNextExit: <ide> waitCondition = containerpkg.WaitConditionNextExit <ide> case container.WaitConditionRemoved: <ide><path>integration/container/wait_test.go <ide> func TestWaitBlocked(t *testing.T) { <ide> }) <ide> } <ide> } <add> <add>func TestWaitConditions(t *testing.T) { <add> defer setupTest(t)() <add> cli := request.NewAPIClient(t) <add> <add> testCases := []struct { <add> doc string <add> waitCond containertypes.WaitCondition <add> expectedCode int64 <add> }{ <add> { <add> doc: "default", <add> expectedCode: 99, <add> }, <add> { <add> doc: "not-running", <add> expectedCode: 99, <add> waitCond: containertypes.WaitConditionNotRunning, <add> }, <add> { <add> doc: "next-exit", <add> expectedCode: 99, <add> waitCond: containertypes.WaitConditionNextExit, <add> }, <add> { <add> doc: "removed", <add> expectedCode: 99, <add> waitCond: containertypes.WaitConditionRemoved, <add> }, <add> } <add> <add> for _, tc := range testCases { <add> tc := tc <add> t.Run(tc.doc, func(t *testing.T) { <add> t.Parallel() <add> ctx := context.Background() <add> opts := []func(*container.TestContainerConfig){ <add> container.WithCmd("sh", "-c", "sleep 1; exit 99"), <add> } <add> if tc.waitCond == containertypes.WaitConditionRemoved { <add> opts = append(opts, container.WithAutoRemove) <add> } <add> containerID := container.Run(ctx, t, cli, opts...) <add> poll.WaitOn(t, container.IsInState(ctx, cli, containerID, "running"), poll.WithTimeout(30*time.Second), poll.WithDelay(100*time.Millisecond)) <add> <add> waitResC, errC := cli.ContainerWait(ctx, containerID, tc.waitCond) <add> select { <add> case err := <-errC: <add> assert.NilError(t, err) <add> case waitRes := <-waitResC: <add> assert.Check(t, is.Equal(tc.expectedCode, waitRes.StatusCode)) <add> } <add> }) <add> } <add>}
2
PHP
PHP
change local database user
b9c69c6d9484d759742100c666367d8327d9f6ae
<ide><path>app/config/local/database.php <ide> 'driver' => 'mysql', <ide> 'host' => 'localhost', <ide> 'database' => 'homestead', <del> 'username' => 'vagrant', <add> 'username' => 'homestead', <ide> 'password' => '', <ide> 'charset' => 'utf8', <ide> 'collation' => 'utf8_unicode_ci', <ide> 'driver' => 'pgsql', <ide> 'host' => 'localhost', <ide> 'database' => 'homestead', <del> 'username' => 'vagrant', <add> 'username' => 'homestead', <ide> 'password' => '', <ide> 'charset' => 'utf8', <ide> 'prefix' => '',
1
Text
Text
create players meeting narrative document
7ccf233bfe319b39361f6152140ce3dd7c0a8c80
<ide><path>guide/english/game-development/player-meets-narrative/index.md <add>--- <add>title: The Game Player Meets Game Conflict Narrative <add>--- <add> <add>The narrative in a game turns its challenges into conflicts. There are several types of game conflicts, and they are similar to the classic types of conflict in literature. <add> <add>## Man versus Man <add> <add>Man versus man is a conflict between people. In games, the player can be in conflict with another player or a computer-generated avatar. Man versus man can also be extended to include two-versus-one scenarios and conflicts between individuals and small groups. <add> <add>Common narratives for man versus man conflicts include: <add> <add> a battle between good and evil <add> a battle for an object <add> a race to a location <add> a scenario of betrayal or revenge <add> a top score or ranking scenario. <add> <add>An example of a game that uses man versus man conflict is Beyond: Two Souls. In this game, the main character, Jodie, struggles for freedom against the head of a paranormal CIA unit that wants to detain her because of her psychic connection to a ghost. <add> <add>## Man versus Environment <add> <add>In man versus environment, the player wants to be in a particular place or state, and must struggle against the environment. Common elements of man versus environment in games include: <add> <add> bad weather <add> locked doors <add> limits of geography (a river you can’t cross) <add> prison <add> security systems. <add> <add>Man versus environment often traps players so they must find a way in or out. Survival-horror games like the Resident Evil series include aspects of man versus environment. In Resident Evil, the player must navigate environments inhabited by zombies. <add> <add>## Man versus Society <add> <add>The man versus society narrative is created when a law or societal code of conduct prevents the player from achieving his goal. The player must struggle against the law or social rule in order to move forward. An example of man versus society is the Grand Theft Auto series, where protagonists advance through the games by improving their rank in a criminal organization. <add> <add>## Man versus Himself <add> <add>In a man versus himself narrative, the character or avatar’s conflict is internal. The conflict could be a moral dilemma or a character struggling with a personal weakness. <add> <add>This is one of the most difficult types of narrative conflicts because of the nature of the game design medium. Games are interactive, so designers want the experience and solutions to come from the player. Man versus himself games are typically third-person games with a developed main character that the player controls, like Max Payne, Alice: Madness Returns or Psychonauts.
1
PHP
PHP
add auth type option
7d974ae23f4a96c318b65840135e6ec9d90a8d38
<ide><path>src/Mailer/Transport/SmtpTransport.php <ide> class SmtpTransport extends AbstractTransport <ide> 'client' => null, <ide> 'tls' => false, <ide> 'keepAlive' => false, <add> 'authType' => null, <ide> ]; <ide> <ide> /** <ide> protected function _bufferResponseLines(array $responseLines): void <ide> $this->_lastResponse = array_merge($this->_lastResponse, $response); <ide> } <ide> <add> /** <add> * Parses the last response line and extract the preferred authentication type. <add> * <add> * @return void <add> */ <add> protected function _parseAuthType(): void <add> { <add> if (!empty($this->_config['authType'])) { <add> return; <add> } <add> <add> $auth = ''; <add> foreach ($this->_lastResponse as $line) { <add> if (empty($line['message']) || substr($line['message'], 0, 5) === 'AUTH ') { <add> $auth = $line['message']; <add> break; <add> } <add> } <add> <add> if (strpos($auth, 'PLAIN') !== false) { <add> $this->_config['authType'] = 'PLAIN'; <add> <add> return; <add> } <add> <add> if (strpos($auth, 'LOGIN') !== false) { <add> $this->_config['authType'] = 'LOGIN'; <add> <add> return; <add> } <add> } <add> <ide> /** <ide> * Connect to SMTP Server <ide> * <ide> protected function _connect(): void <ide> throw new SocketException('SMTP server did not accept the connection.', null, $e2); <ide> } <ide> } <add> <add> $this->_parseAuthType(); <ide> } <ide> <ide> /** <ide> protected function _auth(): void <ide> <ide> $username = $this->_config['username']; <ide> $password = $this->_config['password']; <add> if (empty($this->_options['authType'])) { <add> $replyCode = $this->_authPlain($username, $password); <add> if ($replyCode === '235') { <add> return; <add> } <add> <add> $this->_authLogin($username, $password); <ide> <del> $replyCode = $this->_authPlain($username, $password); <del> if ($replyCode === '235') { <ide> return; <ide> } <ide> <del> $this->_authLogin($username, $password); <add> if ($this->_options['authType'] === 'PLAIN') { <add> $this->_authPlain($username, $password); <add> <add> return; <add> } <add> <add> if ($this->_options['authType'] === 'LOGIN') { <add> $this->_authLogin($username, $password); <add> <add> return; <add> } <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> public function testConnectEhloNoTlsOnRequiredTlsServer(): void <ide> $this->SmtpTransport->connect(); <ide> } <ide> <add> public function testConnectEhloWithAuthPlain(): void <add> { <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <add> <add> $this->socket->expects($this->any()) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n250 AUTH PLAIN LOGIN\r\n", <add> "235 OK\r\n", <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"] <add> ); <add> <add> $this->SmtpTransport->setConfig($this->credentials); <add> $this->SmtpTransport->connect(); <add> $this->assertEquals($this->SmtpTransport->getConfig('authType'), 'PLAIN'); <add> } <add> <add> public function testConnectEhloWithAuthLogin(): void <add> { <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <add> <add> $this->socket->expects($this->any()) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n250 AUTH LOGIN\r\n", <add> "235 OK\r\n", <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["AUTH LOGIN\r\n"], <add> ["bWFyaw==\r\n"], <add> ["c3Rvcnk=\r\n"] <add> ); <add> <add> $this->SmtpTransport->setConfig($this->credentials); <add> $this->SmtpTransport->connect(); <add> $this->assertEquals($this->SmtpTransport->getConfig('authType'), 'LOGIN'); <add> } <add> <ide> /** <ide> * testConnectHelo method <ide> */
2
Text
Text
add resources for data analysis videos
b352f361694c3303a39e7b8ac461a98108b9e43b
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-analysis-example-a.english.md <ide> videoId: nVAaxZ34khk <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-pandas-real-life-example-24fa5bf8" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-analysis-example-b.english.md <ide> videoId: 0kJz0q0pvgQ <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-pandas-real-life-example-24fa5bf8" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-and-visualizations.english.md <ide> videoId: mHjxzFS5_Z0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/data-cleaning-rmotr-freecodecamp-fd76fa59" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-duplicates.english.md <ide> videoId: kj7QqjXhH6A <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/data-cleaning-rmotr-freecodecamp-fd76fa59" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-introduction.english.md <ide> videoId: ovYNhnltVxY <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/data-cleaning-rmotr-freecodecamp-fd76fa59" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-with-dataframes.english.md <ide> videoId: sTMN_pdI6S0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/data-cleaning-rmotr-freecodecamp-fd76fa59" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/how-to-use-jupyter-notebooks-intro.english.md <ide> videoId: h8caJq2Bb9w <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/interactive-jupyterlab-tutorial-ac5fa63f" target='_blank'>Notebook</a> <add>- <a href="https://twitter.com/rmotr_com/status/1122176794696847361" target='_blank'>Twitter Cheat Sheet</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/introduction-to-data-analysis.english.md <ide> videoId: VJrP2FUzKP0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://docs.google.com/presentation/d/1fDpjlyMiOMJyuc7_jMekcYLPP2XlSl1eWw9F7yE7byk" target='_blank'>Slides</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/jupyter-notebooks-cells.english.md <ide> videoId: 5PPegAs9aLA <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/interactive-jupyterlab-tutorial-ac5fa63f" target='_blank'>Notebook</a> <add>- <a href="https://twitter.com/rmotr_com/status/1122176794696847361" target='_blank'>Twitter Cheat Sheet</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/jupyter-notebooks-importing-and-exporting-data.english.md <ide> videoId: k1msxD3JIxE <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/interactive-jupyterlab-tutorial-ac5fa63f" target='_blank'>Notebook</a> <add>- <a href="https://twitter.com/rmotr_com/status/1122176794696847361" target='_blank'>Twitter Cheat Sheet</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-algebra-and-size.english.md <ide> videoId: XAT97YLOKD8 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-arrays.english.md <ide> videoId: VDYVFHBL1AM <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-boolean-arrays.english.md <ide> videoId: N1ttsMmcVMM <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-introduction-a.english.md <ide> videoId: P-JjV6GBCmk <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-introduction-b.english.md <ide> videoId: YIqgrNLAZkA <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-operations.english.md <ide> videoId: eqSVcJbaPdk <ide> ## Description <ide> <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-numpy-6c285b74" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-condtitional-selection-and-modifying-dataframes.english.md <ide> videoId: BFlH0fN5xRQ <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-pandas-902ae59b" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-creating-columns.english.md <ide> videoId: _sSo2XZoB3E <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-pandas-902ae59b" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-dataframes.english.md <ide> videoId: 7SgFBYXaiH0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-pandas-902ae59b" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-indexing-and-conditional-selection.english.md <ide> videoId: -ZOrgV_aA9A <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-pandas-902ae59b" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-introduction.english.md <ide> videoId: 0xACW-8cZU0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/freecodecamp-intro-to-pandas-902ae59b" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/parsing-html-and-saving-data.english.md <ide> videoId: bJaqnTWQmb0 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-csv-and-txt-files-fb829f46" target='_blank'>Reading CSVs Notebook</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-data-from-relational-databases-2a3a889b" target='_blank'>Reading SQL</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-html-tables-eb9cca73" target='_blank'>Reading HTML</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-excel-files-a6b99973" target='_blank'>Reading Excel files</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-functions-and-collections.english.md <ide> videoId: NzpU17ZVlUw <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/python-under-10-minutes-15addcb2" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-introduction.english.md <ide> videoId: PrQV9JkLhb4 <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/python-under-10-minutes-15addcb2" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-iteration-and-modules.english.md <ide> videoId: XzosGWLafrY <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/python-under-10-minutes-15addcb2" target='_blank'>Notebook</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-csv-and-txt.english.md <ide> videoId: ViGEv0zOzUk <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-csv-and-txt-files-fb829f46" target='_blank'>Reading CSVs Notebook</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-data-from-relational-databases-2a3a889b" target='_blank'>Reading SQL</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-html-tables-eb9cca73" target='_blank'>Reading HTML</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-excel-files-a6b99973" target='_blank'>Reading Excel files</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-from-databases.english.md <ide> videoId: MtgXS1MofRw <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-csv-and-txt-files-fb829f46" target='_blank'>Reading CSVs Notebook</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-data-from-relational-databases-2a3a889b" target='_blank'>Reading SQL</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-html-tables-eb9cca73" target='_blank'>Reading HTML</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-excel-files-a6b99973" target='_blank'>Reading Excel files</a> <ide> </section> <ide> <ide> ## Tests <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-introduction.english.md <ide> videoId: cDnt02BcHng <ide> <ide> ## Description <ide> <section id='description'> <add>More resources: <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-csv-and-txt-files-fb829f46" target='_blank'>Reading CSVs Notebook</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-data-from-relational-databases-2a3a889b" target='_blank'>Reading SQL</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-html-tables-eb9cca73" target='_blank'>Reading HTML</a> <add>- <a href="https://notebooks.ai/rmotr-curriculum/rdp-reading-excel-files-a6b99973" target='_blank'>Reading Excel files</a> <ide> </section> <ide> <ide> ## Tests
28
Python
Python
add layer_idx to crossattention of gpt2 model
142b69f24b57e5d358edeaa1569955f7684fee93
<ide><path>src/transformers/models/gpt2/modeling_gpt2.py <ide> def __init__(self, config, layer_idx=None): <ide> self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) <ide> <ide> if config.add_cross_attention: <del> self.crossattention = GPT2Attention(config, is_cross_attention=True) <add> self.crossattention = GPT2Attention(config, is_cross_attention=True, layer_idx=layer_idx) <ide> self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) <ide> <ide> self.mlp = GPT2MLP(inner_dim, config) <ide><path>src/transformers/models/imagegpt/modeling_imagegpt.py <ide> def __init__(self, config, layer_idx=None): <ide> self.ln_2 = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsilon) <ide> <ide> if config.add_cross_attention: <del> self.crossattention = ImageGPTAttention(config, is_cross_attention=True) <add> self.crossattention = ImageGPTAttention(config, is_cross_attention=True, layer_idx=layer_idx) <ide> self.ln_cross_attn = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsilon) <ide> <ide> self.mlp = ImageGPTMLP(inner_dim, config)
2
Text
Text
remove unused heading
fd7ed5c07db51f5d7053d5c831186ed8c212d831
<ide><path>guides/source/5_1_release_notes.md <ide> Please refer to the [Changelog][railties] for detailed changes. <ide> * Remove -j (--javascript) option from `rails new` command. <ide> ([Pull Request](https://github.com/rails/rails/pull/28546)) <ide> <del>### Deprecations <del> <ide> ### Notable changes <ide> <ide> * Added a shared section to `config/secrets.yml` that will be loaded for all
1
PHP
PHP
use strtotime() instead of a single format
606239a1a5993d27a80bb0965f264b0897eff3f7
<ide><path>lib/Cake/Network/Http/Cookies.php <ide> */ <ide> namespace Cake\Network\Http; <ide> <add>use DateTime; <ide> use Cake\Network\Http\Request; <ide> use Cake\Network\Http\Response; <ide> <ide> public function store(Response $response, $url) { <ide> $key = implode(';', [$cookie['name'], $cookie['domain'], $cookie['path']]); <ide> <ide> $expires = isset($cookie['expires']) ? $cookie['expires'] : false; <add> $expiresTime = false; <ide> if ($expires) { <del> $expires = \DateTime::createFromFormat('D, j-M-Y H:i:s e', $expires); <add> $expiresTime = strtotime($expires); <ide> } <del> if ($expires && $expires->getTimestamp() <= time()) { <add> if ($expiresTime && $expiresTime <= time()) { <ide> unset($this->_cookies[$key]); <ide> continue; <ide> } <ide><path>lib/Cake/Test/TestCase/Network/Http/CookiesTest.php <ide> public function testStoreExpiring() { <ide> $result = $this->cookies->getAll(); <ide> $this->assertCount(2, $result, 'Path does not match, no expiration'); <ide> <add> // Use a more common date format that doesn't match <ide> $headers = [ <ide> 'HTTP/1.0 200 Ok', <ide> 'Set-Cookie: first=1; Domain=.foo.example.com; Expires=Wed, 09-Jun-1999 10:18:14 GMT', <ide> public function testStoreExpiring() { <ide> $result = $this->cookies->getAll(); <ide> $this->assertCount(2, $result, 'Domain does not match, no expiration'); <ide> <add> // Use an RFC1123 date <ide> $headers = [ <ide> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Expires=Wed, 09-Jun-1999 10:18:14 GMT', <add> 'Set-Cookie: first=1; Expires=Wed, 09 Jun 1999 10:18:14 GMT', <ide> ]; <ide> $response = new Response($headers, ''); <ide> $this->cookies->store($response, 'http://example.com/some/path');
2
Python
Python
add tests for longer and mixed english texts
8216ba599b6c33207f413381b755d8db25c01440
<ide><path>spacy/tests/en/tokenizer/test_text.py <add># coding: utf-8 <add>"""Test that longer and mixed texts are tokenized correctly.""" <add> <add> <add>from __future__ import unicode_literals <add> <add>import pytest <add> <add> <add>def test_tokenizer_handles_long_text(en_tokenizer): <add> text = """Tributes pour in for late British Labour Party leader <add> <add>Tributes poured in from around the world Thursday <add>to the late Labour Party leader John Smith, who died earlier from a massive <add>heart attack aged 55. <add> <add>In Washington, the US State Department issued a statement regretting "the <add>untimely death" of the rapier-tongued Scottish barrister and parliamentarian. <add> <add>"Mr. Smith, throughout his distinguished""" <add> tokens = en_tokenizer(text) <add> assert len(tokens) == 76 <add> <add> <add>@pytest.mark.parametrize('text,length', [ <add> ("The U.S. Army likes Shock and Awe.", 8), <add> ("U.N. regulations are not a part of their concern.", 10), <add> ("“Isn't it?”", 6), <add> ("""Yes! "I'd rather have a walk", Ms. Comble sighed. """, 15), <add> ("""'Me too!', Mr. P. Delaware cried. """, 11), <add> ("They ran about 10km.", 6), <add> # ("But then the 6,000-year ice age came...", 10) <add> ]) <add>def test_tokenizer_handles_cnts(en_tokenizer, text, length): <add> tokens = en_tokenizer(text) <add> assert len(tokens) == length
1
Javascript
Javascript
add example for emberarray#isevery
568fdeb1be4666bc51acc9bee074af402b84632c
<ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js <ide> const ArrayMixin = Mixin.create(Enumerable, { <ide> <ide> Note that like the native `Array.every`, `isEvery` will return true when called <ide> on any empty array. <add> ```javascript <add> class Language { <add> constructor(name, isProgrammingLanguage) { <add> this.name = name; <add> this.programmingLanguage = isProgrammingLanguage; <add> } <add> } <add> <add> const compiledLanguages = [ <add> new Language('Java', true), <add> new Language('Go', true), <add> new Language('Rust', true) <add> ] <add> <add> const languagesKnownByMe = [ <add> new Language('Javascript', true), <add> new Language('English', false), <add> new Language('Ruby', true) <add> ] <add> <add> compiledLanguages.isEvery('programmingLanguage'); // true <add> languagesKnownByMe.isEvery('programmingLanguage'); // false <add> ``` <ide> <ide> @method isEvery <ide> @param {String} key the property to test
1
Javascript
Javascript
add property to list of deduped tags
a6e069d4f9601e1cbe6436080ecb2a1adcb33d16
<ide><path>lib/head.js <ide> function onStateChange (head) { <ide> } <ide> } <ide> <del>const METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp'] <add>const METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp', 'property'] <ide> <ide> // returns a function for filtering head child elements <ide> // which shouldn't be duplicated, like <title/>.
1
Javascript
Javascript
remove unused var in test-tls-server-verify
2bd89421d5e8d77cd52380161b29a9b64024db2b
<ide><path>test/parallel/test-tls-server-verify.js <ide> function runTest(port, testIndex) { <ide> rejectUnauthorized: tcase.rejectUnauthorized <ide> }; <ide> <del> var connections = 0; <del> <ide> /* <ide> * If renegotiating - session might be resumed and openssl won't request <ide> * client's certificate (probably because of bug in the openssl) <ide> function runTest(port, testIndex) { <ide> return; <ide> } <ide> <del> connections++; <ide> if (c.authorized) { <ide> console.error(prefix + '- authed connection: ' + <ide> c.getPeerCertificate().subject.CN);
1
Javascript
Javascript
minimize terminal.log() work
3e9dedf1ac56a219e27ab42915e2fea0d2636b88
<ide><path>packager/src/lib/__tests__/TransformCache-test.js <ide> jest <ide> .dontMock('json-stable-stringify') <ide> .dontMock('../TransformCache') <ide> .dontMock('../toFixedHex') <del> .dontMock('left-pad'); <add> .dontMock('left-pad') <add> .dontMock('lodash/throttle'); <ide> <ide> const imurmurhash = require('imurmurhash'); <ide> <ide><path>packager/src/lib/__tests__/terminal-test.js <ide> <ide> 'use strict'; <ide> <del>jest.dontMock('../terminal'); <add>jest.dontMock('../terminal').dontMock('lodash/throttle'); <ide> <ide> jest.mock('readline', () => ({ <ide> moveCursor: (stream, dx, dy) => { <ide> describe('terminal', () => { <ide> terminal.log('foo %s', 'smth'); <ide> terminal.status('status'); <ide> terminal.log('bar'); <del> expect(stream.buffer.join('').trim()) <del> .toEqual('foo smth bar'); <add> jest.runAllTimers(); <add> expect(stream.buffer.join('').trim()).toEqual('foo smth bar'); <add> }); <add> <add> it('print status', () => { <add> const {stream, terminal} = prepare(true); <add> terminal.log('foo'); <add> terminal.status('status'); <add> jest.runAllTimers(); <add> expect(stream.buffer.join('').trim()).toEqual('foo status'); <ide> }); <ide> <ide> it('updates status when logging, single line', () => { <ide> describe('terminal', () => { <ide> terminal.status('status'); <ide> terminal.status('status2'); <ide> terminal.log('bar'); <del> expect(stream.buffer.join('').trim()) <del> .toEqual('foo bar status2'); <add> jest.runAllTimers(); <add> expect(stream.buffer.join('').trim()).toEqual('foo bar status2'); <add> terminal.log('beep'); <add> jest.runAllTimers(); <add> expect(stream.buffer.join('').trim()).toEqual('foo bar beep status2'); <ide> }); <ide> <ide> it('updates status when logging, multi-line', () => { <ide> const {stream, terminal} = prepare(true); <ide> terminal.log('foo'); <ide> terminal.status('status\nanother'); <ide> terminal.log('bar'); <add> jest.runAllTimers(); <ide> expect(stream.buffer.join('').trim()) <ide> .toEqual('foo bar status another'); <ide> }); <ide> describe('terminal', () => { <ide> terminal.status('status'); <ide> terminal.persistStatus(); <ide> terminal.log('bar'); <del> expect(stream.buffer.join('').trim()) <del> .toEqual('foo status bar'); <add> jest.runAllTimers(); <add> expect(stream.buffer.join('').trim()).toEqual('foo status bar'); <ide> }); <ide> <ide> }); <ide><path>packager/src/lib/terminal.js <ide> 'use strict'; <ide> <ide> const readline = require('readline'); <add>const throttle = require('lodash/throttle'); <ide> const tty = require('tty'); <ide> const util = require('util'); <ide> <ide> function chunkString(str: string, size: number): Array<string> { <ide> */ <ide> class Terminal { <ide> <add> _logLines: Array<string>; <add> _nextStatusStr: string; <add> _scheduleUpdate: () => void; <ide> _statusStr: string; <ide> _stream: net$Socket; <ide> <ide> constructor(stream: net$Socket) { <del> this._stream = stream; <add> this._logLines = []; <add> this._nextStatusStr = ''; <add> this._scheduleUpdate = throttle(this._update, 0); <ide> this._statusStr = ''; <add> this._stream = stream; <ide> } <ide> <ide> /** <del> * Same as status() without the formatting capabilities. We just clear and <del> * rewrite with the new status. If the stream is non-interactive we still <del> * keep track of the string so that `persistStatus` works. <add> * Clear and write the new status, logging in bulk in-between. Doing this in a <add> * throttled way (in a different tick than the calls to `log()` and <add> * `status()`) prevents us from repeatedly rewriting the status in case <add> * `terminal.log()` is called several times. <ide> */ <del> _setStatus(str: string): string { <add> _update(): void { <ide> const {_statusStr, _stream} = this; <del> if (_statusStr !== str && _stream instanceof tty.WriteStream) { <add> if (_statusStr === this._nextStatusStr && this._logLines.length === 0) { <add> return; <add> } <add> if (_stream instanceof tty.WriteStream) { <ide> clearStringBackwards(_stream, _statusStr); <del> str = chunkString(str, _stream.columns).join('\n'); <del> _stream.write(str); <ide> } <del> this._statusStr = str; <del> return _statusStr; <add> this._logLines.forEach(line => { <add> _stream.write(line); <add> _stream.write('\n'); <add> }); <add> this._logLines = []; <add> if (_stream instanceof tty.WriteStream) { <add> this._nextStatusStr = chunkString(this._nextStatusStr, _stream.columns).join('\n'); <add> _stream.write(this._nextStatusStr); <add> } <add> this._statusStr = this._nextStatusStr; <ide> } <ide> <ide> /** <ide> class Terminal { <ide> * file, then we don't care too much about having a progress bar. <ide> */ <ide> status(format: string, ...args: Array<mixed>): string { <del> return this._setStatus(util.format(format, ...args)); <add> const {_nextStatusStr} = this; <add> this._nextStatusStr = util.format(format, ...args); <add> this._scheduleUpdate(); <add> return _nextStatusStr; <ide> } <ide> <ide> /** <ide> class Terminal { <ide> * `console.log`. <ide> */ <ide> log(format: string, ...args: Array<mixed>): void { <del> const oldStatus = this._setStatus(''); <del> this._stream.write(util.format(format, ...args) + '\n'); <del> this._setStatus(oldStatus); <add> this._logLines.push(util.format(format, ...args)); <add> this._scheduleUpdate(); <ide> } <ide> <ide> /** <ide> * Log the current status and start from scratch. This is useful if the last <ide> * status was the last one of a series of updates. <ide> */ <ide> persistStatus(): void { <del> return this.log(this.status('')); <add> this.log(this._nextStatusStr); <add> this._nextStatusStr = ''; <ide> } <ide> <ide> }
3
PHP
PHP
remove commas from values
da4d4a468eee174bd619b4a04aab57e419d10ff4
<ide><path>src/Illuminate/Validation/Rules/Unique.php <ide> public function ignore($id, $idColumn = null) <ide> return $this->ignoreModel($id, $idColumn); <ide> } <ide> <del> $this->ignore = $id; <del> $this->idColumn = $idColumn ?? 'id'; <add> $this->ignore = str_replace(',', '', $id); <add> $this->idColumn = str_replace(',', '', $idColumn ?? 'id'); <ide> <ide> return $this; <ide> } <ide> public function ignore($id, $idColumn = null) <ide> */ <ide> public function ignoreModel($model, $idColumn = null) <ide> { <del> $this->idColumn = $idColumn ?? $model->getKeyName(); <del> $this->ignore = $model->{$this->idColumn}; <add> $this->idColumn = str_replace(',', '', $idColumn ?? $model->getKeyName()); <add> $this->ignore = str_replace(',', '', $model->{$this->idColumn}); <ide> <ide> return $this; <ide> } <ide><path>tests/Validation/ValidationUniqueRuleTest.php <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore('Taylor, Otwell', 'id_column'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,column,"Taylor, Otwell",id_column,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,column,"Taylor Otwell",id_column,foo,bar', (string) $rule); <ide> <ide> $rule = new Unique('table', 'column'); <ide> $rule->ignore(null, 'id_column');
2
Javascript
Javascript
add semicolon for react-dom source files
e9e70365c35465c911e749b45841c523108cc86d
<ide><path>docs/js/react-dom.js <ide> <ide> // <script> <ide> } else { <del> var g; <add> var g <ide> if (typeof window !== "undefined") { <ide> g = window; <ide> } else if (typeof global !== "undefined") { <ide><path>vendor/react-dom-server.js <ide> <ide> // <script> <ide> } else { <del> var g <add> var g; <ide> if (typeof window !== "undefined") { <ide> g = window; <ide> } else if (typeof global !== "undefined") { <ide><path>vendor/react-dom.js <ide> <ide> // <script> <ide> } else { <del> var g <add> var g; <ide> if (typeof window !== "undefined") { <ide> g = window; <ide> } else if (typeof global !== "undefined") {
3
Ruby
Ruby
provide a logger
dd593b98b5ef6e66d72942065dd1c0a9b266b9bc
<ide><path>lib/action_mailbox.rb <ide> module ActionMailbox <ide> autoload :Router <ide> autoload :Callbacks <ide> autoload :Routing <add> <add> mattr_accessor :logger <ide> end <ide><path>lib/action_mailbox/base.rb <ide> class ActionMailbox::Base <ide> attr_reader :inbound_email <ide> delegate :mail, :bounced!, to: :inbound_email <ide> <add> delegate :logger, to: ActionMailbox <add> <ide> def self.receive(inbound_email) <ide> new(inbound_email).perform_processing <ide> end <ide> def perform_processing <ide> def process <ide> # Overwrite in subclasses <ide> end <del> <add> <ide> private <ide> def track_status_of_inbound_email <ide> inbound_email.processing! <ide><path>lib/action_mailbox/engine.rb <ide> class Engine < Rails::Engine <ide> isolate_namespace ActionMailbox <ide> config.eager_load_namespaces << ActionMailbox <ide> <add> config.action_mailbox = ActiveSupport::OrderedOptions.new <add> <ide> initializer "action_mailbox.config" do <ide> config.after_initialize do |app| <del> # Configure <add> ActionMailbox.logger = app.config.action_mailbox.logger || Rails.logger <ide> end <ide> end <ide> end
3
Go
Go
fix typo in idtools tests
5d8b88b114da7c40f04a95909a35287ae1dac37f
<ide><path>pkg/idtools/idtools_unix_test.go <ide> func TestGetRootUIDGID(t *testing.T) { <ide> <ide> uid, gid, err := GetRootUIDGID(uidMap, gidMap) <ide> assert.Check(t, err) <del> assert.Check(t, is.Equal(os.Getegid(), uid)) <add> assert.Check(t, is.Equal(os.Geteuid(), uid)) <ide> assert.Check(t, is.Equal(os.Getegid(), gid)) <ide> <ide> uidMapError := []IDMap{
1
Python
Python
create dummy models
dcca71be6151c04ec89116d3275f7173b7936601
<ide><path>utils/check_config_docstrings.py <ide> } <ide> <ide> <del>def check_config_docstrings_have_checkpoints(): <del> configs_without_checkpoint = [] <add>def get_checkpoint_from_config_class(config_class): <add> checkpoint = None <ide> <del> for config_class in list(CONFIG_MAPPING.values()): <del> checkpoint_found = False <add> # source code of `config_class` <add> config_source = inspect.getsource(config_class) <add> checkpoints = _re_checkpoint.findall(config_source) <add> <add> for checkpoint in checkpoints: <add> # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. <add> # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` <add> ckpt_name, ckpt_link = checkpoint <add> <add> # verify the checkpoint name corresponds to the checkpoint link <add> ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" <add> if ckpt_link == ckpt_link_from_name: <add> checkpoint = ckpt_name <add> break <ide> <del> # source code of `config_class` <del> config_source = inspect.getsource(config_class) <del> checkpoints = _re_checkpoint.findall(config_source) <add> return checkpoint <ide> <del> for checkpoint in checkpoints: <del> # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. <del> # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` <del> ckpt_name, ckpt_link = checkpoint <ide> <del> # verify the checkpoint name corresponds to the checkpoint link <del> ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" <del> if ckpt_link == ckpt_link_from_name: <del> checkpoint_found = True <del> break <add>def check_config_docstrings_have_checkpoints(): <add> configs_without_checkpoint = [] <add> <add> for config_class in list(CONFIG_MAPPING.values()): <add> checkpoint = get_checkpoint_from_config_class(config_class) <ide> <ide> name = config_class.__name__ <del> if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: <add> if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: <ide> configs_without_checkpoint.append(name) <ide> <ide> if len(configs_without_checkpoint) > 0: <ide><path>utils/create_dummy_models.py <add># coding=utf-8 <add># Copyright 2022 The HuggingFace Inc. team. All rights reserved. <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> <add>import argparse <add>import collections.abc <add>import importlib <add>import inspect <add>import json <add>import os <add>import shutil <add>import sys <add>from pathlib import Path <add> <add>from datasets import load_dataset <add> <add>from check_config_docstrings import get_checkpoint_from_config_class <add>from transformers import ( <add> CONFIG_MAPPING, <add> FEATURE_EXTRACTOR_MAPPING, <add> PROCESSOR_MAPPING, <add> TOKENIZER_MAPPING, <add> AutoTokenizer, <add> LayoutLMv3TokenizerFast, <add> PreTrainedTokenizerFast, <add> logging, <add>) <add>from transformers.feature_extraction_utils import FeatureExtractionMixin <add>from transformers.file_utils import is_tf_available, is_torch_available <add>from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name <add>from transformers.processing_utils import ProcessorMixin, transformers_module <add>from transformers.tokenization_utils_base import PreTrainedTokenizerBase <add> <add> <add>logging.set_verbosity_error() <add>logger = logging.get_logger(__name__) <add> <add>sys.path.append(".") <add>os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" <add> <add>if not is_torch_available(): <add> raise ValueError("Please install PyTorch.") <add> <add>if not is_tf_available(): <add> raise ValueError("Please install TensorFlow.") <add> <add>FRAMEWORKS = ["pytorch", "tensorflow"] <add>INVALID_ARCH = [] <add>TARGET_VOCAB_SIZE = 1024 <add> <add> <add>def get_processor_types_from_config_class(config_class, allowed_mappings=None): <add> """Return a tuple of processors for `config_class`. <add> <add> We use `tuple` here to include (potentially) both slow & fast tokenizers. <add> """ <add> if allowed_mappings is None: <add> allowed_mappings = ["processor", "tokenizer", "feature_extractor"] <add> <add> processor_types = () <add> <add> # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers or a feature extractor. <add> if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings: <add> processor_types = PROCESSOR_MAPPING[config_class] <add> elif config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings: <add> processor_types = TOKENIZER_MAPPING[config_class] <add> elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings: <add> processor_types = FEATURE_EXTRACTOR_MAPPING[config_class] <add> else: <add> # Some configurations have no processor at all. For example, generic composite models like <add> # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't <add> # require any processor. <add> pass <add> <add> # make a uniform return type <add> if not isinstance(processor_types, collections.abc.Sequence): <add> processor_types = (processor_types,) <add> else: <add> processor_types = tuple(processor_types) <add> <add> # We might get `None` for some tokenizers - remove them here. <add> processor_types = tuple(p for p in processor_types if p is not None) <add> <add> return processor_types <add> <add> <add>def get_architectures_from_config_class(config_class, arch_mappings): <add> """Return a tuple of all possible architectures attributed to a configuration class `config_class`. <add> <add> For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering]. <add> """ <add> # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in <add> # - MODEL_FOR_PRETRAINING_MAPPING_NAMES <add> # - MODEL_WITH_LM_HEAD_MAPPING_NAMES <add> # - MODEL_FOR_MASKED_LM_MAPPING_NAMES <add> # - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES <add> # We avoid the duplication. <add> architectures = set() <add> <add> for mapping in arch_mappings: <add> if config_class in mapping: <add> models = mapping[config_class] <add> models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,) <add> for model in models: <add> if model.__name__ not in unexportable_model_architectures: <add> architectures.add(model) <add> <add> architectures = tuple(architectures) <add> <add> return architectures <add> <add> <add>def get_config_class_from_processor_class(processor_class): <add> """Get the config class from a processor class. <add> <add> Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses <add> `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to <add> create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it <add> to find a checkpoint in order to create the processor. <add> """ <add> <add> processor_prefix = processor_class.__name__ <add> for postfix in ["Processor", "TokenizerFast", "Tokenizer", "FeatureExtractor"]: <add> processor_prefix = processor_prefix.replace(postfix, "") <add> <add> # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config` <add> if processor_prefix == "Wav2Vec2CTC": <add> processor_prefix = "Wav2Vec2" <add> <add> # Find the new configuration class <add> new_config_name = f"{processor_prefix}Config" <add> new_config_class = getattr(transformers_module, new_config_name) <add> <add> return new_config_class <add> <add> <add>def build_processor(config_class, processor_class): <add> """Create a processor for `processor_class`. <add> <add> If a processor is not able to be built with the original arguments, this method tries to change the arguments and <add> call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to <add> find a checkpoint containing the necessary files to build a processor. <add> <add> The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in <add> `convert_processors`. For each model architecture`, a copy will be created and saved along the built model. <add> """ <add> # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint. <add> checkpoint = get_checkpoint_from_config_class(config_class) <add> <add> if checkpoint is None: <add> # try to get the checkpoint from the config class for `processor_class`. <add> # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`. <add> config_class_from_processor_class = get_config_class_from_processor_class(processor_class) <add> checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class) <add> <add> processor = None <add> try: <add> processor = processor_class.from_pretrained(checkpoint) <add> except Exception as e: <add> logger.error(e) <add> pass <add> <add> # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load <add> # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in <add> # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint <add> # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get <add> # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from <add> # `checkpoint`, but it helps this recursive method to find a way to build a processor). <add> if ( <add> processor is None <add> and checkpoint is not None <add> and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer)) <add> ): <add> try: <add> config = AutoConfig.from_pretrained(checkpoint) <add> except Exception as e: <add> logger.error(e) <add> config = None <add> if config is not None: <add> assert isinstance(config, config_class) <add> tokenizer_class = config.tokenizer_class <add> new_processor_class = None <add> if tokenizer_class is not None: <add> new_processor_class = getattr(transformers_module, tokenizer_class) <add> if new_processor_class != processor_class: <add> processor = build_processor(config_class, new_processor_class) <add> # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto <add> # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build <add> if processor is None: <add> new_processor_classes = get_processor_types_from_config_class( <add> config.__class__, allowed_mappings=["tokenizer"] <add> ) <add> # Used to avoid infinite recursion between a pair of fast/slow tokenizer types <add> names = [ <add> x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None <add> ] <add> new_processor_classes = [ <add> x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names <add> ] <add> if len(new_processor_classes) > 0: <add> new_processor_class = new_processor_classes[0] <add> processor = build_processor(config_class, new_processor_class) <add> <add> if processor is None: <add> # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`. <add> if issubclass(processor_class, ProcessorMixin): <add> attrs = {} <add> for attr_name in processor_class.attributes: <add> attrs[attr_name] = [] <add> # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has <add> # - feature_extractor_class = "CLIPFeatureExtractor" <add> # - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") <add> attr_class_names = getattr(processor_class, f"{attr_name}_class") <add> if not isinstance(attr_class_names, tuple): <add> attr_class_names = (attr_class_names,) <add> <add> for name in attr_class_names: <add> attr_class = getattr(transformers_module, name) <add> attr = build_processor(config_class, attr_class) <add> if attr is not None: <add> attrs[attr_name].append(attr) <add> <add> # try to build a `ProcessorMixin`, so we can return a single value <add> if all(len(v) > 0 for v in attrs.values()): <add> try: <add> processor = processor_class(**{k: v[0] for k, v in attrs.items()}) <add> except Exception as e: <add> logger.error(e) <add> pass <add> else: <add> # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960` <add> # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor <add> # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`. <add> config_class_from_processor_class = get_config_class_from_processor_class(processor_class) <add> if config_class_from_processor_class != config_class: <add> processor = build_processor(config_class_from_processor_class, processor_class) <add> <add> # validation <add> if processor is not None: <add> assert isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto") <add> <add> return processor <add> <add> <add>def get_tiny_config(config_class): <add> """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`. <add> <add> Args: <add> config_class: Subclass of `PreTrainedConfig`. <add> <add> Returns: <add> An instance of `config_class` with tiny hyperparameters <add> """ <add> model_type = config_class.model_type <add> <add> # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via <add> # `model_type` as it would be sth. like `configuration_data2vec_vision.py`. <add> # A simple way is to use `inspect.getsourcefile(config_class)`. <add> config_source_file = inspect.getsourcefile(config_class) <add> # The modeling file name without prefix (`modeling_`) and postfix (`.py`) <add> modeling_name = config_source_file.split("/")[-1].replace("configuration_", "").replace(".py", "") <add> <add> try: <add> print("Importing", model_type_to_module_name(model_type)) <add> module_name = model_type_to_module_name(model_type) <add> assert modeling_name.startswith(module_name) <add> module = importlib.import_module(f".models.{module_name}.test_modeling_{modeling_name}", package="tests") <add> camel_case_model_name = config_class.__name__.split("Config")[0] <add> model_tester_class = getattr(module, f"{camel_case_model_name}ModelTester", None) <add> except ModuleNotFoundError as e: <add> error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name." <add> raise ValueError(f"{error}: {str(e)}") <add> <add> if model_tester_class is None: <add> error = f"Tiny config not created for {model_type} - no model tester is found in the testing module." <add> raise ValueError(error) <add> <add> # `parent` is an instance of `unittest.TestCase`, but we don't need it here. <add> model_tester = model_tester_class(parent=None) <add> <add> if hasattr(model_tester, "get_pipeline_config"): <add> return model_tester.get_pipeline_config() <add> elif hasattr(model_tester, "prepare_config_and_inputs"): <add> # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if <add> # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`. <add> return model_tester.prepare_config_and_inputs()[0] <add> elif hasattr(model_tester, "get_config"): <add> return model_tester.get_config() <add> else: <add> error = ( <add> f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks" <add> " necessary method to create config." <add> ) <add> raise ValueError(error) <add> <add> <add>def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast): <add> <add> new_tokenizer = tokenizer_fast.train_new_from_iterator(training_ds["text"], TARGET_VOCAB_SIZE, show_progress=False) <add> <add> # Make sure it at least runs <add> if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast): <add> new_tokenizer(testing_ds["text"]) <add> <add> return new_tokenizer <add> <add> <add>def convert_feature_extractor(feature_extractor, tiny_config): <add> <add> to_convert = False <add> kwargs = {} <add> if hasattr(tiny_config, "image_size"): <add> kwargs["size"] = tiny_config.image_size <add> kwargs["crop_size"] = tiny_config.image_size <add> to_convert = True <add> elif ( <add> hasattr(tiny_config, "vision_config") <add> and tiny_config.vision_config is not None <add> and hasattr(tiny_config.vision_config, "image_size") <add> ): <add> kwargs["size"] = tiny_config.vision_config.image_size <add> kwargs["crop_size"] = tiny_config.vision_config.image_size <add> to_convert = True <add> <add> # Speech2TextModel specific. <add> if hasattr(tiny_config, "input_feat_per_channel"): <add> kwargs["feature_size"] = tiny_config.input_feat_per_channel <add> kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel <add> to_convert = True <add> <add> if to_convert: <add> feature_extractor = feature_extractor.__class__(**kwargs) <add> <add> return feature_extractor <add> <add> <add>def convert_processors(processors, tiny_config, output_folder, result): <add> """Change a processor to work with smaller inputs. <add> <add> For tokenizers, we try to reduce their vocabulary size. <add> <add> For feature extractor, we use smaller image size or change <add> other attributes using the values from `tiny_config`. See `convert_feature_extractor`. <add> <add> This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages. <add> """ <add> <add> tokenizers = [] <add> feature_extractors = [] <add> for processor in processors: <add> if isinstance(processor, PreTrainedTokenizerBase): <add> tokenizers.append(processor) <add> elif isinstance(processor, FeatureExtractionMixin): <add> feature_extractors.append(processor) <add> elif isinstance(processor, ProcessorMixin): <add> # Currently, we only have these 2 possibilities <add> tokenizers.append(processor.tokenizer) <add> feature_extractors.append(processor.feature_extractor) <add> <add> # check the built processors have the unique type <add> assert len(set([x.__class__.__name__ for x in feature_extractors])) < 2 <add> assert len(set([x.__class__.__name__.replace("Fast", "") for x in tokenizers])) < 2 <add> <add> fast_tokenizer = None <add> slow_tokenizer = None <add> for tokenizer in tokenizers: <add> if isinstance(tokenizer, PreTrainedTokenizerFast): <add> if fast_tokenizer is None: <add> fast_tokenizer = tokenizer <add> try: <add> # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can <add> # be retrained <add> if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE: <add> fast_tokenizer = convert_tokenizer(tokenizer) <add> except Exception as e: <add> result["warnings"].append( <add> f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}: {e}" <add> ) <add> continue <add> elif slow_tokenizer is None: <add> slow_tokenizer = tokenizer <add> <add> # Make sure the fast tokenizer can be saved <add> if fast_tokenizer: <add> try: <add> fast_tokenizer.save_pretrained(output_folder) <add> except Exception as e: <add> result["warnings"].append( <add> f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}: {e}" <add> ) <add> fast_tokenizer = None <add> <add> # Make sure the slow tokenizer (if any) corresponds to the fast version (as it might be converted above) <add> if fast_tokenizer: <add> try: <add> slow_tokenizer = AutoTokenizer.from_pretrained(output_folder, use_fast=False) <add> except Exception as e: <add> result["warnings"].append( <add> f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}: {e}" <add> ) <add> # Let's just keep the fast version <add> slow_tokenizer = None <add> <add> # If the fast version can't be created and saved, let's use the slow version <add> if not fast_tokenizer and slow_tokenizer: <add> try: <add> slow_tokenizer.save_pretrained(output_folder) <add> except Exception as e: <add> result["warnings"].append( <add> f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}: {e}" <add> ) <add> slow_tokenizer = None <add> <add> # update feature extractors using the tiny config <add> try: <add> feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors] <add> except Exception as e: <add> result["warnings"].append(f"Failed to convert feature extractors: {e}") <add> feature_extractors = [] <add> <add> processors = [fast_tokenizer, slow_tokenizer] + feature_extractors <add> processors = [p for p in processors if p is not None] <add> for p in processors: <add> p.save_pretrained(output_folder) <add> <add> return processors <add> <add> <add>def get_checkpoint_dir(output_dir, model_arch): <add> """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory.""" <add> <add> arch_name = model_arch.__name__ <add> if arch_name.startswith("TF"): <add> arch_name = arch_name[2:] <add> elif arch_name.startswith("Flax"): <add> arch_name = arch_name[4:] <add> <add> return os.path.join(output_dir, arch_name) <add> <add> <add>def build_model(model_arch, tiny_config, output_dir): <add> """Create and save a model for `model_arch`. <add> <add> Also copy the set of processors to each model (under the same model type) output folder. <add> """ <add> <add> checkpoint_dir = get_checkpoint_dir(output_dir, model_arch) <add> <add> processor_output_dir = os.path.join(output_dir, "processors") <add> # copy the (same set of) processors (for a model type) to the model arch. specific folder <add> if os.path.isdir(processor_output_dir): <add> shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True) <add> <add> model = model_arch(config=tiny_config) <add> model.save_pretrained(checkpoint_dir) <add> model.from_pretrained(checkpoint_dir) <add> <add> return model <add> <add> <add>def fill_result_with_error(result, error, models_to_create): <add> """Fill `result` with errors for all target model arch if we can't build processor""" <add> <add> result["error"] = error <add> for framework in FRAMEWORKS: <add> if framework in models_to_create: <add> result[framework] = {} <add> for model_arch in models_to_create[framework]: <add> result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error} <add> <add> <add>def build_composite_models(config_class, output_dir): <add> <add> import tempfile <add> <add> from transformers import ( <add> BertConfig, <add> BertLMHeadModel, <add> BertModel, <add> BertTokenizer, <add> BertTokenizerFast, <add> EncoderDecoderModel, <add> GPT2Config, <add> GPT2LMHeadModel, <add> GPT2Tokenizer, <add> GPT2TokenizerFast, <add> SpeechEncoderDecoderModel, <add> TFEncoderDecoderModel, <add> TFVisionEncoderDecoderModel, <add> VisionEncoderDecoderModel, <add> VisionTextDualEncoderModel, <add> ViTConfig, <add> ViTFeatureExtractor, <add> ViTModel, <add> Wav2Vec2Config, <add> Wav2Vec2Model, <add> Wav2Vec2Processor, <add> ) <add> <add> # These will be removed at the end if they are empty <add> result = {"error": None, "warnings": []} <add> <add> if config_class.model_type == "encoder-decoder": <add> encoder_config_class = BertConfig <add> decoder_config_class = BertConfig <add> encoder_processor = (BertTokenizerFast, BertTokenizer) <add> decoder_processor = (BertTokenizerFast, BertTokenizer) <add> encoder_class = BertModel <add> decoder_class = BertLMHeadModel <add> model_class = EncoderDecoderModel <add> tf_model_class = TFEncoderDecoderModel <add> elif config_class.model_type == "vision-encoder-decoder": <add> encoder_config_class = ViTConfig <add> decoder_config_class = GPT2Config <add> encoder_processor = (ViTFeatureExtractor,) <add> decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer) <add> encoder_class = ViTModel <add> decoder_class = GPT2LMHeadModel <add> model_class = VisionEncoderDecoderModel <add> tf_model_class = TFVisionEncoderDecoderModel <add> elif config_class.model_type == "speech-encoder-decoder": <add> encoder_config_class = Wav2Vec2Config <add> decoder_config_class = BertConfig <add> encoder_processor = (Wav2Vec2Processor,) <add> decoder_processor = (BertTokenizerFast, BertTokenizer) <add> encoder_class = Wav2Vec2Model <add> decoder_class = BertLMHeadModel <add> model_class = SpeechEncoderDecoderModel <add> tf_model_class = None <add> elif config_class.model_type == "vision-text-dual-encoder": <add> # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier <add> encoder_config_class = ViTConfig <add> decoder_config_class = BertConfig <add> encoder_processor = (ViTFeatureExtractor,) <add> decoder_processor = (BertTokenizerFast, BertTokenizer) <add> encoder_class = ViTModel <add> decoder_class = BertModel <add> model_class = VisionTextDualEncoderModel <add> tf_model_class = None <add> <add> with tempfile.TemporaryDirectory() as tmpdir: <add> <add> try: <add> # build encoder <add> models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []} <add> encoder_output_dir = os.path.join(tmpdir, "encoder") <add> build(encoder_config_class, models_to_create, encoder_output_dir) <add> <add> # build decoder <add> models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []} <add> decoder_output_dir = os.path.join(tmpdir, "decoder") <add> build(decoder_config_class, models_to_create, decoder_output_dir) <add> <add> # build encoder-decoder <add> encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__) <add> decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__) <add> <add> if config_class.model_type != "vision-text-dual-encoder": <add> # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it <add> # has no decoder. <add> decoder_config = decoder_config_class.from_pretrained(decoder_path) <add> decoder_config.is_decoder = True <add> decoder_config.add_cross_attention = True <add> model = model_class.from_encoder_decoder_pretrained( <add> encoder_path, <add> decoder_path, <add> decoder_config=decoder_config, <add> ) <add> elif config_class.model_type == "vision-text-dual-encoder": <add> model = model_class.from_vision_text_pretrained(encoder_path, decoder_path) <add> <add> model_path = os.path.join( <add> output_dir, <add> f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}", <add> ) <add> model.save_pretrained(model_path) <add> <add> if tf_model_class is not None: <add> model = tf_model_class.from_pretrained(model_path, from_pt=True) <add> model.save_pretrained(model_path) <add> <add> # copy the processors <add> encoder_processor_path = os.path.join(encoder_output_dir, "processors") <add> decoder_processor_path = os.path.join(decoder_output_dir, "processors") <add> if os.path.isdir(encoder_processor_path): <add> shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True) <add> if os.path.isdir(decoder_processor_path): <add> shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True) <add> <add> # fill `result` <add> result["processor"] = tuple(set([x.__name__ for x in encoder_processor + decoder_processor])) <add> <add> result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}} <add> <add> result["tensorflow"] = {} <add> if tf_model_class is not None: <add> result["tensorflow"] = { <add> tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path} <add> } <add> <add> except Exception as e: <add> result["error"] = f"Failed to build models for {config_class.__name__}: {e}" <add> <add> if not result["error"]: <add> del result["error"] <add> if not result["warnings"]: <add> del result["warnings"] <add> <add> return result <add> <add> <add>def build(config_class, models_to_create, output_dir): <add> """Create all models for a certain model type. <add> <add> Args: <add> config_class (`PretrainedConfig`): <add> A subclass of `PretrainedConfig` that is used to determine `models_to_create`. <add> models_to_create (`dict`): <add> A dictionary containing the processor/model classes that we want to create the instances. These models are <add> of the same model type which is associated to `config_class`. <add> output_dir (`str`): <add> The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under <add> it. Models in different frameworks with the same architecture will be saved in the same subdirectory. <add> """ <add> <add> if config_class.model_type in [ <add> "encoder-decoder", <add> "vision-encoder-decoder", <add> "speech-encoder-decoder", <add> "vision-text-dual-encoder", <add> ]: <add> return build_composite_models(config_class, output_dir) <add> <add> result = {k: {} for k in models_to_create} <add> <add> # These will be removed at the end if they are empty <add> result["error"] = None <add> result["warnings"] = [] <add> <add> # Build processors <add> processor_classes = models_to_create["processor"] <add> <add> if len(processor_classes) == 0: <add> error = f"No processor class could be found in {config_class.__name__}." <add> fill_result_with_error(result, error, models_to_create) <add> logger.error(result["error"]) <add> return result <add> <add> for processor_class in processor_classes: <add> processor = build_processor(config_class, processor_class) <add> if processor is not None: <add> result["processor"][processor_class] = processor <add> <add> if len(result["processor"]) == 0: <add> error = f"No processor could be built for {config_class.__name__}." <add> fill_result_with_error(result, error, models_to_create) <add> logger.error(result["error"]) <add> return result <add> <add> try: <add> tiny_config = get_tiny_config(config_class) <add> except Exception as e: <add> # Let's still return the processors, so we know they could be built. <add> result["processor"] = {type(p).__name__: p.__class__.__name__ for p in result["processor"]} <add> error = str(e) <add> fill_result_with_error(result, error, models_to_create) <add> logger.error(result["error"]) <add> return result <add> <add> # Convert the processors (reduce vocabulary size, smaller image size, etc.) <add> processors = list(result["processor"].values()) <add> processor_output_folder = os.path.join(output_dir, "processors") <add> processors = convert_processors(processors, tiny_config, processor_output_folder, result) <add> # update `result["processor"]` <add> result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors} <add> <add> if len(result["processor"]) == 0: <add> error = f"No processor could be converted for {config_class.__name__}." <add> fill_result_with_error(result, error, models_to_create) <add> logger.error(result["error"]) <add> return result <add> <add> # Update the config with the properties of the converted processors (smaller vocab size, image size, etc.) <add> for processor in processors: <add> if isinstance(processor, PreTrainedTokenizerBase): <add> vocab_size = processor.vocab_size <add> result["vocab_size"] = vocab_size <add> config_overrides = {k: v for k, v in result.items() if k in ["vocab_size"] and v is not None} <add> # Update `vocab_size` <add> for k, v in config_overrides.items(): <add> if hasattr(tiny_config, k): <add> setattr(tiny_config, k, v) <add> # currently only `vocab_size` is involved, so let's just look `text_config` <add> elif ( <add> hasattr(tiny_config, "text_config") <add> and tiny_config.text_config is not None <add> and hasattr(tiny_config.text_config, k) <add> ): <add> setattr(tiny_config.text_config, k, v) <add> # If `text_config_dict` exists, we need to update its value here too in order to # make <add> # `save_pretrained -> from_pretrained` work. <add> if hasattr(tiny_config, "text_config_dict"): <add> tiny_config.text_config_dict[k] = v <add> <add> if result["warnings"]: <add> logger.warning(result["warnings"]) <add> <add> for pytorch_arch in models_to_create["pytorch"]: <add> result["pytorch"][pytorch_arch.__name__] = {} <add> error = None <add> try: <add> model = build_model(pytorch_arch, tiny_config, output_dir=output_dir) <add> except Exception as e: <add> model = None <add> error = f"Failed to create the pytorch model for {pytorch_arch}: {e}" <add> <add> result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None <add> result["pytorch"][pytorch_arch.__name__]["checkpoint"] = ( <add> get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None <add> ) <add> if error: <add> result["pytorch"][pytorch_arch.__name__]["error"] = error <add> logger.error(f"{pytorch_arch.__name__}: {error}") <add> <add> for tensorflow_arch in models_to_create["tensorflow"]: <add> # Make PT/TF weights compatible <add> pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF` <add> pt_arch = getattr(transformers_module, pt_arch_name) <add> <add> result["tensorflow"][tensorflow_arch.__name__] = {} <add> error = None <add> if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None: <add> ckpt = get_checkpoint_dir(output_dir, pt_arch) <add> # Use the same weights from PyTorch. <add> try: <add> model = tensorflow_arch.from_pretrained(ckpt, from_pt=True) <add> model.save_pretrained(ckpt) <add> except Exception as e: <add> # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now). <add> model = None <add> error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}" <add> else: <add> try: <add> model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir) <add> except Exception as e: <add> model = None <add> error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}" <add> <add> result["tensorflow"][tensorflow_arch.__name__]["model"] = ( <add> model.__class__.__name__ if model is not None else None <add> ) <add> result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = ( <add> get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None <add> ) <add> if error: <add> result["tensorflow"][tensorflow_arch.__name__]["error"] = error <add> logger.error(f"{tensorflow_arch.__name__}: {error}") <add> <add> if not result["error"]: <add> del result["error"] <add> if not result["warnings"]: <add> del result["warnings"] <add> <add> return result <add> <add> <add>def build_failed_report(results, include_warning=True): <add> <add> failed_results = {} <add> for config_name in results: <add> if "error" in results[config_name]: <add> if config_name not in failed_results: <add> failed_results[config_name] = {} <add> failed_results[config_name] = {"error": results[config_name]["error"]} <add> <add> if include_warning and "warnings" in results[config_name]: <add> if config_name not in failed_results: <add> failed_results[config_name] = {} <add> failed_results[config_name]["warnings"] = results[config_name]["warnings"] <add> <add> for framework in FRAMEWORKS: <add> if framework not in results[config_name]: <add> continue <add> for arch_name in results[config_name][framework]: <add> if "error" in results[config_name][framework][arch_name]: <add> if config_name not in failed_results: <add> failed_results[config_name] = {} <add> if framework not in failed_results[config_name]: <add> failed_results[config_name][framework] = {} <add> if arch_name not in failed_results[config_name][framework]: <add> failed_results[config_name][framework][arch_name] = {} <add> error = results[config_name][framework][arch_name]["error"] <add> failed_results[config_name][framework][arch_name]["error"] = error <add> <add> return failed_results <add> <add> <add>def build_simple_report(results): <add> <add> text = "" <add> failed_text = "" <add> for config_name in results: <add> for framework in FRAMEWORKS: <add> if framework not in results[config_name]: <add> continue <add> for arch_name in results[config_name][framework]: <add> if "error" in results[config_name][framework][arch_name]: <add> result = results[config_name][framework][arch_name]["error"] <add> failed_text += f"{arch_name}: {result}\n" <add> else: <add> result = "OK" <add> text += f"{arch_name}: {result}\n" <add> <add> return text, failed_text <add> <add> <add>if __name__ == "__main__": <add> <add> clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) <add> if os.getcwd() != clone_path: <add> raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}") <add> <add> _pytorch_arch_mappings = [ <add> x <add> for x in dir(transformers_module) <add> if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING" <add> ] <add> _tensorflow_arch_mappings = [ <add> x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING") <add> ] <add> # _flax_arch_mappings = [x for x in dir(transformers_module) if x.startswith("FLAX_MODEL_") and x.endswith("_MAPPING")] <add> <add> pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings] <add> tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings] <add> # flax_arch_mappings = [getattr(transformers_module, x) for x in _flax_arch_mappings] <add> <add> unexportable_model_architectures = [] <add> <add> ds = load_dataset("wikitext", "wikitext-2-raw-v1") <add> training_ds = ds["train"] <add> testing_ds = ds["test"] <add> <add> def list_str(values): <add> return values.split(",") <add> <add> parser = argparse.ArgumentParser() <add> parser.add_argument("--all", action="store_true", help="Will create all tiny models.") <add> parser.add_argument( <add> "--no_check", <add> action="store_true", <add> help="If set, will not check the validity of architectures. Use with caution.", <add> ) <add> parser.add_argument( <add> "-m", <add> "--model_types", <add> type=list_str, <add> help="Comma-separated list of model type(s) from which the tiny models will be created.", <add> ) <add> parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.") <add> <add> args = parser.parse_args() <add> <add> if not args.all and not args.model_types: <add> raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.") <add> <add> config_classes = CONFIG_MAPPING.values() <add> if not args.all: <add> config_classes = [CONFIG_MAPPING[model_type] for model_type in args.model_types] <add> <add> # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes <add> processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes} <add> <add> to_create = { <add> c: { <add> "processor": processor_type_map[c], <add> "pytorch": get_architectures_from_config_class(c, pytorch_arch_mappings), <add> "tensorflow": get_architectures_from_config_class(c, tensorflow_arch_mappings), <add> # "flax": get_architectures_from_config_class(c, flax_arch_mappings), <add> } <add> for c in config_classes <add> } <add> <add> results = {} <add> for c, models_to_create in list(to_create.items()): <add> print(f"Create models for {c.__name__} ...") <add> result = build(c, models_to_create, output_dir=os.path.join(args.output_path, c.model_type)) <add> results[c.__name__] = result <add> print("=" * 40) <add> <add> with open("tiny_model_creation_report.json", "w") as fp: <add> json.dump(results, fp, indent=4) <add> <add> # Build the failure report <add> failed_results = build_failed_report(results) <add> with open("failed_report.json", "w") as fp: <add> json.dump(failed_results, fp, indent=4) <add> <add> # Build the failure report <add> simple_report, failed_report = build_simple_report(results) <add> with open("simple_report.txt", "w") as fp: <add> fp.write(simple_report) <add> <add> with open("simple_failed_report.txt", "w") as fp: <add> fp.write(failed_report)
2
Ruby
Ruby
remove useless callable_cache_key? check
61b03f37d8117c71ede59b335e493fd8016c414a
<ide><path>actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb <ide> def cache_collection? <ide> end <ide> <ide> def automatic_cache_eligible? <del> @template && !callable_cache_key? && <del> @template.eligible_for_collection_caching?(as: @options[:as]) <add> @template && @template.eligible_for_collection_caching?(as: @options[:as]) <ide> end <ide> <ide> def callable_cache_key?
1
Javascript
Javascript
remove unused variable in combinedcamera.js
e48977f91658cc8cd896d2ac34445f232212c4f5
<ide><path>examples/js/cameras/CombinedCamera.js <ide> THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orth <ide> <ide> this.toPerspective(); <ide> <del> var aspect = width / height; <del> <ide> }; <ide> <ide> THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
1
Java
Java
call the doon{dispose|cancel} handler at most once
76abb7beef3aa0b808cdbe193fd96ef04a5f0903
<ide><path>src/main/java/io/reactivex/Observable.java <ide> public final Observable<T> doOnError(Consumer<? super Throwable> onError) { <ide> <ide> /** <ide> * Calls the appropriate onXXX method (shared between all Observer) for the lifecycle events of <del> * the sequence (subscription, disposal, requesting). <add> * the sequence (subscription, disposal). <ide> * <p> <ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnLifecycle.o.png" alt=""> <ide> * <dl> <ide><path>src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java <ide> public void onNext(T t) { <ide> @Override <ide> public void onError(Throwable t) { <ide> if (upstream != DisposableHelper.DISPOSED) { <add> upstream = DisposableHelper.DISPOSED; <ide> downstream.onError(t); <ide> } else { <ide> RxJavaPlugins.onError(t); <ide> public void onError(Throwable t) { <ide> @Override <ide> public void onComplete() { <ide> if (upstream != DisposableHelper.DISPOSED) { <add> upstream = DisposableHelper.DISPOSED; <ide> downstream.onComplete(); <ide> } <ide> } <ide> <ide> @Override <ide> public void dispose() { <del> try { <del> onDispose.run(); <del> } catch (Throwable e) { <del> Exceptions.throwIfFatal(e); <del> RxJavaPlugins.onError(e); <add> Disposable d = upstream; <add> if (d != DisposableHelper.DISPOSED) { <add> upstream = DisposableHelper.DISPOSED; <add> try { <add> onDispose.run(); <add> } catch (Throwable e) { <add> Exceptions.throwIfFatal(e); <add> RxJavaPlugins.onError(e); <add> } <add> d.dispose(); <ide> } <del> upstream.dispose(); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java <ide> public void request(long n) { <ide> <ide> @Override <ide> public void cancel() { <del> try { <del> onCancel.run(); <del> } catch (Throwable e) { <del> Exceptions.throwIfFatal(e); <del> RxJavaPlugins.onError(e); <add> Subscription s = upstream; <add> if (s != SubscriptionHelper.CANCELLED) { <add> upstream = SubscriptionHelper.CANCELLED; <add> try { <add> onCancel.run(); <add> } catch (Throwable e) { <add> Exceptions.throwIfFatal(e); <add> RxJavaPlugins.onError(e); <add> } <add> s.cancel(); <ide> } <del> upstream.cancel(); <ide> } <ide> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java <ide> public void run() throws Exception { <ide> ); <ide> <ide> assertEquals(1, calls[0]); <del> assertEquals(2, calls[1]); <add> assertEquals(1, calls[1]); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnUnsubscribeTest.java <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.functions.*; <add>import io.reactivex.processors.BehaviorProcessor; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public class FlowableDoOnUnsubscribeTest { <ide> public void run() { <ide> assertEquals("There should exactly 1 un-subscription events for upper stream", 1, upperCount.get()); <ide> assertEquals("There should exactly 1 un-subscription events for lower stream", 1, lowerCount.get()); <ide> } <add> <add> @Test <add> public void noReentrantDispose() { <add> <add> final AtomicInteger cancelCalled = new AtomicInteger(); <add> <add> final BehaviorProcessor<Integer> p = BehaviorProcessor.create(); <add> p.doOnCancel(new Action() { <add> @Override <add> public void run() throws Exception { <add> cancelCalled.incrementAndGet(); <add> p.onNext(2); <add> } <add> }) <add> .firstOrError() <add> .subscribe() <add> .dispose(); <add> <add> assertEquals(1, cancelCalled.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java <ide> public void testUnsubscribeSource() throws Exception { <ide> o.subscribe(); <ide> o.subscribe(); <ide> o.subscribe(); <del> verify(unsubscribe, times(1)).run(); <add> verify(unsubscribe, never()).run(); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnUnsubscribeTest.java <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.observers.TestObserver; <add>import io.reactivex.subjects.BehaviorSubject; <ide> <ide> public class ObservableDoOnUnsubscribeTest { <ide> <ide> public void run() { <ide> assertEquals("There should exactly 1 un-subscription events for upper stream", 1, upperCount.get()); <ide> assertEquals("There should exactly 1 un-subscription events for lower stream", 1, lowerCount.get()); <ide> } <add> <add> @Test <add> public void noReentrantDispose() { <add> <add> final AtomicInteger disposeCalled = new AtomicInteger(); <add> <add> final BehaviorSubject<Integer> s = BehaviorSubject.create(); <add> s.doOnDispose(new Action() { <add> @Override <add> public void run() throws Exception { <add> disposeCalled.incrementAndGet(); <add> s.onNext(2); <add> } <add> }) <add> .firstOrError() <add> .subscribe() <add> .dispose(); <add> <add> assertEquals(1, disposeCalled.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java <ide> public void accept(String v) { <ide> @Test <ide> public void testUnsubscribeSource() throws Exception { <ide> Action unsubscribe = mock(Action.class); <del> Observable<Integer> o = Observable.just(1).doOnDispose(unsubscribe).cache(); <add> Observable<Integer> o = Observable.just(1).doOnDispose(unsubscribe).replay().autoConnect(); <ide> o.subscribe(); <ide> o.subscribe(); <ide> o.subscribe(); <del> verify(unsubscribe, times(1)).run(); <add> verify(unsubscribe, never()).run(); <ide> } <ide> <ide> @Test
8
Mixed
Ruby
add instrumentation for read_multi
62023884f76c108127c8966f4d67bb717338dd66
<ide><path>activesupport/CHANGELOG.md <add>* Add missing instrumentation for `read_multi` in `ActiveSupport::Cache::Store` <add> <add> *Ignatius Reza Lesmana* <add> <ide> * Allow the hash function used to generate non-sensitive digests, such as the <ide> ETag header, to be specified with `config.active_support.hash_digest_class`. <ide> <ide><path>activesupport/lib/active_support/cache.rb <ide> def read_multi(*names) <ide> options = names.extract_options! <ide> options = merged_options(options) <ide> <del> results = {} <del> names.each do |name| <del> key = normalize_key(name, options) <del> version = normalize_version(name, options) <del> entry = read_entry(key, options) <del> <del> if entry <del> if entry.expired? <del> delete_entry(key, options) <del> elsif entry.mismatched?(version) <del> # Skip mismatched versions <del> else <del> results[name] = entry.value <del> end <add> instrument :read_multi, names, options do |payload| <add> read_multi_entries(names, options).tap do |results| <add> payload[:hits] = results.keys <ide> end <ide> end <del> results <ide> end <ide> <ide> # Cache Storage API to write multiple values at once. <ide> def fetch_multi(*names) <ide> options = names.extract_options! <ide> options = merged_options(options) <ide> <del> read_multi(*names, options).tap do |results| <del> writes = {} <add> instrument :read_multi, names, options do |payload| <add> read_multi_entries(names, options).tap do |results| <add> payload[:hits] = results.keys <add> payload[:super_operation] = :fetch_multi <ide> <del> (names - results.keys).each do |name| <del> results[name] = writes[name] = yield(name) <del> end <add> writes = {} <ide> <del> write_multi writes, options <add> (names - results.keys).each do |name| <add> results[name] = writes[name] = yield(name) <add> end <add> <add> write_multi writes, options <add> end <ide> end <ide> end <ide> <ide> def write_entry(key, entry, options) <ide> raise NotImplementedError.new <ide> end <ide> <add> # Reads multiple entries from the cache implementation. Subclasses MAY <add> # implement this method. <add> def read_multi_entries(names, options) <add> results = {} <add> names.each do |name| <add> key = normalize_key(name, options) <add> version = normalize_version(name, options) <add> entry = read_entry(key, options) <add> <add> if entry <add> if entry.expired? <add> delete_entry(key, options) <add> elsif entry.mismatched?(version) <add> # Skip mismatched versions <add> else <add> results[name] = entry.value <add> end <add> end <add> end <add> results <add> end <add> <ide> # Writes multiple entries to the cache implementation. Subclasses MAY <ide> # implement this method. <ide> def write_multi_entries(hash, options) <ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb <ide> def initialize(*addresses) <ide> end <ide> end <ide> <del> # Reads multiple values from the cache using a single call to the <del> # servers for all keys. Options can be passed in the last argument. <del> def read_multi(*names) <del> options = names.extract_options! <del> options = merged_options(options) <del> <del> keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }] <del> <del> raw_values = @data.get_multi(keys_to_names.keys) <del> values = {} <del> <del> raw_values.each do |key, value| <del> entry = deserialize_entry(value) <del> <del> unless entry.expired? || entry.mismatched?(normalize_version(keys_to_names[key], options)) <del> values[keys_to_names[key]] = entry.value <del> end <del> end <del> <del> values <del> end <del> <ide> # Increment a cached value. This method uses the memcached incr atomic <ide> # operator and can only be used on values written with the :raw option. <ide> # Calling it on a value not stored with :raw will initialize that value <ide> def write_entry(key, entry, options) <ide> end <ide> end <ide> <add> # Reads multiple entries from the cache implementation. <add> def read_multi_entries(names, options) <add> keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }] <add> <add> raw_values = @data.get_multi(keys_to_names.keys) <add> values = {} <add> <add> raw_values.each do |key, value| <add> entry = deserialize_entry(value) <add> <add> unless entry.expired? || entry.mismatched?(normalize_version(keys_to_names[key], options)) <add> values[keys_to_names[key]] = entry.value <add> end <add> end <add> <add> values <add> end <add> <ide> # Delete an entry from the cache. <ide> def delete_entry(key, options) <ide> rescue_error_with(false) { @data.delete(key) } <ide><path>activesupport/test/cache/cache_store_write_multi_test.rb <ide> class CacheStoreWriteMultiEntriesStoreProviderInterfaceTest < ActiveSupport::Tes <ide> <ide> class CacheStoreWriteMultiInstrumentationTest < ActiveSupport::TestCase <ide> setup do <del> @cache = ActiveSupport::Cache.lookup_store(:null_store) <add> @cache = ActiveSupport::Cache.lookup_store(:memory_store) <ide> end <ide> <ide> test "instrumentation" do <ide> class CacheStoreWriteMultiInstrumentationTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "instrumentation with fetch_multi as super operation" do <del> skip "fetch_multi isn't instrumented yet" <add> @cache.write("b", "bb") <ide> <del> events = with_instrumentation "write_multi" do <add> events = with_instrumentation "read_multi" do <ide> @cache.fetch_multi("a", "b") { |key| key * 2 } <ide> end <ide> <del> assert_equal %w[ cache_write_multi.active_support ], events.map(&:name) <del> assert_nil events[0].payload[:super_operation] <del> assert !events[0].payload[:hit] <add> assert_equal %w[ cache_read_multi.active_support ], events.map(&:name) <add> assert_equal :fetch_multi, events[0].payload[:super_operation] <add> assert_equal ["b"], events[0].payload[:hits] <ide> end <ide> <ide> private
4
Javascript
Javascript
add test case for watching in production
d9af746c147e3a7b0a8be239ba2c012e5431cab7
<ide><path>test/watchCases/simple/production/0/changing-file.js <add>module.exports = "0"; <ide><path>test/watchCases/simple/production/0/changing-module.js <add>export default "0"; <ide><path>test/watchCases/simple/production/0/index.js <add>import module from "./changing-module"; <add> <add>it("should watch for changes", function () { <add> expect(require("./changing-file")).toBe(WATCH_STEP); <add> expect(module).toBe(WATCH_STEP); <add>}); <ide><path>test/watchCases/simple/production/1/changing-file.js <add>module.exports = "1"; <ide><path>test/watchCases/simple/production/1/changing-module.js <add>export default "1"; <ide><path>test/watchCases/simple/production/2/changing-file.js <add>module.exports = "2"; <ide><path>test/watchCases/simple/production/2/changing-module.js <add>export default "2"; <ide><path>test/watchCases/simple/production/webpack.config.js <add>/** @type {import("../../../../").Configuration} */ <add>module.exports = { <add> mode: "production" <add>};
8
Python
Python
update ctrl configuration
bd5363cc8330229b14c668bdc3340e8a4902e608
<ide><path>transformers/configuration_ctrl.py <ide> def __init__( <ide> """ <ide> super(CTRLConfig, self).__init__(**kwargs) <ide> <add> self.vocab_size = vocab_size_or_config_json_file if isinstance(vocab_size_or_config_json_file, int) else -1 <add> self.n_ctx = n_ctx <add> self.n_positions = n_positions <add> self.n_embd = n_embd <add> self.n_layer = n_layer <add> self.n_head = n_head <add> self.dff = dff <add> self.resid_pdrop = resid_pdrop <add> self.embd_pdrop = embd_pdrop <add> self.attn_pdrop = attn_pdrop <add> self.layer_norm_epsilon = layer_norm_epsilon <add> self.initializer_range = initializer_range <add> <add> self.num_labels = num_labels <add> self.summary_type = summary_type <add> self.summary_use_proj = summary_use_proj <add> self.summary_activation = summary_activation <add> self.summary_first_dropout = summary_first_dropout <add> self.summary_proj_to_labels = summary_proj_to_labels <ide> if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2 <ide> and isinstance(vocab_size_or_config_json_file, unicode)): <ide> with open(vocab_size_or_config_json_file, "r", encoding="utf-8") as reader: <ide> json_config = json.loads(reader.read()) <ide> for key, value in json_config.items(): <ide> self.__dict__[key] = value <del> elif isinstance(vocab_size_or_config_json_file, int): <del> self.vocab_size = vocab_size_or_config_json_file <del> self.n_ctx = n_ctx <del> self.n_positions = n_positions <del> self.n_embd = n_embd <del> self.n_layer = n_layer <del> self.n_head = n_head <del> self.dff = dff <del> self.resid_pdrop = resid_pdrop <del> self.embd_pdrop = embd_pdrop <del> self.attn_pdrop = attn_pdrop <del> self.layer_norm_epsilon = layer_norm_epsilon <del> self.initializer_range = initializer_range <del> <del> self.num_labels = num_labels <del> self.summary_type = summary_type <del> self.summary_use_proj = summary_use_proj <del> self.summary_activation = summary_activation <del> self.summary_first_dropout = summary_first_dropout <del> self.summary_proj_to_labels = summary_proj_to_labels <del> else: <add> elif not isinstance(vocab_size_or_config_json_file, int): <ide> raise ValueError( <ide> "First argument must be either a vocabulary size (int)" <ide> "or the path to a pretrained model config file (str)"
1
Text
Text
suggest vectors changes
052d82aa4e758f0e7fe4665240fe0c7a9e0497fc
<ide><path>website/docs/usage/vectors-embeddings.md <ide> title: Vectors and Embeddings <ide> menu: <ide> - ["What's a Word Vector?", 'whats-a-vector'] <del> - ['Word Vectors', 'vectors'] <del> - ['Other Embeddings', 'embeddings'] <add> - ['Using Word Vectors', 'usage'] <add> - ['Converting and Importing', 'converting'] <ide> next: /usage/transformers <ide> --- <ide> <del>An old idea in linguistics is that you can "know a word by the company it <del>keeps": that is, word meanings can be understood relationally, based on their <del>patterns of usage. This idea inspired a branch of NLP research known as <del>"distributional semantics" that has aimed to compute databases of lexical <del>knowledge automatically. The [Word2vec](https://en.wikipedia.org/wiki/Word2vec) <del>family of algorithms are a key milestone in this line of research. For <del>simplicity, we will refer to a distributional word representation as a "word <del>vector", and algorithms that computes word vectors (such as <del>[GloVe](https://nlp.stanford.edu/projects/glove/), <del>[FastText](https://fasttext.cc), etc.) as "Word2vec algorithms". <del> <add>Word vector tables (or "embeddings") let you find similar terms, and can improve <add>the accuracy of some of your components. You can even use word vectors as a <add>quick-and-dirty text-classification solution when you don't have any training data. <ide> Word vector tables are included in some of the spaCy [model packages](/models) <ide> we distribute, and you can easily create your own model packages with word <del>vectors you train or download yourself. In some cases you can also add word <del>vectors to an existing pipeline, although each pipeline can only have a single <del>word vectors table, and a model package that already has word vectors is <del>unlikely to work correctly if you replace the vectors with new ones. <add>vectors you train or download yourself. <ide> <ide> ## What's a word vector? {#whats-a-vector} <ide> <ide> def what_is_a_word_vector( <ide> return vectors_table[key2row.get(word_id, default_row)] <ide> ``` <ide> <add>An old idea in linguistics is that you can "know a word by the company it <add>keeps": that is, word meanings can be understood relationally, based on their <add>patterns of usage. This idea inspired a branch of NLP research known as <add>"distributional semantics" that has aimed to compute databases of lexical <add>knowledge automatically. The [Word2vec](https://en.wikipedia.org/wiki/Word2vec) <add>family of algorithms are a key milestone in this line of research. For <add>simplicity, we will refer to a distributional word representation as a "word <add>vector", and algorithms that computes word vectors (such as <add>[GloVe](https://nlp.stanford.edu/projects/glove/), <add>[FastText](https://fasttext.cc), etc.) as "Word2vec algorithms". <add> <ide> Word2vec algorithms try to produce vectors tables that let you estimate useful <ide> relationships between words using simple linear algebra operations. For <ide> instance, you can often find close synonyms of a word by finding the vectors <ide> statistical models. <ide> <ide> ### Word vectors vs. contextual language models {#vectors-vs-language-models} <ide> <del>The key difference between word vectors and contextual language models such as <del>ElMo, BERT and GPT-2 is that word vectors model **lexical types**, rather than <del>_tokens_. If you have a list of terms with no context around them, a model like <del>BERT can't really help you. BERT is designed to understand language **in <del>context**, which isn't what you have. A word vectors table will be a much better <del>fit for your task. However, if you do have words in context — whole sentences or <del>paragraphs of running text — word vectors will only provide a very rough <del>approximation of what the text is about. <add>The key difference between word vectors and contextual language models such <add>as [transformers](/usage/transformers) <add>is that word vectors model **lexical types**, rather than <add>_tokens_. If you have a list of terms with no context around them, <add>a transformer model like BERT can't really help you. BERT is designed to understand <add>language **in context**, which isn't what you have. A word vectors table will be <add>a much better fit for your task. However, if you do have words in context — whole <add>sentences or paragraphs of running text — word vectors will only provide a very <add>rough approximation of what the text is about. <ide> <ide> Word vectors are also very computationally efficient, as they map a word to a <ide> vector with a single indexing operation. Word vectors are therefore useful as a <ide> gradients to the pretrained word vectors table. The static vectors table is <ide> usually used in combination with a smaller table of learned task-specific <ide> embeddings. <ide> <del>## Using word vectors directly {#vectors} <add>## Using word vectors {#usage} <ide> <ide> spaCy stores word vector information in the <ide> [`Vocab.vectors`](/api/vocab#attributes) attribute, so you can access the whole <ide> whether you've configured spaCy to use GPU memory), with dtype `float32`. The <ide> array is read-only so that spaCy can avoid unnecessary copy operations where <ide> possible. You can modify the vectors via the `Vocab` or `Vectors` table. <ide> <del>### Converting word vectors for use in spaCy <add>### Word vectors and similarity <add> <add>A common use-case of word vectors is to answer _similarity questions_. You can <add>ask how similar a `token`, `span`, `doc` or `lexeme` is to another object using <add>the `.similarity()` method. You can even check the similarity of mismatched <add>types, asking how similar a whole document is to a particular word, how similar <add>a span is to a document, etc. By default, the `.similarity()` method will use <add>return the cosine of the `.vector` attribute of the two objects being compared. <add>You can customize this behavior by setting one or more <add>[user hooks](/usage/processing-pipelines#custom-components-user-hooks) for the <add>types you want to customize. <add> <add>Word vector similarity is a practical technique for many situations, especially <add>since it's easy to use and relatively efficient to compute. However, it's <add>important to maintain realistic expectations about what information it can <add>provide. Words can be related to each over in many ways, so a single <add>"similarity" score will always be a mix of different signals. The word vectors <add>model is also not trained for your specific use-case, so you have no way of <add>telling it which results are more or less useful for your purpose. These <add>problems are even more accute when you go from measuring the similarity of <add>single words to the similarity of spans or documents. The vector averaging <add>process is insensitive to the order of the words, so `doc1.similarity(doc2)` <add>will mostly be based on the overlap in lexical items between the two documents <add>objects. Two documents expressing the same meaning with dissimilar wording will <add>return a lower similarity score than two documents that happen to contain the <add>same words while expressing different meanings. <add> <add>### Using word vectors in your models <add> <add>Many neural network models are able to use word vector tables as additional <add>features, which sometimes results in significant improvements in accuracy. <add>spaCy's built-in embedding layer, `spacy.MultiHashEmbed.v1`, can be configured <add>to use word vector tables using the `also_use_static_vectors` flag. This <add>setting is also available on the `spacy.MultiHashEmbedCNN.v1` layer, which <add>builds the default token-to-vector encoding architecture. <add> <add>``` <add>[tagger.model.tok2vec.embed] <add>@architectures = "spacy.MultiHashEmbed.v1" <add>width = 128 <add>rows = 7000 <add>also_embed_subwords = true <add>also_use_static_vectors = true <add>``` <add> <add><Infobox title="How it works"> <add>The configuration system will look up the string `spacy.MultiHashEmbed.v1` <add>in the `architectures` registry, and call the returned object with the <add>rest of the arguments from the block. This will result in a call to the <add>`spacy.ml.models.tok2vec.MultiHashEmbed` function, which will return <add>a Thinc model object with the type signature `Model[List[Doc], <add>List[Floats2d]]`. Because the embedding layer takes a list of `Doc` objects as <add>input, it does not need to store a copy of the vectors table. The vectors will <add>be retrieved from the `Doc` objects that are passed in, via the <add>`doc.vocab.vectors` attribute. This part of the process is handled by the <add>`spacy.ml.staticvectors.StaticVectors` layer. <add></Infobox> <add> <add>#### Creating a custom embedding layer <add> <add>The `MultiHashEmbed` layer is spaCy's recommended strategy for constructing <add>initial word representations for your neural network models, but you can also <add>implement your own. You can register any function to a string name, and then <add>reference that function within your config (see the [training]("/usage/training") <add>section for more details). To try this out, you can save the following little <add>example to a new Python file: <add> <add>``` <add>from spacy.ml.staticvectors import StaticVectors <add>from spacy.util import registry <add> <add>print("I was imported!") <add> <add>@registry.architectures("my_example.MyEmbedding.v1") <add>def MyEmbedding(output_width: int) -> Model[List[Doc], List[Floats2d]]: <add> print("I was called!") <add> return StaticVectors(nO=output_width) <add>``` <add> <add>If you pass the path to your file to the `spacy train` command using the `-c` <add>argument, your file will be imported, which means the decorator registering the <add>function will be run. Your function is now on equal footing with any of spaCy's <add>built-ins, so you can drop it in instead of any other model with the same input <add>and output signature. For instance, you could use it in the tagger model as <add>follows: <add> <add>``` <add>[tagger.model.tok2vec.embed] <add>@architectures = "my_example.MyEmbedding.v1" <add>output_width = 128 <add>``` <add> <add>Now that you have a custom function wired into the network, you can start <add>implementing the logic you're interested in. For example, let's say you want to <add>try a relatively simple embedding strategy that makes use of static word vectors, <add>but combines them via summation with a smaller table of learned embeddings. <add> <add>```python <add>from thinc.api import add, chain, remap_ids, Embed <add>from spacy.ml.staticvectors import StaticVectors <add> <add>@registry.architectures("my_example.MyEmbedding.v1") <add>def MyCustomVectors( <add> output_width: int, <add> vector_width: int, <add> embed_rows: int, <add> key2row: Dict[int, int] <add>) -> Model[List[Doc], List[Floats2d]]: <add> return add( <add> StaticVectors(nO=output_width), <add> chain( <add> FeatureExtractor(["ORTH"]), <add> remap_ids(key2row), <add> Embed(nO=output_width, nV=embed_rows) <add> ) <add> ) <add>``` <add> <add>#### When should you add word vectors to your model? <add> <add>Word vectors are not compatible with most [transformer models](/usage/transformers), <add>but if you're training another type of NLP network, it's almost always worth <add>adding word vectors to your model. As well as improving your final accuracy, <add>word vectors often make experiments more consistent, as the accuracy you <add>reach will be less sensitive to how the network is randomly initialized. High <add>variance due to random chance can slow down your progress significantly, as you <add>need to run many experiments to filter the signal from the noise. <add> <add>Word vector features need to be enabled prior to training, and the same word vectors <add>table will need to be available at runtime as well. You cannot add word vector <add>features once the model has already been trained, and you usually cannot <add>replace one word vectors table with another without causing a significant loss <add>of performance. <add> <add>## Converting word vectors for use in spaCy {#converting} <ide> <ide> Custom word vectors can be trained using a number of open-source libraries, such <ide> as [Gensim](https://radimrehurek.com/gensim), [Fast Text](https://fasttext.cc), <ide> vector among those retained. <ide> <ide> ### Adding vectors {#adding-vectors} <ide> <add>You can also add word vectors individually, using the method `vocab.set_vector`. <add>This is often the easiest approach if you have vectors in an arbitrary format, <add>as you can read in the vectors with your own logic, and just set them with <add>a simple loop. This method is likely to be slower than approaches that work <add>with the whole vectors table at once, but it's a great approach for once-off <add>conversions before you save out your model to disk. <add> <ide> ```python <ide> ### Adding vectors <ide> from spacy.vocab import Vocab <ide> vocab = Vocab() <ide> for word, vector in vector_data.items(): <ide> vocab.set_vector(word, vector) <ide> ``` <del> <del>### Using custom similarity methods {#custom-similarity} <del> <del>By default, [`Token.vector`](/api/token#vector) returns the vector for its <del>underlying [`Lexeme`](/api/lexeme), while [`Doc.vector`](/api/doc#vector) and <del>[`Span.vector`](/api/span#vector) return an average of the vectors of their <del>tokens. You can customize these behaviors by modifying the `doc.user_hooks`, <del>`doc.user_span_hooks` and `doc.user_token_hooks` dictionaries. <del> <del><Infobox title="Custom user hooks" emoji="📖"> <del> <del>For more details on **adding hooks** and **overwriting** the built-in `Doc`, <del>`Span` and `Token` methods, see the usage guide on <del>[user hooks](/usage/processing-pipelines#custom-components-user-hooks). <del> <del></Infobox> <del> <del><!-- TODO: <del> <del>### Storing vectors on a GPU {#gpu} <del> <del>--> <del> <del>## Other embeddings {#embeddings} <del> <del><!-- TODO: something about other embeddings -->
1
Text
Text
add link for guide to illustrator
7f690b8b3c08ad1874df15b7516b28e8b38f53cc
<ide><path>guide/english/designer-tools/illustrator/index.md <ide> The main feature that separates Adobe Illustrator from Photoshop is the use of v <ide> - [Introduction to Flat Design](https://design.tutsplus.com/tutorials/10-top-tips-on-creating-flat-design-graphics--cms-25888) <ide> - [Creating flat icons using illustrator](https://design.tutsplus.com/tutorials/create-a-set-of-flat-precious-gems-icons-in-adobe-illustrator--vector-26188) <ide> - [Illustrator tutorials](https://helpx.adobe.com/illustrator/tutorials.html) <add>- [The Complete Beginners Guide To Adobe Illustrator | Tutorial Overview & Breakdown](https://www.youtube.com/watch?v=IBouhf4seWQ)
1
Go
Go
remove checkout directory on error
4ea320cb8ef71c2fc9ee391e2e8be915ba99b17e
<ide><path>builder/remotecontext/git/gitutils.go <ide> func Clone(remoteURL string) (string, error) { <ide> return cloneGitRepo(repo) <ide> } <ide> <del>func cloneGitRepo(repo gitRepo) (string, error) { <add>func cloneGitRepo(repo gitRepo) (checkoutDir string, err error) { <ide> fetch := fetchArgs(repo.remote, repo.ref) <ide> <ide> root, err := ioutil.TempDir("", "docker-build-git") <ide> if err != nil { <ide> return "", err <ide> } <ide> <add> defer func() { <add> if err != nil { <add> os.RemoveAll(root) <add> } <add> }() <add> <ide> if out, err := gitWithinDir(root, "init"); err != nil { <ide> return "", errors.Wrapf(err, "failed to init repo at %s: %s", root, out) <ide> } <ide> func cloneGitRepo(repo gitRepo) (string, error) { <ide> return "", errors.Wrapf(err, "error fetching: %s", output) <ide> } <ide> <del> root, err = checkoutGit(root, repo.ref, repo.subdir) <add> checkoutDir, err = checkoutGit(root, repo.ref, repo.subdir) <ide> if err != nil { <ide> return "", err <ide> } <ide> func cloneGitRepo(repo gitRepo) (string, error) { <ide> return "", errors.Wrapf(err, "error initializing submodules: %s", output) <ide> } <ide> <del> return root, nil <add> return checkoutDir, nil <ide> } <ide> <ide> func parseRemoteURL(remoteURL string) (gitRepo, error) { <ide><path>builder/remotecontext/git/gitutils_test.go <ide> func TestCheckoutGit(t *testing.T) { <ide> if c.fail { <ide> assert.Error(t, err) <ide> continue <del> } else { <add> } <add> require.NoError(t, err) <add> defer os.RemoveAll(r) <add> if c.submodule { <add> b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile")) <ide> require.NoError(t, err) <del> if c.submodule { <del> b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile")) <del> require.NoError(t, err) <del> assert.Equal(t, "subcontents", string(b)) <del> } else { <del> _, err := os.Stat(filepath.Join(r, "sub/subfile")) <del> require.Error(t, err) <del> require.True(t, os.IsNotExist(err)) <del> } <add> assert.Equal(t, "subcontents", string(b)) <add> } else { <add> _, err := os.Stat(filepath.Join(r, "sub/subfile")) <add> require.Error(t, err) <add> require.True(t, os.IsNotExist(err)) <ide> } <ide> <ide> b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
2
Text
Text
add hints on how to deal with values of new fields
1cf8e18f165081b259da0cae51657857eb7c8c2b
<ide><path>guides/source/getting_started.md <ide> And next, let's update the database with the generated migrations: <ide> $ bin/rails db:migrate <ide> ``` <ide> <add>To choose the status for the existing articles and comments you can add a default value to the generated migration files by adding the `default: "public"` option and launch the migrations again. You can also call in a rails console `Article.update_all(status: "public")` and `Comment.update_all(status: "public")`. <add> <add> <ide> TIP: To learn more about migrations, see [Active Record Migrations]( <ide> active_record_migrations.html). <ide>
1
Text
Text
remove good luck! comment from challenge seed code
8788ad946b02e4fdbbe7dc45e5fd906aad6ab1d3
<ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-1-multiples-of-3-and-5.english.md <ide> tests: <ide> <ide> ```js <ide> function multiplesOf3and5(number) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function primeSummation(n) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-100-arranged-probability.english.md <ide> tests: <ide> <ide> ```js <ide> function arrangedProbability() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-101-optimum-polynomial.english.md <ide> tests: <ide> <ide> ```js <ide> function euler101() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-102-triangle-containment.english.md <ide> tests: <ide> <ide> ```js <ide> function euler102() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-103-special-subset-sums-optimum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler103() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-104-pandigital-fibonacci-ends.english.md <ide> tests: <ide> <ide> ```js <ide> function euler104() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-105-special-subset-sums-testing.english.md <ide> tests: <ide> <ide> ```js <ide> function euler105() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-106-special-subset-sums-meta-testing.english.md <ide> tests: <ide> <ide> ```js <ide> function euler106() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-107-minimal-network.english.md <ide> tests: <ide> <ide> ```js <ide> function euler107() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-108-diophantine-reciprocals-i.english.md <ide> tests: <ide> <ide> ```js <ide> function diophantineOne() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-109-darts.english.md <ide> tests: <ide> <ide> ```js <ide> function euler109() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-11-largest-product-in-a-grid.english.md <ide> tests: <ide> <ide> ```js <ide> function largestGridProduct(arr) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-110-diophantine-reciprocals-ii.english.md <ide> tests: <ide> <ide> ```js <ide> function diophantineTwo() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-111-primes-with-runs.english.md <ide> tests: <ide> <ide> ```js <ide> function euler111() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-112-bouncy-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler112() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-113-non-bouncy-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler113() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-114-counting-block-combinations-i.english.md <ide> tests: <ide> <ide> ```js <ide> function euler114() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-115-counting-block-combinations-ii.english.md <ide> tests: <ide> <ide> ```js <ide> function euler115() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-116-red-green-or-blue-tiles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler116() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-117-red-green-and-blue-tiles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler117() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-118-pandigital-prime-sets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler118() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-119-digit-power-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler119() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-12-highly-divisible-triangular-number.english.md <ide> tests: <ide> <ide> ```js <ide> function divisibleTriangleNumber(n) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-120-square-remainders.english.md <ide> tests: <ide> <ide> ```js <ide> function euler120() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-121-disc-game-prize-fund.english.md <ide> tests: <ide> <ide> ```js <ide> function euler121() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-122-efficient-exponentiation.english.md <ide> tests: <ide> <ide> ```js <ide> function euler122() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-123-prime-square-remainders.english.md <ide> tests: <ide> <ide> ```js <ide> function euler123() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-124-ordered-radicals.english.md <ide> tests: <ide> <ide> ```js <ide> function euler124() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-125-palindromic-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function euler125() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-126-cuboid-layers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler126() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-127-abc-hits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler127() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-128-hexagonal-tile-differences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler128() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-129-repunit-divisibility.english.md <ide> tests: <ide> <ide> ```js <ide> function euler129() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-13-large-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function largeSum(arr) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-130-composites-with-prime-repunit-property.english.md <ide> tests: <ide> <ide> ```js <ide> function euler130() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-131-prime-cube-partnership.english.md <ide> tests: <ide> <ide> ```js <ide> function euler131() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-132-large-repunit-factors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler132() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-133-repunit-nonfactors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler133() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-134-prime-pair-connection.english.md <ide> tests: <ide> <ide> ```js <ide> function euler134() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-135-same-differences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler135() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-136-singleton-difference.english.md <ide> tests: <ide> <ide> ```js <ide> function euler136() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-137-fibonacci-golden-nuggets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler137() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-138-special-isosceles-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler138() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-139-pythagorean-tiles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler139() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-14-longest-collatz-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function longestCollatzSequence(limit) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-140-modified-fibonacci-golden-nuggets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler140() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-141-investigating-progressive-numbers-n-which-are-also-square.english.md <ide> tests: <ide> <ide> ```js <ide> function euler141() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-142-perfect-square-collection.english.md <ide> tests: <ide> <ide> ```js <ide> function euler142() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-143-investigating-the-torricelli-point-of-a-triangle.english.md <ide> tests: <ide> <ide> ```js <ide> function euler143() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-144-investigating-multiple-reflections-of-a-laser-beam.english.md <ide> tests: <ide> <ide> ```js <ide> function euler144() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-145-how-many-reversible-numbers-are-there-below-one-billion.english.md <ide> tests: <ide> <ide> ```js <ide> function euler145() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-146-investigating-a-prime-pattern.english.md <ide> tests: <ide> <ide> ```js <ide> function euler146() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-147-rectangles-in-cross-hatched-grids.english.md <ide> tests: <ide> <ide> ```js <ide> function euler147() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-148-exploring-pascals-triangle.english.md <ide> tests: <ide> <ide> ```js <ide> function euler148() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-149-searching-for-a-maximum-sum-subsequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler149() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-15-lattice-paths.english.md <ide> tests: <ide> <ide> ```js <ide> function latticePaths(gridSize) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-150-searching-a-triangular-array-for-a-sub-triangle-having-minimum-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler150() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-151-paper-sheets-of-standard-sizes-an-expected-value-problem.english.md <ide> tests: <ide> <ide> ```js <ide> function euler151() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-152-writing-one-half-as-a-sum-of-inverse-squares.english.md <ide> tests: <ide> <ide> ```js <ide> function euler152() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-153-investigating-gaussian-integers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler153() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-154-exploring-pascals-pyramid.english.md <ide> tests: <ide> <ide> ```js <ide> function euler154() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-155-counting-capacitor-circuits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler155() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-156-counting-digits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler156() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-157-solving-the-diophantine-equation.english.md <ide> tests: <ide> <ide> ```js <ide> function euler157() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-158-exploring-strings-for-which-only-one-character-comes-lexicographically-after-its-neighbour-to-the-left.english.md <ide> tests: <ide> <ide> ```js <ide> function euler158() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-159-digital-root-sums-of-factorisations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler159() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-16-power-digit-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function powerDigitSum(exponent) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-160-factorial-trailing-digits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler160() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-161-triominoes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler161() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-162-hexadecimal-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler162() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-163-cross-hatched-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler163() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-164-numbers-for-which-no-three-consecutive-digits-have-a-sum-greater-than-a-given-value.english.md <ide> tests: <ide> <ide> ```js <ide> function euler164() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-165-intersections.english.md <ide> tests: <ide> <ide> ```js <ide> function euler165() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-166-criss-cross.english.md <ide> tests: <ide> <ide> ```js <ide> function euler166() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-167-investigating-ulam-sequences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler167() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-168-number-rotations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler168() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-169-exploring-the-number-of-different-ways-a-number-can-be-expressed-as-a-sum-of-powers-of-2.english.md <ide> tests: <ide> <ide> ```js <ide> function euler169() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-17-number-letter-counts.english.md <ide> tests: <ide> <ide> ```js <ide> function numberLetterCounts(limit) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-170-find-the-largest-0-to-9-pandigital-that-can-be-formed-by-concatenating-products.english.md <ide> tests: <ide> <ide> ```js <ide> function euler170() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-171-finding-numbers-for-which-the-sum-of-the-squares-of-the-digits-is-a-square.english.md <ide> tests: <ide> <ide> ```js <ide> function euler171() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-172-investigating-numbers-with-few-repeated-digits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler172() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-173-using-up-to-one-million-tiles-how-many-different-hollow-square-laminae-can-be-formed.english.md <ide> tests: <ide> <ide> ```js <ide> function euler173() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-174-counting-the-number-of-hollow-square-laminae-that-can-form-one-two-three-...-distinct-arrangements.english.md <ide> tests: <ide> <ide> ```js <ide> function euler174() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-175-fractions-involving-the-number-of-different-ways-a-number-can-be-expressed-as-a-sum-of-powers-of-2.english.md <ide> tests: <ide> <ide> ```js <ide> function euler175() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-176-right-angled-triangles-that-share-a-cathetus.english.md <ide> tests: <ide> <ide> ```js <ide> function euler176() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-177-integer-angled-quadrilaterals.english.md <ide> tests: <ide> <ide> ```js <ide> function euler177() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-178-step-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler178() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-179-consecutive-positive-divisors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler179() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-18-maximum-path-sum-i.english.md <ide> tests: <ide> <ide> ```js <ide> function maximumPathSumI(triangle) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-180-rational-zeros-of-a-function-of-three-variables.english.md <ide> tests: <ide> <ide> ```js <ide> function euler180() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-181-investigating-in-how-many-ways-objects-of-two-different-colours-can-be-grouped.english.md <ide> tests: <ide> <ide> ```js <ide> function euler181() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-182-rsa-encryption.english.md <ide> tests: <ide> <ide> ```js <ide> function euler182() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-183-maximum-product-of-parts.english.md <ide> tests: <ide> <ide> ```js <ide> function euler183() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-184-triangles-containing-the-origin.english.md <ide> tests: <ide> <ide> ```js <ide> function euler184() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-185-number-mind.english.md <ide> tests: <ide> <ide> ```js <ide> function euler185() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-186-connectedness-of-a-network.english.md <ide> tests: <ide> <ide> ```js <ide> function euler186() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-187-semiprimes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler187() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-188-the-hyperexponentiation-of-a-number.english.md <ide> tests: <ide> <ide> ```js <ide> function euler188() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-189-tri-colouring-a-triangular-grid.english.md <ide> tests: <ide> <ide> ```js <ide> function euler189() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-19-counting-sundays.english.md <ide> tests: <ide> <ide> ```js <ide> function countingSundays(firstYear, lastYear) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-190-maximising-a-weighted-product.english.md <ide> tests: <ide> <ide> ```js <ide> function euler190() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-191-prize-strings.english.md <ide> tests: <ide> <ide> ```js <ide> function euler191() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-192-best-approximations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler192() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-193-squarefree-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler193() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-194-coloured-configurations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler194() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-195-inscribed-circles-of-triangles-with-one-angle-of-60-degrees.english.md <ide> tests: <ide> <ide> ```js <ide> function euler195() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-196-prime-triplets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler196() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-197-investigating-the-behaviour-of-a-recursively-defined-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler197() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-198-ambiguous-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler198() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-199-iterative-circle-packing.english.md <ide> tests: <ide> <ide> ```js <ide> function iterativeCirclePacking(n) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-20-factorial-digit-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function sumFactorialDigits(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-200-find-the-200th-prime-proof-sqube-containing-the-contiguous-sub-string-200.english.md <ide> tests: <ide> <ide> ```js <ide> function euler200() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-201-subsets-with-a-unique-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler201() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-202-laserbeam.english.md <ide> tests: <ide> <ide> ```js <ide> function euler202() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-203-squarefree-binomial-coefficients.english.md <ide> tests: <ide> <ide> ```js <ide> function euler203() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-204-generalised-hamming-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler204() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-205-dice-game.english.md <ide> tests: <ide> <ide> ```js <ide> function euler205() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-206-concealed-square.english.md <ide> tests: <ide> <ide> ```js <ide> function euler206() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-207-integer-partition-equations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler207() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-208-robot-walks.english.md <ide> tests: <ide> <ide> ```js <ide> function euler208() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-209-circular-logic.english.md <ide> tests: <ide> <ide> ```js <ide> function euler209() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-21-amicable-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function sumAmicableNum(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-210-obtuse-angled-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler210() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-211-divisor-square-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler211() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-212-combined-volume-of-cuboids.english.md <ide> tests: <ide> <ide> ```js <ide> function euler212() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-213-flea-circus.english.md <ide> tests: <ide> <ide> ```js <ide> function euler213() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-214-totient-chains.english.md <ide> tests: <ide> <ide> ```js <ide> function euler214() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-215-crack-free-walls.english.md <ide> tests: <ide> <ide> ```js <ide> function euler215() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-216-investigating-the-primality-of-numbers-of-the-form-2n2-1.english.md <ide> tests: <ide> <ide> ```js <ide> function euler216() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-217-balanced-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler217() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-218-perfect-right-angled-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler218() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-219-skew-cost-coding.english.md <ide> tests: <ide> <ide> ```js <ide> function euler219() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-22-names-scores.english.md <ide> tests: <ide> <ide> ```js <ide> function namesScores(arr) { <del> // Good luck! <add> <ide> return arr; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-220-heighway-dragon.english.md <ide> tests: <ide> <ide> ```js <ide> function euler220() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-221-alexandrian-integers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler221() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-222-sphere-packing.english.md <ide> tests: <ide> <ide> ```js <ide> function euler222() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-223-almost-right-angled-triangles-i.english.md <ide> tests: <ide> <ide> ```js <ide> function euler223() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-224-almost-right-angled-triangles-ii.english.md <ide> tests: <ide> <ide> ```js <ide> function euler224() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-225-tribonacci-non-divisors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler225() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-226-a-scoop-of-blancmange.english.md <ide> tests: <ide> <ide> ```js <ide> function euler226() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-227-the-chase.english.md <ide> tests: <ide> <ide> ```js <ide> function euler227() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-228-minkowski-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function euler228() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-229-four-representations-using-squares.english.md <ide> tests: <ide> <ide> ```js <ide> function euler229() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-23-non-abundant-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function sumOfNonAbundantNumbers(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-230-fibonacci-words.english.md <ide> tests: <ide> <ide> ```js <ide> function euler230() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-231-the-prime-factorisation-of-binomial-coefficients.english.md <ide> tests: <ide> <ide> ```js <ide> function euler231() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-232-the-race.english.md <ide> tests: <ide> <ide> ```js <ide> function euler232() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-233-lattice-points-on-a-circle.english.md <ide> tests: <ide> <ide> ```js <ide> function euler233() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-234-semidivisible-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler234() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-235-an-arithmetic-geometric-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler235() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-236-luxury-hampers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler236() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-237-tours-on-a-4-x-n-playing-board.english.md <ide> tests: <ide> <ide> ```js <ide> function euler237() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-238-infinite-string-tour.english.md <ide> tests: <ide> <ide> ```js <ide> function euler238() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-239-twenty-two-foolish-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler239() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-24-lexicographic-permutations.english.md <ide> tests: <ide> <ide> ```js <ide> function lexicographicPermutations(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-240-top-dice.english.md <ide> tests: <ide> <ide> ```js <ide> function euler240() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-241-perfection-quotients.english.md <ide> tests: <ide> <ide> ```js <ide> function euler241() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-242-odd-triplets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler242() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-243-resilience.english.md <ide> tests: <ide> <ide> ```js <ide> function euler243() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-244-sliders.english.md <ide> tests: <ide> <ide> ```js <ide> function euler244() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-245-coresilience.english.md <ide> tests: <ide> <ide> ```js <ide> function euler245() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-246-tangents-to-an-ellipse.english.md <ide> tests: <ide> <ide> ```js <ide> function euler246() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-247-squares-under-a-hyperbola.english.md <ide> tests: <ide> <ide> ```js <ide> function euler247() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-248-numbers-for-which-eulers-totient-function-equals-13.english.md <ide> tests: <ide> <ide> ```js <ide> function euler248() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-249-prime-subset-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function euler249() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-25-1000-digit-fibonacci-number.english.md <ide> tests: <ide> <ide> ```js <ide> function digitFibonacci(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-250-250250.english.md <ide> tests: <ide> <ide> ```js <ide> function euler250() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-251-cardano-triplets.english.md <ide> tests: <ide> <ide> ```js <ide> function euler251() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-252-convex-holes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler252() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-253-tidying-up.english.md <ide> tests: <ide> <ide> ```js <ide> function euler253() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-254-sums-of-digit-factorials.english.md <ide> tests: <ide> <ide> ```js <ide> function euler254() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-255-rounded-square-roots.english.md <ide> tests: <ide> <ide> ```js <ide> function euler255() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-256-tatami-free-rooms.english.md <ide> tests: <ide> <ide> ```js <ide> function euler256() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-257-angular-bisectors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler257() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-258-a-lagged-fibonacci-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler258() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-259-reachable-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler259() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-26-reciprocal-cycles.english.md <ide> tests: <ide> <ide> ```js <ide> function reciprocalCycles(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-260-stone-game.english.md <ide> tests: <ide> <ide> ```js <ide> function euler260() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-261-pivotal-square-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function euler261() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-262-mountain-range.english.md <ide> tests: <ide> <ide> ```js <ide> function euler262() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-263-an-engineers-dream-come-true.english.md <ide> tests: <ide> <ide> ```js <ide> function euler263() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-264-triangle-centres.english.md <ide> tests: <ide> <ide> ```js <ide> function euler264() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-265-binary-circles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler265() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-266-pseudo-square-root.english.md <ide> tests: <ide> <ide> ```js <ide> function euler266() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-267-billionaire.english.md <ide> tests: <ide> <ide> ```js <ide> function euler267() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-268-counting-numbers-with-at-least-four-distinct-prime-factors-less-than-100.english.md <ide> tests: <ide> <ide> ```js <ide> function euler268() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-269-polynomials-with-at-least-one-integer-root.english.md <ide> tests: <ide> <ide> ```js <ide> function euler269() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-27-quadratic-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function quadraticPrimes(range) { <del> // Good luck! <add> <ide> return range; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-270-cutting-squares.english.md <ide> tests: <ide> <ide> ```js <ide> function euler270() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-271-modular-cubes-part-1.english.md <ide> tests: <ide> <ide> ```js <ide> function euler271() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-272-modular-cubes-part-2.english.md <ide> tests: <ide> <ide> ```js <ide> function euler272() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-273-sum-of-squares.english.md <ide> tests: <ide> <ide> ```js <ide> function euler273() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-274-divisibility-multipliers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler274() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-275-balanced-sculptures.english.md <ide> tests: <ide> <ide> ```js <ide> function euler275() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-276-primitive-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler276() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-277-a-modified-collatz-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler277() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-278-linear-combinations-of-semiprimes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler278() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-279-triangles-with-integral-sides-and-an-integral-angle.english.md <ide> tests: <ide> <ide> ```js <ide> function euler279() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-28-number-spiral-diagonals.english.md <ide> tests: <ide> <ide> ```js <ide> function spiralDiagonals(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-280-ant-and-seeds.english.md <ide> tests: <ide> <ide> ```js <ide> function euler280() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-281-pizza-toppings.english.md <ide> tests: <ide> <ide> ```js <ide> function euler281() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-282-the-ackermann-function.english.md <ide> tests: <ide> <ide> ```js <ide> function euler282() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-283-integer-sided-triangles-for-which-the-area--perimeter-ratio-is-integral.english.md <ide> tests: <ide> <ide> ```js <ide> function euler283() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-284-steady-squares.english.md <ide> tests: <ide> <ide> ```js <ide> function euler284() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-285-pythagorean-odds.english.md <ide> tests: <ide> <ide> ```js <ide> function euler285() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-286-scoring-probabilities.english.md <ide> tests: <ide> <ide> ```js <ide> function euler286() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-287-quadtree-encoding-a-simple-compression-algorithm.english.md <ide> tests: <ide> <ide> ```js <ide> function euler287() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-288-an-enormous-factorial.english.md <ide> tests: <ide> <ide> ```js <ide> function euler288() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-289-eulerian-cycles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler289() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-29-distinct-powers.english.md <ide> tests: <ide> <ide> ```js <ide> function distinctPowers(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-290-digital-signature.english.md <ide> tests: <ide> <ide> ```js <ide> function euler290() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-291-panaitopol-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler291() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-292-pythagorean-polygons.english.md <ide> tests: <ide> <ide> ```js <ide> function euler292() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-293-pseudo-fortunate-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler293() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-294-sum-of-digits---experience-23.english.md <ide> tests: <ide> <ide> ```js <ide> function euler294() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-295-lenticular-holes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler295() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-296-angular-bisector-and-tangent.english.md <ide> tests: <ide> <ide> ```js <ide> function euler296() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-297-zeckendorf-representation.english.md <ide> tests: <ide> <ide> ```js <ide> function euler297() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-298-selective-amnesia.english.md <ide> tests: <ide> <ide> ```js <ide> function euler298() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-299-three-similar-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler299() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-3-largest-prime-factor.english.md <ide> tests: <ide> <ide> ```js <ide> function largestPrimeFactor(number) { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-30-digit-n-powers.english.md <ide> tests: <ide> <ide> ```js <ide> function digitnPowers(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-300-protein-folding.english.md <ide> tests: <ide> <ide> ```js <ide> function euler300() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-301-nim.english.md <ide> tests: <ide> <ide> ```js <ide> function euler301() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-302-strong-achilles-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler302() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-303-multiples-with-small-digits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler303() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-304-primonacci.english.md <ide> tests: <ide> <ide> ```js <ide> function euler304() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-305-reflexive-position.english.md <ide> tests: <ide> <ide> ```js <ide> function euler305() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-306-paper-strip-game.english.md <ide> tests: <ide> <ide> ```js <ide> function euler306() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-307-chip-defects.english.md <ide> tests: <ide> <ide> ```js <ide> function euler307() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-308-an-amazing-prime-generating-automaton.english.md <ide> tests: <ide> <ide> ```js <ide> function euler308() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-309-integer-ladders.english.md <ide> tests: <ide> <ide> ```js <ide> function euler309() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-31-coin-sums.english.md <ide> tests: <ide> <ide> ```js <ide> function coinSums(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-310-nim-square.english.md <ide> tests: <ide> <ide> ```js <ide> function euler310() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-311-biclinic-integral-quadrilaterals.english.md <ide> tests: <ide> <ide> ```js <ide> function euler311() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-312-cyclic-paths-on-sierpiski-graphs.english.md <ide> tests: <ide> <ide> ```js <ide> function euler312() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-313-sliding-game.english.md <ide> tests: <ide> <ide> ```js <ide> function euler313() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-314-the-mouse-on-the-moon.english.md <ide> tests: <ide> <ide> ```js <ide> function euler314() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-315-digital-root-clocks.english.md <ide> tests: <ide> <ide> ```js <ide> function euler315() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-316-numbers-in-decimal-expansions.english.md <ide> tests: <ide> <ide> ```js <ide> function euler316() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-317-firecracker.english.md <ide> tests: <ide> <ide> ```js <ide> function euler317() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-318-2011-nines.english.md <ide> tests: <ide> <ide> ```js <ide> function euler318() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-319-bounded-sequences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler319() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-32-pandigital-products.english.md <ide> tests: <ide> <ide> ```js <ide> function pandigitalProducts() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-320-factorials-divisible-by-a-huge-integer.english.md <ide> tests: <ide> <ide> ```js <ide> function euler320() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-321-swapping-counters.english.md <ide> tests: <ide> <ide> ```js <ide> function euler321() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-322-binomial-coefficients-divisible-by-10.english.md <ide> tests: <ide> <ide> ```js <ide> function euler322() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-323-bitwise-or-operations-on-random-integers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler323() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-324-building-a-tower.english.md <ide> tests: <ide> <ide> ```js <ide> function euler324() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-325-stone-game-ii.english.md <ide> tests: <ide> <ide> ```js <ide> function euler325() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-326-modulo-summations.english.md <ide> tests: <ide> <ide> ```js <ide> function euler326() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-327-rooms-of-doom.english.md <ide> tests: <ide> <ide> ```js <ide> function euler327() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-328-lowest-cost-search.english.md <ide> tests: <ide> <ide> ```js <ide> function euler328() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-329-prime-frog.english.md <ide> tests: <ide> <ide> ```js <ide> function euler329() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-33-digit-cancelling-fractions.english.md <ide> tests: <ide> <ide> ```js <ide> function digitCancellingFractions() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-330-eulers-number.english.md <ide> tests: <ide> <ide> ```js <ide> function euler330() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-331-cross-flips.english.md <ide> tests: <ide> <ide> ```js <ide> function euler331() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-332-spherical-triangles.english.md <ide> tests: <ide> <ide> ```js <ide> function euler332() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-333-special-partitions.english.md <ide> tests: <ide> <ide> ```js <ide> function euler333() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-334-spilling-the-beans.english.md <ide> tests: <ide> <ide> ```js <ide> function euler334() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-335-gathering-the-beans.english.md <ide> tests: <ide> <ide> ```js <ide> function euler335() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-336-maximix-arrangements.english.md <ide> tests: <ide> <ide> ```js <ide> function euler336() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-337-totient-stairstep-sequences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler337() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-338-cutting-rectangular-grid-paper.english.md <ide> tests: <ide> <ide> ```js <ide> function euler338() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-339-peredur-fab-efrawg.english.md <ide> tests: <ide> <ide> ```js <ide> function euler339() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-34-digit-factorials.english.md <ide> tests: <ide> <ide> ```js <ide> function digitFactorial() { <del> // Good luck! <add> <ide> var sum = 0; <ide> var numbers = []; <ide> return { sum, numbers }; <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-340-crazy-function.english.md <ide> tests: <ide> <ide> ```js <ide> function euler340() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-341-golombs-self-describing-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler341() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-342-the-totient-of-a-square-is-a-cube.english.md <ide> tests: <ide> <ide> ```js <ide> function euler342() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-343-fractional-sequences.english.md <ide> tests: <ide> <ide> ```js <ide> function euler343() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-344-silver-dollar-game.english.md <ide> tests: <ide> <ide> ```js <ide> function euler344() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-345-matrix-sum.english.md <ide> tests: <ide> <ide> ```js <ide> function euler345() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-346-strong-repunits.english.md <ide> tests: <ide> <ide> ```js <ide> function euler346() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-347-largest-integer-divisible-by-two-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function euler347() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-348-sum-of-a-square-and-a-cube.english.md <ide> tests: <ide> <ide> ```js <ide> function euler348() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-349-langtons-ant.english.md <ide> tests: <ide> <ide> ```js <ide> function euler349() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-35-circular-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function circularPrimes(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-350-constraining-the-least-greatest-and-the-greatest-least.english.md <ide> tests: <ide> <ide> ```js <ide> function euler350() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-351-hexagonal-orchards.english.md <ide> tests: <ide> <ide> ```js <ide> function euler351() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-352-blood-tests.english.md <ide> tests: <ide> <ide> ```js <ide> function euler352() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-353-risky-moon.english.md <ide> tests: <ide> <ide> ```js <ide> function euler353() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-354-distances-in-a-bees-honeycomb.english.md <ide> tests: <ide> <ide> ```js <ide> function euler354() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-355-maximal-coprime-subset.english.md <ide> tests: <ide> <ide> ```js <ide> function euler355() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-356-largest-roots-of-cubic-polynomials.english.md <ide> tests: <ide> <ide> ```js <ide> function euler356() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-357-prime-generating-integers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler357() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-358-cyclic-numbers.english.md <ide> tests: <ide> <ide> ```js <ide> function euler358() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-359-hilberts-new-hotel.english.md <ide> tests: <ide> <ide> ```js <ide> function euler359() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-36-double-base-palindromes.english.md <ide> tests: <ide> <ide> ```js <ide> function doubleBasePalindromes(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-360-scary-sphere.english.md <ide> tests: <ide> <ide> ```js <ide> function euler360() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-361-subsequence-of-thue-morse-sequence.english.md <ide> tests: <ide> <ide> ```js <ide> function euler361() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-362-squarefree-factors.english.md <ide> tests: <ide> <ide> ```js <ide> function euler362() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-363-bzier-curves.english.md <ide> tests: <ide> <ide> ```js <ide> function euler363() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-364-comfortable-distance.english.md <ide> tests: <ide> <ide> ```js <ide> function euler364() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-365-a-huge-binomial-coefficient.english.md <ide> tests: <ide> <ide> ```js <ide> function euler365() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-366-stone-game-iii.english.md <ide> tests: <ide> <ide> ```js <ide> function euler366() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-367-bozo-sort.english.md <ide> tests: <ide> <ide> ```js <ide> function euler367() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-368-a-kempner-like-series.english.md <ide> tests: <ide> <ide> ```js <ide> function euler368() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-369-badugi.english.md <ide> tests: <ide> <ide> ```js <ide> function euler369() { <del> // Good luck! <add> <ide> return true; <ide> } <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-37-truncatable-primes.english.md <ide> tests: <ide> <ide> ```js <ide> function truncatablePrimes(n) { <del> // Good luck! <add> <ide> return n; <ide> } <ide>
300
Python
Python
fix crash in repr of 0d timedelta array
67aa4e738bf4298f1ccf0411f8df6116861adab1
<ide><path>numpy/core/arrayprint.py <ide> <ide> import numpy as np <ide> from . import numerictypes as _nt <del>from .umath import absolute, not_equal, isnan, isinf, isfinite <add>from .umath import absolute, not_equal, isnan, isinf, isfinite, isnat <ide> from . import multiarray <ide> from .multiarray import (array, dragon4_positional, dragon4_scientific, <ide> datetime_as_string, datetime_data, dtype, ndarray, <ide> def __call__(self, x): <ide> <ide> class TimedeltaFormat(object): <ide> def __init__(self, data): <del> nat_value = array(['NaT'], dtype=data.dtype)[0] <del> int_dtype = dtype(data.dtype.byteorder + 'i8') <del> int_view = data.view(int_dtype) <del> v = int_view[not_equal(int_view, nat_value.view(int_dtype))] <del> if len(v) > 0: <add> non_nat = data[~isnat(data)] <add> if len(non_nat) > 0: <ide> # Max str length of non-NaT elements <del> max_str_len = max(len(str(np.max(v))), <del> len(str(np.min(v)))) <add> max_str_len = max(len(str(np.max(non_nat).astype('i8'))), <add> len(str(np.min(non_nat).astype('i8')))) <ide> else: <ide> max_str_len = 0 <del> if len(v) < len(data): <add> if len(non_nat) < data.size: <ide> # data contains a NaT <ide> max_str_len = max(max_str_len, 5) <ide> self.format = '%' + str(max_str_len) + 'd' <ide> self._nat = "'NaT'".rjust(max_str_len) <ide> <ide> def __call__(self, x): <del> # TODO: After NAT == NAT deprecation should be simplified: <del> if (x + 1).view('i8') == x.view('i8'): <add> if isnat(x): <ide> return self._nat <ide> else: <ide> return self.format % x.astype('i8') <ide><path>numpy/core/tests/test_arrayprint.py <ide> def test_structure_format(self): <ide> ('NaT',) ('NaT',) ('NaT',)]""") <ide> ) <ide> <add> # and again, with timedeltas <add> A = np.full(10, 123456, dtype=[("A", "m8[s]")]) <add> A[5:].fill(np.datetime64('NaT')) <add> assert_equal( <add> np.array2string(A), <add> textwrap.dedent("""\ <add> [(123456,) (123456,) (123456,) (123456,) (123456,) ( 'NaT',) ( 'NaT',) <add> ( 'NaT',) ( 'NaT',) ( 'NaT',)]""") <add> ) <ide> <ide> # See #8160 <ide> struct_int = np.array([([1, -1],), ([123, 1],)], dtype=[('B', 'i4', 2)]) <ide> def test_0d_arrays(self): <ide> assert_equal(repr(np.datetime64('2005-02-25')[...]), <ide> "array('2005-02-25', dtype='datetime64[D]')") <ide> <add> assert_equal(repr(np.timedelta64('10', 'Y')[...]), <add> "array(10, dtype='timedelta64[Y]')") <add> <ide> # repr of 0d arrays is affected by printoptions <ide> x = np.array(1) <ide> np.set_printoptions(formatter={'all':lambda x: "test"})
2
Go
Go
fix syscall name
e69f7142190451eb1e0553e2dfab8e916dc9cead
<ide><path>term/termios_linux.go <ide> func MakeRaw(fd uintptr) (*State, error) { <ide> <ide> newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON) <ide> newState.Oflag &^= syscall.OPOST <del> newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.EXTEN) <add> newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) <ide> newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) <ide> newState.Cflag |= syscall.CS8 <ide>
1
Text
Text
use instance variables in redirect_to
9c18cb1e70718c2b3fc20efed26f544b79c3ce6d
<ide><path>guides/source/getting_started.md <ide> def create <ide> @post = Post.new(params[:post]) <ide> <ide> @post.save <del> redirect_to post <add> redirect_to @post <ide> end <ide> ``` <ide> <ide> look like this: <ide> @post = Post.new(params[:post].permit(:title, :text)) <ide> <ide> @post.save <del> redirect_to post <add> redirect_to @post <ide> end <ide> ``` <ide> <ide> def create <ide> @post = Post.new(params[:post].permit(:title, :text)) <ide> <ide> if @post.save <del> redirect_to post <add> redirect_to @post <ide> else <ide> render 'new' <ide> end <ide> def update <ide> @post = Post.find(params[:id]) <ide> <ide> if @post.update(params[:post].permit(:title, :text)) <del> redirect_to post <add> redirect_to @post <ide> else <ide> render 'edit' <ide> end
1
Text
Text
add note about multiple patterns
d176afd32f99615360d1d23e622e187b7c5833f4
<ide><path>website/docs/api/matcher.md <ide> string where an integer is expected) or unexpected property names. <ide> <ide> Find all token sequences matching the supplied patterns on the `Doc` or `Span`. <ide> <add>Note that if a single label has multiple patterns associated with it, the <add>returned matches don't provide a way to tell which pattern was responsible for <add>the match. <add> <ide> > #### Example <ide> > <ide> > ```python <ide> Find all token sequences matching the supplied patterns on the `Doc` or `Span`. <ide> | _keyword-only_ | | <ide> | `as_spans` <Tag variant="new">3</Tag> | Instead of tuples, return a list of [`Span`](/api/span) objects of the matches, with the `match_id` assigned as the span label. Defaults to `False`. ~~bool~~ | <ide> | `allow_missing` <Tag variant="new">3</Tag> | Whether to skip checks for missing annotation for attributes included in patterns. Defaults to `False`. ~~bool~~ | <del>| `with_alignments` <Tag variant="new">3.0.6</Tag> | Return match alignment information as part of the match tuple as `List[int]` with the same length as the matched span. Each entry denotes the corresponding index of the token pattern. If `as_spans` is set to `True`, this setting is ignored. Defaults to `False`. ~~bool~~ | <add>| `with_alignments` <Tag variant="new">3.0.6</Tag> | Return match alignment information as part of the match tuple as `List[int]` with the same length as the matched span. Each entry denotes the corresponding index of the token in the pattern. If `as_spans` is set to `True`, this setting is ignored. Defaults to `False`. ~~bool~~ | <ide> | **RETURNS** | A list of `(match_id, start, end)` tuples, describing the matches. A match tuple describes a span `doc[start:end`]. The `match_id` is the ID of the added match pattern. If `as_spans` is set to `True`, a list of `Span` objects is returned instead. ~~Union[List[Tuple[int, int, int]], List[Span]]~~ | <ide> <ide> ## Matcher.\_\_len\_\_ {#len tag="method" new="2"}
1
Ruby
Ruby
remove unused private methods
22cbc1a14da1562797c0b3388805034fb9fc1b7f
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb <ide> def add_method_to_attributes!(html_options, method) <ide> html_options["data-method"] = method <ide> end <ide> <del> def options_for_javascript(options) <del> if options.empty? <del> '{}' <del> else <del> "{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}" <del> end <del> end <del> <del> def array_or_string_for_javascript(option) <del> if option.kind_of?(Array) <del> "['#{option.join('\',\'')}']" <del> elsif !option.nil? <del> "'#{option}'" <del> end <del> end <del> <ide> # Processes the +html_options+ hash, converting the boolean <ide> # attributes from true/false form into the form required by <ide> # HTML/XHTML. (An attribute is considered to be boolean if
1
Ruby
Ruby
fix console tests
efd808755cac74f0001907a1d635856160d11f6a
<ide><path>railties/lib/rails/command/environment_argument.rb <ide> module EnvironmentArgument #:nodoc: <ide> def extract_environment_option_from_argument <ide> if environment <ide> self.options = options.merge(environment: acceptable_environment(environment)) <add> elsif !options[:environment] <add> self.options = options.merge(environment: Rails::Command.environment) <ide> end <ide> end <ide> <ide><path>railties/lib/rails/commands/console/console_command.rb <ide> class ConsoleCommand < Base <ide> class_option :sandbox, aliases: "-s", type: :boolean, default: false, <ide> desc: "Rollback database modifications on exit." <ide> <del> class_option :environment, aliases: "-e", type: :string, default: Rails::Command.environment, <add> class_option :environment, aliases: "-e", type: :string, <ide> desc: "Specifies the environment to run this console under (test/development/production)." <ide> <ide> def perform <ide><path>railties/test/commands/console_test.rb <ide> require "abstract_unit" <ide> require "env_helpers" <del>require "rails/commands/console" <add>require "rails/command" <add>require "rails/commands/console/console_command" <ide> <ide> class Rails::ConsoleTest < ActiveSupport::TestCase <ide> include EnvHelpers <ide> def test_rails_env_is_development_when_argument_is_d <ide> end <ide> <ide> def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present <del> stubbed_console = Class.new(Rails::Console) do <del> def available_environments <add> Rails::Command::ConsoleCommand.class_eval do <add> alias_method :old_environments, :available_environments <add> <add> define_method :available_environments do <ide> ["dev"] <ide> end <ide> end <del> options = stubbed_console.parse_arguments(["dev"]) <del> assert_match("dev", options[:environment]) <add> <add> assert_match("dev", parse_arguments(["dev"])[:environment]) <add> ensure <add> Rails::Command::ConsoleCommand.class_eval do <add> undef_method :available_environments <add> alias_method :available_environments, :old_environments <add> undef_method :old_environments <add> end <ide> end <ide> <ide> attr_reader :output <ide> def load_console <ide> end <ide> <ide> def parse_arguments(args) <del> Rails::Console.parse_arguments(args) <add> Rails::Command::ConsoleCommand.class_eval do <add> alias_method :old_perform, :perform <add> define_method(:perform) do <add> extract_environment_option_from_argument <add> <add> options <add> end <add> end <add> <add> Rails::Command.invoke(:console, args) <add> ensure <add> Rails::Command::ConsoleCommand.class_eval do <add> undef_method :perform <add> alias_method :perform, :old_perform <add> undef_method :old_perform <add> end <ide> end <ide> end
3
Javascript
Javascript
add comments on netinfo.js
433c0e80211f7c16fd02c5f02844a796aa766e02
<ide><path>Libraries/Network/NetInfo.js <ide> const _isConnectedSubscriptions = new Map(); <ide> * ``` <ide> */ <ide> const NetInfo = { <add> /** <add> * Invokes the listener whenever network status changes. <add> * The listener receives one of the connectivity types listed above. <add> */ <ide> addEventListener( <ide> eventName: ChangeEventName, <ide> handler: Function <ide> const NetInfo = { <ide> }; <ide> }, <ide> <add> /** <add> * Removes the listener for network status changes. <add> */ <ide> removeEventListener( <ide> eventName: ChangeEventName, <ide> handler: Function <ide> const NetInfo = { <ide> _subscriptions.delete(handler); <ide> }, <ide> <add> /** <add> * Returns a promise that resolves with one of the connectivity types listed <add> * above. <add> */ <ide> fetch(): Promise { <ide> return RCTNetInfo.getCurrentConnectivity().then(resp => resp.network_info); <ide> }, <ide> <add> /** <add> * An object with the same methods as above but the listener receives a <add> * boolean which represents the internet connectivity. <add> * Use this if you are only interested with whether the device has internet <add> * connectivity. <add> */ <ide> isConnected: { <ide> addEventListener( <ide> eventName: ChangeEventName,
1
Mixed
Python
convert hans to trainer
d5477baf7d87b9bdad386f2f317732b85277b06b
<ide><path>examples/README.md <ide> This is still a work-in-progress – in particular documentation is still sparse <ide> | [**`summarization`**](https://github.com/huggingface/transformers/tree/master/examples/summarization) | CNN/Daily Mail | - | - | - | - <ide> | [**`translation`**](https://github.com/huggingface/transformers/tree/master/examples/translation) | WMT | - | - | - | - <ide> | [**`bertology`**](https://github.com/huggingface/transformers/tree/master/examples/bertology) | - | - | - | - | - <del>| [**`adversarial`**](https://github.com/huggingface/transformers/tree/master/examples/adversarial) | HANS | - | - | - | - <add>| [**`adversarial`**](https://github.com/huggingface/transformers/tree/master/examples/adversarial) | HANS | ✅ | - | - | - <ide> <ide> <ide> <br> <ide><path>examples/adversarial/run_hans.py <add># coding=utf-8 <add># Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. <add># Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. <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>""" Finetuning the library models for sequence classification on HANS.""" <add> <add>import logging <add>import os <add>from dataclasses import dataclass, field <add>from typing import Dict, List, Optional <add> <add>import numpy as np <add>import torch <add> <add>from transformers import ( <add> AutoConfig, <add> AutoModelForSequenceClassification, <add> AutoTokenizer, <add> HfArgumentParser, <add> Trainer, <add> TrainingArguments, <add> default_data_collator, <add> set_seed, <add>) <add>from utils_hans import HansDataset, InputFeatures, hans_processors <add> <add> <add>logger = logging.getLogger(__name__) <add> <add> <add>@dataclass <add>class ModelArguments: <add> """ <add> Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. <add> """ <add> <add> model_name_or_path: str = field( <add> metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} <add> ) <add> config_name: Optional[str] = field( <add> default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} <add> ) <add> tokenizer_name: Optional[str] = field( <add> default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} <add> ) <add> cache_dir: Optional[str] = field( <add> default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} <add> ) <add> <add> <add>@dataclass <add>class DataTrainingArguments: <add> """ <add> Arguments pertaining to what data we are going to input our model for training and eval. <add> """ <add> <add> task_name: str = field( <add> metadata={"help": "The name of the task to train selected in the list: " + ", ".join(hans_processors.keys())} <add> ) <add> data_dir: str = field( <add> metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} <add> ) <add> max_seq_length: int = field( <add> default=128, <add> metadata={ <add> "help": "The maximum total input sequence length after tokenization. Sequences longer " <add> "than this will be truncated, sequences shorter will be padded." <add> }, <add> ) <add> overwrite_cache: bool = field( <add> default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} <add> ) <add> <add> <add>def hans_data_collator(features: List[InputFeatures]) -> Dict[str, torch.Tensor]: <add> """ <add> Data collator that removes the "pairID" key if present. <add> """ <add> batch = default_data_collator(features) <add> _ = batch.pop("pairID", None) <add> return batch <add> <add> <add>def main(): <add> # See all possible arguments in src/transformers/training_args.py <add> # or by passing the --help flag to this script. <add> # We now keep distinct sets of args, for a cleaner separation of concerns. <add> <add> parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) <add> model_args, data_args, training_args = parser.parse_args_into_dataclasses() <add> <add> if ( <add> os.path.exists(training_args.output_dir) <add> and os.listdir(training_args.output_dir) <add> and training_args.do_train <add> and not training_args.overwrite_output_dir <add> ): <add> raise ValueError( <add> f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." <add> ) <add> <add> # Setup logging <add> logging.basicConfig( <add> format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", <add> datefmt="%m/%d/%Y %H:%M:%S", <add> level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, <add> ) <add> logger.warning( <add> "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", <add> training_args.local_rank, <add> training_args.device, <add> training_args.n_gpu, <add> bool(training_args.local_rank != -1), <add> training_args.fp16, <add> ) <add> logger.info("Training/evaluation parameters %s", training_args) <add> <add> # Set seed <add> set_seed(training_args.seed) <add> <add> try: <add> processor = hans_processors[data_args.task_name]() <add> label_list = processor.get_labels() <add> num_labels = len(label_list) <add> except KeyError: <add> raise ValueError("Task not found: %s" % (data_args.task_name)) <add> <add> # Load pretrained model and tokenizer <add> # <add> # Distributed training: <add> # The .from_pretrained methods guarantee that only one local process can concurrently <add> # download model & vocab. <add> <add> config = AutoConfig.from_pretrained( <add> model_args.config_name if model_args.config_name else model_args.model_name_or_path, <add> num_labels=num_labels, <add> finetuning_task=data_args.task_name, <add> cache_dir=model_args.cache_dir, <add> ) <add> tokenizer = AutoTokenizer.from_pretrained( <add> model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, <add> cache_dir=model_args.cache_dir, <add> ) <add> model = AutoModelForSequenceClassification.from_pretrained( <add> model_args.model_name_or_path, <add> from_tf=bool(".ckpt" in model_args.model_name_or_path), <add> config=config, <add> cache_dir=model_args.cache_dir, <add> ) <add> <add> # Get datasets <add> train_dataset = ( <add> HansDataset( <add> data_dir=data_args.data_dir, <add> tokenizer=tokenizer, <add> task=data_args.task_name, <add> max_seq_length=data_args.max_seq_length, <add> overwrite_cache=data_args.overwrite_cache, <add> ) <add> if training_args.do_train <add> else None <add> ) <add> eval_dataset = ( <add> HansDataset( <add> data_dir=data_args.data_dir, <add> tokenizer=tokenizer, <add> task=data_args.task_name, <add> max_seq_length=data_args.max_seq_length, <add> overwrite_cache=data_args.overwrite_cache, <add> evaluate=True, <add> ) <add> if training_args.do_eval <add> else None <add> ) <add> <add> # Initialize our Trainer <add> trainer = Trainer( <add> model=model, <add> args=training_args, <add> train_dataset=train_dataset, <add> eval_dataset=eval_dataset, <add> data_collator=hans_data_collator, <add> ) <add> <add> # Training <add> if training_args.do_train: <add> trainer.train( <add> model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None <add> ) <add> trainer.save_model() <add> # For convenience, we also re-save the tokenizer to the same directory, <add> # so that you can share your model easily on huggingface.co/models =) <add> if trainer.is_world_master(): <add> tokenizer.save_pretrained(training_args.output_dir) <add> <add> # Evaluation <add> if training_args.do_eval: <add> logger.info("*** Evaluate ***") <add> <add> output = trainer.predict(eval_dataset) <add> preds = output.predictions <add> preds = np.argmax(preds, axis=1) <add> <add> pair_ids = [ex.pairID for ex in eval_dataset] <add> output_eval_file = os.path.join(training_args.output_dir, "hans_predictions.txt") <add> if trainer.is_world_master(): <add> with open(output_eval_file, "w") as writer: <add> for pid, pred in zip(pair_ids, preds): <add> writer.write("ex" + str(pid) + "," + label_list[int(pred)] + "\n") <add> <add> trainer._log(output.metrics) <add> <add> <add>def _mp_fn(index): <add> # For xla_spawn (TPUs) <add> main() <add> <add> <add>if __name__ == "__main__": <add> main() <ide><path>examples/adversarial/test_hans.py <del># coding=utf-8 <del># Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. <del># Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. <del># <del># Licensed under the Apache License, Version 2.0 (the "License"); <del># you may not use this file except in compliance with the License. <del># You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del># limitations under the License. <del>""" Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa).""" <del> <del>from __future__ import absolute_import, division, print_function <del> <del>import argparse <del>import glob <del>import logging <del>import os <del>import random <del> <del>import numpy as np <del>import torch <del>from torch.utils.data import DataLoader, RandomSampler, SequentialSampler <del>from torch.utils.data.distributed import DistributedSampler <del>from tqdm import tqdm, trange <del> <del>from transformers import ( <del> WEIGHTS_NAME, <del> AdamW, <del> AlbertConfig, <del> AlbertForSequenceClassification, <del> AlbertTokenizer, <del> BertConfig, <del> BertForSequenceClassification, <del> BertTokenizer, <del> DistilBertConfig, <del> DistilBertForSequenceClassification, <del> DistilBertTokenizer, <del> RobertaConfig, <del> RobertaForSequenceClassification, <del> RobertaTokenizer, <del> XLMConfig, <del> XLMForSequenceClassification, <del> XLMTokenizer, <del> XLNetConfig, <del> XLNetForSequenceClassification, <del> XLNetTokenizer, <del> default_data_collator, <del> get_linear_schedule_with_warmup, <del>) <del>from utils_hans import HansDataset, hans_output_modes, hans_processors <del> <del> <del>try: <del> from torch.utils.tensorboard import SummaryWriter <del>except ImportError: <del> from tensorboardX import SummaryWriter <del> <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>MODEL_CLASSES = { <del> "bert": (BertConfig, BertForSequenceClassification, BertTokenizer), <del> "xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer), <del> "xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer), <del> "roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer), <del> "distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer), <del> "albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer), <del>} <del> <del> <del>def set_seed(args): <del> random.seed(args.seed) <del> np.random.seed(args.seed) <del> torch.manual_seed(args.seed) <del> if args.n_gpu > 0: <del> torch.cuda.manual_seed_all(args.seed) <del> <del> <del>def train(args, train_dataset, model, tokenizer): <del> """ Train the model """ <del> if args.local_rank in [-1, 0]: <del> tb_writer = SummaryWriter() <del> <del> args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) <del> train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) <del> train_dataloader = DataLoader( <del> train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=default_data_collator, <del> ) <del> <del> if args.max_steps > 0: <del> t_total = args.max_steps <del> args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 <del> else: <del> t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs <del> <del> # Prepare optimizer and schedule (linear warmup and decay) <del> no_decay = ["bias", "LayerNorm.weight"] <del> optimizer_grouped_parameters = [ <del> { <del> "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], <del> "weight_decay": args.weight_decay, <del> }, <del> {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0}, <del> ] <del> <del> optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) <del> scheduler = get_linear_schedule_with_warmup( <del> optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total <del> ) <del> if args.fp16: <del> try: <del> from apex import amp <del> except ImportError: <del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") <del> model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level) <del> <del> # multi-gpu training (should be after apex fp16 initialization) <del> if args.n_gpu > 1: <del> model = torch.nn.DataParallel(model) <del> <del> # Distributed training (should be after apex fp16 initialization) <del> if args.local_rank != -1: <del> model = torch.nn.parallel.DistributedDataParallel( <del> model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True <del> ) <del> <del> # Train! <del> logger.info("***** Running training *****") <del> logger.info(" Num examples = %d", len(train_dataset)) <del> logger.info(" Num Epochs = %d", args.num_train_epochs) <del> logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size) <del> logger.info( <del> " Total train batch size (w. parallel, distributed & accumulation) = %d", <del> args.train_batch_size <del> * args.gradient_accumulation_steps <del> * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), <del> ) <del> logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) <del> logger.info(" Total optimization steps = %d", t_total) <del> <del> global_step = 0 <del> tr_loss, logging_loss = 0.0, 0.0 <del> model.zero_grad() <del> train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]) <del> set_seed(args) # Added here for reproductibility (even between python 2 and 3) <del> for _ in train_iterator: <del> epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0]) <del> for step, batch in enumerate(epoch_iterator): <del> model.train() <del> inputs = {k: t.to(args.device) for k, t in batch.items() if k != "pairID"} <del> outputs = model(**inputs) <del> loss = outputs[0] # model outputs are always tuple in transformers (see doc) <del> <del> if args.n_gpu > 1: <del> loss = loss.mean() # mean() to average on multi-gpu parallel training <del> if args.gradient_accumulation_steps > 1: <del> loss = loss / args.gradient_accumulation_steps <del> <del> if args.fp16: <del> with amp.scale_loss(loss, optimizer) as scaled_loss: <del> scaled_loss.backward() <del> else: <del> loss.backward() <del> <del> tr_loss += loss.item() <del> if (step + 1) % args.gradient_accumulation_steps == 0: <del> if args.fp16: <del> torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm) <del> else: <del> torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) <del> <del> optimizer.step() <del> scheduler.step() # Update learning rate schedule <del> model.zero_grad() <del> global_step += 1 <del> <del> if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0: <del> logs = {} <del> if ( <del> args.local_rank == -1 and args.evaluate_during_training <del> ): # Only evaluate when single GPU otherwise metrics may not average well <del> results = evaluate(args, model, tokenizer) <del> for key, value in results.items(): <del> eval_key = "eval_{}".format(key) <del> logs[eval_key] = value <del> <del> loss_scalar = (tr_loss - logging_loss) / args.logging_steps <del> learning_rate_scalar = scheduler.get_lr()[0] <del> logs["learning_rate"] = learning_rate_scalar <del> logs["loss"] = loss_scalar <del> logging_loss = tr_loss <del> <del> for key, value in logs.items(): <del> tb_writer.add_scalar(key, value, global_step) <del> # print(json.dumps({**logs, **{'step': global_step}})) <del> <del> if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0: <del> # Save model checkpoint <del> output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) <del> if not os.path.exists(output_dir): <del> os.makedirs(output_dir) <del> model_to_save = ( <del> model.module if hasattr(model, "module") else model <del> ) # Take care of distributed/parallel training <del> model_to_save.save_pretrained(output_dir) <del> torch.save(args, os.path.join(output_dir, "training_args.bin")) <del> logger.info("Saving model checkpoint to %s", output_dir) <del> <del> if args.max_steps > 0 and global_step > args.max_steps: <del> epoch_iterator.close() <del> break <del> if args.max_steps > 0 and global_step > args.max_steps: <del> train_iterator.close() <del> break <del> <del> if args.local_rank in [-1, 0]: <del> tb_writer.close() <del> <del> return global_step, tr_loss / global_step <del> <del> <del>def evaluate(args, model, tokenizer, label_list, prefix=""): <del> # Loop to handle MNLI double evaluation (matched, mis-matched) <del> eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,) <del> eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,) <del> <del> results = {} <del> for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs): <del> eval_dataset = HansDataset( <del> args.data_dir, <del> tokenizer, <del> args.task_name, <del> args.max_seq_length, <del> overwrite_cache=args.overwrite_cache, <del> evaluate=True, <del> ) <del> <del> if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: <del> os.makedirs(eval_output_dir) <del> <del> args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) <del> # Note that DistributedSampler samples randomly <del> eval_sampler = SequentialSampler(eval_dataset) <del> eval_dataloader = DataLoader( <del> eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size, collate_fn=default_data_collator, <del> ) <del> <del> # multi-gpu eval <del> if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel): <del> model = torch.nn.DataParallel(model) <del> <del> # Eval! <del> logger.info("***** Running evaluation {} *****".format(prefix)) <del> logger.info(" Num examples = %d", len(eval_dataset)) <del> logger.info(" Batch size = %d", args.eval_batch_size) <del> eval_loss = 0.0 <del> nb_eval_steps = 0 <del> preds = None <del> out_label_ids = None <del> for batch in tqdm(eval_dataloader, desc="Evaluating"): <del> model.eval() <del> inputs = {k: t.to(args.device) for k, t in batch.items() if k != "pairID"} <del> pair_ids = batch.pop("pairID", None) <del> with torch.no_grad(): <del> outputs = model(**inputs) <del> tmp_eval_loss, logits = outputs[:2] <del> <del> eval_loss += tmp_eval_loss.mean().item() <del> nb_eval_steps += 1 <del> if preds is None: <del> preds = logits.detach().cpu().numpy() <del> out_label_ids = inputs["labels"].detach().cpu().numpy() <del> pair_ids = pair_ids.detach().cpu().numpy() <del> else: <del> preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) <del> out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) <del> pair_ids = np.append(pair_ids, pair_ids.detach().cpu().numpy(), axis=0) <del> <del> eval_loss = eval_loss / nb_eval_steps <del> if args.output_mode == "classification": <del> preds = np.argmax(preds, axis=1) <del> elif args.output_mode == "regression": <del> preds = np.squeeze(preds) <del> <del> output_eval_file = os.path.join(eval_output_dir, "hans_predictions.txt") <del> with open(output_eval_file, "w") as writer: <del> writer.write("pairID,gld_label\n") <del> for pid, pred in zip(pair_ids, preds): <del> writer.write("ex" + str(pid) + "," + label_list[int(pred)] + "\n") <del> <del> return results <del> <del> <del>def main(): <del> parser = argparse.ArgumentParser() <del> <del> # Required parameters <del> parser.add_argument( <del> "--data_dir", <del> default=None, <del> type=str, <del> required=True, <del> help="The input data dir. Should contain the .tsv files (or other data files) for the task.", <del> ) <del> parser.add_argument( <del> "--model_type", <del> default=None, <del> type=str, <del> required=True, <del> help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()), <del> ) <del> parser.add_argument( <del> "--model_name_or_path", <del> default=None, <del> type=str, <del> required=True, <del> help="Path to pretrained model or model identifier from huggingface.co/models", <del> ) <del> parser.add_argument( <del> "--task_name", <del> default=None, <del> type=str, <del> required=True, <del> help="The name of the task to train selected in the list: " + ", ".join(hans_processors.keys()), <del> ) <del> parser.add_argument( <del> "--output_dir", <del> default=None, <del> type=str, <del> required=True, <del> help="The output directory where the model predictions and checkpoints will be written.", <del> ) <del> <del> # Other parameters <del> parser.add_argument( <del> "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name" <del> ) <del> parser.add_argument( <del> "--tokenizer_name", <del> default="", <del> type=str, <del> help="Pretrained tokenizer name or path if not the same as model_name", <del> ) <del> parser.add_argument( <del> "--cache_dir", <del> default="", <del> type=str, <del> help="Where do you want to store the pre-trained models downloaded from s3", <del> ) <del> parser.add_argument( <del> "--max_seq_length", <del> default=128, <del> type=int, <del> help="The maximum total input sequence length after tokenization. Sequences longer " <del> "than this will be truncated, sequences shorter will be padded.", <del> ) <del> parser.add_argument("--do_train", action="store_true", help="Whether to run training.") <del> parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.") <del> parser.add_argument( <del> "--evaluate_during_training", action="store_true", help="Rul evaluation during training at each logging step." <del> ) <del> parser.add_argument( <del> "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model." <del> ) <del> <del> parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.") <del> parser.add_argument( <del> "--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation." <del> ) <del> parser.add_argument( <del> "--gradient_accumulation_steps", <del> type=int, <del> default=1, <del> help="Number of updates steps to accumulate before performing a backward/update pass.", <del> ) <del> parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") <del> parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.") <del> parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") <del> parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") <del> parser.add_argument( <del> "--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform." <del> ) <del> parser.add_argument( <del> "--max_steps", <del> default=-1, <del> type=int, <del> help="If > 0: set total number of training steps to perform. Override num_train_epochs.", <del> ) <del> parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") <del> <del> parser.add_argument("--logging_steps", type=int, default=50, help="Log every X updates steps.") <del> parser.add_argument("--save_steps", type=int, default=50, help="Save checkpoint every X updates steps.") <del> parser.add_argument( <del> "--eval_all_checkpoints", <del> action="store_true", <del> help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number", <del> ) <del> parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available") <del> parser.add_argument( <del> "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory" <del> ) <del> parser.add_argument( <del> "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets" <del> ) <del> parser.add_argument("--seed", type=int, default=42, help="random seed for initialization") <del> <del> parser.add_argument( <del> "--fp16", <del> action="store_true", <del> help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", <del> ) <del> parser.add_argument( <del> "--fp16_opt_level", <del> type=str, <del> default="O1", <del> help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." <del> "See details at https://nvidia.github.io/apex/amp.html", <del> ) <del> parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") <del> parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.") <del> parser.add_argument("--server_port", type=str, default="", help="For distant debugging.") <del> args = parser.parse_args() <del> <del> if ( <del> os.path.exists(args.output_dir) <del> and os.listdir(args.output_dir) <del> and args.do_train <del> and not args.overwrite_output_dir <del> ): <del> raise ValueError( <del> "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( <del> args.output_dir <del> ) <del> ) <del> <del> # Setup distant debugging if needed <del> if args.server_ip and args.server_port: <del> # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script <del> import ptvsd <del> <del> print("Waiting for debugger attach") <del> ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) <del> ptvsd.wait_for_attach() <del> <del> # Setup CUDA, GPU & distributed training <del> if args.local_rank == -1 or args.no_cuda: <del> device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") <del> args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count() <del> else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs <del> torch.cuda.set_device(args.local_rank) <del> device = torch.device("cuda", args.local_rank) <del> torch.distributed.init_process_group(backend="nccl") <del> args.n_gpu = 1 <del> args.device = device <del> <del> # Setup logging <del> logging.basicConfig( <del> format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", <del> datefmt="%m/%d/%Y %H:%M:%S", <del> level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, <del> ) <del> logger.warning( <del> "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", <del> args.local_rank, <del> device, <del> args.n_gpu, <del> bool(args.local_rank != -1), <del> args.fp16, <del> ) <del> <del> # Set seed <del> set_seed(args) <del> <del> # Prepare GLUE task <del> args.task_name = args.task_name.lower() <del> if args.task_name not in hans_processors: <del> raise ValueError("Task not found: %s" % (args.task_name)) <del> processor = hans_processors[args.task_name]() <del> args.output_mode = hans_output_modes[args.task_name] <del> label_list = processor.get_labels() <del> num_labels = len(label_list) <del> <del> # Load pretrained model and tokenizer <del> if args.local_rank not in [-1, 0]: <del> torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab <del> <del> args.model_type = args.model_type.lower() <del> config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] <del> config = config_class.from_pretrained( <del> args.config_name if args.config_name else args.model_name_or_path, <del> num_labels=num_labels, <del> finetuning_task=args.task_name, <del> cache_dir=args.cache_dir if args.cache_dir else None, <del> ) <del> tokenizer = tokenizer_class.from_pretrained( <del> args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, <del> do_lower_case=args.do_lower_case, <del> cache_dir=args.cache_dir if args.cache_dir else None, <del> ) <del> model = model_class.from_pretrained( <del> args.model_name_or_path, <del> from_tf=bool(".ckpt" in args.model_name_or_path), <del> config=config, <del> cache_dir=args.cache_dir if args.cache_dir else None, <del> ) <del> <del> if args.local_rank == 0: <del> torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab <del> <del> model.to(args.device) <del> <del> logger.info("Training/evaluation parameters %s", args) <del> <del> # Training <del> if args.do_train: <del> train_dataset = HansDataset( <del> args.data_dir, tokenizer, args.task_name, args.max_seq_length, overwrite_cache=args.overwrite_cache <del> ) <del> global_step, tr_loss = train(args, train_dataset, model, tokenizer) <del> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <del> <del> # Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained() <del> if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0): <del> # Create output directory if needed <del> if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: <del> os.makedirs(args.output_dir) <del> <del> logger.info("Saving model checkpoint to %s", args.output_dir) <del> # Save a trained model, configuration and tokenizer using `save_pretrained()`. <del> # They can then be reloaded using `from_pretrained()` <del> model_to_save = ( <del> model.module if hasattr(model, "module") else model <del> ) # Take care of distributed/parallel training <del> model_to_save.save_pretrained(args.output_dir) <del> tokenizer.save_pretrained(args.output_dir) <del> <del> # Good practice: save your training arguments together with the trained model <del> torch.save(args, os.path.join(args.output_dir, "training_args.bin")) <del> <del> # Load a trained model and vocabulary that you have fine-tuned <del> model = model_class.from_pretrained(args.output_dir) <del> tokenizer = tokenizer_class.from_pretrained(args.output_dir) <del> model.to(args.device) <del> <del> # Evaluation <del> results = {} <del> if args.do_eval and args.local_rank in [-1, 0]: <del> tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case) <del> checkpoints = [args.output_dir] <del> if args.eval_all_checkpoints: <del> checkpoints = list( <del> os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True)) <del> ) <del> logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging <del> logger.info("Evaluate the following checkpoints: %s", checkpoints) <del> for checkpoint in checkpoints: <del> global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else "" <del> prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else "" <del> <del> model = model_class.from_pretrained(checkpoint) <del> model.to(args.device) <del> result = evaluate(args, model, tokenizer, label_list, prefix=prefix) <del> result = dict((k + "_{}".format(global_step), v) for k, v in result.items()) <del> results.update(result) <del> <del> return results <del> <del> <del>if __name__ == "__main__": <del> main() <ide><path>examples/adversarial/utils_hans.py <ide> import tqdm <ide> from filelock import FileLock <ide> <del>from transformers import ( <del> DataProcessor, <del> PreTrainedTokenizer, <del> RobertaTokenizer, <del> RobertaTokenizerFast, <del> XLMRobertaTokenizer, <del> is_tf_available, <del> is_torch_available, <del>) <add>from transformers import DataProcessor, PreTrainedTokenizer, is_tf_available, is_torch_available <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide> def __init__( <ide> evaluate: bool = False, <ide> ): <ide> processor = hans_processors[task]() <del> output_mode = hans_output_modes[task] <ide> <ide> cached_features_file = os.path.join( <ide> data_dir, <ide> def __init__( <ide> logger.info(f"Creating features from dataset file at {data_dir}") <ide> label_list = processor.get_labels() <ide> <del> if task in ["mnli", "mnli-mm"] and tokenizer.__class__ in ( <del> RobertaTokenizer, <del> RobertaTokenizerFast, <del> XLMRobertaTokenizer, <del> ): <del> # HACK(label indices are swapped in RoBERTa pretrained model) <del> label_list[1], label_list[2] = label_list[2], label_list[1] <ide> examples = ( <ide> processor.get_dev_examples(data_dir) if evaluate else processor.get_train_examples(data_dir) <ide> ) <ide> <ide> logger.info("Training examples: %s", len(examples)) <del> # TODO clean up all this to leverage built-in features of tokenizers <del> self.features = hans_convert_examples_to_features( <del> examples, label_list, max_seq_length, tokenizer, output_mode <del> ) <add> self.features = hans_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer) <ide> logger.info("Saving features into cached file %s", cached_features_file) <ide> torch.save(self.features, cached_features_file) <ide> <ide> def __init__( <ide> evaluate: bool = False, <ide> ): <ide> processor = hans_processors[task]() <del> output_mode = hans_output_modes[task] <ide> label_list = processor.get_labels() <ide> <del> if task in ["mnli", "mnli-mm"] and tokenizer.__class__ in ( <del> RobertaTokenizer, <del> RobertaTokenizerFast, <del> XLMRobertaTokenizer, <del> ): <del> # HACK(label indices are swapped in RoBERTa pretrained model) <del> label_list[1], label_list[2] = label_list[2], label_list[1] <del> <ide> examples = processor.get_dev_examples(data_dir) if evaluate else processor.get_train_examples(data_dir) <del> self.features = hans_convert_examples_to_features( <del> examples, label_list, max_seq_length, tokenizer, output_mode <del> ) <add> self.features = hans_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer) <ide> <ide> def gen(): <ide> for (ex_index, ex) in tqdm.tqdm(enumerate(self.features), desc="convert examples to features"): <ide> def __getitem__(self, i) -> InputFeatures: <ide> class HansProcessor(DataProcessor): <ide> """Processor for the HANS data set.""" <ide> <del> def get_example_from_tensor_dict(self, tensor_dict): <del> """See base class.""" <del> return InputExample( <del> tensor_dict["idx"].numpy(), <del> tensor_dict["premise"].numpy().decode("utf-8"), <del> tensor_dict["hypothesis"].numpy().decode("utf-8"), <del> str(tensor_dict["label"].numpy()), <del> ) <del> <ide> def get_train_examples(self, data_dir): <ide> """See base class.""" <ide> return self._create_examples(self._read_tsv(os.path.join(data_dir, "heuristics_train_set.txt")), "train") <ide> def _create_examples(self, lines, set_type): <ide> <ide> <ide> def hans_convert_examples_to_features( <del> examples: List[InputExample], <del> label_list: List[str], <del> max_length: int, <del> tokenizer: PreTrainedTokenizer, <del> output_mode: str, <add> examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, <ide> ): <ide> """ <ide> Loads a data file into a list of ``InputFeatures`` <ide> def hans_convert_examples_to_features( <ide> pad_to_max_length=True, <ide> return_overflowing_tokens=True, <ide> ) <del> if "num_truncated_tokens" in inputs and inputs["num_truncated_tokens"] > 0: <del> logger.info( <del> "Attention! you are cropping tokens (swag task is ok). " <del> "If you are training ARC and RACE and you are poping question + options," <del> "you need to try to use a bigger max seq length!" <del> ) <ide> <del> if output_mode == "classification": <del> label = label_map[example.label] if example.label in label_map else 0 <del> elif output_mode == "regression": <del> label = float(example.label) <del> else: <del> raise KeyError(output_mode) <add> label = label_map[example.label] if example.label in label_map else 0 <ide> <ide> pairID = int(example.pairID) <ide> <ide> def hans_convert_examples_to_features( <ide> hans_processors = { <ide> "hans": HansProcessor, <ide> } <del> <del>hans_output_modes = { <del> "hans": "classification", <del>}
4
Text
Text
add missing changelogs to assert docs
1789dcfc873eea0b993a1fa20f2e30819a57b9c9
<ide><path>doc/api/assert.md <ide> An alias of [`assert.ok()`][]. <ide> <!-- YAML <ide> added: v0.1.21 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/15001 <add> description: Error names and messages are now properly compared <ide> - version: v8.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12142 <ide> description: Set and Map content is also compared <ide> parameter is undefined, a default error message is assigned. <ide> added: v1.2.0 <ide> changes: <ide> - version: REPLACEME <del> pr-url: https://github.com/nodejs/node/pull/12142 <add> pr-url: https://github.com/nodejs/node/pull/15001 <ide> description: Error names and messages are now properly compared <ide> - version: v8.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12142 <ide> assert.ifError(new Error()); <ide> ## assert.notDeepEqual(actual, expected[, message]) <ide> <!-- YAML <ide> added: v0.1.21 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/15001 <add> description: Error names and messages are now properly compared <add> - version: v8.0.0 <add> pr-url: https://github.com/nodejs/node/pull/12142 <add> description: Set and Map content is also compared <add> - version: v6.4.0, v4.7.1 <add> pr-url: https://github.com/nodejs/node/pull/8002 <add> description: Typed array slices are handled correctly now. <add> - version: v6.1.0, v4.5.0 <add> pr-url: https://github.com/nodejs/node/pull/6432 <add> description: Objects with circular references can be used as inputs now. <add> - version: v5.10.1, v4.4.3 <add> pr-url: https://github.com/nodejs/node/pull/5910 <add> description: Handle non-`Uint8Array` typed arrays correctly. <ide> --> <ide> * `actual` {any} <ide> * `expected` {any} <ide> parameter is undefined, a default error message is assigned. <ide> ## assert.notDeepStrictEqual(actual, expected[, message]) <ide> <!-- YAML <ide> added: v1.2.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/15001 <add> description: Error names and messages are now properly compared <add> - version: v8.0.0 <add> pr-url: https://github.com/nodejs/node/pull/12142 <add> description: Set and Map content is also compared <add> - version: v6.4.0, v4.7.1 <add> pr-url: https://github.com/nodejs/node/pull/8002 <add> description: Typed array slices are handled correctly now. <add> - version: v6.1.0 <add> pr-url: https://github.com/nodejs/node/pull/6432 <add> description: Objects with circular references can be used as inputs now. <add> - version: v5.10.1, v4.4.3 <add> pr-url: https://github.com/nodejs/node/pull/5910 <add> description: Handle non-`Uint8Array` typed arrays correctly. <ide> --> <ide> * `actual` {any} <ide> * `expected` {any}
1
Text
Text
add return value which might be 0
522fce544ef3c4b6e529c80af2fd7facb115c723
<ide><path>guide/english/python/abs-function/index.md <ide> It takes one argument `x` - an integer, or decimal, or a complex number. <ide> <ide> ## Return Value <ide> <del>The return value would be a positive number. Even if complex number is passed, it would return its magnitude, computed as per complex number algebra. <add>The return value would be a positive number or zero. Even if complex number is passed, it would return its magnitude, computed as per complex number algebra. <ide> <ide> ## Code Sample <ide> ```python
1
Javascript
Javascript
fix linting errors
dba9654a0928ee011b8f7114f29f98a4c90a6e35
<ide><path>client/commonFramework/update-preview.js <ide> window.common = (function(global) { <ide> window.__err = new Error( <ide> 'Potential infinite loop at line ' + <ide> line + <del> '. To disable loop protection, write: \\n\\/\\/ noprotect\\nas the first' + <add> '. To disable loop protection, write:' + <add> ' \\n\\/\\/ noprotect\\nas the first' + <ide> ' line. Beware that if you do have an infinite loop in your code' + <ide> ' this will crash your browser.' <ide> ); <ide><path>server/utils/date-utils.js <ide> import moment from 'moment'; <ide> export function dayCount([head, tail]) { <ide> return Math.ceil( <ide> moment(moment(head).endOf('day')).diff( <del> moment(tail).startOf('day'), <del> 'days', <add> moment(tail).startOf('day'), <add> 'days', <ide> true) <ide> ); <ide> }
2
Mixed
Python
add algorithm for n-body simulation - retry
536fb4bca48f69cb66cfbd03aeb02550def07977
<ide><path>DIRECTORY.md <ide> * [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py) <ide> * [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py) <ide> <add>## Physics <add> * [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py) <add> <ide> ## Project Euler <ide> * Problem 001 <ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py) <ide><path>physics/n_body_simulation.py <add>""" <add>In physics and astronomy, a gravitational N-body simulation is a simulation of a <add>dynamical system of particles under the influence of gravity. The system <add>consists of a number of bodies, each of which exerts a gravitational force on all <add>other bodies. These forces are calculated using Newton's law of universal <add>gravitation. The Euler method is used at each time-step to calculate the change in <add>velocity and position brought about by these forces. Softening is used to prevent <add>numerical divergences when a particle comes too close to another (and the force <add>goes to infinity). <add>(Description adapted from https://en.wikipedia.org/wiki/N-body_simulation ) <add>(See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) <add>""" <add> <add> <add>from __future__ import annotations <add> <add>import random <add> <add>from matplotlib import animation <add>from matplotlib import pyplot as plt <add> <add> <add>class Body: <add> def __init__( <add> self, <add> position_x: float, <add> position_y: float, <add> velocity_x: float, <add> velocity_y: float, <add> mass: float = 1.0, <add> size: float = 1.0, <add> color: str = "blue", <add> ) -> None: <add> """ <add> The parameters "size" & "color" are not relevant for the simulation itself, <add> they are only used for plotting. <add> """ <add> self.position_x = position_x <add> self.position_y = position_y <add> self.velocity_x = velocity_x <add> self.velocity_y = velocity_y <add> self.mass = mass <add> self.size = size <add> self.color = color <add> <add> @property <add> def position(self) -> tuple[float, float]: <add> return self.position_x, self.position_y <add> <add> @property <add> def velocity(self) -> tuple[float, float]: <add> return self.velocity_x, self.velocity_y <add> <add> def update_velocity( <add> self, force_x: float, force_y: float, delta_time: float <add> ) -> None: <add> """ <add> Euler algorithm for velocity <add> <add> >>> body_1 = Body(0.,0.,0.,0.) <add> >>> body_1.update_velocity(1.,0.,1.) <add> >>> body_1.velocity <add> (1.0, 0.0) <add> <add> >>> body_1.update_velocity(1.,0.,1.) <add> >>> body_1.velocity <add> (2.0, 0.0) <add> <add> >>> body_2 = Body(0.,0.,5.,0.) <add> >>> body_2.update_velocity(0.,-10.,10.) <add> >>> body_2.velocity <add> (5.0, -100.0) <add> <add> >>> body_2.update_velocity(0.,-10.,10.) <add> >>> body_2.velocity <add> (5.0, -200.0) <add> """ <add> self.velocity_x += force_x * delta_time <add> self.velocity_y += force_y * delta_time <add> <add> def update_position(self, delta_time: float) -> None: <add> """ <add> Euler algorithm for position <add> <add> >>> body_1 = Body(0.,0.,1.,0.) <add> >>> body_1.update_position(1.) <add> >>> body_1.position <add> (1.0, 0.0) <add> <add> >>> body_1.update_position(1.) <add> >>> body_1.position <add> (2.0, 0.0) <add> <add> >>> body_2 = Body(10.,10.,0.,-2.) <add> >>> body_2.update_position(1.) <add> >>> body_2.position <add> (10.0, 8.0) <add> <add> >>> body_2.update_position(1.) <add> >>> body_2.position <add> (10.0, 6.0) <add> """ <add> self.position_x += self.velocity_x * delta_time <add> self.position_y += self.velocity_y * delta_time <add> <add> <add>class BodySystem: <add> """ <add> This class is used to hold the bodies, the gravitation constant, the time <add> factor and the softening factor. The time factor is used to control the speed <add> of the simulation. The softening factor is used for softening, a numerical <add> trick for N-body simulations to prevent numerical divergences when two bodies <add> get too close to each other. <add> """ <add> <add> def __init__( <add> self, <add> bodies: list[Body], <add> gravitation_constant: float = 1.0, <add> time_factor: float = 1.0, <add> softening_factor: float = 0.0, <add> ) -> None: <add> self.bodies = bodies <add> self.gravitation_constant = gravitation_constant <add> self.time_factor = time_factor <add> self.softening_factor = softening_factor <add> <add> def __len__(self) -> int: <add> return len(self.bodies) <add> <add> def update_system(self, delta_time: float) -> None: <add> """ <add> For each body, loop through all other bodies to calculate the total <add> force they exert on it. Use that force to update the body's velocity. <add> <add> >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) <add> >>> len(body_system_1) <add> 2 <add> >>> body_system_1.update_system(1) <add> >>> body_system_1.bodies[0].position <add> (0.01, 0.0) <add> >>> body_system_1.bodies[0].velocity <add> (0.01, 0.0) <add> <add> >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) <add> >>> body_system_2.update_system(1) <add> >>> body_system_2.bodies[0].position <add> (-9.0, 0.0) <add> >>> body_system_2.bodies[0].velocity <add> (0.1, 0.0) <add> """ <add> for body1 in self.bodies: <add> force_x = 0.0 <add> force_y = 0.0 <add> for body2 in self.bodies: <add> if body1 != body2: <add> dif_x = body2.position_x - body1.position_x <add> dif_y = body2.position_y - body1.position_y <add> <add> # Calculation of the distance using Pythagoras's theorem <add> # Extra factor due to the softening technique <add> distance = (dif_x ** 2 + dif_y ** 2 + self.softening_factor) ** ( <add> 1 / 2 <add> ) <add> <add> # Newton's law of universal gravitation. <add> force_x += ( <add> self.gravitation_constant * body2.mass * dif_x / distance ** 3 <add> ) <add> force_y += ( <add> self.gravitation_constant * body2.mass * dif_y / distance ** 3 <add> ) <add> <add> # Update the body's velocity once all the force components have been added <add> body1.update_velocity(force_x, force_y, delta_time * self.time_factor) <add> <add> # Update the positions only after all the velocities have been updated <add> for body in self.bodies: <add> body.update_position(delta_time * self.time_factor) <add> <add> <add>def update_step( <add> body_system: BodySystem, delta_time: float, patches: list[plt.Circle] <add>) -> None: <add> """ <add> Updates the body-system and applies the change to the patch-list used for plotting <add> <add> >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) <add> >>> patches_1 = [plt.Circle((body.position_x, body.position_y), body.size, <add> ... fc=body.color)for body in body_system_1.bodies] #doctest: +ELLIPSIS <add> >>> update_step(body_system_1, 1, patches_1) <add> >>> patches_1[0].center <add> (0.01, 0.0) <add> <add> >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) <add> >>> patches_2 = [plt.Circle((body.position_x, body.position_y), body.size, <add> ... fc=body.color)for body in body_system_2.bodies] #doctest: +ELLIPSIS <add> >>> update_step(body_system_2, 1, patches_2) <add> >>> patches_2[0].center <add> (-9.0, 0.0) <add> """ <add> # Update the positions of the bodies <add> body_system.update_system(delta_time) <add> <add> # Update the positions of the patches <add> for patch, body in zip(patches, body_system.bodies): <add> patch.center = (body.position_x, body.position_y) <add> <add> <add>def plot( <add> title: str, <add> body_system: BodySystem, <add> x_start: float = -1, <add> x_end: float = 1, <add> y_start: float = -1, <add> y_end: float = 1, <add>) -> None: <add> """ <add> Utility function to plot how the given body-system evolves over time. <add> No doctest provided since this function does not have a return value. <add> """ <add> <add> INTERVAL = 20 # Frame rate of the animation <add> DELTA_TIME = INTERVAL / 1000 # Time between time steps in seconds <add> <add> fig = plt.figure() <add> fig.canvas.set_window_title(title) <add> ax = plt.axes( <add> xlim=(x_start, x_end), ylim=(y_start, y_end) <add> ) # Set section to be plotted <add> plt.gca().set_aspect("equal") # Fix aspect ratio <add> <add> # Each body is drawn as a patch by the plt-function <add> patches = [ <add> plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) <add> for body in body_system.bodies <add> ] <add> <add> for patch in patches: <add> ax.add_patch(patch) <add> <add> # Function called at each step of the animation <add> def update(frame: int) -> list[plt.Circle]: <add> update_step(body_system, DELTA_TIME, patches) <add> return patches <add> <add> anim = animation.FuncAnimation( # noqa: F841 <add> fig, update, interval=INTERVAL, blit=True <add> ) <add> <add> plt.show() <add> <add> <add>def example_1() -> BodySystem: <add> """ <add> Example 1: figure-8 solution to the 3-body-problem <add> This example can be seen as a test of the implementation: given the right <add> initial conditions, the bodies should move in a figure-8. <add> (initial conditions taken from http://www.artcompsci.org/vol_1/v1_web/node56.html) <add> >>> body_system = example_1() <add> >>> len(body_system) <add> 3 <add> """ <add> <add> position_x = 0.9700436 <add> position_y = -0.24308753 <add> velocity_x = 0.466203685 <add> velocity_y = 0.43236573 <add> <add> bodies1 = [ <add> Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), <add> Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), <add> Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), <add> ] <add> return BodySystem(bodies1, time_factor=3) <add> <add> <add>def example_2() -> BodySystem: <add> """ <add> Example 2: Moon's orbit around the earth <add> This example can be seen as a test of the implementation: given the right <add> initial conditions, the moon should orbit around the earth as it actually does. <add> (mass, velocity and distance taken from https://en.wikipedia.org/wiki/Earth <add> and https://en.wikipedia.org/wiki/Moon) <add> No doctest provided since this function does not have a return value. <add> """ <add> <add> moon_mass = 7.3476e22 <add> earth_mass = 5.972e24 <add> velocity_dif = 1022 <add> earth_moon_distance = 384399000 <add> gravitation_constant = 6.674e-11 <add> <add> # Calculation of the respective velocities so that total impulse is zero, <add> # i.e. the two bodies together don't move <add> moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) <add> earth_velocity = moon_velocity - velocity_dif <add> <add> moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") <add> earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") <add> return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) <add> <add> <add>def example_3() -> BodySystem: <add> """ <add> Example 3: Random system with many bodies. <add> No doctest provided since this function does not have a return value. <add> """ <add> <add> bodies = [] <add> for i in range(10): <add> velocity_x = random.uniform(-0.5, 0.5) <add> velocity_y = random.uniform(-0.5, 0.5) <add> <add> # Bodies are created pairwise with opposite velocities so that the <add> # total impulse remains zero <add> bodies.append( <add> Body( <add> random.uniform(-0.5, 0.5), <add> random.uniform(-0.5, 0.5), <add> velocity_x, <add> velocity_y, <add> size=0.05, <add> ) <add> ) <add> bodies.append( <add> Body( <add> random.uniform(-0.5, 0.5), <add> random.uniform(-0.5, 0.5), <add> -velocity_x, <add> -velocity_y, <add> size=0.05, <add> ) <add> ) <add> return BodySystem(bodies, 0.01, 10, 0.1) <add> <add> <add>if __name__ == "__main__": <add> plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) <add> plot( <add> "Moon's orbit around the earth", <add> example_2(), <add> -430000000, <add> 430000000, <add> -430000000, <add> 430000000, <add> ) <add> plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
2
Python
Python
remove deplicated symbols from link step
b0222e05b9b98395fcdab4e6ac7f5fed518ec387
<ide><path>numpy/core/setup.py <ide> def generate_umath_c(ext, build_dir): <ide> ], <ide> depends=deps + multiarray_deps + umath_deps + <ide> common_deps, <del> libraries=['npymath', 'npysort'], <add> libraries=['npysort'], <ide> extra_info=extra_info) <ide> <ide> #######################################################################
1
Ruby
Ruby
limit length of secret being passed
c79c40ed82186fc5000cf5beea697b286422bcdb
<ide><path>railties/test/application/middleware/session_test.rb <ide> def read_raw_cookie <ide> <ide> secret = app.key_generator.generate_key("encrypted cookie") <ide> sign_secret = app.key_generator.generate_key("signed encrypted cookie") <del> encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) <add> encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], sign_secret) <ide> <ide> get "/foo/read_raw_cookie" <ide> assert_equal 1, encryptor.decrypt_and_verify(last_response.body)["foo"] <ide> def read_raw_cookie <ide> <ide> secret = app.key_generator.generate_key("encrypted cookie") <ide> sign_secret = app.key_generator.generate_key("signed encrypted cookie") <del> encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) <add> encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], sign_secret) <ide> <ide> get "/foo/read_raw_cookie" <ide> assert_equal 1, encryptor.decrypt_and_verify(last_response.body)["foo"] <ide> def read_raw_cookie <ide> <ide> secret = app.key_generator.generate_key("encrypted cookie") <ide> sign_secret = app.key_generator.generate_key("signed encrypted cookie") <del> encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) <add> encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], sign_secret) <ide> <ide> get "/foo/read_raw_cookie" <ide> assert_equal 2, encryptor.decrypt_and_verify(last_response.body)["foo"]
1
PHP
PHP
apply patch from 'eärendil' to fix formhelper
a65a5eb506c4c056646d5a9f015a9b1d4fb14e58
<ide><path>cake/libs/view/helpers/form.php <ide> function __secure($field = null, $value = null) { <ide> } <ide> } <ide> } <add> <add> $last = end($field); <add> if (is_numeric($last) || empty($last)) { <add> array_pop($field); <add> } <add> <ide> $field = implode('.', $field); <ide> if (!in_array($field, $this->fields)) { <ide> if ($value !== null) { <ide><path>cake/tests/cases/libs/view/helpers/form.test.php <ide> function testFormSecurityMultipleInputFields() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test form security with Model.field.0 style inputs <add> * <add> * @return void <add> */ <add> function testFormSecurityArrayFields() { <add> $key = 'testKey'; <add> <add> $this->Form->params['_Token']['key'] = $key; <add> $this->Form->create('Address'); <add> $this->Form->input('Address.primary.1'); <add> $this->assertEqual('Address.primary', $this->Form->fields[0]); <add> } <add> <ide> /** <ide> * testFormSecurityMultipleInputDisabledFields method <ide> *
2
Text
Text
update examples readme
3312eb57cc858b91c8d2968cc721414ee2e33369
<ide><path>examples/README.md <ide> # Examples <ide> ## Aggressive Merging <del>[aggressive-merging](aggressive-merging) <add>[aggressive-merging](aggressive-merging) <ide> <ide> ## Chunk <ide> [chunkhash](chunkhash) <ide> <ide> [code-splitting-bundle-loader](code-splitting-bundle-loader) example demonstrating Code Splitting through the builder loader <ide> <del>[code-splitting-harmony](code-splitting-harmony) <add>[code-splitting-harmony](code-splitting-harmony) <ide> <del>[code-splitting-native-import-context](code-splitting-native-import-context) <add>[code-splitting-native-import-context](code-splitting-native-import-context) <ide> <ide> [code-splitting-specify-chunk-name](code-splitting-specify-chunk-name) <ide> <ide> If you think an example is missing, please report it as issue. :) <ide> <ide> # Building an Example <del>1. Run `yarn` in the root of the project. <add>1. Run `yarn setup` in the root of the project. <ide> 2. Run `yarn link webpack` in the root of the project. <ide> 3. Run `yarn add --dev webpack-cli` in the root of the project. <ide> 4. Run `node build.js` in the specific example directory. (Ex: `cd examples/commonjs && node build.js`)
1
PHP
PHP
remove duplicate code
f3464b002f92ec528e4f1ea77980680fe76150b8
<ide><path>lib/Cake/Controller/Controller.php <ide> public function redirect($url, $status = null, $exit = true) { <ide> $response = $event->result; <ide> extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); <ide> <del> if (function_exists('session_write_close')) { <del> session_write_close(); <del> } <del> <ide> if ($url !== null) { <ide> $this->response->header('Location', Router::url($url, true)); <ide> } <ide><path>lib/Cake/Model/Datasource/CakeSession.php <ide> class CakeSession { <ide> public static $requestCountdown = 10; <ide> <ide> /** <del> * Constructor. <add> * Pseudo constructor. <ide> * <ide> * @param string $base The base path for the Session <ide> * @return void <ide> public static function init($base = null) { <ide> } <ide> self::_setPath($base); <ide> self::_setHost(env('HTTP_HOST')); <add> <add> register_shutdown_function('session_write_close'); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Model/Datasource/Session/CacheSession.php <ide> public function gc($expires = null) { <ide> return Cache::gc(Configure::read('Session.handler.config'), $expires); <ide> } <ide> <del>/** <del> * Writes and closes a session <del> * <del> * @return void <del> */ <del> protected function _writeSession() { <del> session_write_close(); <del> } <del> <del>/** <del> * Closes the session before the objects handling it become unavailable <del> * <del> * @return void <del> */ <del> public function __destruct() { <del> $this->_writeSession(); <del> } <del> <ide> } <ide><path>lib/Cake/Model/Datasource/Session/DatabaseSession.php <ide> public function gc($expires = null) { <ide> return $this->_model->deleteAll(array($this->_model->alias . ".expires <" => $expires), false, false); <ide> } <ide> <del>/** <del> * Writes and closes a session <del> * <del> * @return void <del> */ <del> protected function _writeSession() { <del> session_write_close(); <del> } <del> <del>/** <del> * Closes the session before the objects handling it become unavailable <del> * <del> * @return void <del> */ <del> public function __destruct() { <del> $this->_writeSession(); <del> } <del> <ide> }
4
Text
Text
add docs for wrap-guide extension
7ce292af616fa73470e2287dc605d12450be4c20
<ide><path>docs/intro.md <ide> ## Welcome to the Atom guide <add> <add>## Extensions <add> <add>### Wrap Guide <add> <add>The wrap-guide extension places a vertical line in each editor at a certain <add>column to guide your formatting so lines do not exceed a certain width. <add> <add>By default the wrap-guide is placed at the 80th column. <add> <add>#### Configuration <add> <add>You can configure where this column is on a per-path basis using the following <add>configuration data options: <add> <add>```coffeescript <add>wrapGuideConfig = <add> getGuideColumn: (path, defaultColumn) -> <add> if path.indexOf('.mm', path.length - 3) isnt -1 <add> return -1 # Disable the guide for Objective-C files <add> else <add> return defaultColumn <add>requireExtension 'wrap-guide', wrapGuideConfig <add>``` <add> <add>You can configure the color of the line by adding the following CSS to a custom <add>stylesheet: <add> <add>```css <add>.wrap-guide { <add> width: 10px; <add> background-color: red; <add>} <add>```
1
Python
Python
solve memory inefficiency in rnns
3fe7a484d2f945b304afe6d96ff9adb80d885097
<ide><path>keras/backend.py <ide> def rnn(step_function, <ide> unroll=False, <ide> input_length=None, <ide> time_major=False, <del> zero_output_for_mask=False): <add> zero_output_for_mask=False, <add> return_all_outputs=True): <ide> """Iterates over the time dimension of a tensor. <ide> <ide> Args: <ide> def rnn(step_function, <ide> zero_output_for_mask: Boolean. If True, the output for masked timestep <ide> will be zeros, whereas in the False case, output from previous <ide> timestep is returned. <add> return_all_outputs: Boolean. If True, all outputs of the process will be <add> returned, whereas in the False case, only last_output will be kept <add> during the process, saving the corresponding memory, and <add> outputs=[last_output] is returned. <ide> <ide> Returns: <ide> A tuple, `(last_output, outputs, new_states)`. <ide> last_output: the latest output of the rnn, of shape `(samples, ...)` <del> outputs: tensor with shape `(samples, time, ...)` where each <del> entry `outputs[s, t]` is the output of the step function <del> at time `t` for sample `s`. <add> outputs: <add> - If `return_all_outputs`: a tensor with shape <add> `(samples, time, ...)` where each entry `outputs[s, t]` is the <add> output of the step function at time `t` for sample `s` <add> - Else, a tensor equal to last_output <ide> new_states: list of tensors, latest states returned by <ide> the step function, of shape `(samples, ...)`. <ide> <ide> def _get_input_tensor(time): <ide> for m, s, ps in zip(tiled_mask_t, flat_new_states, flat_states)) <ide> states = tf.nest.pack_sequence_as(states, flat_final_states) <ide> <del> successive_outputs.append(output) <del> successive_states.append(states) <add> if return_all_outputs: <add> successive_outputs.append(output) <add> successive_states.append(states) <add> else: <add> successive_outputs = [output] <add> successive_states = [states] <ide> last_output = successive_outputs[-1] <ide> new_states = successive_states[-1] <ide> outputs = tf.stack(successive_outputs) <ide> def _get_input_tensor(time): <ide> for i in range(time_steps): <ide> inp = _get_input_tensor(i) <ide> output, states = step_function(inp, tuple(states) + tuple(constants)) <del> successive_outputs.append(output) <del> successive_states.append(states) <add> if return_all_outputs: <add> successive_outputs.append(output) <add> successive_states.append(states) <add> else: <add> successive_outputs = [output] <add> successive_states = [states] <ide> last_output = successive_outputs[-1] <ide> new_states = successive_states[-1] <ide> outputs = tf.stack(successive_outputs) <ide> def _get_input_tensor(time): <ide> # the value is discarded. <ide> output_time_zero, _ = step_function( <ide> input_time_zero, tuple(initial_states) + tuple(constants)) <add> <add> output_ta_size = time_steps_t if return_all_outputs else 1 <ide> output_ta = tuple( <ide> tf.TensorArray( <ide> dtype=out.dtype, <del> size=time_steps_t, <add> size=output_ta_size, <ide> element_shape=out.shape, <ide> tensor_array_name='output_ta_%s' % i) <ide> for i, out in enumerate(tf.nest.flatten(output_time_zero))) <ide> def _step(time, output_ta_t, prev_output, *states): <ide> flat_state) <ide> new_states = tf.nest.pack_sequence_as(new_states, flat_final_state) <ide> <add> ta_index_to_write = time if return_all_outputs else 0 <ide> output_ta_t = tuple( <del> ta.write(time, out) <add> ta.write(ta_index_to_write, out) <ide> for ta, out in zip(output_ta_t, flat_new_output)) <add> <ide> return (time + 1, output_ta_t, <ide> tuple(flat_new_output)) + tuple(new_states) <ide> <ide> def _step(time, output_ta_t, *states): <ide> new_state.set_shape(state.shape) <ide> <ide> flat_output = tf.nest.flatten(output) <add> ta_index_to_write = time if return_all_outputs else 0 <ide> output_ta_t = tuple( <del> ta.write(time, out) for ta, out in zip(output_ta_t, flat_output)) <add> ta.write(ta_index_to_write, out) <add> for ta, out in zip(output_ta_t, flat_output)) <add> <ide> new_states = tf.nest.pack_sequence_as(initial_states, flat_new_state) <ide> return (time + 1, output_ta_t) + tuple(new_states) <ide> <ide> def _step(time, output_ta_t, *states): <ide> def set_shape(output_): <ide> if isinstance(output_, tf.Tensor): <ide> shape = output_.shape.as_list() <del> shape[0] = time_steps <add> if return_all_outputs: <add> shape[0] = time_steps <add> else: <add> shape[0] = 1 <ide> shape[1] = batch <ide> output_.set_shape(shape) <ide> return output_ <ide><path>keras/layers/rnn/base_conv_rnn.py <ide> def step(inputs, states): <ide> constants=constants, <ide> go_backwards=self.go_backwards, <ide> mask=mask, <del> input_length=timesteps) <add> input_length=timesteps, <add> return_all_outputs=self.return_sequences) <ide> if self.stateful: <ide> updates = [ <ide> backend.update(self_state, state)
2
Mixed
Python
fix 2 ongoing issues
e96ceb7860f170acca005aa891d44ac9a6c6ee2c
<ide><path>TODO.md <ide> TODO <ide> ----- <ide> #### UI <del>* Run / backfill wizard <add>* Run button / backfill wizard <ide> * Add templating to adhoc queries <ide> * Charts: better error handling <ide> <ide> TODO <ide> * Merge Cascading <ide> <ide> #### Backend <add>* Add a run_only_latest flag to BaseOperator, runs only most recent task instance where deps are met <ide> * Pickle all the THINGS! <ide> * Master auto dag refresh at time intervals <ide> * Prevent timezone chagne on import <ide><path>airflow/jobs.py <ide> def signal_handler(signum, frame): <ide> i = 0 <ide> while (not self.test_mode) or i < 1: <ide> i += 1 <del> if i % self.refresh_dags_every == 0: <del> dagbag = models.DagBag(self.subdir, sync_to_db=True) <del> else: <del> dagbag.collect_dags(only_if_updated=True) <add> try: <add> if i % self.refresh_dags_every == 0: <add> dagbag = models.DagBag(self.subdir, sync_to_db=True) <add> else: <add> dagbag.collect_dags(only_if_updated=True) <add> except: <add> logging.error("Failed at reloading the dagbag") <add> if statsd: <add> statsd.incr('dag_refresh_error', 1, 1) <add> sleep(5) <add> <ide> if dag_id: <ide> dags = [dagbag.dags[dag_id]] <ide> else: <ide><path>airflow/www/app.py <ide> def dag_link(v, c, m, p): <ide> class DagModelView(SuperUserMixin, ModelView): <ide> column_list = ('dag_id', 'owners') <ide> column_editable_list = ('is_paused',) <add> form_excluded_columns = ('is_subdag', 'is_active') <ide> column_searchable_list = ('dag_id',) <ide> column_filters = ( <ide> 'dag_id', 'owners', 'is_paused', 'is_active', 'is_subdag', <ide> class DagModelView(SuperUserMixin, ModelView): <ide> 'last_loaded': {'disabled': True}, <ide> 'last_expired': {'disabled': True}, <ide> 'pickle_size': {'disabled': True}, <del> 'is_subdag': {'disabled': True}, <del> 'is_active': {'disabled': True}, <ide> 'scheduler_lock': {'disabled': True}, <ide> 'owners': {'disabled': True}, <ide> }
3
PHP
PHP
apply fixes from styleci
a29b94f0dc78f5c4111b36a8acaa6ce818cd8709
<ide><path>src/Illuminate/Database/DatabaseServiceProvider.php <ide> protected function registerEloquentFactory() <ide> $locale = $parameters['locale'] ?? $app['config']->get('app.faker_locale', 'en_US'); <ide> <ide> if (! isset(static::$fakers[$locale])) { <del> static::$fakers[$locale] = FakerFactory::create($locale);; <add> static::$fakers[$locale] = FakerFactory::create($locale); <ide> } <ide> <ide> return static::$fakers[$locale];
1
Text
Text
improve the warning a bit [ci skip]
056d06627af1c99647d88521557c65ddc476520f
<ide><path>guides/source/action_controller_overview.md <ide> Create the controller and views. <ide> <ide> Do not forget to set the correct status code on the controller as shown before. <ide> <del>WARNING: You should avoid using the database or any complex operations because the user is already on the error page. Generating another error while on an error page could cause issues. <add>WARNING: You should avoid using the database or any complex operations because the user is already on the error page. Generating another error while on an error page could cause issues like presenting an empty page for the users. <ide> <ide> Force HTTPS protocol <ide> --------------------
1
Javascript
Javascript
adapt tests to new object/es7 polyfill
b9ceecb31fcafcc59870fd8bc92bf42d0cdaf7b9
<ide><path>packager/react-packager/src/BundlesLayout/__tests__/BundlesLayoutIntegration-test.js <ide> describe('BundlesLayout', () => { <ide> 'polyfills/String.prototype.es6.js', <ide> 'polyfills/Array.prototype.es6.js', <ide> 'polyfills/Array.es6.js', <add> 'polyfills/Object.es7.js', <ide> 'polyfills/babelHelpers.js', <ide> ]; <ide> const baseFs = getBaseFs(); <ide><path>packager/react-packager/src/Resolver/__tests__/Resolver-test.js <ide> describe('Resolver', function() { <ide> 'polyfills/Array.prototype.es6.js', <ide> ], <ide> }, <add> { id: 'polyfills/Object.es7.js', <add> isPolyfill: true, <add> path: 'polyfills/Object.es7.js', <add> dependencies: [ <add> 'polyfills/polyfills.js', <add> 'polyfills/console.js', <add> 'polyfills/error-guard.js', <add> 'polyfills/String.prototype.es6.js', <add> 'polyfills/Array.prototype.es6.js', <add> 'polyfills/Array.es6.js', <add> ], <add> }, <ide> { id: 'polyfills/babelHelpers.js', <ide> isPolyfill: true, <ide> path: 'polyfills/babelHelpers.js', <ide> describe('Resolver', function() { <ide> 'polyfills/String.prototype.es6.js', <ide> 'polyfills/Array.prototype.es6.js', <ide> 'polyfills/Array.es6.js', <add> 'polyfills/Object.es7.js', <ide> ], <ide> }, <ide> ]); <ide> describe('Resolver', function() { <ide> 'polyfills/String.prototype.es6.js', <ide> 'polyfills/Array.prototype.es6.js', <ide> 'polyfills/Array.es6.js', <add> 'polyfills/Object.es7.js', <ide> 'polyfills/babelHelpers.js', <ide> ] <ide> },
2
Javascript
Javascript
fix fizz exported types
8f6163cbed64d1eff23b91159d6eef34a2ee9c27
<ide><path>packages/react-dom/src/server/ReactDOMFizzServerBrowser.js <ide> import { <ide> createRootFormatContext, <ide> } from './ReactDOMServerFormatConfig'; <ide> <del>type Options = { <add>type Options = {| <ide> identifierPrefix?: string, <ide> namespaceURI?: string, <ide> progressiveChunkSize?: number, <ide> signal?: AbortSignal, <ide> onReadyToStream?: () => void, <ide> onCompleteAll?: () => void, <ide> onError?: (error: mixed) => void, <del>}; <add>|}; <ide> <ide> function renderToReadableStream( <ide> children: ReactNodeList, <ide><path>packages/react-dom/src/server/ReactDOMFizzServerNode.js <ide> function createDrainHandler(destination, request) { <ide> return () => startFlowing(request); <ide> } <ide> <del>type Options = { <add>type Options = {| <ide> identifierPrefix?: string, <ide> namespaceURI?: string, <ide> progressiveChunkSize?: number, <ide> onReadyToStream?: () => void, <ide> onCompleteAll?: () => void, <ide> onError?: (error: mixed) => void, <del>}; <add>|}; <ide> <del>type Controls = { <add>type Controls = {| <ide> // Cancel any pending I/O and put anything remaining into <ide> // client rendered mode. <ide> abort(): void, <del>}; <add> startWriting(): void, <add>|}; <ide> <ide> function pipeToNodeWritable( <ide> children: ReactNodeList,
2
Ruby
Ruby
add --no-html to scaffold generator
cb025f850c45f26355892961d5cf05145d247a4d
<ide><path>railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb <ide> class ScaffoldGenerator < ResourceGenerator # :nodoc: <ide> class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets" <ide> class_option :stylesheet_engine, desc: "Engine for Stylesheets" <ide> <add> class_option :html, type: :boolean, default: true, <add> desc: "Generate a scaffold with HTML output" <add> <add> def handle_skip <add> if !options[:html] || !options[:stylesheets] <add> @options = @options.merge(stylesheet_engine: false) <add> end <add> end <add> <ide> hook_for :scaffold_controller, required: true <ide> <ide> hook_for :assets do |assets| <ide> invoke assets, [controller_name] <ide> end <ide> <ide> hook_for :stylesheet_engine do |stylesheet_engine| <del> invoke stylesheet_engine, [controller_name] if options[:stylesheets] && behavior == :invoke <add> if behavior == :invoke <add> invoke stylesheet_engine, [controller_name] <add> end <ide> end <ide> end <ide> end <ide><path>railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb <ide> class ScaffoldControllerGenerator < NamedBase # :nodoc: <ide> class_option :orm, banner: "NAME", type: :string, required: true, <ide> desc: "ORM to generate the controller for" <ide> <add> class_option :html, type: :boolean, default: true, <add> desc: "Generate a scaffold with HTML output" <add> <ide> argument :attributes, type: :array, default: [], banner: "field:type field:type" <ide> <add> def handle_skip <add> unless options[:html] <add> @options = @options.merge(template_engine: false, helper: false) <add> end <add> end <add> <ide> def create_controller_files <ide> template "controller.rb", File.join('app/controllers', class_path, "#{controller_file_name}_controller.rb") <ide> end <ide><path>railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb <ide> def index <ide> @<%= plural_table_name %> = <%= orm_class.all(class_name) %> <ide> <ide> respond_to do |format| <del> format.html # index.html.erb <add> <%- if options[:html] -%>format.html # index.html.erb<%- end -%> <ide> format.json { render json: <%= "@#{plural_table_name}" %> } <ide> end <ide> end <ide> def index <ide> # GET <%= route_url %>/1.json <ide> def show <ide> respond_to do |format| <del> format.html # show.html.erb <add> <%- if options[:html] -%>format.html # show.html.erb<%- end -%> <ide> format.json { render json: <%= "@#{singular_table_name}" %> } <ide> end <ide> end <ide> <add> <%- if options[:html] -%> <ide> # GET <%= route_url %>/new <ide> # GET <%= route_url %>/new.json <ide> def new <ide> def new <ide> # GET <%= route_url %>/1/edit <ide> def edit <ide> end <add> <%- end -%> <ide> <ide> # POST <%= route_url %> <ide> # POST <%= route_url %>.json <ide> def create <ide> <ide> respond_to do |format| <ide> if @<%= orm_instance.save %> <add> <%- if options[:html] -%> <ide> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %> } <add> <%- end -%> <ide> format.json { render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %> } <ide> else <del> format.html { render action: "new" } <add> <%- if options[:html] -%>format.html { render action: "new" }<%- end -%> <ide> format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity } <ide> end <ide> end <ide> def create <ide> def update <ide> respond_to do |format| <ide> if @<%= orm_instance.update_attributes("#{singular_table_name}_params") %> <add> <%- if options[:html] -%> <ide> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> } <add> <%- end -%> <ide> format.json { head :no_content } <ide> else <del> format.html { render action: "edit" } <add> <%- if options[:html] -%>format.html { render action: "edit" }<%- end -%> <ide> format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity } <ide> end <ide> end <ide> def destroy <ide> @<%= orm_instance.destroy %> <ide> <ide> respond_to do |format| <del> format.html { redirect_to <%= index_helper %>_url } <add> <%- if options[:html] -%>format.html { redirect_to <%= index_helper %>_url }<%- end -%> <ide> format.json { head :no_content } <ide> end <ide> end <ide> def set_<%= singular_table_name %> <ide> @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> <ide> end <ide> <del> # Use this method to whitelist the permissible parameters. Example: params.require(:person).permit(:name, :age) <del> # Also, you can specialize this method with per-user checking of permissible attributes. <add> # Use this method to whitelist the permissible parameters. Example: <add> # params.require(:person).permit(:name, :age) <add> # <add> # Also, you can specialize this method with per-user checking of permissible <add> # attributes. <ide> def <%= "#{singular_table_name}_params" %> <ide> <%- if attributes_names.empty? -%> <ide> params[<%= ":#{singular_table_name}" %>] <ide><path>railties/test/generators/scaffold_controller_generator_test.rb <ide> def test_skip_layout_if_required <ide> assert_no_file "app/views/layouts/users.html.erb" <ide> end <ide> <add> def test_skip_html_if_required <add> run_generator [ "User", "name:string", "age:integer", "--no-html" ] <add> assert_no_file "app/helpers/users_helper.rb" <add> assert_no_file "app/views/users" <add> <add> assert_file "app/controllers/users_controller.rb" do |content| <add> assert_no_match(/format\.html/, content) <add> assert_no_match(/def edit/, content) <add> assert_no_match(/def new/, content) <add> end <add> end <add> <ide> def test_default_orm_is_used <ide> run_generator ["User", "--orm=unknown"] <ide> <ide><path>railties/test/generators/scaffold_generator_test.rb <ide> def test_scaffold_generator_no_stylesheets <ide> assert_no_file "app/assets/stylesheets/posts.css" <ide> end <ide> <add> def test_scaffold_generator_no_html <add> run_generator [ "posts", "--no-html" ] <add> assert_no_file "app/assets/stylesheets/scaffold.css" <add> end <add> <ide> def test_scaffold_generator_no_javascripts <ide> run_generator [ "posts", "--no-javascripts" ] <ide> assert_file "app/assets/stylesheets/scaffold.css"
5
Javascript
Javascript
use fetchifref to get annotation dictionaries
ff4f7f1028e4dcae34dd3ae3e36606ac29cc14aa
<ide><path>src/core.js <ide> var Page = (function PageClosure() { <ide> var items = []; <ide> for (i = 0; i < n; ++i) { <ide> var annotationRef = annotations[i]; <del> var annotation = xref.fetch(annotationRef); <add> var annotation = xref.fetchIfRef(annotationRef); <ide> if (!isDict(annotation)) <ide> continue; <ide> var subtype = annotation.get('Subtype');
1
PHP
PHP
queue() method signature
9f19107fe952aac76560a694d580b5ca328323e9
<ide><path>src/Illuminate/Contracts/Cookie/QueueingFactory.php <ide> interface QueueingFactory extends Factory <ide> /** <ide> * Queue a cookie to send with the next response. <ide> * <add> * @param array $params <add> * <ide> * @return void <ide> */ <del> public function queue(); <add> public function queue(...$params); <ide> <ide> /** <ide> * Remove a cookie from the queue. <ide><path>src/Illuminate/Cookie/CookieJar.php <ide> public function queued($key, $default = null) <ide> /** <ide> * Queue a cookie to send with the next response. <ide> * <add> * @param array $params <add> * <ide> * @return void <ide> */ <del> public function queue() <add> public function queue(...$params) <ide> { <del> if (head(func_get_args()) instanceof Cookie) { <del> $cookie = head(func_get_args()); <add> if (head($params) instanceof Cookie) { <add> $cookie = head($params); <ide> } else { <del> $cookie = call_user_func_array([$this, 'make'], func_get_args()); <add> $cookie = call_user_func_array([$this, 'make'], $params); <ide> } <ide> <ide> $this->queued[$cookie->getName()] = $cookie;
2
PHP
PHP
remove a use statement
d485e31d1dd38be1b2091f8b6ed4ecef762dd32a
<ide><path>tests/TestCase/Database/Schema/TableTest.php <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\ORM\TableRegistry; <ide> use Cake\TestSuite\TestCase; <del>use Symfony\Component\Yaml\Exception\RuntimeException; <ide> <ide> /** <ide> * Test case for Table
1
Javascript
Javascript
fix uiexplorer ios swipe back
e3c6d8c93132741f802133d14d3240aa07d8b055
<ide><path>Examples/UIExplorer/js/UIExplorerApp.ios.js <ide> class UIExplorerApp extends React.Component { <ide> style={styles.container} <ide> renderHeader={this._renderHeader} <ide> renderScene={this._renderScene} <del> <add> onNavigateBack={this._handleBack} <ide> /> <ide> ); <ide> }
1
Text
Text
fix syntax error in nested conditions example
e64f432c0dcfc603636c7d11470d5f34102f0bcf
<ide><path>doc/api/packages.md <ide> use in Node.js but not the browser: <ide> "import": "./feature-node.mjs", <ide> "require": "./feature-node.cjs" <ide> }, <del> "default": "./feature.mjs", <add> "default": "./feature.mjs" <ide> } <ide> } <ide> ```
1
Javascript
Javascript
add err handling to test run
d2be64cfb5fbb98224cc0d6dd7016d4141c547fc
<ide><path>client/commonFramework/end.js <ide> $(document).ready(function() { <ide> common.editorKeyUp$ <ide> .debounce(750) <ide> .map(() => common.editor.getValue()) <add> .distinctUntilChanged() <ide> .doOnNext(() => console.log('updating value')) <ide> .subscribe( <ide> code => { <ide> $(document).ready(function() { <ide> common.updateOutputDisplay('' + output); <ide> }, <ide> ({ err }) => { <add> if (err.stack) { <add> console.error(err); <add> } <ide> common.updateOutputDisplay('' + err); <ide> } <ide> ); <ide> $(document).ready(function() { <ide> ) <ide> .flatMap(() => { <ide> common.appendToOutputDisplay('\n// testing challenge...'); <del> return common.executeChallenge$(); <del> }) <del> .map(({ tests, ...rest }) => { <del> const solved = tests.every(test => !test.err); <del> return { ...rest, tests, solved }; <add> return common.executeChallenge$() <add> .map(({ tests, ...rest }) => { <add> const solved = tests.every(test => !test.err); <add> return { ...rest, tests, solved }; <add> }) <add> .catch(err => Observable.just(err)); <ide> }) <ide> .subscribe( <del> ({ solved, output, tests }) => { <add> ({ err, solved, output, tests }) => { <add> if (err) { <add> console.error(err); <add> return common.updateOutputDisplay('' + err); <add> } <ide> common.updateOutputDisplay(output); <ide> common.displayTestResults(tests); <ide> if (solved) { <ide> common.showCompletion(); <ide> } <add> }, <add> (err) => { <add> console.error(err); <add> common.updateOutputDisplay('' + err); <ide> } <ide> ); <ide>
1
Go
Go
remove cgo from term
64f346779fbe4ba9587ec65eedd0e8373f7e29c0
<ide><path>term/term.go <ide> import ( <ide> ) <ide> <ide> type Termios struct { <del> Iflag uintptr <del> Oflag uintptr <del> Cflag uintptr <del> Lflag uintptr <add> Iflag uint32 <add> Oflag uint32 <add> Cflag uint32 <add> Lflag uint32 <ide> Cc [20]byte <del> Ispeed uintptr <del> Ospeed uintptr <add> Ispeed uint32 <add> Ospeed uint32 <ide> } <ide> <ide> const ( <ide><path>term/termios_linux.go <ide> import ( <ide> "unsafe" <ide> ) <ide> <del>// #include <termios.h> <del>// #include <sys/ioctl.h> <del>/* <del>void MakeRaw(int fd) { <del> struct termios t; <del> <del> // FIXME: Handle errors? <del> ioctl(fd, TCGETS, &t); <del> <del> t.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); <del> t.c_oflag &= ~OPOST; <del> t.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG); <del> t.c_cflag &= ~(CSIZE | PARENB); <del> t.c_cflag |= CS8; <del> <del> ioctl(fd, TCSETS, &t); <del>} <del>*/ <del>import "C" <del> <ide> const ( <ide> getTermios = syscall.TCGETS <ide> setTermios = syscall.TCSETS <ide> const ( <ide> // restored. <ide> func MakeRaw(fd int) (*State, error) { <ide> var oldState State <del> if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), syscall.TCGETS, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 { <add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { <ide> return nil, err <ide> } <del> C.MakeRaw(C.int(fd)) <del> return &oldState, nil <del> <del> // FIXME: post on goland issues this: very same as the C function bug non-working <ide> <del> // newState := oldState.termios <add> newState := oldState.termios <ide> <del> // newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) <del> // newState.Oflag &^= OPOST <del> // newState.Lflag &^= (ECHO | syscall.ECHONL | ICANON | ISIG | IEXTEN) <del> // newState.Cflag &^= (CSIZE | syscall.PARENB) <del> // newState.Cflag |= CS8 <add> newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON) <add> newState.Oflag &^= syscall.OPOST <add> newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) <add> newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) <add> newState.Cflag |= syscall.CS8 <ide> <del> // if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TCSETS, uintptr(unsafe.Pointer(&newState))); err != 0 { <del> // return nil, err <del> // } <del> // return &oldState, nil <add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { <add> return nil, err <add> } <add> return &oldState, nil <ide> }
2
Javascript
Javascript
fix handling of `snicallback` server option
ea7b817266512b93b99032189984a3bd0f8386dc
<ide><path>lib/_tls_wrap.js <ide> TLSSocket.prototype._init = function() { <ide> } <ide> }; <ide> <add> // If custom SNICallback was given, or if <add> // there're SNI contexts to perform match against - <add> // set `.onsniselect` callback. <ide> if (process.features.tls_sni && <ide> options.isServer && <ide> options.server && <del> options.SNICallback && <del> options.server._contexts.length) { <add> (options.SNICallback !== SNICallback || <add> options.server._contexts.length)) { <add> assert(typeof options.SNICallback === 'function'); <ide> this.ssl.onsniselect = options.SNICallback; <ide> } <ide> <ide> Server.prototype.addContext = function(servername, credentials) { <ide> this._contexts.push([re, crypto.createCredentials(credentials).context]); <ide> }; <ide> <del>Server.prototype.SNICallback = function(servername) { <add>function SNICallback(servername) { <ide> var ctx; <ide> <ide> this._contexts.some(function(elem) { <ide> Server.prototype.SNICallback = function(servername) { <ide> }); <ide> <ide> return ctx; <del>}; <add>} <add> <add>Server.prototype.SNICallback = SNICallback; <ide> <ide> <ide> // Target API: <ide><path>test/simple/test-tls-sni-option.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>if (!process.features.tls_sni) { <add> console.error('Skipping because node compiled without OpenSSL or ' + <add> 'with old OpenSSL version.'); <add> process.exit(0); <add>} <add> <add>var common = require('../common'), <add> assert = require('assert'), <add> crypto = require('crypto'), <add> fs = require('fs'), <add> tls = require('tls'); <add> <add>function filenamePEM(n) { <add> return require('path').join(common.fixturesDir, 'keys', n + '.pem'); <add>} <add> <add>function loadPEM(n) { <add> return fs.readFileSync(filenamePEM(n)); <add>} <add> <add>var serverOptions = { <add> key: loadPEM('agent2-key'), <add> cert: loadPEM('agent2-cert'), <add> SNICallback: function(servername) { <add> var credentials = SNIContexts[servername]; <add> if (credentials) <add> return crypto.createCredentials(credentials).context; <add> } <add>}; <add> <add>var SNIContexts = { <add> 'a.example.com': { <add> key: loadPEM('agent1-key'), <add> cert: loadPEM('agent1-cert') <add> }, <add> 'b.example.com': { <add> key: loadPEM('agent3-key'), <add> cert: loadPEM('agent3-cert') <add> } <add>}; <add> <add>var serverPort = common.PORT; <add> <add>var clientsOptions = [{ <add> port: serverPort, <add> key: loadPEM('agent1-key'), <add> cert: loadPEM('agent1-cert'), <add> ca: [loadPEM('ca1-cert')], <add> servername: 'a.example.com', <add> rejectUnauthorized: false <add>}, { <add> port: serverPort, <add> key: loadPEM('agent2-key'), <add> cert: loadPEM('agent2-cert'), <add> ca: [loadPEM('ca2-cert')], <add> servername: 'b.example.com', <add> rejectUnauthorized: false <add>}, { <add> port: serverPort, <add> key: loadPEM('agent3-key'), <add> cert: loadPEM('agent3-cert'), <add> ca: [loadPEM('ca1-cert')], <add> servername: 'c.wrong.com', <add> rejectUnauthorized: false <add>}]; <add> <add>var serverResults = [], <add> clientResults = []; <add> <add>var server = tls.createServer(serverOptions, function(c) { <add> serverResults.push(c.servername); <add>}); <add> <add>server.listen(serverPort, startTest); <add> <add>function startTest() { <add> function connectClient(options, callback) { <add> var client = tls.connect(options, function() { <add> clientResults.push( <add> /Hostname\/IP doesn't/.test(client.authorizationError || '')); <add> client.destroy(); <add> <add> callback(); <add> }); <add> }; <add> <add> connectClient(clientsOptions[0], function() { <add> connectClient(clientsOptions[1], function() { <add> connectClient(clientsOptions[2], function() { <add> server.close(); <add> }); <add> }); <add> }); <add>} <add> <add>process.on('exit', function() { <add> assert.deepEqual(serverResults, ['a.example.com', 'b.example.com', <add> 'c.wrong.com']); <add> assert.deepEqual(clientResults, [true, true, false]); <add>});
2
Ruby
Ruby
prevent accessibility access for macos >= 10.12
15f3f2065625b05496632c1f5cf61fd150afef3c
<ide><path>Library/Homebrew/cask/lib/hbc/installer.rb <ide> def print_caveats <ide> def enable_accessibility_access <ide> return unless @cask.accessibility_access <ide> ohai "Enabling accessibility access" <del> if MacOS.version <= :mountain_lion <add> if MacOS.version >= :sierra <add> opoo <<-EOS.undent <add> Access denied to accessibility DB (TCC.db) by SIP on this version of macOS. <add> If needed, enable manually via the app or System Preferences. <add> EOS <add> elsif MacOS.version <= :mountain_lion <ide> @command.run!("/usr/bin/touch", <ide> args: [Hbc.pre_mavericks_accessibility_dotfile], <ide> sudo: true) <ide> def enable_accessibility_access <ide> <ide> def disable_accessibility_access <ide> return unless @cask.accessibility_access <del> if MacOS.version >= :mavericks <add> if MacOS.version >= :sierra <add> opoo <<-EOS.undent <add> Access denied to accessibility DB (TCC.db) by SIP on this version of macOS. <add> If needed, disable manually via the app or System Preferences. <add> EOS <add> elsif MacOS.version >= :mavericks <ide> ohai "Disabling accessibility access" <ide> @command.run!("/usr/bin/sqlite3", <ide> args: [
1
Python
Python
fix t5 shard on tpu pods
5e68675755e3d45aade61950764e361ae82c7022
<ide><path>examples/flax/language-modeling/run_t5_mlm_flax.py <ide> def group_texts(examples): <ide> <ide> num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs <ide> <add> num_of_hosts = jax.process_count() <add> current_host_idx = jax.process_index() <add> <ide> # Create learning rate schedule <ide> warmup_fn = optax.linear_schedule( <ide> init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps <ide> def eval_step(params, batch): <ide> samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx] <ide> model_inputs = data_collator(samples) <ide> <add> local_host_model_inputs = { <add> key: np.split(model_inputs.data[key], num_of_hosts, axis=0)[current_host_idx] <add> for key, value in model_inputs.data.items() <add> } <add> <ide> # Model forward <del> model_inputs = shard(model_inputs.data) <add> model_inputs = shard(local_host_model_inputs) <ide> state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs) <ide> train_metrics.append(train_metric) <ide>
1
Python
Python
add initial array_api sub-namespace
012343dec5599418b77512733fc5b8db6bc14c4c
<ide><path>numpy/_array_api/__init__.py <add>__all__ = [] <add> <add>from .constants import e, inf, nan, pi <add> <add>__all__ += ['e', 'inf', 'nan', 'pi'] <add> <add>from .creation_functions import arange, empty, empty_like, eye, full, full_like, linspace, ones, ones_like, zeros, zeros_like <add> <add>__all__ += ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like', 'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like'] <add> <add>from .elementwise_functions import abs, acos, acosh, add, asin, asinh, atan, atan2, atanh, bitwise_and, bitwise_left_shift, bitwise_invert, bitwise_or, bitwise_right_shift, bitwise_xor, ceil, cos, cosh, divide, equal, exp, expm1, floor, floor_divide, greater, greater_equal, isfinite, isinf, isnan, less, less_equal, log, log1p, log2, log10, logical_and, logical_not, logical_or, logical_xor, multiply, negative, not_equal, positive, pow, remainder, round, sign, sin, sinh, square, sqrt, subtract, tan, tanh, trunc <add> <add>__all__ += ['abs', 'acos', 'acosh', 'add', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'bitwise_and', 'bitwise_left_shift', 'bitwise_invert', 'bitwise_or', 'bitwise_right_shift', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', 'equal', 'exp', 'expm1', 'floor', 'floor_divide', 'greater', 'greater_equal', 'isfinite', 'isinf', 'isnan', 'less', 'less_equal', 'log', 'log1p', 'log2', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'multiply', 'negative', 'not_equal', 'positive', 'pow', 'remainder', 'round', 'sign', 'sin', 'sinh', 'square', 'sqrt', 'subtract', 'tan', 'tanh', 'trunc'] <add> <add>from .linear_algebra_functions import cross, det, diagonal, inv, norm, outer, trace, transpose <add> <add>__all__ += ['cross', 'det', 'diagonal', 'inv', 'norm', 'outer', 'trace', 'transpose'] <add> <add># from .linear_algebra_functions import cholesky, cross, det, diagonal, dot, eig, eigvalsh, einsum, inv, lstsq, matmul, matrix_power, matrix_rank, norm, outer, pinv, qr, slogdet, solve, svd, trace, transpose <add># <add># __all__ += ['cholesky', 'cross', 'det', 'diagonal', 'dot', 'eig', 'eigvalsh', 'einsum', 'inv', 'lstsq', 'matmul', 'matrix_power', 'matrix_rank', 'norm', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'trace', 'transpose'] <add> <add>from .manipulation_functions import concat, expand_dims, flip, reshape, roll, squeeze, stack <add> <add>__all__ += ['concat', 'expand_dims', 'flip', 'reshape', 'roll', 'squeeze', 'stack'] <add> <add>from .searching_functions import argmax, argmin, nonzero, where <add> <add>__all__ += ['argmax', 'argmin', 'nonzero', 'where'] <add> <add>from .set_functions import unique <add> <add>__all__ += ['unique'] <add> <add>from .sorting_functions import argsort, sort <add> <add>__all__ += ['argsort', 'sort'] <add> <add>from .statistical_functions import max, mean, min, prod, std, sum, var <add> <add>__all__ += ['max', 'mean', 'min', 'prod', 'std', 'sum', 'var'] <add> <add>from .utility_functions import all, any <add> <add>__all__ += ['all', 'any'] <ide><path>numpy/_array_api/constants.py <add>from .. import e, inf, nan, pi <add> <add>__all__ = ['e', 'inf', 'nan', 'pi'] <ide><path>numpy/_array_api/creation_functions.py <add>def arange(start, /, *, stop=None, step=1, dtype=None): <add> from .. import arange <add> return arange(start, stop=stop, step=step, dtype=dtype) <add> <add>def empty(shape, /, *, dtype=None): <add> from .. import empty <add> return empty(shape, dtype=dtype) <add> <add>def empty_like(x, /, *, dtype=None): <add> from .. import empty_like <add> return empty_like(x, dtype=dtype) <add> <add>def eye(N, /, *, M=None, k=0, dtype=None): <add> from .. import eye <add> return eye(N, M=M, k=k, dtype=dtype) <add> <add>def full(shape, fill_value, /, *, dtype=None): <add> from .. import full <add> return full(shape, fill_value, dtype=dtype) <add> <add>def full_like(x, fill_value, /, *, dtype=None): <add> from .. import full_like <add> return full_like(x, fill_value, dtype=dtype) <add> <add>def linspace(start, stop, num, /, *, dtype=None, endpoint=True): <add> from .. import linspace <add> return linspace(start, stop, num, dtype=dtype, endpoint=endpoint) <add> <add>def ones(shape, /, *, dtype=None): <add> from .. import ones <add> return ones(shape, dtype=dtype) <add> <add>def ones_like(x, /, *, dtype=None): <add> from .. import ones_like <add> return ones_like(x, dtype=dtype) <add> <add>def zeros(shape, /, *, dtype=None): <add> from .. import zeros <add> return zeros(shape, dtype=dtype) <add> <add>def zeros_like(x, /, *, dtype=None): <add> from .. import zeros_like <add> return zeros_like(x, dtype=dtype) <add> <add>__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like', 'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like'] <ide><path>numpy/_array_api/elementwise_functions.py <add>def abs(x, /): <add> from .. import abs <add> return abs(x) <add> <add>def acos(x, /): <add> from .. import acos <add> return acos(x) <add> <add>def acosh(x, /): <add> from .. import acosh <add> return acosh(x) <add> <add>def add(x1, x2, /): <add> from .. import add <add> return add(x1, x2) <add> <add>def asin(x, /): <add> from .. import asin <add> return asin(x) <add> <add>def asinh(x, /): <add> from .. import asinh <add> return asinh(x) <add> <add>def atan(x, /): <add> from .. import atan <add> return atan(x) <add> <add>def atan2(x1, x2, /): <add> from .. import atan2 <add> return atan2(x1, x2) <add> <add>def atanh(x, /): <add> from .. import atanh <add> return atanh(x) <add> <add>def bitwise_and(x1, x2, /): <add> from .. import bitwise_and <add> return bitwise_and(x1, x2) <add> <add>def bitwise_left_shift(x1, x2, /): <add> from .. import bitwise_left_shift <add> return bitwise_left_shift(x1, x2) <add> <add>def bitwise_invert(x, /): <add> from .. import bitwise_invert <add> return bitwise_invert(x) <add> <add>def bitwise_or(x1, x2, /): <add> from .. import bitwise_or <add> return bitwise_or(x1, x2) <add> <add>def bitwise_right_shift(x1, x2, /): <add> from .. import bitwise_right_shift <add> return bitwise_right_shift(x1, x2) <add> <add>def bitwise_xor(x1, x2, /): <add> from .. import bitwise_xor <add> return bitwise_xor(x1, x2) <add> <add>def ceil(x, /): <add> from .. import ceil <add> return ceil(x) <add> <add>def cos(x, /): <add> from .. import cos <add> return cos(x) <add> <add>def cosh(x, /): <add> from .. import cosh <add> return cosh(x) <add> <add>def divide(x1, x2, /): <add> from .. import divide <add> return divide(x1, x2) <add> <add>def equal(x1, x2, /): <add> from .. import equal <add> return equal(x1, x2) <add> <add>def exp(x, /): <add> from .. import exp <add> return exp(x) <add> <add>def expm1(x, /): <add> from .. import expm1 <add> return expm1(x) <add> <add>def floor(x, /): <add> from .. import floor <add> return floor(x) <add> <add>def floor_divide(x1, x2, /): <add> from .. import floor_divide <add> return floor_divide(x1, x2) <add> <add>def greater(x1, x2, /): <add> from .. import greater <add> return greater(x1, x2) <add> <add>def greater_equal(x1, x2, /): <add> from .. import greater_equal <add> return greater_equal(x1, x2) <add> <add>def isfinite(x, /): <add> from .. import isfinite <add> return isfinite(x) <add> <add>def isinf(x, /): <add> from .. import isinf <add> return isinf(x) <add> <add>def isnan(x, /): <add> from .. import isnan <add> return isnan(x) <add> <add>def less(x1, x2, /): <add> from .. import less <add> return less(x1, x2) <add> <add>def less_equal(x1, x2, /): <add> from .. import less_equal <add> return less_equal(x1, x2) <add> <add>def log(x, /): <add> from .. import log <add> return log(x) <add> <add>def log1p(x, /): <add> from .. import log1p <add> return log1p(x) <add> <add>def log2(x, /): <add> from .. import log2 <add> return log2(x) <add> <add>def log10(x, /): <add> from .. import log10 <add> return log10(x) <add> <add>def logical_and(x1, x2, /): <add> from .. import logical_and <add> return logical_and(x1, x2) <add> <add>def logical_not(x, /): <add> from .. import logical_not <add> return logical_not(x) <add> <add>def logical_or(x1, x2, /): <add> from .. import logical_or <add> return logical_or(x1, x2) <add> <add>def logical_xor(x1, x2, /): <add> from .. import logical_xor <add> return logical_xor(x1, x2) <add> <add>def multiply(x1, x2, /): <add> from .. import multiply <add> return multiply(x1, x2) <add> <add>def negative(x, /): <add> from .. import negative <add> return negative(x) <add> <add>def not_equal(x1, x2, /): <add> from .. import not_equal <add> return not_equal(x1, x2) <add> <add>def positive(x, /): <add> from .. import positive <add> return positive(x) <add> <add>def pow(x1, x2, /): <add> from .. import pow <add> return pow(x1, x2) <add> <add>def remainder(x1, x2, /): <add> from .. import remainder <add> return remainder(x1, x2) <add> <add>def round(x, /): <add> from .. import round <add> return round(x) <add> <add>def sign(x, /): <add> from .. import sign <add> return sign(x) <add> <add>def sin(x, /): <add> from .. import sin <add> return sin(x) <add> <add>def sinh(x, /): <add> from .. import sinh <add> return sinh(x) <add> <add>def square(x, /): <add> from .. import square <add> return square(x) <add> <add>def sqrt(x, /): <add> from .. import sqrt <add> return sqrt(x) <add> <add>def subtract(x1, x2, /): <add> from .. import subtract <add> return subtract(x1, x2) <add> <add>def tan(x, /): <add> from .. import tan <add> return tan(x) <add> <add>def tanh(x, /): <add> from .. import tanh <add> return tanh(x) <add> <add>def trunc(x, /): <add> from .. import trunc <add> return trunc(x) <add> <add>__all__ = ['abs', 'acos', 'acosh', 'add', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'bitwise_and', 'bitwise_left_shift', 'bitwise_invert', 'bitwise_or', 'bitwise_right_shift', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', 'equal', 'exp', 'expm1', 'floor', 'floor_divide', 'greater', 'greater_equal', 'isfinite', 'isinf', 'isnan', 'less', 'less_equal', 'log', 'log1p', 'log2', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'multiply', 'negative', 'not_equal', 'positive', 'pow', 'remainder', 'round', 'sign', 'sin', 'sinh', 'square', 'sqrt', 'subtract', 'tan', 'tanh', 'trunc'] <ide><path>numpy/_array_api/linear_algebra_functions.py <add># def cholesky(): <add># from .. import cholesky <add># return cholesky() <add> <add>def cross(x1, x2, /, *, axis=-1): <add> from .. import cross <add> return cross(x1, x2, axis=axis) <add> <add>def det(x, /): <add> from .. import det <add> return det(x) <add> <add>def diagonal(x, /, *, axis1=0, axis2=1, offset=0): <add> from .. import diagonal <add> return diagonal(x, axis1=axis1, axis2=axis2, offset=offset) <add> <add># def dot(): <add># from .. import dot <add># return dot() <add># <add># def eig(): <add># from .. import eig <add># return eig() <add># <add># def eigvalsh(): <add># from .. import eigvalsh <add># return eigvalsh() <add># <add># def einsum(): <add># from .. import einsum <add># return einsum() <add> <add>def inv(x): <add> from .. import inv <add> return inv(x) <add> <add># def lstsq(): <add># from .. import lstsq <add># return lstsq() <add># <add># def matmul(): <add># from .. import matmul <add># return matmul() <add># <add># def matrix_power(): <add># from .. import matrix_power <add># return matrix_power() <add># <add># def matrix_rank(): <add># from .. import matrix_rank <add># return matrix_rank() <add> <add>def norm(x, /, *, axis=None, keepdims=False, ord=None): <add> from .. import norm <add> return norm(x, axis=axis, keepdims=keepdims, ord=ord) <add> <add>def outer(x1, x2, /): <add> from .. import outer <add> return outer(x1, x2) <add> <add># def pinv(): <add># from .. import pinv <add># return pinv() <add># <add># def qr(): <add># from .. import qr <add># return qr() <add># <add># def slogdet(): <add># from .. import slogdet <add># return slogdet() <add># <add># def solve(): <add># from .. import solve <add># return solve() <add># <add># def svd(): <add># from .. import svd <add># return svd() <add> <add>def trace(x, /, *, axis1=0, axis2=1, offset=0): <add> from .. import trace <add> return trace(x, axis1=axis1, axis2=axis2, offset=offset) <add> <add>def transpose(x, /, *, axes=None): <add> from .. import transpose <add> return transpose(x, axes=axes) <add> <add># __all__ = ['cholesky', 'cross', 'det', 'diagonal', 'dot', 'eig', 'eigvalsh', 'einsum', 'inv', 'lstsq', 'matmul', 'matrix_power', 'matrix_rank', 'norm', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'trace', 'transpose'] <add> <add>__all__ = ['cross', 'det', 'diagonal', 'inv', 'norm', 'outer', 'trace', 'transpose'] <ide><path>numpy/_array_api/manipulation_functions.py <add>def concat(arrays, /, *, axis=0): <add> from .. import concat <add> return concat(arrays, axis=axis) <add> <add>def expand_dims(x, axis, /): <add> from .. import expand_dims <add> return expand_dims(x, axis) <add> <add>def flip(x, /, *, axis=None): <add> from .. import flip <add> return flip(x, axis=axis) <add> <add>def reshape(x, shape, /): <add> from .. import reshape <add> return reshape(x, shape) <add> <add>def roll(x, shift, /, *, axis=None): <add> from .. import roll <add> return roll(x, shift, axis=axis) <add> <add>def squeeze(x, /, *, axis=None): <add> from .. import squeeze <add> return squeeze(x, axis=axis) <add> <add>def stack(arrays, /, *, axis=0): <add> from .. import stack <add> return stack(arrays, axis=axis) <add> <add>__all__ = ['concat', 'expand_dims', 'flip', 'reshape', 'roll', 'squeeze', 'stack'] <ide><path>numpy/_array_api/searching_functions.py <add>def argmax(x, /, *, axis=None, keepdims=False): <add> from .. import argmax <add> return argmax(x, axis=axis, keepdims=keepdims) <add> <add>def argmin(x, /, *, axis=None, keepdims=False): <add> from .. import argmin <add> return argmin(x, axis=axis, keepdims=keepdims) <add> <add>def nonzero(x, /): <add> from .. import nonzero <add> return nonzero(x) <add> <add>def where(condition, x1, x2, /): <add> from .. import where <add> return where(condition, x1, x2) <add> <add>__all__ = ['argmax', 'argmin', 'nonzero', 'where'] <ide><path>numpy/_array_api/set_functions.py <add>def unique(x, /, *, return_counts=False, return_index=False, return_inverse=False, sorted=True): <add> from .. import unique <add> return unique(x, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse, sorted=sorted) <add> <add>__all__ = ['unique'] <ide><path>numpy/_array_api/sorting_functions.py <add>def argsort(x, /, *, axis=-1, descending=False, stable=True): <add> from .. import argsort <add> return argsort(x, axis=axis, descending=descending, stable=stable) <add> <add>def sort(x, /, *, axis=-1, descending=False, stable=True): <add> from .. import sort <add> return sort(x, axis=axis, descending=descending, stable=stable) <add> <add>__all__ = ['argsort', 'sort'] <ide><path>numpy/_array_api/statistical_functions.py <add>def max(x, /, *, axis=None, keepdims=False): <add> from .. import max <add> return max(x, axis=axis, keepdims=keepdims) <add> <add>def mean(x, /, *, axis=None, keepdims=False): <add> from .. import mean <add> return mean(x, axis=axis, keepdims=keepdims) <add> <add>def min(x, /, *, axis=None, keepdims=False): <add> from .. import min <add> return min(x, axis=axis, keepdims=keepdims) <add> <add>def prod(x, /, *, axis=None, keepdims=False): <add> from .. import prod <add> return prod(x, axis=axis, keepdims=keepdims) <add> <add>def std(x, /, *, axis=None, correction=0.0, keepdims=False): <add> from .. import std <add> return std(x, axis=axis, correction=correction, keepdims=keepdims) <add> <add>def sum(x, /, *, axis=None, keepdims=False): <add> from .. import sum <add> return sum(x, axis=axis, keepdims=keepdims) <add> <add>def var(x, /, *, axis=None, correction=0.0, keepdims=False): <add> from .. import var <add> return var(x, axis=axis, correction=correction, keepdims=keepdims) <add> <add>__all__ = ['max', 'mean', 'min', 'prod', 'std', 'sum', 'var'] <ide><path>numpy/_array_api/utility_functions.py <add>def all(x, /, *, axis=None, keepdims=False): <add> from .. import all <add> return all(x, axis=axis, keepdims=keepdims) <add> <add>def any(x, /, *, axis=None, keepdims=False): <add> from .. import any <add> return any(x, axis=axis, keepdims=keepdims) <add> <add>__all__ = ['all', 'any']
11
Ruby
Ruby
fix linting errors
95d4a258914867ef6237709dd03971dbec765324
<ide><path>Library/Homebrew/cask/lib/hbc/cli/reinstall.rb <ide> def self.install_casks(cask_tokens, force, skip_cask_deps, require_sha) <ide> <ide> unless latest_installed_version.nil? <ide> latest_installed_cask_file = installed_cask.metadata_master_container_path <del> .join(latest_installed_version.join(File::Separator), <del> "Casks", "#{cask_token}.rb") <add> .join(latest_installed_version <add> .join(File::Separator), <add> "Casks", "#{cask_token}.rb") <ide> <ide> # use the same cask file that was used for installation, if possible <ide> installed_cask = Hbc.load(latest_installed_cask_file) if latest_installed_cask_file.exist?
1
Text
Text
provide example activities
99e2d4380120d3aad0cd4dafc59b83be9f970256
<ide><path>GOVERNANCE.md <ide> For the current list of Collaborators, see the project <ide> A guide for Collaborators is maintained in <ide> [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md). <ide> <add>Typical activities of a Collaborator include: <add> <add>* helping users and novice contributors <add>* contributing code and documentation changes that improve the project <add>* reviewing and commenting on issues and pull requests <add>* participation in working groups <add>* merging pull requests <add> <add>While the above are typical things done by Collaborators, there are no required <add>activities to retain Collaborator status. There is currently no process by which <add>inactive Collaborators are removed from the project. <add> <ide> ## CTC Membership <ide> <ide> CTC seats are not time-limited. There is no fixed size of the CTC. The CTC <ide> the CTC membership shares an employer, then the situation must be <ide> immediately remedied by the resignation or removal of one or more CTC <ide> members affiliated with the over-represented employer(s). <ide> <add>Typical activities of a CTC member include: <add> <add>* attending the weekly meeting <add>* commenting on the weekly CTC meeting issue and issues labeled `ctc-agenda` <add>* participating in CTC email threads <add>* volunteering for tasks that arise from CTC meetings and related discussions <add>* other activities (beyond those typical of Collaborators) that facilitate the <add> smooth day-to-day operation of the Node.js project <add> <add>Note that CTC members are also Collaborators and therefore typically perform <add>Collaborator activities as well. <add> <ide> ## CTC Meetings <ide> <ide> The CTC meets weekly in a voice conference call. The meeting is run by a
1
Go
Go
change code in container restore
6184ff312dce3222d71ec7c2769002e2dd7595ed
<ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/reference" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/runconfig" <del> "github.com/docker/docker/utils" <ide> volumedrivers "github.com/docker/docker/volume/drivers" <ide> "github.com/docker/docker/volume/local" <ide> "github.com/docker/docker/volume/store" <ide> type Daemon struct { <ide> <ide> func (daemon *Daemon) restore() error { <ide> var ( <del> debug = utils.IsDebugEnabled() <ide> currentDriver = daemon.GraphDriverName() <ide> containers = make(map[string]*container.Container) <ide> ) <ide> <del> if !debug { <del> logrus.Info("Loading containers: start.") <del> } <add> logrus.Info("Loading containers: start.") <add> <ide> dir, err := ioutil.ReadDir(daemon.repository) <ide> if err != nil { <ide> return err <ide> } <ide> <del> containerCount := 0 <ide> for _, v := range dir { <ide> id := v.Name() <ide> container, err := daemon.load(id) <del> if !debug && logrus.GetLevel() == logrus.InfoLevel { <del> fmt.Print(".") <del> containerCount++ <del> } <ide> if err != nil { <ide> logrus.Errorf("Failed to load container %v: %v", id, err) <ide> continue <ide> func (daemon *Daemon) restore() error { <ide> <ide> group.Wait() <ide> <del> if !debug { <del> if logrus.GetLevel() == logrus.InfoLevel && containerCount > 0 { <del> fmt.Println() <del> } <del> logrus.Info("Loading containers: done.") <del> } <add> logrus.Info("Loading containers: done.") <ide> <ide> return nil <ide> } <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { <ide> c.Assert(out, checker.Contains, expected) <ide> } <ide> <del>func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) { <del> if err := s.d.StartWithBusybox(); err != nil { <del> c.Fatal(err) <del> } <del> <del> // Now create 4 containers <del> if _, err := s.d.Cmd("create", "busybox"); err != nil { <del> c.Fatalf("Error creating container: %q", err) <del> } <del> if _, err := s.d.Cmd("create", "busybox"); err != nil { <del> c.Fatalf("Error creating container: %q", err) <del> } <del> if _, err := s.d.Cmd("create", "busybox"); err != nil { <del> c.Fatalf("Error creating container: %q", err) <del> } <del> if _, err := s.d.Cmd("create", "busybox"); err != nil { <del> c.Fatalf("Error creating container: %q", err) <del> } <del> <del> s.d.Stop() <del> <del> s.d.Start("--log-level=debug") <del> s.d.Stop() <del> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <del> if strings.Contains(string(content), "....") { <del> c.Fatalf("Debug level should not have ....\n%s", string(content)) <del> } <del> <del> s.d.Start("--log-level=error") <del> s.d.Stop() <del> content, _ = ioutil.ReadFile(s.d.logFile.Name()) <del> if strings.Contains(string(content), "....") { <del> c.Fatalf("Error level should not have ....\n%s", string(content)) <del> } <del> <del> s.d.Start("--log-level=info") <del> s.d.Stop() <del> content, _ = ioutil.ReadFile(s.d.logFile.Name()) <del> if !strings.Contains(string(content), "....") { <del> c.Fatalf("Info level should have ....\n%s", string(content)) <del> } <del>} <del> <ide> func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) { <ide> dir, err := ioutil.TempDir("", "socket-cleanup-test") <ide> if err != nil {
2
Ruby
Ruby
add test cases for migration#inverse_of
c195317a56061593316d7b5d163d868022010132
<ide><path>activerecord/test/cases/migration/command_recorder_test.rb <ide> def test_invert_add_column <ide> assert_equal [:remove_column, [:table, :column, :type, {}], nil], remove <ide> end <ide> <add> def test_invert_change_column <add> assert_raises(ActiveRecord::IrreversibleMigration) do <add> @recorder.inverse_of :change_column, [:table, :column, :type, {}] <add> end <add> end <add> <add> def test_invert_change_column_default <add> assert_raises(ActiveRecord::IrreversibleMigration) do <add> @recorder.inverse_of :change_column_default, [:table, :column, 'default_value'] <add> end <add> end <add> <add> def test_invert_change_column_null <add> add = @recorder.inverse_of :change_column_null, [:table, :column, true] <add> assert_equal [:change_column_null, [:table, :column, false]], add <add> end <add> <ide> def test_invert_remove_column <ide> add = @recorder.inverse_of :remove_column, [:table, :column, :type, {}] <ide> assert_equal [:add_column, [:table, :column, :type, {}], nil], add
1
Python
Python
remove batch_size when doing stepwise fit
bfc6a25a6e7ade316922fc8bf83748553fbb39c1
<ide><path>keras/engine/training_arrays.py <ide> def fit_loop(model, f, ins, <ide> <ide> if do_validation: <ide> val_outs = test_loop(model, val_f, val_ins, <del> batch_size=batch_size, <ide> steps=validation_steps, <ide> verbose=0) <ide> if not isinstance(val_outs, list):
1
PHP
PHP
add missing create() for creating a new record
f62f46562c73b893f06726d267e8010f48a114cc
<ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php <ide> public function testDetectInvalidLeft() { <ide> $save[$modelClass]['id'] = $result[$modelClass]['id']; <ide> $save[$modelClass][$leftField] = 0; <ide> <add> $this->Tree->create(); <ide> $this->Tree->save($save); <ide> $result = $this->Tree->verify(); <ide> $this->assertNotSame($result, true); <ide> public function testDetectInvalidRight() { <ide> $save[$modelClass]['id'] = $result[$modelClass]['id']; <ide> $save[$modelClass][$rightField] = 0; <ide> <add> $this->Tree->create(); <ide> $this->Tree->save($save); <ide> $result = $this->Tree->verify(); <ide> $this->assertNotSame($result, true); <ide> public function testRecoverUsingParentMode() { <ide> $this->Tree->order = null; <ide> $this->Tree->Behaviors->disable('Tree'); <ide> <add> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0)); <ide> $node1 = $this->Tree->id; <ide> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0)); <ide> $node11 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0)); <ide> $node12 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0)); <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0)); <ide> <ide> public function testRecoverUsingParentModeAndDelete() { <ide> $this->Tree->order = null; <ide> $this->Tree->Behaviors->disable('Tree'); <ide> <add> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0)); <ide> $node1 = $this->Tree->id; <ide> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0)); <ide> $node11 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0)); <ide> $node12 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0)); <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0)); <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Lost', $parentField => 9, $leftField => 0, $rightField => 0)); <ide> <ide> public function testAddOrphan() { <ide> $this->Tree->order = null; <ide> $this->Tree->initialize(2, 2); <ide> <add> $this->Tree->create(); <ide> $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); <ide> $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); <ide> $expected = array($modelClass => array('name' => 'testAddOrphan', $parentField => null)); <ide> public function testAddInvalid() { <ide> $initialCount = $this->Tree->find('count'); <ide> //$this->expectError('Trying to save a node under a none-existant node in TreeBehavior::beforeSave'); <ide> <add> $this->Tree->create(); <ide> $saveSuccess = $this->Tree->save(array($modelClass => array('name' => 'testAddInvalid', $parentField => 99999))); <ide> $this->assertFalse($saveSuccess); <ide> <ide> public function testAddNotIndexedByModel() { <ide> $this->Tree->order = null; <ide> $this->Tree->initialize(2, 2); <ide> <add> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null)); <ide> $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); <ide> $expected = array($modelClass => array('name' => 'testAddNotIndexed', $parentField => null)); <ide> public function testInsertWithWhitelist() { <ide> $this->Tree->initialize(2, 2); <ide> <ide> $this->Tree->whitelist = array('name', $parentField); <add> $this->Tree->create(); <ide> $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); <ide> $result = $this->Tree->findByName('testAddOrphan', array('name', $parentField, $leftField, $rightField)); <ide> $expected = array('name' => 'testAddOrphan', $parentField => null, $leftField => '15', $rightField => 16); <ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php <ide> public function testTranslatingTree() { <ide> $this->Tree->Behaviors->attach('Translate', array('title')); <ide> <ide> //Save <add> $this->Tree->create(); <ide> $this->Tree->locale = 'eng'; <ide> $data = array('FlagTree' => array( <ide> 'title' => 'name #1', <ide> public function testRecoverUsingParentMode() { <ide> $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); <ide> $this->Tree->Behaviors->disable('Tree'); <ide> <add> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0, 'flag' => 1)); <ide> $node1 = $this->Tree->id; <ide> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0, 'flag' => 1)); <ide> $node11 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0, 'flag' => 1)); <ide> $node12 = $this->Tree->id; <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0, 'flag' => 1)); <add> <ide> $this->Tree->create(); <ide> $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0, 'flag' => 1)); <ide>
2
Javascript
Javascript
add warnings for extracted components
f295d7f60843a45bb09fc366e497f512c2bc0046
<ide><path>index.js <ide> module.exports = { <ide> return require('./Libraries/Components/Picker/PickerIOS'); <ide> }, <ide> get ProgressBarAndroid(): ProgressBarAndroid { <add> warnOnce( <add> 'progress-bar-android-moved', <add> 'ProgressBarAndroid has been extracted from react-native core and will be removed in a future release. ' + <add> "It can now be installed and imported from '@react-native-community/progress-bar-android' instead of 'react-native'. " + <add> 'See https://github.com/react-native-community/react-native-progress-bar-android', <add> ); <ide> return require('./Libraries/Components/ProgressBarAndroid/ProgressBarAndroid'); <ide> }, <ide> get ProgressViewIOS(): ProgressViewIOS { <add> warnOnce( <add> 'progress-view-ios-moved', <add> 'ProgressViewIOS has been extracted from react-native core and will be removed in a future release. ' + <add> "It can now be installed and imported from '@react-native-community/progress-view' instead of 'react-native'. " + <add> 'See https://github.com/react-native-community/react-native-progress-view', <add> ); <ide> return require('./Libraries/Components/ProgressViewIOS/ProgressViewIOS'); <ide> }, <ide> get SafeAreaView(): SafeAreaView { <ide> module.exports = { <ide> return require('./Libraries/Lists/SectionList'); <ide> }, <ide> get SegmentedControlIOS(): SegmentedControlIOS { <add> warnOnce( <add> 'segmented-control-ios-moved', <add> 'SegmentedControlIOS has been extracted from react-native core and will be removed in a future release. ' + <add> "It can now be installed and imported from '@react-native-community/segmented-control' instead of 'react-native'. " + <add> 'See https://github.com/react-native-community/react-native-segmented-control', <add> ); <ide> return require('./Libraries/Components/SegmentedControlIOS/SegmentedControlIOS'); <ide> }, <ide> get Slider(): Slider { <ide> module.exports = { <ide> return require('./Libraries/Utilities/BackHandler'); <ide> }, <ide> get Clipboard(): Clipboard { <add> warnOnce( <add> 'clipboard-moved', <add> 'Clipboard has been extracted from react-native core and will be removed in a future release. ' + <add> "It can now be installed and imported from '@react-native-community/clipboard' instead of 'react-native'. " + <add> 'See https://github.com/react-native-community/react-native-clipboard', <add> ); <ide> return require('./Libraries/Components/Clipboard/Clipboard'); <ide> }, <ide> get DatePickerAndroid(): DatePickerAndroid {
1
Python
Python
add helper routines for gufuncs
2e8b24e30345c75eb9101ea29e96c9fde48add7f
<ide><path>numpy/linalg/linalg.py <ide> intc, single, double, csingle, cdouble, inexact, complexfloating, \ <ide> newaxis, ravel, all, Inf, dot, add, multiply, identity, sqrt, \ <ide> maximum, flatnonzero, diagonal, arange, fastCopyAndTranspose, sum, \ <del> isfinite, size, finfo, absolute, log, exp <add> isfinite, size, finfo, absolute, log, exp, errstate, geterrobj <ide> from numpy.lib import triu <ide> from numpy.linalg import lapack_lite <ide> from numpy.matrixlib.defmatrix import matrix_power <ide> from numpy.compat import asbytes <ide> <add>from numpy.core import _umath_linalg <add> <ide> # For Python2/3 compatibility <ide> _N = asbytes('N') <ide> _V = asbytes('V') <ide> class LinAlgError(Exception): <ide> """ <ide> pass <ide> <add># Dealing with errors in _umath_linalg <add> <add>_linalg_error_extobj = None <add> <add>def _determine_error_states(): <add> global _linalg_error_extobj <add> errobj = geterrobj() <add> bufsize = errobj[0] <add> <add> with errstate(invalid='call', over='ignore', <add> divide='ignore', under='ignore'): <add> invalid_call_errmask = geterrobj()[1] <add> <add> _linalg_error_extobj = [bufsize, invalid_call_errmask, None] <add> <add>_determine_error_states() <add> <add>def _raise_linalgerror_singular(err, flag): <add> raise LinAlgError("Singular matrix") <add> <add>def _raise_linalgerror_nonposdef(err, flag): <add> raise LinAlgError("Matrix is not positive definite") <add> <add>def _raise_linalgerror_eigenvalues_nonconvergence(err, flag): <add> raise LinAlgError("Eigenvalues did not converge") <add> <add>def _raise_linalgerror_svd_nonconvergence(err, flag): <add> raise LinAlgError("SVD did not converge") <add> <add>def get_linalg_error_extobj(callback): <add> extobj = list(_linalg_error_extobj) <add> extobj[2] = callback <add> return extobj <add> <ide> def _makearray(a): <ide> new = asarray(a) <ide> wrap = getattr(a, "__array_prepare__", new.__array_wrap__) <ide> def _assertRank2(*arrays): <ide> raise LinAlgError('%d-dimensional array given. Array must be ' <ide> 'two-dimensional' % len(a.shape)) <ide> <add>def _assertRankAtLeast2(*arrays): <add> for a in arrays: <add> if len(a.shape) < 2: <add> raise LinAlgError('%d-dimensional array given. Array must be ' <add> 'at least two-dimensional' % len(a.shape)) <add> <ide> def _assertSquareness(*arrays): <ide> for a in arrays: <ide> if max(a.shape) != min(a.shape): <ide> raise LinAlgError('Array must be square') <ide> <add>def _assertNdSquareness(*arrays): <add> for a in arrays: <add> if max(a.shape[-2:]) != min(a.shape[-2:]): <add> raise LinAlgError('Last 2 dimensions of the array must be square') <add> <ide> def _assertFinite(*arrays): <ide> for a in arrays: <ide> if not (isfinite(a).all()):
1
Text
Text
add missing code highlight
b66e199e5321d925c8077ea8c9f01f95827c6be2
<ide><path>docs/tutorials/essentials/part-4-using-data.md <ide> export const AddPostForm = () => { <ide> value={content} <ide> onChange={onContentChanged} <ide> /> <add> // highlight-next-line <ide> <button type="button" onClick={onSavePostClicked} disabled={!canSave}> <ide> Save Post <ide> </button>
1
PHP
PHP
apply fixes from styleci
20f5605b6cf0d0b3e0aee6bebd007ac24a9ae96c
<ide><path>src/Illuminate/Routing/CompiledRouteCollection.php <ide> public function match(Request $request) <ide> } <ide> } <ide> <del> <ide> return $this->handleMatchedRoute($request, $route); <ide> } <ide>
1
Ruby
Ruby
unify indentation of access modifiers
9db0e68eb60b7634eb26f9b734e7b1e47cc3f2ba
<ide><path>Library/Homebrew/cmd/list.rb <ide> def list <ide> end <ide> end <ide> <del>private <add> private <ide> <ide> def list_unbrewed <ide> dirs = HOMEBREW_PREFIX.children.select{ |pn| pn.directory? }.map{ |pn| pn.basename.to_s } <ide><path>Library/Homebrew/dependency_collector.rb <ide> def build(spec) <ide> parse_spec(spec, tag) <ide> end <ide> <del>private <add> private <ide> <ide> def parse_spec spec, tag <ide> case spec <ide><path>Library/Homebrew/download_strategy.rb <ide> def stage <ide> end <ide> end <ide> <del>private <add> private <add> <ide> def chdir <ide> entries=Dir['*'] <ide> case entries.length <ide> def stage <ide> end <ide> end <ide> <del>private <add> private <add> <ide> def split_url(in_url) <ide> parts=in_url.sub(%r[^cvs://], '').split(/:/) <ide> mod=parts.pop <ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> <ide> end <ide> <del>protected <add> protected <ide> <ide> # Pretty titles the command and buffers stdout/stderr <ide> # Throws if there's an error <ide> def system cmd, *args <ide> end if removed_ENV_variables <ide> end <ide> <del>public <add> public <ide> <ide> # For brew-fetch and others. <ide> def fetch <ide> def test_defined? <ide> not self.class.instance_variable_get(:@test_defined).nil? <ide> end <ide> <del>private <add> private <ide> <ide> def stage <ide> fetched, downloader = fetch <ide> def test &block <ide> @test = block <ide> end <ide> <del> private <add> private <ide> <ide> def post_depends_on(dep) <ide> # Generate with- or without- options for optional and recommended <ide><path>Library/Homebrew/keg.rb <ide> def optlink <ide> from.make_relative_symlink(self) <ide> end <ide> <del>protected <add> protected <add> <ide> def resolve_any_conflicts dst <ide> # if it isn't a directory then a severe conflict is about to happen. Let <ide> # it, and the exception that is generated will message to the user about <ide><path>Library/Homebrew/metafiles.rb <ide> def should_list? file <ide> not include? file <ide> end <ide> <del>private <add> private <ide> <ide> def include? p <ide> p = p.to_s # Might be a pathname <ide><path>Library/Homebrew/patches.rb <ide> def download! <ide> external_patches.each{|p| p.stage!} <ide> end <ide> <del>private <add> private <ide> <ide> def external_patches <ide> @patches.select{|p| p.external?} <ide> def curl_args <ide> [@url, '-o', @patch_filename] <ide> end <ide> <del>private <add> private <ide> <ide> # Detect compression type from the downloaded patch. <ide> def detect_compression!
7
PHP
PHP
remove todo to satisfy linter
5fc1e97a178248c5bdc7bd48d684ad27475a01d3
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testSaveReplaceSaveStrategyDependent() <ide> /** <ide> * Test that the associated entities are unlinked and deleted when they are dependent <ide> * <del> * TODO in the future this should change and apply the finder. <add> * In the future this should change and apply the finder. <ide> * <ide> * @return void <ide> */
1
Go
Go
omit empty defaultaddresspools
c161d6564d755c0b6b4356ceff87fbd6a898b675
<ide><path>api/types/types.go <ide> type Info struct { <ide> RuncCommit Commit <ide> InitCommit Commit <ide> SecurityOptions []string <del> ProductLicense string `json:",omitempty"` <del> DefaultAddressPools []NetworkAddressPool <add> ProductLicense string `json:",omitempty"` <add> DefaultAddressPools []NetworkAddressPool `json:",omitempty"` <ide> Warnings []string <ide> } <ide>
1
PHP
PHP
add extra tests for validation
7fd7ad17cf5077fcbdd12b3d39003b4726afa447
<ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testBeforeAndAfterWithFormat() <ide> $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'nullable|date_format:d/m/Y|after:start']); <ide> $this->assertTrue($v->passes()); <ide> <add> $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'before:ends']); <add> $this->assertTrue($v->fails()); <add> <add> $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'before:ends', 'ends' => 'nullable']); <add> $this->assertTrue($v->fails()); <add> <ide> $v = new Validator($trans, ['x' => date('d/m/Y')], ['x' => 'date_format:d/m/Y|after:yesterday|before:tomorrow']); <ide> $this->assertTrue($v->passes()); <ide> <ide> public function testWeakBeforeAndAfter() <ide> <ide> $v = new Validator($trans, ['x' => '17:44'], ['x' => 'date_format:H:i|after_or_equal:17:45']); <ide> $this->assertTrue($v->fails()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-14', 'bar' => '2012-01-15'], ['foo' => 'before_or_equal:bar']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15', 'bar' => '2012-01-15'], ['foo' => 'before_or_equal:bar']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15 13:00', 'bar' => '2012-01-15 12:00'], ['foo' => 'before_or_equal:bar']); <add> $this->assertTrue($v->fails()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15 11:00', 'bar' => null], ['foo' => 'date_format:Y-m-d H:i|before_or_equal:bar', 'bar' => 'date_format:Y-m-d H:i']); <add> $this->assertTrue($v->fails()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15 11:00', 'bar' => null], ['foo' => 'date_format:Y-m-d H:i|before_or_equal:bar', 'bar' => 'date_format:Y-m-d H:i|nullable']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15 11:00', 'bar' => null], ['foo' => 'before_or_equal:bar']); <add> $this->assertTrue($v->fails()); <add> <add> $v = new Validator($trans, ['foo' => '2012-01-15 11:00', 'bar' => null], ['foo' => 'before_or_equal:bar', 'bar' => 'nullable']); <add> $this->assertTrue($v->fails()); <ide> } <ide> <ide> public function testSometimesAddingRules()
1
Javascript
Javascript
fix errors in preparation for v0.17.0
08ec89d2e69f67bd5ffb5690077f91138b50e319
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> var flattenStyle = require('flattenStyle'); <ide> var invariant = require('invariant'); <ide> var requestAnimationFrame = require('requestAnimationFrame'); <ide> <del>import type InterpolationConfigType from 'Interpolation'; <add>import type { InterpolationConfigType } from 'Interpolation'; <ide> <ide> type EndResult = {finished: bool}; <ide> type EndCallback = (result: EndResult) => void; <ide><path>Libraries/Animated/src/Interpolation.js <ide> var invariant = function(condition, message) { <ide> <ide> type ExtrapolateType = 'extend' | 'identity' | 'clamp'; <ide> <del>// $FlowFixMe D2163827 <ide> export type InterpolationConfigType = { <ide> inputRange: Array<number>; <ide> outputRange: (Array<number> | Array<string>);
2
Ruby
Ruby
call method locally inside the class
5b9505871bc605a39d5ed04ca44fdb6a6eb5a630
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb <ide> def create_current(environment = env, name = nil) <ide> def prepare_all <ide> seed = false <ide> <del> configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| <add> configs_for(env_name: env).each do |db_config| <ide> ActiveRecord::Base.establish_connection(db_config) <ide> <ide> # Skipped when no database <del> ActiveRecord::Tasks::DatabaseTasks.migrate <add> migrate <ide> <ide> if ActiveRecord::Base.dump_schema_after_migration <del> ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config, ActiveRecord::Base.schema_format) <add> dump_schema(db_config, ActiveRecord::Base.schema_format) <ide> end <ide> rescue ActiveRecord::NoDatabaseError <ide> config_name = db_config.name <del> ActiveRecord::Tasks::DatabaseTasks.create_current(db_config.env_name, config_name) <add> create_current(db_config.env_name, config_name) <ide> <del> if File.exist?(ActiveRecord::Tasks::DatabaseTasks.dump_filename(config_name)) <del> ActiveRecord::Tasks::DatabaseTasks.load_schema( <add> if File.exist?(dump_filename(config_name)) <add> load_schema( <ide> db_config, <ide> ActiveRecord::Base.schema_format, <ide> nil <ide> ) <ide> else <del> ActiveRecord::Tasks::DatabaseTasks.migrate <add> migrate <ide> end <ide> <ide> seed = true <ide> end <ide> <ide> ActiveRecord::Base.establish_connection <del> ActiveRecord::Tasks::DatabaseTasks.load_seed if seed <add> load_seed if seed <ide> end <ide> <ide> def drop(configuration, *arguments)
1
Ruby
Ruby
move appswitch to homebrew-binary
92c359c3e71f8641fe3ba0f14ebab7477022c40c
<ide><path>Library/Homebrew/tap_migrations.rb <ide> TAP_MIGRATIONS = { <ide> "agedu" => "homebrew/headonly", <ide> "aimage" => "homebrew/boneyard", <del> "aws-iam-tools" => "homebrew/boneyard", <ide> "apple-gcc42" => "homebrew/versions", <add> "appswitch" => "homebrew/binary", <add> "aws-iam-tools" => "homebrew/boneyard", <ide> "blackbox" => "homebrew/boneyard", <ide> "boost149" => "homebrew/versions", <ide> "catdoc" => "homebrew/boneyard",
1
Text
Text
add options argument to crypto docs
447715543b5f80cbee6496657179f1393a631fbf
<ide><path>doc/api/crypto.md <ide> added: v6.0.0 <ide> Property for checking and controlling whether a FIPS compliant crypto provider is <ide> currently in use. Setting to true requires a FIPS build of Node.js. <ide> <del>### crypto.createCipher(algorithm, password) <add>### crypto.createCipher(algorithm, password[, options]) <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> - `algorithm` {string} <ide> - `password` {string | Buffer | TypedArray | DataView} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns a `Cipher` object that uses the given `algorithm` and <del>`password`. <add>`password`. Optional `options` argument controls stream behavior. <ide> <ide> The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On <ide> recent OpenSSL releases, `openssl list-cipher-algorithms` will display the <ide> they are used in order to avoid the risk of IV reuse that causes <ide> vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting <ide> Adversaries][] for details. <ide> <del>### crypto.createCipheriv(algorithm, key, iv) <add>### crypto.createCipheriv(algorithm, key, iv[, options]) <ide> - `algorithm` {string} <ide> - `key` {string | Buffer | TypedArray | DataView} <ide> - `iv` {string | Buffer | TypedArray | DataView} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns a `Cipher` object, with the given `algorithm`, `key` and <del>initialization vector (`iv`). <add>initialization vector (`iv`). Optional `options` argument controls stream behavior. <ide> <ide> The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On <ide> recent OpenSSL releases, `openssl list-cipher-algorithms` will display the <ide> value. <ide> Returns a `tls.SecureContext`, as-if [`tls.createSecureContext()`][] had been <ide> called. <ide> <del>### crypto.createDecipher(algorithm, password) <add>### crypto.createDecipher(algorithm, password[, options]) <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> - `algorithm` {string} <ide> - `password` {string | Buffer | TypedArray | DataView} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns a `Decipher` object that uses the given `algorithm` and <del>`password` (key). <add>`password` (key). Optional `options` argument controls stream behavior. <ide> <ide> The implementation of `crypto.createDecipher()` derives keys using the OpenSSL <ide> function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one <ide> In line with OpenSSL's recommendation to use pbkdf2 instead of <ide> their own using [`crypto.pbkdf2()`][] and to use [`crypto.createDecipheriv()`][] <ide> to create the `Decipher` object. <ide> <del>### crypto.createDecipheriv(algorithm, key, iv) <add>### crypto.createDecipheriv(algorithm, key, iv[, options]) <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> - `algorithm` {string} <ide> - `key` {string | Buffer | TypedArray | DataView} <ide> - `iv` {string | Buffer | TypedArray | DataView} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns a `Decipher` object that uses the given `algorithm`, `key` <del>and initialization vector (`iv`). <add>and initialization vector (`iv`). Optional `options` argument controls stream <add>behavior. <ide> <ide> The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On <ide> recent OpenSSL releases, `openssl list-cipher-algorithms` will display the <ide> predefined curve specified by the `curveName` string. Use <ide> OpenSSL releases, `openssl ecparam -list_curves` will also display the name <ide> and description of each available elliptic curve. <ide> <del>### crypto.createHash(algorithm) <add>### crypto.createHash(algorithm[, options]) <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> - `algorithm` {string} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns a `Hash` object that can be used to generate hash digests <del>using the given `algorithm`. <add>using the given `algorithm`. Optional `options` argument controls stream <add>behavior. <ide> <ide> The `algorithm` is dependent on the available algorithms supported by the <ide> version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. <ide> input.on('readable', () => { <ide> }); <ide> ``` <ide> <del>### crypto.createHmac(algorithm, key) <add>### crypto.createHmac(algorithm, key[, options]) <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> - `algorithm` {string} <ide> - `key` {string | Buffer | TypedArray | DataView} <add>- `options` {Object} [`stream.transform` options][] <ide> <ide> Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. <add>Optional `options` argument controls stream behavior. <ide> <ide> The `algorithm` is dependent on the available algorithms supported by the <ide> version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. <ide> input.on('readable', () => { <ide> }); <ide> ``` <ide> <del>### crypto.createSign(algorithm) <add>### crypto.createSign(algorithm[, options]) <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> - `algorithm` {string} <add>- `options` {Object} [`stream.Writable` options][] <ide> <ide> Creates and returns a `Sign` object that uses the given `algorithm`. <ide> Use [`crypto.getHashes()`][] to obtain an array of names of the available <del>signing algorithms. <add>signing algorithms. Optional `options` argument controls the <add>`stream.Writable` behavior. <ide> <del>### crypto.createVerify(algorithm) <add>### crypto.createVerify(algorithm[, options]) <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> - `algorithm` {string} <add>- `options` {Object} [`stream.Writable` options][] <ide> <ide> Creates and returns a `Verify` object that uses the given algorithm. <ide> Use [`crypto.getHashes()`][] to obtain an array of names of the available <del>signing algorithms. <add>signing algorithms. Optional `options` argument controls the <add>`stream.Writable` behavior. <ide> <ide> ### crypto.getCiphers() <ide> <!-- YAML <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> [`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size <ide> [`cipher.final()`]: #crypto_cipher_final_outputencoding <ide> [`cipher.update()`]: #crypto_cipher_update_data_inputencoding_outputencoding <del>[`crypto.createCipher()`]: #crypto_crypto_createcipher_algorithm_password <del>[`crypto.createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv <del>[`crypto.createDecipher()`]: #crypto_crypto_createdecipher_algorithm_password <del>[`crypto.createDecipheriv()`]: #crypto_crypto_createdecipheriv_algorithm_key_iv <add>[`crypto.createCipher()`]: #crypto_crypto_createcipher_algorithm_password_options <add>[`crypto.createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv_options <add>[`crypto.createDecipher()`]: #crypto_crypto_createdecipher_algorithm_password_options <add>[`crypto.createDecipheriv()`]: #crypto_crypto_createdecipheriv_algorithm_key_iv_options <ide> [`crypto.createDiffieHellman()`]: #crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding <ide> [`crypto.createECDH()`]: #crypto_crypto_createecdh_curvename <del>[`crypto.createHash()`]: #crypto_crypto_createhash_algorithm <del>[`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key <del>[`crypto.createSign()`]: #crypto_crypto_createsign_algorithm <del>[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm <add>[`crypto.createHash()`]: #crypto_crypto_createhash_algorithm_options <add>[`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key_options <add>[`crypto.createSign()`]: #crypto_crypto_createsign_algorithm_options <add>[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm_options <ide> [`crypto.getCurves()`]: #crypto_crypto_getcurves <ide> [`crypto.getHashes()`]: #crypto_crypto_gethashes <ide> [`crypto.pbkdf2()`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> [`hmac.update()`]: #crypto_hmac_update_data_inputencoding <ide> [`sign.sign()`]: #crypto_sign_sign_privatekey_outputformat <ide> [`sign.update()`]: #crypto_sign_update_data_inputencoding <add>[`stream.transform` options]: stream.html#stream_new_stream_transform_options <add>[`stream.Writable` options]: stream.html#stream_constructor_new_stream_writable_options <ide> [`tls.createSecureContext()`]: tls.html#tls_tls_createsecurecontext_options <ide> [`verify.update()`]: #crypto_verifier_update_data_inputencoding <ide> [`verify.verify()`]: #crypto_verifier_verify_object_signature_signatureformat
1
PHP
PHP
fix json responses
291c64d0255d267a2dd62f6d760424a795a64bf5
<ide><path>src/Illuminate/Http/JsonResponse.php <add><?php namespace Illuminate\Http; <add> <add>class JsonResponse extends \Symfony\Component\HttpFoundation\JsonResponse { <add> <add> /** <add> * {@inheritdoc} <add> */ <add> public function setData($data = array()) <add> { <add> $this->data = json_encode($data); <add> <add> return $this->update(); <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/Illuminate/Support/Facades/Response.php <ide> <?php namespace Illuminate\Support\Facades; <ide> <add>use Illuminate\Http\JsonResponse; <ide> use Illuminate\Support\Contracts\ArrayableInterface; <ide> use Symfony\Component\HttpFoundation\BinaryFileResponse; <ide> <ide> public static function view($view, $data = array(), $status = 200, array $header <ide> * @param string|array $data <ide> * @param int $status <ide> * @param array $headers <del> * @return Symfony\Component\HttpFoundation\JsonResponse <add> * @return Illuminate\Http\JsonResponse <ide> */ <ide> public static function json($data = array(), $status = 200, array $headers = array()) <ide> { <ide> public static function json($data = array(), $status = 200, array $headers = arr <ide> $data = $data->toArray(); <ide> } <ide> <del> return static::make(json_encode($data), $status, $headers)->header('Content-Type', 'application/json'); <add> return new JsonResponse($data, $status, $headers); <ide> } <ide> <ide> /**
2
Text
Text
add direct link to examples
29f7adefc53cc2113bc9a2feec49daf284f3212a
<ide><path>README.md <ide> **D3.js** is a JavaScript library for manipulating documents based on data. **D3** helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. <ide> <ide> Want to learn more? [See the wiki.](/mbostock/d3/wiki) <add> <add>For examples, [see the gallery](/mbostock/d3/wiki/Gallery) and [mbostock’s bl.ocks](http://bl.ocks.org/mbostock).
1
Python
Python
add fixture for entity recognizer
eac3f700fb243a35b983628823823628c00b1dba
<ide><path>spacy/tests/conftest.py <ide> def stringstore(): <ide> return StringStore() <ide> <ide> <add>@pytest.fixture <add>def en_entityrecognizer(): <add> return English.Defaults.create_entity() <add> <add> <ide> @pytest.fixture <ide> def text_file(): <ide> return StringIO()
1