content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Go | Go | move ensureremoveall() to pkg/containerfs | 25ee00c494ff588f6347b4735f2080df9eb05262 | <ide><path>daemon/delete.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/errdefs"
<del> "github.com/docker/docker/pkg/system"
<add> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/opencontainers/selinux/go-selinux"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide> container.RWLayer = nil
<ide> }
<ide>
<del> if err := system.EnsureRemoveAll(container.Root); err != nil {
<add> if err := containerfs.EnsureRemoveAll(container.Root); err != nil {
<ide> err = errors.Wrapf(err, "unable to remove filesystem for %s", container.ID)
<ide> container.SetRemovalError(err)
<ide> return err
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> import (
<ide> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/directory"
<ide> "github.com/docker/docker/pkg/idtools"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/locker"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> }
<ide> if strings.HasSuffix(entry.Name(), "-removing") {
<ide> logger.WithField("dir", entry.Name()).Debug("Cleaning up stale layer dir")
<del> if err := system.EnsureRemoveAll(filepath.Join(p, entry.Name())); err != nil {
<add> if err := containerfs.EnsureRemoveAll(filepath.Join(p, entry.Name())); err != nil {
<ide> logger.WithField("dir", entry.Name()).WithError(err).Error("Error removing stale layer dir")
<ide> }
<ide> }
<ide> func atomicRemove(source string) error {
<ide> return errors.Wrapf(err, "error preparing atomic delete")
<ide> }
<ide>
<del> return system.EnsureRemoveAll(target)
<add> return containerfs.EnsureRemoveAll(target)
<ide> }
<ide>
<ide> // Get returns the rootfs path for the id.
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> import (
<ide> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/system"
<ide> units "github.com/docker/go-units"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> func (d *Driver) Remove(id string) error {
<ide> //
<ide> // From https://github.com/containers/storage/pull/508/commits/831e32b6bdcb530acc4c1cb9059d3c6dba14208c
<ide> }
<del> if err := system.EnsureRemoveAll(dir); err != nil {
<add> if err := containerfs.EnsureRemoveAll(dir); err != nil {
<ide> return err
<ide> }
<ide> return d.subvolRescanQuota()
<ide><path>daemon/graphdriver/fuse-overlayfs/fuseoverlayfs.go
<ide> import (
<ide> "github.com/docker/docker/pkg/directory"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/locker"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide> }
<ide>
<del> if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
<add> if err := containerfs.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
<ide> return err
<ide> }
<ide> return nil
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> import (
<ide> "github.com/docker/docker/pkg/fsutils"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/locker"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<del> return system.EnsureRemoveAll(d.dir(id))
<add> return containerfs.EnsureRemoveAll(d.dir(id))
<ide> }
<ide>
<ide> // Get creates and mounts the required file system for the given id and returns the mount path.
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> import (
<ide> "github.com/docker/docker/pkg/fsutils"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/quota"
<ide> units "github.com/docker/go-units"
<ide> "github.com/moby/locker"
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide> }
<ide>
<del> if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
<add> if err := containerfs.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
<ide> return err
<ide> }
<ide> return nil
<ide><path>daemon/graphdriver/vfs/driver.go
<ide> import (
<ide> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/quota"
<ide> units "github.com/docker/go-units"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> func (d *Driver) dir(id string) string {
<ide>
<ide> // Remove deletes the content from the directory for a given id.
<ide> func (d *Driver) Remove(id string) error {
<del> return system.EnsureRemoveAll(d.dir(id))
<add> return containerfs.EnsureRemoveAll(d.dir(id))
<ide> }
<ide>
<ide> // Get returns the directory for the given id.
<ide><path>pkg/containerfs/archiver.go
<ide> package containerfs // import "github.com/docker/docker/pkg/containerfs"
<ide>
<ide> import (
<ide> "archive/tar"
<del> "fmt"
<add> "errors"
<ide> "io"
<ide> "os"
<ide> "path/filepath"
<ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (retErr error) {
<ide> }
<ide>
<ide> if srcSt.IsDir() {
<del> return fmt.Errorf("Can't copy a directory")
<add> return errors.New("cannot copy a directory")
<ide> }
<ide>
<ide> // Clean up the trailing slash. This must be done in an operating
<add><path>pkg/containerfs/rm.go
<del><path>pkg/system/rm.go
<ide> //go:build !darwin && !windows
<ide> // +build !darwin,!windows
<ide>
<del>package system // import "github.com/docker/docker/pkg/system"
<add>package containerfs // import "github.com/docker/docker/pkg/containerfs"
<ide>
<ide> import (
<ide> "os"
<add><path>pkg/containerfs/rm_nodarwin_test.go
<del><path>pkg/system/rm_nodarwin_test.go
<ide> //go:build !darwin
<ide> // +build !darwin
<ide>
<del>package system // import "github.com/docker/docker/pkg/system"
<add>package containerfs // import "github.com/docker/docker/pkg/containerfs"
<ide>
<ide> import (
<ide> "os"
<add><path>pkg/containerfs/rm_test.go
<del><path>pkg/system/rm_test.go
<ide> //go:build !darwin && !windows
<ide> // +build !darwin,!windows
<ide>
<del>package system // import "github.com/docker/docker/pkg/system"
<add>package containerfs // import "github.com/docker/docker/pkg/containerfs"
<ide>
<ide> import (
<ide> "os"
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/moby/sys/mount"
<del> "gotest.tools/v3/skip"
<ide> )
<ide>
<ide> func TestEnsureRemoveAllWithMount(t *testing.T) {
<del> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<add> if os.Getuid() != 0 {
<add> t.Skip("skipping test that requires root")
<add> }
<ide>
<ide> dir1, err := os.MkdirTemp("", "test-ensure-removeall-with-dir1")
<ide> if err != nil {
<add><path>pkg/containerfs/rm_windows.go
<del><path>pkg/system/rm_windows.go
<del>package system
<add>package containerfs // import "github.com/docker/docker/pkg/containerfs"
<ide>
<ide> import "os"
<ide>
<ide><path>plugin/backend_linux.go
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/pkg/authorization"
<ide> "github.com/docker/docker/pkg/chrootarchive"
<add> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/system"
<ide> v2 "github.com/docker/docker/plugin/v2"
<ide> "github.com/moby/sys/mount"
<ide> digest "github.com/opencontainers/go-digest"
<ide> func atomicRemoveAll(dir string) error {
<ide> // even if `dir` doesn't exist, we can still try and remove `renamed`
<ide> case os.IsExist(err):
<ide> // Some previous remove failed, check if the origin dir exists
<del> if e := system.EnsureRemoveAll(renamed); e != nil {
<add> if e := containerfs.EnsureRemoveAll(renamed); e != nil {
<ide> return errors.Wrap(err, "rename target already exists and could not be removed")
<ide> }
<ide> if _, err := os.Stat(dir); os.IsNotExist(err) {
<ide> func atomicRemoveAll(dir string) error {
<ide> return errors.Wrap(err, "failed to rename dir for atomic removal")
<ide> }
<ide>
<del> if err := system.EnsureRemoveAll(renamed); err != nil {
<add> if err := containerfs.EnsureRemoveAll(renamed); err != nil {
<ide> os.Rename(renamed, dir)
<ide> return err
<ide> }
<ide><path>plugin/manager.go
<ide> import (
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/pkg/authorization"
<add> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/pubsub"
<del> "github.com/docker/docker/pkg/system"
<ide> v2 "github.com/docker/docker/plugin/v2"
<ide> "github.com/docker/docker/registry"
<ide> digest "github.com/opencontainers/go-digest"
<ide> func (pm *Manager) reload() error { // todo: restore
<ide> } else {
<ide> if validFullID.MatchString(strings.TrimSuffix(v.Name(), "-removing")) {
<ide> // There was likely some error while removing this plugin, let's try to remove again here
<del> if err := system.EnsureRemoveAll(v.Name()); err != nil {
<add> if err := containerfs.EnsureRemoveAll(v.Name()); err != nil {
<ide> logrus.WithError(err).WithField("id", v.Name()).Warn("error while attempting to clean up previously removed plugin")
<ide> }
<ide> }
<ide><path>plugin/manager_linux_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/system"
<ide> v2 "github.com/docker/docker/plugin/v2"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/moby/sys/mountinfo"
<ide> func TestManagerWithPluginMounts(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> defer system.EnsureRemoveAll(root)
<add> defer containerfs.EnsureRemoveAll(root)
<ide>
<ide> s := NewStore()
<ide> managerRoot := filepath.Join(root, "manager")
<ide> func TestCreateFailed(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> defer system.EnsureRemoveAll(root)
<add> defer containerfs.EnsureRemoveAll(root)
<ide>
<ide> s := NewStore()
<ide> managerRoot := filepath.Join(root, "manager")
<ide> func TestPluginAlreadyRunningOnStartup(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> defer system.EnsureRemoveAll(root)
<add> defer containerfs.EnsureRemoveAll(root)
<ide>
<ide> for _, test := range []struct {
<ide> desc string
<ide> func TestPluginAlreadyRunningOnStartup(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> defer system.EnsureRemoveAll(config.ExecRoot)
<add> defer containerfs.EnsureRemoveAll(config.ExecRoot)
<ide>
<ide> m, err := NewManager(config)
<ide> if err != nil { | 15 |
Text | Text | fix replaceme for tls min/max protocol option | 5202b70fecd3cedb752ffccdb12fc7ac9a472340 | <ide><path>doc/api/tls.md
<ide> argument.
<ide> <!-- YAML
<ide> added: v0.11.13
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/24405
<add> description: The `minVersion` and `maxVersion` can be used to restrict
<add> the allowed TLS protocol versions.
<ide> - version: v10.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/19794
<ide> description: The `ecdhCurve` cannot be set to `false` anymore due to a
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/4099
<ide> description: The `ca` option can now be a single string containing multiple
<ide> CA certificates.
<del> - version: REPLACEME
<del> pr-url: REPLACEME
<del> description: The `minVersion` and `maxVersion` can be used to restrict
<del> the allowed TLS protocol versions.
<ide> -->
<ide>
<ide> * `options` {Object} | 1 |
Python | Python | move settings into more sensible ordering | dce47a11d3d65a697ea8aa322455d626190bc1e5 | <ide><path>rest_framework/settings.py
<ide> ),
<ide> 'DEFAULT_THROTTLE_CLASSES': (
<ide> ),
<del>
<ide> 'DEFAULT_CONTENT_NEGOTIATION_CLASS':
<ide> 'rest_framework.negotiation.DefaultContentNegotiation',
<ide>
<ide> 'PAGINATE_BY': None,
<ide> 'PAGINATE_BY_PARAM': None,
<ide>
<del> # View configuration
<del> 'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name',
<del> 'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description',
<del>
<ide> # Authentication
<ide> 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
<ide> 'UNAUTHENTICATED_TOKEN': None,
<ide>
<add> # View configuration
<add> 'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name',
<add> 'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description',
<add>
<ide> # Testing
<ide> 'TEST_REQUEST_RENDERER_CLASSES': (
<ide> 'rest_framework.renderers.MultiPartRenderer', | 1 |
Text | Text | add plugin localization doc | 9141a6256f0502fb647ff157936261b3c7d7e6bc | <ide><path>docs/guides/languages.md
<ide> During a Video.js player instantiation you can force it to localize to a specifi
<ide> </video>
<ide> ```
<ide>
<add>Localization in Plugins
<add>-----------------------
<add>
<add>When you're developing a plugin, you can also introduce new localized strings. Simply wrap the string with the `localize` function:
<add>
<add>```javascript
<add>var details = '<div class="vjs-errors-details">' + this.localize('Technical details') + '</div>';
<add>```
<add>
<ide> Language Codes
<ide> --------------
<ide> The following is a list of official language codes.
<ide><path>docs/guides/plugins.md
<ide> If you've already initialized your video tag, you can activate a plugin at any t
<ide>
<ide> video.examplePlugin({ exampleOption: true });
<ide>
<del>That's it. Head on over to the Video.js wiki and add your plugin to the list so everyone else can check it out.
<add>That's it. Head on over to the [Video.js wiki](https://github.com/videojs/video.js/wiki/Plugins) and add your plugin to the list so everyone else can check it out. | 2 |
PHP | PHP | use session->get default | bd7956649a55d727ae7cdab83c76fb3bc2a3f1ad | <ide><path>src/Illuminate/Auth/Guard.php
<ide> public function id()
<ide> {
<ide> if ($this->loggedOut) return;
<ide>
<del> return $this->session->get($this->getName()) ?: $this->getRecallerId();
<add> return $this->session->get($this->getName(), $this->getRecallerId());
<ide> }
<ide>
<ide> /** | 1 |
Java | Java | add api to reset cxxmodulewrapper's module pointer | 17020ff9af5648aeb5b45314e4fca7cb2c9352b1 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/cxxbridge/CxxModuleWrapperBase.java
<ide>
<ide> package com.facebook.react.cxxbridge;
<ide>
<del>import java.util.Map;
<ide>
<ide> import com.facebook.jni.HybridData;
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<ide> public void onCatalystInstanceDestroy() {
<ide> protected CxxModuleWrapperBase(HybridData hd) {
<ide> mHybridData = hd;
<ide> }
<add>
<add> // Replace the current native module held by this wrapper by a new instance
<add> protected void resetModule(HybridData hd) {
<add> if (hd != mHybridData) {
<add> mHybridData.resetNative();
<add> mHybridData = hd;
<add> }
<add> }
<ide> } | 1 |
Javascript | Javascript | remove flash until author required bug is fixed | 1906f5d57c4a1f7f6a870f974051f3e35cee6616 | <ide><path>server/utils/middleware.js
<ide> export function ifNoUser401(req, res, next) {
<ide> }
<ide>
<ide> export function flashIfNotVerified(req, res, next) {
<del> const user = req.user;
<del> if (!user) {
<del> return next();
<del> }
<del> const email = req.user.email;
<del> const emailVerified = req.user.emailVerified;
<del> if (!email || !emailVerified) {
<del> req.flash('info', {
<del> msg: 'Please verify your email address ' +
<del> '<a href="/update-email">here</a>.'
<del> });
<del> }
<add> return next();
<add> /*
<add> // disabled until authorized required bug is fixed
<add> const user = req.user;
<add> if (!user) {
<ide> return next();
<add> }
<add> const email = req.user.email;
<add> const emailVerified = req.user.emailVerified;
<add> if (!email || !emailVerified) {
<add> req.flash('info', {
<add> msg: 'Please verify your email address ' +
<add> '<a href="/update-email">here</a>.'
<add> });
<add> }
<add> */
<ide> } | 1 |
PHP | PHP | fix problem with default values and prompts | da7aefe36cf3a82a5357ef136c600e8110f34019 | <ide><path>src/Console/ConsoleOptionParser.php
<ide> public function parse(array $argv, ?ConsoleIo $io = null): array
<ide> $params[$name] = false;
<ide> }
<ide> $prompt = $option->prompt();
<del> if ($useDefault && $prompt) {
<add> if (!isset($params[$name]) && $prompt) {
<ide> if (!$io) {
<ide> throw new ConsoleException(
<ide> 'Cannot use interactive option prompts without a ConsoleIo instance. ' .
<ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> public function testAddOptionWithPrompt(): void
<ide> $this->assertEquals($expected, $messages[0]);
<ide> }
<ide>
<add> /**
<add> * test adding an option and default values
<add> */
<add> public function testAddOptionWithPromptAndDefault(): void
<add> {
<add> $parser = new ConsoleOptionParser('test', false);
<add> $parser->addOption('color', [
<add> 'prompt' => 'What is your favorite?',
<add> 'default' => 'blue'
<add> ]);
<add> $out = new ConsoleOutput();
<add> $io = new ConsoleIo($out, new ConsoleOutput(), new ConsoleInput([]));
<add>
<add> $result = $parser->parse([], $io);
<add> $this->assertEquals(['color' => 'blue', 'help' => false], $result[0]);
<add> $this->assertCount(0, $out->messages());
<add> }
<add>
<ide> /**
<ide> * test adding an option and prompting with cli data
<ide> */ | 2 |
Python | Python | add greedy decoding and sampling | 07bc8efbc30f88e25d78b66811d670584a1bb97b | <ide><path>examples/run_generation.py
<ide>
<ide> import argparse
<ide> import logging
<del>from tqdm import trange
<ide>
<ide> import torch
<del>import torch.nn.functional as F
<ide> import numpy as np
<ide>
<del>from transformers import GPT2Config, OpenAIGPTConfig, XLNetConfig, TransfoXLConfig, XLMConfig, CTRLConfig
<del>
<ide> from transformers import GPT2LMHeadModel, GPT2Tokenizer
<ide> from transformers import OpenAIGPTLMHeadModel, OpenAIGPTTokenizer
<ide> from transformers import XLNetLMHeadModel, XLNetTokenizer
<ide> from transformers import XLMWithLMHeadModel, XLMTokenizer
<ide>
<ide>
<del>logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
<del> datefmt = '%m/%d/%Y %H:%M:%S',
<del> level = logging.INFO)
<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,
<add>)
<ide> logger = logging.getLogger(__name__)
<ide>
<ide> MAX_LENGTH = int(10000) # Hardcoded max length to avoid infinite loop
<ide>
<del>ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (GPT2Config, OpenAIGPTConfig, XLNetConfig, TransfoXLConfig, XLMConfig, CTRLConfig)), ())
<del>
<ide> MODEL_CLASSES = {
<del> 'gpt2': (GPT2LMHeadModel, GPT2Tokenizer),
<del> 'ctrl': (CTRLLMHeadModel, CTRLTokenizer),
<del> 'openai-gpt': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
<del> 'xlnet': (XLNetLMHeadModel, XLNetTokenizer),
<del> 'transfo-xl': (TransfoXLLMHeadModel, TransfoXLTokenizer),
<del> 'xlm': (XLMWithLMHeadModel, XLMTokenizer),
<add> "gpt2": (GPT2LMHeadModel, GPT2Tokenizer),
<add> "ctrl": (CTRLLMHeadModel, CTRLTokenizer),
<add> "openai-gpt": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
<add> "xlnet": (XLNetLMHeadModel, XLNetTokenizer),
<add> "transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
<add> "xlm": (XLMWithLMHeadModel, XLMTokenizer),
<ide> }
<ide>
<ide> # Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
<ide> def set_seed(args):
<ide> if args.n_gpu > 0:
<ide> torch.cuda.manual_seed_all(args.seed)
<ide>
<add>#
<add># Functions to prepare models' input
<add>#
<add>
<add>
<add>def prepare_ctrl_input(args, _, tokenizer, prompt_text):
<add> if args.temperature > 0.7:
<add> logger.info(
<add> "CTRL typically works better with lower temperatures (and lower top_k)."
<add> )
<add>
<add> encoded_prompt = tokenizer.encode(prompt_text, add_special_tokens=False)
<add> if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()):
<add> logger.info(
<add> "WARNING! You are not starting your generation from a control code so you won't get good results"
<add> )
<add> return prompt_text, {}
<add>
<add>
<add>def prepare_xlm_input(args, model, tokenizer, prompt_text):
<add> kwargs = {"language": None, "mask_token": None}
<add>
<add> # Set the language
<add> use_lang_emb = hasattr(model.config, "use_lang_emb") and model.config.use_lang_emb
<add> if hasattr(model.config, "lang2id") and use_lang_emb:
<add> available_languages = model.config.lang2id.keys()
<add> if args.xlm_language in available_languages:
<add> language = args.xlm_language
<add> else:
<add> language = None
<add> while language not in available_languages:
<add> language = input(
<add> "Using XLM. Select language in "
<add> + str(list(available_languages))
<add> + " >>> "
<add> )
<add> kwargs["language"] = tokenizer.lang2id[language]
<add>
<add> # XLM masked-language modeling (MLM) models need masked token
<add> is_xlm_mlm = "mlm" in args.model_name_or_path
<add> if is_xlm_mlm:
<add> kwargs["mask_token"] = tokenizer.mask_token_id
<add>
<add> return prompt_text, kwargs
<add>
<ide>
<del>def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
<del> """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
<del> Args:
<del> logits: logits distribution shape (batch size x vocabulary size)
<del> top_k > 0: keep only top k tokens with highest probability (top-k filtering).
<del> top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
<del> Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
<del> From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
<del> """
<del> top_k = min(top_k, logits.size(-1)) # Safety check
<del> if top_k > 0:
<del> # Remove all tokens with a probability less than the last token of the top-k
<del> indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
<del> logits[indices_to_remove] = filter_value
<del>
<del> if top_p > 0.0:
<del> sorted_logits, sorted_indices = torch.sort(logits, descending=True)
<del> cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
<del>
<del> # Remove tokens with cumulative probability above the threshold
<del> sorted_indices_to_remove = cumulative_probs > top_p
<del> # Shift the indices to the right to keep also the first token above the threshold
<del> sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
<del> sorted_indices_to_remove[..., 0] = 0
<del>
<del> # scatter sorted tensors to original indexing
<del> indices_to_remove = sorted_indices_to_remove.scatter(dim=1, index=sorted_indices, src=sorted_indices_to_remove)
<del> logits[indices_to_remove] = filter_value
<del> return logits
<del>
<del>
<del>def sample_sequence(model, length, context, num_samples=1, temperature=1, top_k=0, top_p=0.0, repetition_penalty=1.0,
<del> is_xlnet=False, is_xlm_mlm=False, xlm_mask_token=None, xlm_lang=None, device='cpu'):
<del> context = torch.tensor(context, dtype=torch.long, device=device)
<del> context = context.unsqueeze(0).repeat(num_samples, 1)
<del> generated = context
<del> with torch.no_grad():
<del> for _ in trange(length):
<del>
<del> inputs = {'input_ids': generated}
<del> if is_xlnet:
<del> # XLNet is a direct (predict same token, not next token) and bi-directional model by default
<del> # => need one additional dummy token in the input (will be masked), attention mask and target mapping (see model docstring)
<del> input_ids = torch.cat((generated, torch.zeros((1, 1), dtype=torch.long, device=device)), dim=1)
<del> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float, device=device)
<del> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
<del> target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float, device=device)
<del> target_mapping[0, 0, -1] = 1.0 # predict last token
<del> inputs = {'input_ids': input_ids, 'perm_mask': perm_mask, 'target_mapping': target_mapping}
<del>
<del> if is_xlm_mlm and xlm_mask_token:
<del> # XLM MLM models are direct models (predict same token, not next token)
<del> # => need one additional dummy token in the input (will be masked and guessed)
<del> input_ids = torch.cat((generated, torch.full((1, 1), xlm_mask_token, dtype=torch.long, device=device)), dim=1)
<del> inputs = {'input_ids': input_ids}
<del>
<del> if xlm_lang is not None:
<del> inputs["langs"] = torch.tensor([xlm_lang] * inputs["input_ids"].shape[1], device=device).view(1, -1)
<del>
<del> outputs = model(**inputs) # Note: we could also use 'past' with GPT-2/Transfo-XL/XLNet/CTRL (cached hidden-states)
<del> next_token_logits = outputs[0][:, -1, :] / (temperature if temperature > 0 else 1.)
<del>
<del> # repetition penalty from CTRL (https://arxiv.org/abs/1909.05858)
<del> for i in range(num_samples):
<del> for _ in set(generated[i].tolist()):
<del> next_token_logits[i, _] /= repetition_penalty
<del>
<del> filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)
<del> if temperature == 0: # greedy sampling:
<del> next_token = torch.argmax(filtered_logits, dim=-1).unsqueeze(-1)
<del> else:
<del> next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
<del> generated = torch.cat((generated, next_token), dim=1)
<del> return generated
<add>def prepare_xlnet_input(args, _, tokenizer, prompt_text):
<add> prompt_text = (args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text
<add> return prompt_text, {}
<add>
<add>
<add>def prepare_transfoxl_input(args, _, tokenizer, prompt_text):
<add> prompt_text = (args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text
<add> return prompt_text, {}
<add>
<add>
<add>PREPROCESSING_FUNCTIONS = {
<add> "ctrl": prepare_ctrl_input,
<add> "xlm": prepare_xlm_input,
<add> "xlnet": prepare_xlnet_input,
<add> "transfo-xl": prepare_transfoxl_input,
<add>}
<add>
<add>
<add>def adjust_length_to_model(length, max_sequence_length):
<add> if length < 0 and max_sequence_length > 0:
<add> length = max_sequence_length
<add> elif 0 < max_sequence_length < length:
<add> length = max_sequence_length # No generation bigger than model size
<add> elif length < 0:
<add> length = MAX_LENGTH # avoid infinite loop
<add> return length
<ide>
<ide>
<ide> def main():
<ide> parser = argparse.ArgumentParser()
<ide> parser.add_argument("--model_type", default=None, type=str, required=True,
<ide> help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
<ide> parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
<del> help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS))
<add> help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
<add>
<ide> parser.add_argument("--prompt", type=str, default="")
<del> parser.add_argument("--padding_text", type=str, default="")
<del> parser.add_argument("--xlm_lang", type=str, default="", help="Optional language when used with the XLM model.")
<ide> parser.add_argument("--length", type=int, default=20)
<del> parser.add_argument("--num_samples", type=int, default=1)
<del> parser.add_argument("--temperature", type=float, default=1.0,
<del> help="temperature of 0 implies greedy sampling")
<del> parser.add_argument("--repetition_penalty", type=float, default=1.0,
<del> help="primarily useful for CTRL model; in that case, use 1.2")
<del> parser.add_argument("--top_k", type=int, default=0)
<del> parser.add_argument("--top_p", type=float, default=0.9)
<del> parser.add_argument("--no_cuda", action='store_true',
<del> help="Avoid using CUDA when available")
<del> parser.add_argument('--seed', type=int, default=42,
<del> help="random seed for initialization")
<del> parser.add_argument('--stop_token', type=str, default=None,
<del> help="Token at which text generation is stopped")
<add> parser.add_argument("--stop_token", type=str, default=None, help="Token at which text generation is stopped")
<add>
<add> parser.add_argument("--temperature", type=float, default=1.0, help="temperature of 0 implies greedy sampling")
<add> parser.add_argument("--repetition_penalty", type=float, default=1.0, help="primarily useful for CTRL model; in that case, use 1.2")
<add> parser.add_argument("--k", type=int, default=0)
<add> parser.add_argument("--p", type=float, default=0.9)
<add>
<add> parser.add_argument("--padding_text", type=str, default="", help="Padding text for Transfo-XL and XLNet.")
<add> parser.add_argument("--xlm_language", type=str, default="", help="Optional language when used with the XLM model.")
<add>
<add> parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
<add> parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
<ide> args = parser.parse_args()
<ide>
<del> args.device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
<add> args.device = torch.device(
<add> "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"
<add> )
<ide> args.n_gpu = torch.cuda.device_count()
<ide>
<ide> set_seed(args)
<ide>
<del> args.model_type = args.model_type.lower()
<del> model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
<add> # Initialize the model and tokenizer
<add> try:
<add> args.model_type = args.model_type.lower()
<add> model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
<add> except KeyError as ke:
<add> raise ke(
<add> "the model {} you specified is not supported. You are welcome to add it and open a PR :)"
<add> )
<add>
<ide> tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)
<ide> model = model_class.from_pretrained(args.model_name_or_path)
<ide> model.to(args.device)
<ide> model.eval()
<ide>
<del> if args.length < 0 and model.config.max_position_embeddings > 0:
<del> args.length = model.config.max_position_embeddings
<del> elif 0 < model.config.max_position_embeddings < args.length:
<del> args.length = model.config.max_position_embeddings # No generation bigger than model size
<del> elif args.length < 0:
<del> args.length = MAX_LENGTH # avoid infinite loop
<del>
<add> args.length = adjust_length_to_model(
<add> args.length, max_sequence_length=model.config.max_position_embeddings
<add> )
<ide> logger.info(args)
<del> if args.model_type in ["ctrl"]:
<del> if args.temperature > 0.7:
<del> logger.info('CTRL typically works better with lower temperatures (and lower top_k).')
<del>
<del> while True:
<del> xlm_lang = None
<del> # XLM Language usage detailed in the issues #1414
<del> if args.model_type in ["xlm"] and hasattr(tokenizer, 'lang2id') and hasattr(model.config, 'use_lang_emb') \
<del> and model.config.use_lang_emb:
<del> if args.xlm_lang:
<del> language = args.xlm_lang
<del> else:
<del> language = None
<del> while language not in tokenizer.lang2id.keys():
<del> language = input("Using XLM. Select language in " + str(list(tokenizer.lang2id.keys())) + " >>> ")
<del> xlm_lang = tokenizer.lang2id[language]
<del>
<del> # XLM masked-language modeling (MLM) models need masked token (see details in sample_sequence)
<del> is_xlm_mlm = args.model_type in ["xlm"] and 'mlm' in args.model_name_or_path
<del> if is_xlm_mlm:
<del> xlm_mask_token = tokenizer.mask_token_id
<del> else:
<del> xlm_mask_token = None
<del>
<del> raw_text = args.prompt if args.prompt else input("Model prompt >>> ")
<del> if args.model_type in ["transfo-xl", "xlnet"]:
<del> # Models with memory likes to have a long prompt for short inputs.
<del> raw_text = (args.padding_text if args.padding_text else PADDING_TEXT) + raw_text
<del> context_tokens = tokenizer.encode(raw_text, add_special_tokens=False)
<del> if args.model_type == "ctrl":
<del> if not any(context_tokens[0] == x for x in tokenizer.control_codes.values()):
<del> logger.info("WARNING! You are not starting your generation from a control code so you won't get good results")
<del> out = sample_sequence(
<del> model=model,
<del> context=context_tokens,
<del> num_samples=args.num_samples,
<del> length=args.length,
<del> temperature=args.temperature,
<del> top_k=args.top_k,
<del> top_p=args.top_p,
<del> repetition_penalty=args.repetition_penalty,
<del> is_xlnet=bool(args.model_type == "xlnet"),
<del> is_xlm_mlm=is_xlm_mlm,
<del> xlm_mask_token=xlm_mask_token,
<del> xlm_lang=xlm_lang,
<del> device=args.device,
<del> )
<del> out = out[:, len(context_tokens):].tolist()
<del> for o in out:
<del> text = tokenizer.decode(o, clean_up_tokenization_spaces=True)
<del> text = text[: text.find(args.stop_token) if args.stop_token else None]
<ide>
<del> print(text)
<add> prompt_text = args.prompt if args.prompt else input("Model prompt >>> ")
<add>
<add> # Different models need different input formatting and/or extra arguments
<add> requires_preprocessing = args.model_type in PREPROCESSING_FUNCTIONS.keys()
<add> model_kwargs = {}
<add> if requires_preprocessing:
<add> prepare_input = PREPROCESSING_FUNCTIONS.get(args.model_type)
<add> prompt_text, model_kwargs = prepare_input(args, model, tokenizer, prompt_text)
<add> encoded_prompt = torch.tensor(tokenizer.encode(prompt_text, add_special_tokens=False)).unsqueeze(0)
<add>
<add> output_sequences = model.decode(
<add> prompt_ids=encoded_prompt,
<add> length=args.length,
<add> temperature=args.temperature,
<add> k=args.k,
<add> p=args.p,
<add> repetition_penalty=args.repetition_penalty,
<add> device=args.device,
<add> **model_kwargs,
<add> )
<add>
<add> generated_sequence = output_sequences.tolist()[
<add> encoded_prompt.size(1) :
<add> ] # adapted to case where num_samples > 1
<add> text = tokenizer.decode(generated_sequence, clean_up_tokenization_spaces=True)
<add> text = text[: text.find(args.stop_token) if args.stop_token else None]
<add>
<add> print(text)
<ide>
<del> if args.prompt:
<del> break
<ide> return text
<ide>
<ide>
<del>if __name__ == '__main__':
<add>if __name__ == "__main__":
<ide> main()
<ide><path>transformers/modeling_encoder_decoder.py
<ide>
<ide> import logging
<ide> import os
<add>import warnings
<ide>
<ide> import torch
<ide> from torch import nn
<add>from tqdm import trange
<ide>
<ide> from .modeling_auto import AutoModel, AutoModelWithLMHead
<add>from .modeling_utils import Sampler
<ide>
<ide> logger = logging.getLogger(__name__)
<ide>
<ide> def from_pretrained(
<ide> kwargs_common = {
<ide> argument: value
<ide> for argument, value in kwargs.items()
<del> if not argument.startswith("encoder_")
<del> and not argument.startswith("decoder_")
<add> if not argument.startswith("encoder_") and not argument.startswith("decoder_")
<ide> }
<ide> kwargs_decoder = kwargs_common.copy()
<ide> kwargs_encoder = kwargs_common.copy()
<ide> def forward(self, encoder_input_ids, decoder_input_ids, **kwargs):
<ide> Indices of decoder input sequence tokens in the vocabulary.
<ide> kwargs: (`optional`) Remaining dictionary of keyword arguments.
<ide> """
<del> # keyword arguments come in 3 flavors: encoder-specific (prefixed by
<del> # `encoder_`), decoder-specific (prefixed by `decoder_`) and those
<del> # that apply to the model as whole.
<del> # We let the specific kwargs override the common ones in case of conflict.
<add> kwargs_encoder, kwargs_decoder = self.prepare_model_kwargs(**kwargs)
<add>
<add> # Encode if needed (training, first prediction pass)
<add> encoder_hidden_states = kwargs_encoder.pop("hidden_states", None)
<add> if encoder_hidden_states is None:
<add> encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder)
<add> encoder_hidden_states = encoder_outputs[0]
<add> else:
<add> encoder_outputs = ()
<add>
<add> kwargs_decoder["encoder_hidden_states"] = encoder_hidden_states
<add> decoder_outputs = self.decoder(decoder_input_ids, encoder_hidden_states, **kwargs_decoder)
<add>
<add> return decoder_outputs + encoder_outputs
<add>
<add> def decode(
<add> self,
<add> encoder_input_ids,
<add> decoder_prompt_ids=None,
<add> device=torch.device("cpu"),
<add> length=10,
<add> do_sample=False,
<add> temperature=1.0,
<add> k=9,
<add> p=0.,
<add> repetition_penalty=1.,
<add> **kwargs
<add> ):
<add> """ Generic sequence generator for encoder-decoder models.
<add>
<add> For encoder-decoders the generation consists in:
<add> - Performing a forward pass through the encoder once;
<add> - Pass the encoder's hidden states to a decoding mechanism that
<add> repeatedly calls the decoder to generate sequences.
<add>
<add> The method currently supports greedy decoding and sampling. See the
<add> documentation of the `Sampler` class for more information about the
<add> parameters related to sampling.
<add>
<add> Params:
<add> **encoder_input_ids**: `torch.LongTensor` of shape (1, sequence_length)
<add> The sequence to encode.
<add> **decoder_prompt_ids**: (`optional`) `torch.LongTensor` of shape (1, sequence_length)
<add> The sequence used as a prompt for the generation. If `None` the method initializes
<add> it as an empty `torch.LongTensor` of shape (1,)
<add> **device**: (`optional`) `torch.device`
<add> The device on which the prompt_ids will be initialized if not provided.
<add> **length**: (`optional`) int
<add> The length of the sequence to be generated.
<add> **do_sample**: (`optional`) bool
<add> If set to `False` we use greedy decoding; otherwise sampling.
<add> **temperature**: (`optional`) float
<add> The value used to module the next token probabilities.
<add> **k**: (`optional`) int
<add> The parameter used for k-filtering.
<add> **p**: (`optional`) float
<add> The parameter for nucleus sampling. Must be between 0 and 1.
<add> **repetition_penalty**: (`optional`) float
<add> The parameter for repetition penalty.
<add> """
<add> if decoder_prompt_ids is None:
<add> decoder_prompt_ids = torch.tensor([[]], dtype=torch.long, device=device)
<add>
<add> # When the model does not have a LM head `get_output_embeddings`
<add> # returns `None`. We use this mechanism to determine whether we
<add> # should proceed with decoding or not.
<add> if self.decoder.get_output_embeddings() is None:
<add> raise AttributeError("You tried do generated sequences with a decoder that does not have a LM Head.")
<add>
<add> # The followings checks that the decoder is on the same device as the one
<add> # that is specified. It only works for models that fit on one GPU.
<add> decoder_device = next(self.decoder.parameters()).device
<add> if decoder_device != decoder_prompt_ids.device:
<add> warnings.warn(
<add> "The decoder is not on the same device as the prompt. Expected {}, got {}.".format(
<add> decoder_prompt_ids.device, decoder_device
<add> )
<add> )
<add>
<add> kwargs_encoder, kwargs_decoder = self.prepare_model_kwargs(**kwargs)
<add> with torch.no_grad():
<add> encoder_outputs = self.encoder(encoder_input_ids, **kwargs)
<add> encoder_hidden_states = encoder_outputs[0]
<add> kwargs_decoder["encoder_hidden_states"] = encoder_hidden_states
<add>
<add> sampler_config = {
<add> "k": k,
<add> "p": p,
<add> "do_sample": do_sample,
<add> "temperature": temperature,
<add> "repetition_penalty": repetition_penalty,
<add> }
<add> return self._greedy_decode_or_sample(
<add> decoder_prompt_ids, length, sampler_config, **kwargs_decoder
<add> )
<add>
<add> def _greedy_decode_or_sample(self, prompt_ids, length, sampler_config, **kwargs_decoder):
<add> sampler = Sampler(**sampler_config)
<add> with torch.no_grad():
<add> generated_sequence = prompt_ids
<add> for _ in trange(length):
<add> arguments = self.decoder._prepare_inputs_for_decoding(generated_sequence, **kwargs_decoder)
<add> outputs = self.decoder(**arguments)
<add> next_tokens_logits = outputs[0][:, -1, :]
<add> next_tokens = sampler.get_one_token(next_tokens_logits, generated_sequence)
<add> generated_sequence = torch.cat((generated_sequence, next_tokens), dim=1)
<add>
<add> return generated_sequence.squeeze(0)
<add>
<add> @staticmethod
<add> def prepare_model_kwargs(**kwargs):
<add> """ Prepare the encoder and decoder's keyword arguments.
<add>
<add> Keyword arguments come in 3 flavors:
<add> - encoder-specific (prefixed by `encoder_`)
<add> - decoder-specific (prefixed by `decoder_`)
<add> - those that apply to the model as whole.
<add>
<add> We let the specific kwargs override the common ones in case of
<add> conflict.
<add> """
<ide> kwargs_common = {
<ide> argument: value
<ide> for argument, value in kwargs.items()
<del> if not argument.startswith("encoder_")
<del> and not argument.startswith("decoder_")
<add> if not argument.startswith("encoder_") and not argument.startswith("decoder_")
<ide> }
<del> kwargs_decoder = kwargs_common.copy()
<del> kwargs_encoder = kwargs_common.copy()
<del> kwargs_encoder.update(
<add> decoder_kwargs = kwargs_common.copy()
<add> encoder_kwargs = kwargs_common.copy()
<add> encoder_kwargs.update(
<ide> {
<ide> argument[len("encoder_") :]: value
<ide> for argument, value in kwargs.items()
<ide> if argument.startswith("encoder_")
<ide> }
<ide> )
<del> kwargs_decoder.update(
<add> decoder_kwargs.update(
<ide> {
<ide> argument[len("decoder_") :]: value
<ide> for argument, value in kwargs.items()
<ide> if argument.startswith("decoder_")
<ide> }
<ide> )
<add> decoder_kwargs["encoder_attention_mask"] = encoder_kwargs.get("attention_mask", None)
<ide>
<del> # Encode if needed (training, first prediction pass)
<del> encoder_hidden_states = kwargs_encoder.pop("hidden_states", None)
<del> if encoder_hidden_states is None:
<del> encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder)
<del> encoder_hidden_states = encoder_outputs[
<del> 0
<del> ] # output the last layer hidden state
<del> else:
<del> encoder_outputs = ()
<del>
<del> # Decode
<del> kwargs_decoder["encoder_hidden_states"] = encoder_hidden_states
<del> kwargs_decoder["encoder_attention_mask"] = kwargs_encoder.get(
<del> "attention_mask", None
<del> )
<del> decoder_outputs = self.decoder(decoder_input_ids, **kwargs_decoder)
<del>
<del> return decoder_outputs + encoder_outputs
<add> return encoder_kwargs, decoder_kwargs
<ide>
<ide>
<ide> class Model2Model(PreTrainedEncoderDecoder):
<ide><path>transformers/modeling_transfo_xl.py
<ide>
<ide> from .modeling_utils import PreTrainedModel, Conv1D, prune_conv1d_layer, SequenceSummary
<ide> from .configuration_transfo_xl import TransfoXLConfig
<del>from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax, sample_logits
<add>from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax, sample_logits, LogUniformSampler
<ide> from .file_utils import add_start_docstrings
<ide>
<ide> logger = logging.getLogger(__name__)
<ide> def forward(self, input_ids=None, mems=None, head_mask=None, inputs_embeds=None,
<ide> outputs = [softmax_output, None] + outputs
<ide>
<ide> return outputs # (loss), logits or None if labels is not None (speed up adaptive softmax), new_mems, (all hidden states), (all attentions)
<add>
<add> def get_output_embeddings(self):
<add> """ Double-check if you are using adaptive softmax.
<add> """
<add> if self.sample_softmax > 0:
<add> return self.out_layer
<add> else:
<add> return self.crit.out_layers[-1]
<ide><path>transformers/modeling_utils.py
<ide> import logging
<ide> import os
<ide> from io import open
<add>import warnings
<ide>
<ide> import six
<ide> import torch
<ide> from torch import nn
<ide> from torch.nn import CrossEntropyLoss
<ide> from torch.nn import functional as F
<add>from tqdm import trange
<ide>
<ide> from .configuration_utils import PretrainedConfig
<ide> from .file_utils import cached_path, WEIGHTS_NAME, TF_WEIGHTS_NAME, TF2_WEIGHTS_NAME
<ide> def __init__(self, config, *inputs, **kwargs):
<ide> def base_model(self):
<ide> return getattr(self, self.base_model_prefix, self)
<ide>
<add> def decode(self,
<add> prompt_ids=None,
<add> device=torch.device('cpu'),
<add> length=10,
<add> do_sample=False,
<add> temperature=1.,
<add> k=9,
<add> p=0,
<add> repetition_penalty=1,
<add> **model_kwargs):
<add> """ Generic sequence generator for single-stack models with a LM head.
<add>
<add> The method currently supports greedy decoding and sampling. See the
<add> documentation of the `Sampler` class for more information about the
<add> parameters related to sampling.
<add>
<add> Params:
<add> **encoder_input_ids**: `torch.LongTensor` of shape (1, sequence_length)
<add> The sequence to encode.
<add> **decoder_prompt_ids**: (`optional`) `torch.LongTensor` of shape (1, sequence_length)
<add> The sequence used as a prompt for the generation. If `None` the method initializes
<add> it as an empty `torch.LongTensor` of shape (1,)
<add> **device**: (`optional`) `torch.device`
<add> The device on which the prompt_ids will be initialized if not provided.
<add> **length**: (`optional`) int
<add> The length of the sequence to be generated.
<add> **do_sample**: (`optional`) bool
<add> If set to `False` we use greedy decoding; otherwise sampling.
<add> **temperature**: (`optional`) float
<add> The value used to module the next token probabilities.
<add> **k**: (`optional`) int
<add> The parameter used for k-filtering.
<add> **p**: (`optional`) float
<add> The parameter for nucleus sampling. Must be between 0 and 1.
<add> **repetition_penalty**: (`optional`) float
<add> The parameter for repetition penalty.
<add> """
<add>
<add> if prompt_ids is None:
<add> prompt_ids = torch.tensor([[]], dtype=torch.long, device=device)
<add>
<add> # When the model does not have a LM head `get_output_embeddings`
<add> # returns `None`. We use this mechanism to determine whether we
<add> # should proceed with decoding or not.
<add> if self.get_output_embeddings() is None:
<add> raise AttributeError("You tried do generated sequences with a model that does not have a LM Head.")
<add>
<add> # The followings checks that the model is on the same device as the one
<add> # that is specified. It only works for models that fit on one GPU.
<add> model_device = next(self.parameters()).device
<add> if model_device != prompt_ids.device:
<add> warnings.warn(
<add> "The model is not on the same device as the prompts. Expected {}, got {}.".format(
<add> prompt_ids.device, model_device
<add> )
<add> )
<add>
<add> sampler_config = {
<add> "k": k,
<add> "p": p,
<add> "do_sample": do_sample,
<add> "temperature": temperature,
<add> "repetition_penalty": repetition_penalty,
<add> }
<add> return self._greedy_decode_or_sample(prompt_ids, length, sampler_config, **model_kwargs)
<add>
<add> def _greedy_decode_or_sample(self, prompt_ids, length, sampler_config, **model_kwargs):
<add> """ Generate text using greedy decoding or by sampling tokens."""
<add> sampler = Sampler(**sampler_config)
<add> generated_sequence = prompt_ids
<add> with torch.no_grad():
<add> for _ in trange(length):
<add> arguments = self._prepare_inputs_for_decoding(generated_sequence, **model_kwargs)
<add> outputs = self(**arguments)
<add> next_tokens_logits = outputs[0][:, -1, :]
<add> next_tokens = sampler.get_one_token(
<add> next_tokens_logits, generated_sequence
<add> )
<add> generated_sequence = torch.cat((generated_sequence, next_tokens), dim=1)
<add>
<add> return generated_sequence.squeeze(0)
<add>
<add> def _prepare_inputs_for_decoding(self, input_ids, **kwargs):
<add> arguments = {"input_ids": input_ids}
<add> arguments.update(kwargs)
<add> return arguments
<add>
<ide> def get_input_embeddings(self):
<ide> """ Get model's input embeddings
<ide> """
<ide> def prune_layer(layer, index, dim=None):
<ide> return prune_conv1d_layer(layer, index, dim=1 if dim is None else dim)
<ide> else:
<ide> raise ValueError("Can't prune layer of class {}".format(layer.__class__))
<add>
<add>
<add>class Sampler(object):
<add> r""" Sampler is used to generate sequences of ids from logit inputs.
<add>
<add> Greedy decoding, which consists in chosing the most probable token at each
<add> step, is the default behaviour. Sampling with varying temperature, top_k
<add> and nucleus filtering is also implemented.
<add>
<add> Attributes:
<add> **device**: ``torch.device``
<add> Device on which the computations will be run.
<add> **do_sample**: bool
<add> Whether to sample or do greedy decoding.
<add> **k**: int between 0 and vocab_size
<add> Parameter for the top-k filtering
<add> **p**: float between 0 and 1
<add> Parameter for the nucleus filtering
<add> **temperature**: strictly positive float
<add> Parameter used to modulate the distribution over ids. Low temperatures
<add> put more emphasis on highly probably token while high temperatures tend
<add> to smooth the probability distribution.
<add> **repetition_penalty**: strictly postitive float
<add> The penalty applied to repeating ids
<add> """
<add>
<add> def __init__(
<add> self, do_sample=False, k=9, p=0.0, temperature=1.0, repetition_penalty=1.0
<add> ):
<add> self.k = k
<add> self.p = p
<add> self.do_sample = do_sample
<add> self.temperature = temperature
<add> self.repetition_penalty = repetition_penalty
<add>
<add> self.do_apply_repetition_penalty = True if repetition_penalty > 1 else False
<add>
<add> if self.p > 1:
<add> warnings.warn(
<add> """You are trying to apply nucleus filtering with a value of p greater than 1 ({}).
<add> However p is a probability and its value must lie between 0 and 1. In effect, no filtering
<add> will be applied. If this is not the behavior you expect, change the value of p.""".format(
<add> self.p
<add> )
<add> )
<add>
<add> def get_one_token(self, next_token_logits, past_sequence):
<add> logits = self.apply_repetition_penalty(next_token_logits, past_sequence)
<add> if self.do_sample:
<add> logits = self.apply_temperature(logits)
<add> logits = self.apply_top_k_filter(logits)
<add> logits = self.apply_nucleus_filter(logits)
<add> return torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
<add> return torch.argmax(logits, dim=-1).unsqueeze(-1)
<add>
<add> def apply_repetition_penalty(self, logits, past_sequence):
<add> """ Apply a penalty to tokens that appear more than once in the
<add> generated sequence.
<add>
<add> .. Keskar, Nitish Shirish, et al. "Ctrl: A conditional transformer
<add> language model for controllable generation." arXiv preprint
<add> arXiv:1909.05858 (2019).
<add> """
<add> if self.do_apply_repetition_penalty:
<add> generated_token_idx = set(past_sequence[0].tolist())
<add> for token_idx in generated_token_idx:
<add> logits[0, token_idx] /= self.repetition_penalty
<add> return logits
<add>
<add> def apply_temperature(self, logits):
<add> """ Shape the tokens' distribution through temperature. The higher the value
<add> of the temperature, the more skewed towards high probability events the
<add> distribution is.
<add>
<add> .. Goodfellow, Ian, Yoshua Bengio, and Aaron Courville. Deep learning.
<add> MIT press, 2016.
<add> """
<add> # when dividing a float by 0, torch returns inf which in turns breaks the
<add> # multinomial with an error message that is not very helpful. It is better
<add> # for the user to break the execution and explain why.
<add> if self.temperature == 0:
<add> raise ZeroDivisionError(
<add> """You are trying to sample with a temperature equal to 0.
<add> If you wanted to do greedy sampling, set instead `do_sample` to False.
<add> Otherwise set the temperature to a value different from 0."""
<add> )
<add> return logits / self.temperature
<add>
<add> def apply_top_k_filter(self, logits):
<add> """ Use the probability distribution of the tokens to determine the set
<add> to be sampled from. Specifically we select the set of size k such that
<add> the sum of its items' probabilities is maximum.
<add>
<add> .. Fan, Angela, Mike Lewis, and Yann Dauphin. "Hierarchical neural
<add> story generation." arXiv preprint arXiv:1805.04833 (2018).
<add> """
<add> if self.k > 0:
<add> vocabulary_size = logits.size(-1)
<add> if self.k > vocabulary_size:
<add> warnings.warn(
<add> """You provided a value for k ({}) that is larger than the vocabulary size ({}).
<add> We adjusted k's value to the vocabulary size; if that was what you intended to do
<add> we recommend setting k to 0 instead. It this is not the behavior you expected,
<add> choose a value of k that is smaller than the vocabulary size.""".format(
<add> self.k, vocabulary_size
<add> )
<add> )
<add> self.k = vocabulary_size
<add>
<add> indices_to_remove = logits < torch.topk(logits, self.k)[0][..., -1, None]
<add> logits[indices_to_remove] = -float("Inf")
<add>
<add> return logits
<add>
<add> def apply_nucleus_filter(self, logits):
<add> """ Use the probability distribution of the tokens to determine the set
<add> to be sampled from. Specifically, choose the smallest set such that the
<add> sum of its items' probabilities is greater than a number p in [0,1].
<add>
<add> .. Holtzman, Ari, et al. "The curious case of neural text
<add> degeneration." arXiv preprint arXiv:1904.09751 (2019).
<add> """
<add> if self.p > 0:
<add> sorted_logits, sorted_indices = torch.sort(logits, descending=True)
<add> sorted_probabilities = F.softmax(sorted_logits, dim=-1)
<add> cumulative_probabilities = torch.cumsum(sorted_probabilities, dim=-1)
<add>
<add> # Remove tokens with cumulative probability above the threshold,
<add> # but keep the first token above the threshold.
<add> sorted_indices_to_remove = cumulative_probabilities > self.p
<add> sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
<add> sorted_indices_to_remove[..., 0] = 0
<add>
<add> # scatter sorted tensors to original indexing
<add> indices_to_remove = sorted_indices_to_remove.scatter(
<add> dim=-1, index=sorted_indices, src=sorted_indices_to_remove
<add> )
<add> logits[indices_to_remove] = -float("Inf")
<add>
<add> return logits
<ide><path>transformers/modeling_xlm.py
<ide> def forward(self, input_ids=None, attention_mask=None, langs=None, token_type_id
<ide> langs=langs,
<ide> token_type_ids=token_type_ids,
<ide> position_ids=position_ids,
<del> lengths=lengths,
<add> lengths=lengths,
<ide> cache=cache,
<ide> head_mask=head_mask,
<ide> inputs_embeds=inputs_embeds)
<ide> def forward(self, input_ids=None, attention_mask=None, langs=None, token_type_id
<ide>
<ide> return outputs
<ide>
<add> def _prepare_inputs_for_decoding(self, input_ids, **model_kwargs):
<add> mask_token = model_kwargs.pop("mask_token", None)
<add> language = model_kwargs.pop("language", None)
<add> input_ids = self._append_mask_token(input_ids, mask_token)
<add> langs = self._create_language_embeddings(input_ids, language)
<add> arguments = {"input_ids": input_ids, "langs": langs}
<add> arguments.update(model_kwargs)
<add>
<add> return arguments
<add>
<add> @staticmethod
<add> def _append_mask_token(sequence, mask_token_id):
<add> """ Append a [MASK] token at the end of the sequence that the MLM model
<add> is going to try to predict.
<add> """
<add> if mask_token_id is not None:
<add> tokens_to_append = torch.full((1, 1), mask_token_id, dtype=torch.long)
<add> return torch.cat((sequence, tokens_to_append), dim=1)
<add>
<add> return sequence
<add>
<add> @staticmethod
<add> def _create_language_embeddings(sequence, language):
<add> if language is not None:
<add> return torch.tensor([language] * sequence.shape[1]).view(1, -1)
<add> return None
<add>
<ide>
<ide> @add_start_docstrings("""XLM Model with a sequence classification/regression head on top (a linear layer on top of
<ide> the pooled output) e.g. for GLUE tasks. """,
<ide><path>transformers/modeling_xlnet.py
<ide> def forward(self, input_ids=None, attention_mask=None, mems=None, perm_mask=None
<ide>
<ide> return outputs # return (loss), logits, (mems), (hidden states), (attentions)
<ide>
<add> def _prepare_inputs_for_decoding(self, input_ids, **model_kwargs):
<add> input_ids = self._add_dummy_token(input_ids)
<add> perm_mask = self._create_perm_mask(input_ids)
<add> target_mapping = self._create_target_mapping(input_ids)
<add> arguments = {
<add> "input_ids": input_ids,
<add> "perm_mask": perm_mask,
<add> "target_mapping": target_mapping,
<add> }
<add> return arguments
<add>
<add> @staticmethod
<add> def _add_dummy_token(sequence):
<add> dummy = torch.zeros((sequence.size(0), 1), dtype=torch.long)
<add> return torch.cat((sequence, dummy), dim=1)
<add>
<add> @staticmethod
<add> def _create_perm_mask(sequence):
<add> mask = torch.zeros(
<add> (sequence.shape[0], sequence.shape[1], sequence.shape[1]),
<add> dtype=torch.float,
<add> )
<add> mask[:, :, -1] = 1.0 # Previous tokens don't see last token
<add> return mask
<add>
<add> @staticmethod
<add> def _create_target_mapping(sequence):
<add> target_mapping = torch.zeros(
<add> (sequence.shape[0], 1, sequence.shape[1]),
<add> dtype=torch.float,
<add> )
<add> target_mapping[0, 0, -1] = 1.0 # predict last token
<add> return target_mapping
<add>
<ide>
<ide> @add_start_docstrings("""XLNet Model with a sequence classification/regression head on top (a linear layer on top of
<ide> the pooled output) e.g. for GLUE tasks. """,
<ide><path>transformers/tests/sampling_test.py
<add># coding=utf-8
<add>import sys
<add>import unittest
<add>
<add>import numpy as np
<add>import pytest
<add>
<add>from transformers import is_torch_available
<add>
<add>if is_torch_available():
<add> import torch
<add>
<add> from transformers import (
<add> BertConfig,
<add> BertModel,
<add> GPT2Config,
<add> GPT2LMHeadModel,
<add> OpenAIGPTConfig,
<add> OpenAIGPTLMHeadModel,
<add> TransfoXLConfig,
<add> TransfoXLLMHeadModel,
<add> XLMConfig,
<add> XLMWithLMHeadModel,
<add> XLNetConfig,
<add> XLNetLMHeadModel,
<add> Model2Model,
<add> )
<add> from transformers.modeling_utils import Sampler
<add>else:
<add> pytestmark = pytest.mark.skip("Require Torch")
<add>
<add>
<add>class SamplerTest(unittest.TestCase):
<add> def test_nucleus_sampling(self):
<add> inf = -float("Inf")
<add> test_cases = (
<add> {
<add> "p": 0,
<add> "logits": torch.tensor([0.3, 0.1, 0.2]),
<add> "expected": torch.tensor([0.3, 0.1, 0.2]),
<add> },
<add> {
<add> "p": 0.01,
<add> "logits": torch.tensor([0.3, 0.1, 0.2]),
<add> "expected": torch.tensor([0.3, inf, inf]),
<add> },
<add> {
<add> "p": 1,
<add> "logits": torch.tensor([0.3, 0.1, 0.2]),
<add> "expected": torch.tensor([0.3, 0.1, 0.2]),
<add> },
<add> {
<add> "p": 0.2,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, inf, inf]),
<add> },
<add> {
<add> "p": 0.71,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, inf, 0.2]),
<add> },
<add> {
<add> "p": 0.71,
<add> "logits": torch.tensor([0.1, 0.7, 0.2]),
<add> "expected": torch.tensor([inf, 0.7, 0.2]),
<add> },
<add> {
<add> "p": 0.71,
<add> "logits": torch.tensor([0.7, 0.2, 0.1]),
<add> "expected": torch.tensor([0.7, 0.2, inf]),
<add> },
<add> {
<add> "p": 0.91,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, 0.1, 0.2]),
<add> },
<add> )
<add> for case in test_cases:
<add> config = {
<add> "do_sample": True,
<add> "temperature": 1.0,
<add> "k": 0,
<add> "p": case["p"],
<add> "repetition_penalty": 1.0,
<add> }
<add> sampler = Sampler(**config)
<add> filtered_logits = sampler.apply_nucleus_filter(case["logits"])
<add> np.testing.assert_array_equal(case["expected"].numpy(), filtered_logits.numpy())
<add>
<add> def test_top_k_filter(self):
<add> inf = -float("Inf")
<add> test_cases = (
<add> {
<add> "k": 0,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, 0.1, 0.2]),
<add> },
<add> {
<add> "k": 1,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, inf, inf]),
<add> },
<add> {
<add> "k": 2,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, inf, 0.2]),
<add> },
<add> {
<add> "k": 3,
<add> "logits": torch.tensor([0.7, 0.1, 0.2]),
<add> "expected": torch.tensor([0.7, 0.1, 0.2]),
<add> },
<add> )
<add> for case in test_cases:
<add> config = {
<add> "do_sample": True,
<add> "temperature": 1.0,
<add> "k": case["k"],
<add> "p": 0,
<add> "repetition_penalty": 1.0,
<add> }
<add> sampler = Sampler(**config)
<add> filtered_logits = sampler.apply_top_k_filter(case["logits"])
<add> np.testing.assert_array_equal(case["expected"].numpy(), filtered_logits.numpy())
<add>
<add> @pytest.mark.skipif(sys.version_info < (3, 2), reason="assertWarns() requires Python >= 3.2")
<add> def test_wrong_k_value(self):
<add> case = {"k": 10, "vocab_size": 5}
<add> config = {
<add> "do_sample": True,
<add> "temperature": 1.0,
<add> "k": case["k"],
<add> "p": 0,
<add> "repetition_penalty": 1.0,
<add> }
<add> sampler = Sampler(**config)
<add> next_token_logits = torch.rand(case["vocab_size"]).unsqueeze(0)
<add> past_sequence = torch.tensor([])
<add> with self.assertWarns(UserWarning):
<add> _ = sampler.get_one_token(next_token_logits, past_sequence)
<add>
<add> def test_zero_temperature(self):
<add> temperature = 0
<add> config = {
<add> "do_sample": True,
<add> "temperature": temperature,
<add> "k": 0,
<add> "p": 0,
<add> "repetition_penalty": 1.0,
<add> }
<add> sampler = Sampler(**config)
<add> next_token_logits = torch.rand(10).unsqueeze(0)
<add> past_sequence = torch.tensor([])
<add> with self.assertRaises(ZeroDivisionError):
<add> _ = sampler.get_one_token(next_token_logits, past_sequence)
<add>
<add>
<add>class SamplerSingleStackTest(unittest.TestCase):
<add> def test_raises_exception_when_no_LM_head(self):
<add> models = [BertModel(BertConfig())]
<add> for model in models:
<add> with self.assertRaises(AttributeError):
<add> model.decode()
<add>
<add> @pytest.mark.slow
<add> def test_forward_pass_and_output_length(self):
<add> models = {
<add> "XLNet": XLNetLMHeadModel(XLNetConfig()),
<add> "XLM": XLMWithLMHeadModel(XLMConfig()),
<add> "TransfoXL": TransfoXLLMHeadModel(TransfoXLConfig()),
<add> "GPT2": GPT2LMHeadModel(GPT2Config()),
<add> "GPT": OpenAIGPTLMHeadModel(OpenAIGPTConfig()),
<add> }
<add> kwargs = {
<add> "XLNet": {},
<add> "XLM": {"mask_token": 0},
<add> "TransfoXL": {},
<add> "GPT2": {},
<add> "GPT": {},
<add> }
<add> prompt = torch.tensor([[1, 2, 3]], dtype=torch.long)
<add> generated_length = 5
<add> expected_length = 8
<add>
<add> for name, model in models.items():
<add> kwargs_model = kwargs[name]
<add> output = model.decode(prompt_ids=prompt, length=generated_length, **kwargs_model)
<add> self.assertEqual(len(output), expected_length)
<add>
<add>
<add>class SamplerEncoderDecoderTest(unittest.TestCase):
<add> @pytest.mark.slow
<add> def test_forward_pass_and_output_length(self):
<add> model = Model2Model.from_pretrained("bert-base-uncased")
<add>
<add> encoder_input_ids = torch.tensor([[1, 2, 3]], dtype=torch.long)
<add> prompt = torch.tensor([[1, 2, 3]], dtype=torch.long)
<add> generated_length = 5
<add> expected_length = 8
<add>
<add> output = model.decode(
<add> encoder_input_ids,
<add> decoder_prompt_ids=prompt,
<add> k=2,
<add> p=0.5,
<add> repetition_penalty=2,
<add> length=generated_length,
<add> )
<add> self.assertEqual(len(output), expected_length)
<add>
<add>
<add>if __name__ == "__main__":
<add> unittest.main() | 7 |
Text | Text | capitalize test text for cascading css variables | a284b296fcc65a459212fb9fd2e088a4b36f552f | <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/cascading-css-variables.english.md
<ide> Define a variable named <code>--penguin-belly</code> in the <code>:root</code> s
<ide>
<ide> ```yml
<ide> tests:
<del> - text: declare the <code>--penguin-belly</code> variable in the <code>:root</code> and assign it to <code>pink</code>.
<del> testString: assert(code.match(/:root\s*?{[\s\S]*--penguin-belly\s*?:\s*?pink\s*?;[\s\S]*}/gi), 'declare the <code>--penguin-belly</code> variable in the <code>:root</code> and assign it to <code>pink</code>.');
<add> - text: Declare the <code>--penguin-belly</code> variable in the <code>:root</code> and assign it to <code>pink</code>.
<add> testString: assert(code.match(/:root\s*?{[\s\S]*--penguin-belly\s*?:\s*?pink\s*?;[\s\S]*}/gi), 'Declare the <code>--penguin-belly</code> variable in the <code>:root</code> and assign it to <code>pink</code>.');
<ide>
<ide> ```
<ide> | 1 |
Text | Text | add ssr at soundcloud talk | d5810e46f95ddb8863af4df821bdbd49a4f4b4ed | <ide><path>docs/docs/videos.md
<ide> by [Stoyan Stefanov](http://www.phpied.com/)
<ide> <iframe width="650" height="315" src="//www.youtube.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
<ide>
<ide> Facebook engineers [Bill Fisher](http://twitter.com/fisherwebdev) and [Jing Chen](http://twitter.com/jingc) talk about Flux and React, and how using an application architecture with a unidirectional data flow cleans up a lot of their code.
<add>
<add>### Server-Side Rendering of Isomorphic Apps at SoundCloud
<add>
<add><iframe src="//player.vimeo.com/video/108488724" width="500" height="281" frameborder="0" allowfullscreen></iframe>
<add>
<add>Walk-through by [Andres Suarez](https://github.com/zertosh) on how [SoundCloud](https://developers.soundcloud.com/blog/) is using React and Flux for server-side rendering.
<add>
<add>[Slides and sample code](https://github.com/zertosh/ssr-demo-kit) | 1 |
Javascript | Javascript | remove "onunload" event handler | a117dd05f638a078c21dc57f19966f4ae81f98f0 | <ide><path>src/ajax/xhr.js
<ide> jQuery.ajaxSettings.xhr = function() {
<ide> } catch ( e ) {}
<ide> };
<ide>
<del>var xhrId = 0,
<del> xhrCallbacks = {},
<del> xhrSuccessStatus = {
<add>var xhrSuccessStatus = {
<ide> // file protocol always yields status code 0, assume 200
<ide> 0: 200,
<ide> // Support: IE9
<ide> var xhrId = 0,
<ide> },
<ide> xhrSupported = jQuery.ajaxSettings.xhr();
<ide>
<del>// Support: IE9
<del>// Open requests must be manually aborted on unload (#5280)
<del>// See https://support.microsoft.com/kb/2856746 for more info
<del>if ( window.attachEvent ) {
<del> window.attachEvent( "onunload", function() {
<del> for ( var key in xhrCallbacks ) {
<del> xhrCallbacks[ key ]();
<del> }
<del> });
<del>}
<del>
<ide> support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
<ide> support.ajax = xhrSupported = !!xhrSupported;
<ide>
<ide> jQuery.ajaxTransport(function( options ) {
<ide> return {
<ide> send: function( headers, complete ) {
<ide> var i,
<del> xhr = options.xhr(),
<del> id = ++xhrId;
<add> xhr = options.xhr();
<ide>
<ide> xhr.open(
<ide> options.type,
<ide> jQuery.ajaxTransport(function( options ) {
<ide> callback = function( type ) {
<ide> return function() {
<ide> if ( callback ) {
<del> delete xhrCallbacks[ id ];
<ide> callback = xhr.onload = xhr.onerror = null;
<ide>
<ide> if ( type === "abort" ) {
<ide> jQuery.ajaxTransport(function( options ) {
<ide> xhr.onerror = callback("error");
<ide>
<ide> // Create the abort callback
<del> callback = xhrCallbacks[ id ] = callback("abort");
<add> callback = callback("abort");
<ide>
<ide> try {
<ide> // Do send the request (this may raise an exception) | 1 |
Python | Python | fix typo in siamese example | 71aadf5e8b4020d4c9423ee5a5f42271abd860e5 | <ide><path>examples/mnist_siamese.py
<ide> def contrastive_loss(y_true, y_pred):
<ide> http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
<ide> '''
<ide> margin = 1
<del> sqaure_pred = K.square(y_pred)
<add> square_pred = K.square(y_pred)
<ide> margin_square = K.square(K.maximum(margin - y_pred, 0))
<del> return K.mean(y_true * sqaure_pred + (1 - y_true) * margin_square)
<add> return K.mean(y_true * square_pred + (1 - y_true) * margin_square)
<ide>
<ide>
<ide> def create_pairs(x, digit_indices): | 1 |
Go | Go | add tests for size quota | 8c31e4536a808d4a7224efce857ae63585480aa7 | <ide><path>volume/local/local_linux_test.go
<add>// +build linux
<add>
<add>package local // import "github.com/docker/docker/volume/local"
<add>
<add>import (
<add> "io/ioutil"
<add> "os"
<add> "path/filepath"
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/idtools"
<add> "github.com/docker/docker/quota"
<add> "gotest.tools/v3/assert"
<add> is "gotest.tools/v3/assert/cmp"
<add>)
<add>
<add>const quotaSize = 1024 * 1024
<add>const quotaSizeLiteral = "1M"
<add>
<add>func TestQuota(t *testing.T) {
<add> if msg, ok := quota.CanTestQuota(); !ok {
<add> t.Skip(msg)
<add> }
<add>
<add> // get sparse xfs test image
<add> imageFileName, err := quota.PrepareQuotaTestImage(t)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer os.Remove(imageFileName)
<add>
<add> t.Run("testVolWithQuota", quota.WrapMountTest(imageFileName, true, testVolWithQuota))
<add> t.Run("testVolQuotaUnsupported", quota.WrapMountTest(imageFileName, false, testVolQuotaUnsupported))
<add>}
<add>
<add>func testVolWithQuota(t *testing.T, mountPoint, backingFsDev, testDir string) {
<add> r, err := New(testDir, idtools.Identity{UID: os.Geteuid(), GID: os.Getegid()})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> assert.Assert(t, r.quotaCtl != nil)
<add>
<add> vol, err := r.Create("testing", map[string]string{"size": quotaSizeLiteral})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> dir, err := vol.Mount("1234")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := vol.Unmount("1234"); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> testfile := filepath.Join(dir, "testfile")
<add>
<add> // test writing file smaller than quota
<add> assert.NilError(t, ioutil.WriteFile(testfile, make([]byte, quotaSize/2), 0644))
<add> assert.NilError(t, os.Remove(testfile))
<add>
<add> // test writing fiel larger than quota
<add> err = ioutil.WriteFile(testfile, make([]byte, quotaSize+1), 0644)
<add> assert.ErrorContains(t, err, "")
<add> if _, err := os.Stat(testfile); err == nil {
<add> assert.NilError(t, os.Remove(testfile))
<add> }
<add>}
<add>
<add>func testVolQuotaUnsupported(t *testing.T, mountPoint, backingFsDev, testDir string) {
<add> r, err := New(testDir, idtools.Identity{UID: os.Geteuid(), GID: os.Getegid()})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> assert.Assert(t, is.Nil(r.quotaCtl))
<add>
<add> _, err = r.Create("testing", map[string]string{"size": quotaSizeLiteral})
<add> assert.ErrorContains(t, err, "no quota support")
<add>
<add> vol, err := r.Create("testing", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // this could happen if someone moves volumes from storage with
<add> // quota support to some place without
<add> lv, ok := vol.(*localVolume)
<add> assert.Assert(t, ok)
<add> lv.opts = &optsConfig{
<add> Quota: quota.Quota{Size: quotaSize},
<add> }
<add>
<add> _, err = vol.Mount("1234")
<add> assert.ErrorContains(t, err, "no quota support")
<add>} | 1 |
Go | Go | use prefix naming for restart tests | 1ddd013b194d7f551547bd2940a92ba3db72f95e | <ide><path>integration-cli/docker_cli_restart_test.go
<ide> import (
<ide> "time"
<ide> )
<ide>
<del>func TestDockerRestartStoppedContainer(t *testing.T) {
<add>func TestRestartStoppedContainer(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "echo", "foobar")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> errorOut(err, t, out)
<ide> func TestDockerRestartStoppedContainer(t *testing.T) {
<ide> logDone("restart - echo foobar for stopped container")
<ide> }
<ide>
<del>func TestDockerRestartRunningContainer(t *testing.T) {
<add>func TestRestartRunningContainer(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> errorOut(err, t, out)
<ide> func TestDockerRestartRunningContainer(t *testing.T) {
<ide> }
<ide>
<ide> // Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819.
<del>func TestDockerRestartWithVolumes(t *testing.T) {
<add>func TestRestartWithVolumes(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/test", "busybox", "top")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> errorOut(err, t, out) | 1 |
PHP | PHP | allow publishing of pagination views | 883b6db9d3d2b553637b08adefc97f6b22d188f1 | <ide><path>src/Illuminate/Pagination/PaginationServiceProvider.php
<ide> class PaginationServiceProvider extends ServiceProvider
<ide> public function boot()
<ide> {
<ide> $this->loadViewsFrom(__DIR__.'/resources/views', 'pagination');
<add>
<add> if ($this->app->runningInConsole()) {
<add> $this->publishes([
<add> __DIR__.'/resources/views' => resource_path('views/vendor/pagination'),
<add> ], 'laravel-pagination');
<add> }
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add log_level options to configuration guide | f0466b619bf5f0d79f99962f9e0e242d2ffbd699 | <ide><path>guides/source/configuring.md
<ide> numbers. New applications filter out passwords by adding the following `config.f
<ide>
<ide> * `config.log_formatter` defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all modes except production, where it defaults to `Logger::Formatter`.
<ide>
<del>* `config.log_level` defines the verbosity of the Rails logger. This option defaults to `:debug` for all environments.
<add>* `config.log_level` defines the verbosity of the Rails logger. This option defaults to `:debug` for all environments. The available log levels are: :debug, :info, :warn, :error, :fatal, and :unknown.
<ide>
<ide> * `config.log_tags` accepts a list of methods that the `request` object responds to. This makes it easy to tag log lines with debug information like subdomain and request id - both very helpful in debugging multi-user production applications.
<ide> | 1 |
Python | Python | replace relative imports in cversions.py | 38d987d392a87341f64528cdb55f7a746a7ba8d5 | <ide><path>numpy/core/code_generators/cversions.py
<ide>
<ide> from os.path import dirname
<ide>
<del>from .genapi import fullapi_hash
<del>from . import numpy_api
<add>from genapi import fullapi_hash
<add>import numpy_api
<ide>
<ide>
<ide> if __name__ == '__main__': | 1 |
Python | Python | add gzip support to unitaries tests | 59a5400118500274ad2eae0c3fe134debc0aefb9 | <ide><path>unitest-restful.py
<ide> def setUp(self):
<ide> """The function is called *every time* before test_*."""
<ide> print('\n' + '=' * 78)
<ide>
<add> def http_get(self, url, gzipped=False):
<add> """Make the gt request"""
<add> if gzipped:
<add> ret = requests.get(url,
<add> stream=True,
<add> headers={'Accept-encoding': 'gzip'})
<add> else:
<add> ret = requests.get(url,
<add> headers={'Accept-encoding': 'identity'})
<add> return ret
<add>
<ide> def test_000_start_server(self):
<ide> """Start the Glances Web Server."""
<ide> global pid
<ide> def test_001_all(self):
<ide> method = "all"
<ide> print('INFO: [TEST_001] Get all stats')
<ide> print("HTTP RESTful request: %s/%s" % (URL, method))
<del> req = requests.get("%s/%s" % (URL, method))
<add> req = self.http_get("%s/%s" % (URL, method))
<add>
<add> self.assertTrue(req.ok)
<add>
<add> def test_001a_all_gzip(self):
<add> """All."""
<add> method = "all"
<add> print('INFO: [TEST_001a] Get all stats (with Gzip compression)')
<add> print("HTTP RESTful request: %s/%s" % (URL, method))
<add> req = self.http_get("%s/%s" % (URL, method), gzipped=True)
<ide>
<ide> self.assertTrue(req.ok)
<add> self.assertTrue(req.headers['Content-Encoding'] == 'gzip')
<ide>
<ide> def test_002_pluginslist(self):
<ide> """Plugins list."""
<ide> method = "pluginslist"
<ide> print('INFO: [TEST_002] Plugins list')
<ide> print("HTTP RESTful request: %s/%s" % (URL, method))
<del> req = requests.get("%s/%s" % (URL, method))
<add> req = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), list)
<ide> def test_003_plugins(self):
<ide> """Plugins."""
<ide> method = "pluginslist"
<ide> print('INFO: [TEST_003] Plugins')
<del> plist = requests.get("%s/%s" % (URL, method))
<add> plist = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> for p in plist.json():
<ide> print("HTTP RESTful request: %s/%s" % (URL, p))
<del> req = requests.get("%s/%s" % (URL, p))
<add> req = self.http_get("%s/%s" % (URL, p))
<ide> self.assertTrue(req.ok)
<ide> if p in ('uptime', 'now'):
<ide> self.assertIsInstance(req.json(), text_type)
<ide> def test_004_items(self):
<ide> """Items."""
<ide> method = "cpu"
<ide> print('INFO: [TEST_004] Items for the CPU method')
<del> ilist = requests.get("%s/%s" % (URL, method))
<add> ilist = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> for i in ilist.json():
<ide> print("HTTP RESTful request: %s/%s/%s" % (URL, method, i))
<del> req = requests.get("%s/%s/%s" % (URL, method, i))
<add> req = self.http_get("%s/%s/%s" % (URL, method, i))
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide> print(req.json()[i])
<ide> def test_005_values(self):
<ide> method = "processlist"
<ide> print('INFO: [TEST_005] Item=Value for the PROCESSLIST method')
<ide> print("%s/%s/pid/0" % (URL, method))
<del> req = requests.get("%s/%s/pid/0" % (URL, method))
<add> req = self.http_get("%s/%s/pid/0" % (URL, method))
<ide>
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide> def test_006_all_limits(self):
<ide> method = "all/limits"
<ide> print('INFO: [TEST_006] Get all limits')
<ide> print("HTTP RESTful request: %s/%s" % (URL, method))
<del> req = requests.get("%s/%s" % (URL, method))
<add> req = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide> def test_007_all_views(self):
<ide> method = "all/views"
<ide> print('INFO: [TEST_007] Get all views')
<ide> print("HTTP RESTful request: %s/%s" % (URL, method))
<del> req = requests.get("%s/%s" % (URL, method))
<add> req = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide> def test_008_plugins_limits(self):
<ide> """Plugins limits."""
<ide> method = "pluginslist"
<ide> print('INFO: [TEST_008] Plugins limits')
<del> plist = requests.get("%s/%s" % (URL, method))
<add> plist = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> for p in plist.json():
<ide> print("HTTP RESTful request: %s/%s/limits" % (URL, p))
<del> req = requests.get("%s/%s/limits" % (URL, p))
<add> req = self.http_get("%s/%s/limits" % (URL, p))
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide>
<ide> def test_009_plugins_views(self):
<ide> """Plugins views."""
<ide> method = "pluginslist"
<ide> print('INFO: [TEST_009] Plugins views')
<del> plist = requests.get("%s/%s" % (URL, method))
<add> plist = self.http_get("%s/%s" % (URL, method))
<ide>
<ide> for p in plist.json():
<ide> print("HTTP RESTful request: %s/%s/views" % (URL, p))
<del> req = requests.get("%s/%s/views" % (URL, p))
<add> req = self.http_get("%s/%s/views" % (URL, p))
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<ide>
<ide> def test_010_history(self):
<ide> method = "history"
<ide> print('INFO: [TEST_010] History')
<ide> print("HTTP RESTful request: %s/cpu/%s" % (URL, method))
<del> req = requests.get("%s/cpu/%s" % (URL, method))
<add> req = self.http_get("%s/cpu/%s" % (URL, method))
<ide> self.assertIsInstance(req.json(), dict)
<ide> self.assertIsInstance(req.json()['user'], list)
<ide> self.assertTrue(len(req.json()['user']) > 0)
<ide> print("HTTP RESTful request: %s/cpu/%s/3" % (URL, method))
<del> req = requests.get("%s/cpu/%s/3" % (URL, method))
<add> req = self.http_get("%s/cpu/%s/3" % (URL, method))
<ide> self.assertIsInstance(req.json(), dict)
<ide> self.assertIsInstance(req.json()['user'], list)
<ide> self.assertTrue(len(req.json()['user']) > 1)
<ide> print("HTTP RESTful request: %s/cpu/system/%s" % (URL, method))
<del> req = requests.get("%s/cpu/system/%s" % (URL, method))
<add> req = self.http_get("%s/cpu/system/%s" % (URL, method))
<ide> self.assertIsInstance(req.json(), dict)
<ide> self.assertIsInstance(req.json()['system'], list)
<ide> self.assertTrue(len(req.json()['system']) > 0)
<ide> print("HTTP RESTful request: %s/cpu/system/%s/3" % (URL, method))
<del> req = requests.get("%s/cpu/system/%s/3" % (URL, method))
<add> req = self.http_get("%s/cpu/system/%s/3" % (URL, method))
<ide> self.assertIsInstance(req.json(), dict)
<ide> self.assertIsInstance(req.json()['system'], list)
<ide> self.assertTrue(len(req.json()['system']) > 1) | 1 |
Python | Python | raise error when `source=` use on a child | 8af366a73282359c63eab6e81b80fb859604424f | <ide><path>rest_framework/fields.py
<ide> class ListField(Field):
<ide> def __init__(self, *args, **kwargs):
<ide> self.child = kwargs.pop('child', copy.deepcopy(self.child))
<ide> self.allow_empty = kwargs.pop('allow_empty', True)
<add>
<ide> assert not inspect.isclass(self.child), '`child` has not been instantiated.'
<add> assert self.child.source is None, (
<add> "The `source` argument is not meaningful when applied to a `child=` field. "
<add> "Remove `source=` from the field declaration."
<add> )
<add>
<ide> super(ListField, self).__init__(*args, **kwargs)
<ide> self.child.bind(field_name='', parent=self)
<ide>
<ide> class DictField(Field):
<ide>
<ide> def __init__(self, *args, **kwargs):
<ide> self.child = kwargs.pop('child', copy.deepcopy(self.child))
<add>
<ide> assert not inspect.isclass(self.child), '`child` has not been instantiated.'
<add> assert self.child.source is None, (
<add> "The `source` argument is not meaningful when applied to a `child=` field. "
<add> "Remove `source=` from the field declaration."
<add> )
<add>
<ide> super(DictField, self).__init__(*args, **kwargs)
<ide> self.child.bind(field_name='', parent=self)
<ide>
<ide><path>tests/test_fields.py
<ide> class TestListField(FieldValues):
<ide> ]
<ide> field = serializers.ListField(child=serializers.IntegerField())
<ide>
<add> def test_no_source_on_child(self):
<add> with pytest.raises(AssertionError) as exc_info:
<add> serializers.ListField(child=serializers.IntegerField(source='other'))
<add>
<add> assert str(exc_info.value) == (
<add> "The `source` argument is not meaningful when applied to a `child=` field. "
<add> "Remove `source=` from the field declaration."
<add> )
<add>
<ide>
<ide> class TestEmptyListField(FieldValues):
<ide> """
<ide> class TestDictField(FieldValues):
<ide> ]
<ide> field = serializers.DictField(child=serializers.CharField())
<ide>
<add> def test_no_source_on_child(self):
<add> with pytest.raises(AssertionError) as exc_info:
<add> serializers.DictField(child=serializers.CharField(source='other'))
<add>
<add> assert str(exc_info.value) == (
<add> "The `source` argument is not meaningful when applied to a `child=` field. "
<add> "Remove `source=` from the field declaration."
<add> )
<add>
<ide>
<ide> class TestUnvalidatedDictField(FieldValues):
<ide> """ | 2 |
Text | Text | add fishrock123 to collaborators | a0831c580d50b54fd4add58071341b3b7ec83499 | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org>
<ide> * **Thorsten Lorenz** ([@thlorenz](https://github.com/thlorenz)) <thlorenz@gmx.de>
<ide> * **Stephen Belanger** ([@qard](https://github.com/qard)) <admin@stephenbelanger.com>
<add>* **Jeremiah Senkpiel** ([@fishrock123](https://github.com/fishrock123)) <fishrock123@rocketmail.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Go | Go | prevent exec delete locking | 332f134890246cfc73703b2911c9fdc20e063096 | <ide><path>libcontainerd/client_daemon.go
<ide> import (
<ide> "github.com/containerd/typeurl"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/opencontainers/image-spec/specs-go/v1"
<add> v1 "github.com/opencontainers/image-spec/specs-go/v1"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec *
<ide> defer close(stdinCloseSync)
<ide>
<ide> if err = p.Start(ctx); err != nil {
<del> p.Delete(context.Background())
<add> // use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure
<add> // we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in
<add> // older containerd-shim
<add> ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
<add> defer cancel()
<add> p.Delete(ctx)
<ide> ctr.deleteProcess(processID)
<ide> return -1, wrapError(err)
<ide> } | 1 |
PHP | PHP | limit the supported ciphers and check key length | 9bb8eeaba2864f5d034a8c2649c28c921af861e4 | <ide><path>src/Illuminate/Encryption/Encrypter.php
<ide>
<ide> namespace Illuminate\Encryption;
<ide>
<add>use RuntimeException;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Encryption\DecryptException;
<ide> use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
<ide> class Encrypter implements EncrypterContract
<ide> *
<ide> * @var string
<ide> */
<del> protected $cipher = 'AES-128-CBC';
<add> protected $cipher;
<ide>
<ide> /**
<ide> * The block size of the cipher.
<ide> class Encrypter implements EncrypterContract
<ide> * Create a new encrypter instance.
<ide> *
<ide> * @param string $key
<del> * @param string|null $cipher
<add> * @param string $cipher
<ide> * @return void
<ide> */
<del> public function __construct($key, $cipher = null)
<add> public function __construct($key, $cipher = 'AES-128-CBC')
<ide> {
<del> $this->key = (string) $key;
<add> $len = mb_strlen($key = (string) $key);
<ide>
<del> if ($cipher) {
<add> if ($len === 16 || $len === 32) {
<add> $this->key = $key;
<add> } else {
<add> throw new RuntimeException('The only supported key lengths are 16 bytes and 32 bytes.');
<add> }
<add>
<add> if ($cipher === 'AES-128-CBC' || $cipher === 'AES-256-CBC') {
<ide> $this->cipher = $cipher;
<del> $this->block = openssl_cipher_iv_length($this->cipher);
<add> } else {
<add> throw new RuntimeException('The only supported ciphers are AES-128-CBC and AES-256-CBC.');
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | improve $controller function doc readability | 06ada222c26f717552fad88fb9534abf09824c61 | <ide><path>src/ng/controller.js
<ide> function $ControllerProvider() {
<ide> * @description
<ide> * `$controller` service is responsible for instantiating controllers.
<ide> *
<del> * It's just simple call to {@link AUTO.$injector $injector}, but extracted into
<add> * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
<ide> * a service, so that one can override this service with {@link https://gist.github.com/1649788
<ide> * BC version}.
<ide> */ | 1 |
Javascript | Javascript | use more es6 syntaxes in the todomvc example | 27d9a24d1020685bc723f91ef60d0907df58ec23 | <ide><path>examples/todomvc/src/actions/index.js
<ide> import * as types from '../constants/ActionTypes'
<ide>
<del>export function addTodo(text) {
<del> return { type: types.ADD_TODO, text }
<del>}
<add>export const addTodo = text => ({ type: types.ADD_TODO, text })
<ide>
<del>export function deleteTodo(id) {
<del> return { type: types.DELETE_TODO, id }
<del>}
<add>export const deleteTodo = id => ({ type: types.DELETE_TODO, id })
<ide>
<del>export function editTodo(id, text) {
<del> return { type: types.EDIT_TODO, id, text }
<del>}
<add>export const editTodo = (id, text) => ({ type: types.EDIT_TODO, id, text })
<ide>
<del>export function completeTodo(id) {
<del> return { type: types.COMPLETE_TODO, id }
<del>}
<add>export const completeTodo = id => ({ type: types.COMPLETE_TODO, id })
<ide>
<del>export function completeAll() {
<del> return { type: types.COMPLETE_ALL }
<del>}
<add>export const completeAll = () => ({ type: types.COMPLETE_ALL })
<ide>
<del>export function clearCompleted() {
<del> return { type: types.CLEAR_COMPLETED }
<del>}
<add>export const clearCompleted = () => ({ type: types.CLEAR_COMPLETED })
<ide><path>examples/todomvc/src/components/Footer.js
<ide> const FILTER_TITLES = {
<ide> [SHOW_COMPLETED]: 'Completed'
<ide> }
<ide>
<del>class Footer extends Component {
<del> renderTodoCount() {
<add>export default class Footer extends Component {
<add> static propTypes = {
<add> completedCount: PropTypes.number.isRequired,
<add> activeCount: PropTypes.number.isRequired,
<add> filter: PropTypes.string.isRequired,
<add> onClearCompleted: PropTypes.func.isRequired,
<add> onShow: PropTypes.func.isRequired
<add> }
<add>
<add> renderTodoCount = () => {
<ide> const { activeCount } = this.props
<ide> const itemWord = activeCount === 1 ? 'item' : 'items'
<ide>
<ide> class Footer extends Component {
<ide> )
<ide> }
<ide>
<del> renderFilterLink(filter) {
<add> renderFilterLink = filter => {
<ide> const title = FILTER_TITLES[filter]
<ide> const { filter: selectedFilter, onShow } = this.props
<ide>
<ide> class Footer extends Component {
<ide> )
<ide> }
<ide>
<del> renderClearButton() {
<add> renderClearButton = () => {
<ide> const { completedCount, onClearCompleted } = this.props
<ide> if (completedCount > 0) {
<ide> return (
<ide> class Footer extends Component {
<ide> )
<ide> }
<ide> }
<del>
<del>Footer.propTypes = {
<del> completedCount: PropTypes.number.isRequired,
<del> activeCount: PropTypes.number.isRequired,
<del> filter: PropTypes.string.isRequired,
<del> onClearCompleted: PropTypes.func.isRequired,
<del> onShow: PropTypes.func.isRequired
<del>}
<del>
<del>export default Footer
<ide><path>examples/todomvc/src/components/Footer.spec.js
<ide> import TestUtils from 'react-addons-test-utils'
<ide> import Footer from './Footer'
<ide> import { SHOW_ALL, SHOW_ACTIVE } from '../constants/TodoFilters'
<ide>
<del>function setup(propOverrides) {
<add>const setup = propOverrides => {
<ide> const props = Object.assign({
<ide> completedCount: 0,
<ide> activeCount: 0,
<ide> function setup(propOverrides) {
<ide> }
<ide> }
<ide>
<del>function getTextContent(elem) {
<add>const getTextContent = elem => {
<ide> const children = Array.isArray(elem.props.children) ?
<ide> elem.props.children : [ elem.props.children ]
<ide>
<del> return children.reduce(function concatText(out, child) {
<add> return children.reduce((out, child) =>
<add> // Concatenate the text
<ide> // Children are either elements or text strings
<del> return out + (child.props ? getTextContent(child) : child)
<del> }, '')
<add> out + (child.props ? getTextContent(child) : child)
<add> , '')
<ide> }
<ide>
<ide> describe('components', () => {
<ide><path>examples/todomvc/src/components/Header.js
<ide> import React, { PropTypes, Component } from 'react'
<ide> import TodoTextInput from './TodoTextInput'
<ide>
<del>class Header extends Component {
<del> handleSave(text) {
<add>export default class Header extends Component {
<add> static propTypes = {
<add> addTodo: PropTypes.func.isRequired
<add> }
<add>
<add> handleSave = text => {
<ide> if (text.length !== 0) {
<ide> this.props.addTodo(text)
<ide> }
<ide> class Header extends Component {
<ide> <header className="header">
<ide> <h1>todos</h1>
<ide> <TodoTextInput newTodo
<del> onSave={this.handleSave.bind(this)}
<add> onSave={this.handleSave}
<ide> placeholder="What needs to be done?" />
<ide> </header>
<ide> )
<ide> }
<ide> }
<del>
<del>Header.propTypes = {
<del> addTodo: PropTypes.func.isRequired
<del>}
<del>
<del>export default Header
<ide><path>examples/todomvc/src/components/Header.spec.js
<ide> import TestUtils from 'react-addons-test-utils'
<ide> import Header from './Header'
<ide> import TodoTextInput from './TodoTextInput'
<ide>
<del>function setup() {
<add>const setup = () => {
<ide> const props = {
<ide> addTodo: jest.fn()
<ide> }
<ide><path>examples/todomvc/src/components/MainSection.js
<ide> const TODO_FILTERS = {
<ide> [SHOW_COMPLETED]: todo => todo.completed
<ide> }
<ide>
<del>class MainSection extends Component {
<del> constructor(props, context) {
<del> super(props, context)
<del> this.state = { filter: SHOW_ALL }
<add>export default class MainSection extends Component {
<add> static propTypes = {
<add> todos: PropTypes.array.isRequired,
<add> actions: PropTypes.object.isRequired
<ide> }
<ide>
<del> handleClearCompleted() {
<del> this.props.actions.clearCompleted()
<del> }
<add> state = { filter: SHOW_ALL }
<ide>
<del> handleShow(filter) {
<del> this.setState({ filter })
<del> }
<add> handleClearCompleted = () => this.props.actions.clearCompleted()
<add>
<add> handleShow = filter => this.setState({ filter })
<ide>
<del> renderToggleAll(completedCount) {
<add> renderToggleAll = completedCount => {
<ide> const { todos, actions } = this.props
<ide> if (todos.length > 0) {
<ide> return (
<ide> class MainSection extends Component {
<ide> }
<ide> }
<ide>
<del> renderFooter(completedCount) {
<add> renderFooter = completedCount => {
<ide> const { todos } = this.props
<ide> const { filter } = this.state
<ide> const activeCount = todos.length - completedCount
<ide> class MainSection extends Component {
<ide> )
<ide> }
<ide> }
<del>
<del>MainSection.propTypes = {
<del> todos: PropTypes.array.isRequired,
<del> actions: PropTypes.object.isRequired
<del>}
<del>
<del>export default MainSection
<ide><path>examples/todomvc/src/components/MainSection.spec.js
<ide> import TodoItem from './TodoItem'
<ide> import Footer from './Footer'
<ide> import { SHOW_ALL, SHOW_COMPLETED } from '../constants/TodoFilters'
<ide>
<del>function setup(propOverrides) {
<add>const setup = propOverrides => {
<ide> const props = Object.assign({
<ide> todos: [
<ide> {
<ide><path>examples/todomvc/src/components/TodoItem.js
<ide> import React, { Component, PropTypes } from 'react'
<ide> import classnames from 'classnames'
<ide> import TodoTextInput from './TodoTextInput'
<ide>
<del>class TodoItem extends Component {
<del> constructor(props, context) {
<del> super(props, context)
<del> this.state = {
<del> editing: false
<del> }
<add>export default class TodoItem extends Component {
<add> static propTypes = {
<add> todo: PropTypes.object.isRequired,
<add> editTodo: PropTypes.func.isRequired,
<add> deleteTodo: PropTypes.func.isRequired,
<add> completeTodo: PropTypes.func.isRequired
<ide> }
<ide>
<del> handleDoubleClick() {
<del> this.setState({ editing: true })
<add> state = {
<add> editing: false
<ide> }
<ide>
<del> handleSave(id, text) {
<add> handleDoubleClick = () => this.setState({ editing: true })
<add>
<add> handleSave = (id, text) => {
<ide> if (text.length === 0) {
<ide> this.props.deleteTodo(id)
<ide> } else {
<ide> class TodoItem extends Component {
<ide> type="checkbox"
<ide> checked={todo.completed}
<ide> onChange={() => completeTodo(todo.id)} />
<del> <label onDoubleClick={this.handleDoubleClick.bind(this)}>
<add> <label onDoubleClick={this.handleDoubleClick}>
<ide> {todo.text}
<ide> </label>
<ide> <button className="destroy"
<ide> class TodoItem extends Component {
<ide> )
<ide> }
<ide> }
<del>
<del>TodoItem.propTypes = {
<del> todo: PropTypes.object.isRequired,
<del> editTodo: PropTypes.func.isRequired,
<del> deleteTodo: PropTypes.func.isRequired,
<del> completeTodo: PropTypes.func.isRequired
<del>}
<del>
<del>export default TodoItem
<ide><path>examples/todomvc/src/components/TodoItem.spec.js
<ide> import TestUtils from 'react-addons-test-utils'
<ide> import TodoItem from './TodoItem'
<ide> import TodoTextInput from './TodoTextInput'
<ide>
<del>function setup( editing = false ) {
<add>const setup = ( editing = false ) => {
<ide> const props = {
<ide> todo: {
<ide> id: 0,
<ide><path>examples/todomvc/src/components/TodoTextInput.js
<ide> import React, { Component, PropTypes } from 'react'
<ide> import classnames from 'classnames'
<ide>
<del>class TodoTextInput extends Component {
<del> constructor(props, context) {
<del> super(props, context)
<del> this.state = {
<del> text: this.props.text || ''
<del> }
<add>export default class TodoTextInput extends Component {
<add> static propTypes = {
<add> onSave: PropTypes.func.isRequired,
<add> text: PropTypes.string,
<add> placeholder: PropTypes.string,
<add> editing: PropTypes.bool,
<add> newTodo: PropTypes.bool
<add> }
<add>
<add> state = {
<add> text: this.props.text || ''
<ide> }
<ide>
<del> handleSubmit(e) {
<add> handleSubmit = e => {
<ide> const text = e.target.value.trim()
<ide> if (e.which === 13) {
<ide> this.props.onSave(text)
<ide> class TodoTextInput extends Component {
<ide> }
<ide> }
<ide>
<del> handleChange(e) {
<del> this.setState({ text: e.target.value })
<del> }
<add> handleChange = e => this.setState({ text: e.target.value })
<ide>
<del> handleBlur(e) {
<add>
<add> handleBlur = e => {
<ide> if (!this.props.newTodo) {
<ide> this.props.onSave(e.target.value)
<ide> }
<ide> class TodoTextInput extends Component {
<ide> placeholder={this.props.placeholder}
<ide> autoFocus="true"
<ide> value={this.state.text}
<del> onBlur={this.handleBlur.bind(this)}
<del> onChange={this.handleChange.bind(this)}
<del> onKeyDown={this.handleSubmit.bind(this)} />
<add> onBlur={this.handleBlur}
<add> onChange={this.handleChange}
<add> onKeyDown={this.handleSubmit} />
<ide> )
<ide> }
<ide> }
<del>
<del>TodoTextInput.propTypes = {
<del> onSave: PropTypes.func.isRequired,
<del> text: PropTypes.string,
<del> placeholder: PropTypes.string,
<del> editing: PropTypes.bool,
<del> newTodo: PropTypes.bool
<del>}
<del>
<del>export default TodoTextInput
<ide><path>examples/todomvc/src/components/TodoTextInput.spec.js
<ide> import React from 'react'
<ide> import TestUtils from 'react-addons-test-utils'
<ide> import TodoTextInput from './TodoTextInput'
<ide>
<del>function setup(propOverrides) {
<add>const setup = propOverrides => {
<ide> const props = Object.assign({
<ide> onSave: jest.fn(),
<ide> text: 'Use Redux',
<ide><path>examples/todomvc/src/containers/App.js
<del>import React, { Component, PropTypes } from 'react'
<add>import React, { PropTypes } from 'react'
<ide> import { bindActionCreators } from 'redux'
<ide> import { connect } from 'react-redux'
<ide> import Header from '../components/Header'
<ide> import MainSection from '../components/MainSection'
<ide> import * as TodoActions from '../actions'
<ide>
<del>class App extends Component {
<del> render() {
<del> const { todos, actions } = this.props
<del> return (
<del> <div>
<del> <Header addTodo={actions.addTodo} />
<del> <MainSection todos={todos} actions={actions} />
<del> </div>
<del> )
<del> }
<del>}
<add>const App = ({todos, actions}) => <div>
<add> <Header addTodo={actions.addTodo} />
<add> <MainSection todos={todos} actions={actions} />
<add></div>
<ide>
<ide> App.propTypes = {
<ide> todos: PropTypes.array.isRequired,
<ide> actions: PropTypes.object.isRequired
<ide> }
<ide>
<del>function mapStateToProps(state) {
<del> return {
<del> todos: state.todos
<del> }
<del>}
<add>const mapStateToProps = state => ({todos: state.todos})
<ide>
<del>function mapDispatchToProps(dispatch) {
<del> return {
<add>const mapDispatchToProps = dispatch => ({
<ide> actions: bindActionCreators(TodoActions, dispatch)
<del> }
<del>}
<add>})
<ide>
<ide> export default connect(
<ide> mapStateToProps, | 12 |
Text | Text | remove ccp link | 9eb4daa29731a098ef60b6fe9a4e8bd0e7f1f1e9 | <ide><path>README.md
<ide> within webpack itself use this plugin interface. This makes webpack very
<ide>
<ide> |Name|Status|Description|
<ide> |:--:|:----:|:----------|
<del>|[common-chunks-webpack-plugin][common]|![common-npm]|Generates chunks of common modules shared between entry points and splits them into separate bundles (e.g vendor.bundle.js && app.bundle.js)|
<ide> |[extract-text-webpack-plugin][extract]|![extract-npm]|Extracts Text (CSS) from your bundles into a separate file (app.bundle.css)|
<ide> |[compression-webpack-plugin][compression]|![compression-npm]|Prepares compressed versions of assets to serve them with Content-Encoding|
<ide> |[i18n-webpack-plugin][i18n]|![i18n-npm]|Adds i18n support to your bundles|
<ide> |[html-webpack-plugin][html-plugin]|![html-plugin-npm]| Simplifies creation of HTML files (`index.html`) to serve your bundles|
<ide>
<ide>
<del>[common]: https://github.com/webpack/webpack/blob/master/lib/optimize/CommonsChunkPlugin.js
<ide> [common-npm]: https://img.shields.io/npm/v/webpack.svg
<ide> [extract]: https://github.com/webpack/extract-text-webpack-plugin
<ide> [extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg
<ide> This is how we use the donations:
<ide> <h2 align="center">Premium Partners</h2>
<ide>
<ide> <div align="center">
<del>
<add>
<ide> <a href="https://www.ag-grid.com/?utm_source=webpack&utm_medium=banner&utm_campaign=sponsorship" target="_blank"><img align="center" src="https://raw.githubusercontent.com/webpack/media/2b399d58/horiz-banner-ad-ag-grid.png">
<ide> </a>
<ide>
<ide> This is how we use the donations:
<ide> Before we started using OpenCollective, donations were made anonymously. Now that we have made the switch, we would like to acknowledge these sponsors (and the ones who continue to donate using OpenCollective). If we've missed someone, please send us a PR, and we'll add you to this list.
<ide>
<ide> <div align="center">
<del>
<add>
<ide> [Google Angular Team](https://angular.io/), [Architects.io](http://architects.io/),
<del><a href="https://moonmail.io" target="_blank" title="Email Marketing Software"><img
<del>src="https://static.moonmail.io/moonmail-logo.svg" height="30" alt="MoonMail"></a>
<del><a href="https://monei.net" target="_blank" title="Best payment gateway rates"><img
<add><a href="https://moonmail.io" target="_blank" title="Email Marketing Software"><img
<add>src="https://static.moonmail.io/moonmail-logo.svg" height="30" alt="MoonMail"></a>
<add><a href="https://monei.net" target="_blank" title="Best payment gateway rates"><img
<ide> src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a>
<ide>
<ide> </div> | 1 |
Python | Python | fix docs and bad word tokens generation_utils.py | 9d94aecd516c7540a94b9d781ef28d7375a796bc | <ide><path>src/transformers/generation_tf_utils.py
<ide> def generate(
<ide> model = TFAutoModelWithLMHead.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.
<ide> input_context = 'The dog'
<ide> input_ids = tokenizer.encode(input_context, return_tensors='tf') # encode input context
<del> outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3) # 3 generate sequences using by sampling
<add> outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # generate 3 candidates using sampling
<ide> for i in range(3): # 3 output sequences were generated
<ide> print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))
<ide>
<ide> def _tokens_match(prev_tokens, tokens):
<ide> if len(tokens) == 0:
<ide> # if bad word tokens is just one token always ban it
<ide> return True
<del> if len(tokens) > len(prev_input_ids):
<del> # if bad word tokens are longer then prev input_ids they can't be equal
<add> if len(tokens) > len(prev_tokens):
<add> # if bad word tokens are longer than prev tokens they can't be equal
<ide> return False
<ide>
<ide> if prev_tokens[-len(tokens) :] == tokens:
<ide><path>src/transformers/generation_utils.py
<ide> def generate(
<ide> model = AutoModelWithLMHead.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.
<ide> input_context = 'The dog'
<ide> input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context
<del> outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3) # 3 generate sequences using by sampling
<add> outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # generate 3 candidates using sampling
<ide> for i in range(3): # 3 output sequences were generated
<ide> print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))
<ide>
<ide> def _tokens_match(prev_tokens, tokens):
<ide> if len(tokens) == 0:
<ide> # if bad word tokens is just one token always ban it
<ide> return True
<del> if len(tokens) > len(prev_input_ids):
<del> # if bad word tokens are longer then prev input_ids they can't be equal
<add> if len(tokens) > len(prev_tokens):
<add> # if bad word tokens are longer than prev tokens they can't be equal
<ide> return False
<ide>
<ide> if prev_tokens[-len(tokens) :] == tokens: | 2 |
Javascript | Javascript | fix spec for path | 090bbf9e77fb1e75858aea0312a8b166cafcfab2 | <ide><path>spec/atom-paths-spec.js
<ide> import path from 'path'
<ide> const temp = require('temp').track()
<ide>
<ide> describe("AtomPaths", () => {
<del> const portableAtomHomePath = path.join(atomPaths.getAppDirectory(), '.atom')
<del> console.log(portableAtomHomePath)
<add> const portableAtomHomePath = path.join(atomPaths.getAppDirectory(), '..', '.atom')
<ide>
<ide> afterEach(() => {
<ide> atomPaths.setAtomHome(app.getPath('home')) | 1 |
PHP | PHP | add functional tests | 52bf07957a8edfa5090decc57446785b472a53ab | <ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Event\Event;
<ide> use Cake\I18n\Time;
<add>use Cake\ORM\Query;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public function testFormatDeepDistantAssociationRecords2()
<ide> $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
<ide> $this->assertEquals($expected, $query->toArray());
<ide> }
<add>
<add> /**
<add> * Tests that subqueries can be used with function expressions.
<add> *
<add> * @return void
<add> */
<add> public function testFunctionExpressionWithSubquery()
<add> {
<add> $this->loadFixtures('Articles');
<add> $table = $this->getTableLocator()->get('Articles');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->ABS([
<add> $table
<add> ->getConnection()
<add> ->newQuery()
<add> ->select(-1),
<add> ])
<add> ];
<add> });
<add>
<add> $result = $query->first()->get('value');
<add> $this->assertEquals(1, $result);
<add> }
<add>
<add> /**
<add> * Tests that correlated subqueries can be used with function expressions.
<add> *
<add> * @return void
<add> */
<add> public function testFunctionExpressionWithCorrelatedSubquery()
<add> {
<add> $this->loadFixtures('Articles', 'Authors');
<add> $table = $this->getTableLocator()->get('Articles');
<add> $table->belongsTo('Authors');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->UPPER([
<add> $table
<add> ->getAssociation('Authors')
<add> ->find()
<add> ->select(['Authors.name'])
<add> ->where(function (QueryExpression $exp) {
<add> return $exp->equalFields('Authors.id', 'Articles.author_id');
<add> })
<add> ])
<add> ];
<add> });
<add>
<add> $result = $query->first()->get('value');
<add> $this->assertEquals('MARIANO', $result);
<add> }
<add>
<add> /**
<add> * Tests that subqueries can be used with multi argument function expressions.
<add> *
<add> * @return void
<add> */
<add> public function testMultiArgumentFunctionExpressionWithSubquery()
<add> {
<add> $this->loadFixtures('Articles', 'Authors');
<add> $table = $this->getTableLocator()->get('Articles');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->ROUND(
<add> [
<add> $table
<add> ->getConnection()
<add> ->newQuery()
<add> ->select(1.23456),
<add> 2
<add> ],
<add> [null, 'integer']
<add> )
<add> ];
<add> });
<add>
<add> $result = $query->first()->get('value');
<add> $this->assertEquals('1.23', $result);
<add> }
<add>
<add> /**
<add> * Tests that correlated subqueries can be used with multi argument function expressions.
<add> *
<add> * @return void
<add> */
<add> public function testMultiArgumentFunctionExpressionWithCorrelatedSubquery()
<add> {
<add> $this->loadFixtures('Articles', 'Authors');
<add> $table = $this->getTableLocator()->get('Articles');
<add> $table->belongsTo('Authors');
<add>
<add> $this->assertEquals(
<add> 1,
<add> $table->getAssociation('Authors')->updateAll(['name' => null], ['id' => 3])
<add> );
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->coalesce([
<add> $table
<add> ->getAssociation('Authors')
<add> ->find()
<add> ->select(['Authors.name'])
<add> ->where(function (QueryExpression $exp) {
<add> return $exp->equalFields('Authors.id', 'Articles.author_id');
<add> }),
<add> 1
<add> ])
<add> ];
<add> });
<add>
<add> $results = $query->extract('value')->toArray();
<add> $this->assertEquals(['mariano', '1', 'mariano'], $results);
<add> }
<add>
<add> /**
<add> * Tests that subqueries can be used with function expressions that are being transpiled.
<add> *
<add> * @return void
<add> */
<add> public function testTranspiledFunctionExpressionWithSubquery()
<add> {
<add> $this->loadFixtures('Articles', 'Authors');
<add> $table = $this->getTableLocator()->get('Articles');
<add> $table->belongsTo('Authors');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->concat([
<add> $table
<add> ->getAssociation('Authors')
<add> ->find()
<add> ->select(['Authors.name'])
<add> ->where(['Authors.id' => 1]),
<add> ' appended'
<add> ])
<add> ];
<add> });
<add>
<add> $result = $query->first()->get('value');
<add> $this->assertEquals('mariano appended', $result);
<add> }
<add>
<add> /**
<add> * Tests that correlated subqueries can be used with function expressions that are being transpiled.
<add> *
<add> * @return void
<add> */
<add> public function testTranspiledFunctionExpressionWithCorrelatedSubquery()
<add> {
<add> $this->loadFixtures('Articles', 'Authors');
<add> $table = $this->getTableLocator()->get('Articles');
<add> $table->belongsTo('Authors');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(function (Query $q) use ($table) {
<add> return [
<add> 'value' => $q->func()->concat([
<add> $table
<add> ->getAssociation('Authors')
<add> ->find()
<add> ->select(['Authors.name'])
<add> ->where(function (QueryExpression $exp) {
<add> return $exp->equalFields('Authors.id', 'Articles.author_id');
<add> }),
<add> ' appended'
<add> ])
<add> ];
<add> });
<add>
<add> $result = $query->first()->get('value');
<add> $this->assertEquals('mariano appended', $result);
<add> }
<ide> } | 1 |
Python | Python | add gpt2-xl for tf | ab756f713c7dd5257e27bb74edd906dfdfbf0e5d | <ide><path>src/transformers/modeling_tf_gpt2.py
<ide> "gpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-tf_model.h5",
<ide> "gpt2-medium": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-tf_model.h5",
<ide> "gpt2-large": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-tf_model.h5",
<add> "gpt2-xl": "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-xl-tf_model.h5",
<ide> "distilgpt2": "https://s3.amazonaws.com/models.huggingface.co/bert/distilgpt2-tf_model.h5",
<ide> }
<ide> | 1 |
Python | Python | remove outdated arg from train | 3f0d61232dbc8b45845463b27d766cdbb813af5e | <ide><path>spacy/cli/train.py
<ide> def train_cli(
<ide> def init_pipeline(
<ide> config: Config, output_path: Optional[Path], *, use_gpu: int = -1
<ide> ) -> Language:
<del> init_kwargs = {"use_gpu": use_gpu, "silent": False}
<add> init_kwargs = {"use_gpu": use_gpu}
<ide> if output_path is not None:
<ide> init_path = output_path / "model-initial"
<ide> if not init_path.exists(): | 1 |
Text | Text | fix url for tip about database permission problems | 5cd84c96aa63f2f69b496fa036a94879cb715aa3 | <ide><path>guides/source/testing.md
<ide> default. Loading involves three steps:
<ide> 2. Load the fixture data into the table
<ide> 3. Dump the fixture data into a method in case you want to access it directly
<ide>
<del>TIP: In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions [here](http://blog.endpoint.com/2012/10/postgres-system-triggers-error.html)).
<add>TIP: In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions [here](https://www.postgresql.org/docs/current/sql-altertable.html)).
<ide>
<ide> #### Fixtures are Active Record Objects
<ide> | 1 |
Javascript | Javascript | relativize ignore module paths | a4cf604a4aa2d14f95895d8c3337a722712740de | <ide><path>lib/NormalModuleFactory.js
<ide> Author Tobias Koppers @sokra
<ide> */
<ide> var async = require("async");
<add>var path = require("path");
<ide> var Tapable = require("tapable");
<ide> var NormalModule = require("./NormalModule");
<ide> var RawModule = require("./RawModule");
<ide> function NormalModuleFactory(context, resolvers, options) {
<ide> if(resource === false)
<ide> return callback(null,
<ide> new RawModule("/* (ignored) */",
<del> "ignored " + context + " " + request,
<add> "ignored " + path.resolve(__dirname, context) + " " + request,
<ide> request + " (ignored)")); // ignored
<ide>
<ide> var userRequest = loaders.map(loaderToIdent).concat([resource]).join("!"); | 1 |
Python | Python | add logging options to docker operator | 19d6f54704949d017b028e644bbcf45f5b53120b | <ide><path>airflow/providers/docker/operators/docker.py
<ide> from docker import APIClient, tls # type: ignore[attr-defined]
<ide> from docker.constants import DEFAULT_TIMEOUT_SECONDS # type: ignore[attr-defined]
<ide> from docker.errors import APIError # type: ignore[attr-defined]
<del>from docker.types import DeviceRequest, Mount # type: ignore[attr-defined]
<add>from docker.types import DeviceRequest, LogConfig, Mount # type: ignore[attr-defined]
<ide>
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.models import BaseOperator
<ide> class DockerOperator(BaseOperator):
<ide> output that is not posted to logs
<ide> :param retrieve_output_path: path for output file that will be retrieved and passed to xcom
<ide> :param device_requests: Expose host resources such as GPUs to the container.
<add> :param log_opts_max_size: The maximum size of the log before it is rolled.
<add> A positive integer plus a modifier representing the unit of measure (k, m, or g).
<add> Eg: 10m or 1g Defaults to -1 (unlimited).
<add> :param log_opts_max_file: The maximum number of log files that can be present.
<add> If rolling the logs creates excess files, the oldest file is removed.
<add> Only effective when max-size is also set. A positive integer. Defaults to 1.
<ide> """
<ide>
<ide> template_fields: Sequence[str] = ('image', 'command', 'environment', 'container_name')
<ide> def __init__(
<ide> retrieve_output_path: str | None = None,
<ide> timeout: int = DEFAULT_TIMEOUT_SECONDS,
<ide> device_requests: list[DeviceRequest] | None = None,
<add> log_opts_max_size: str | None = None,
<add> log_opts_max_file: str | None = None,
<ide> **kwargs,
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide> def __init__(
<ide> self.retrieve_output_path = retrieve_output_path
<ide> self.timeout = timeout
<ide> self.device_requests = device_requests
<add> self.log_opts_max_size = log_opts_max_size
<add> self.log_opts_max_file = log_opts_max_file
<ide>
<ide> def get_hook(self) -> DockerHook:
<ide> """
<ide> def _run_image_with_mounts(self, target_mounts, add_tmp_variable: bool) -> list[
<ide> self.environment.pop('AIRFLOW_TMP_DIR', None)
<ide> if not self.cli:
<ide> raise Exception("The 'cli' should be initialized before!")
<add> docker_log_config = {}
<add> if self.log_opts_max_size is not None:
<add> docker_log_config['max-size'] = self.log_opts_max_size
<add> if self.log_opts_max_file is not None:
<add> docker_log_config['max-file'] = self.log_opts_max_file
<ide> self.container = self.cli.create_container(
<ide> command=self.format_command(self.command),
<ide> name=self.container_name,
<ide> def _run_image_with_mounts(self, target_mounts, add_tmp_variable: bool) -> list[
<ide> extra_hosts=self.extra_hosts,
<ide> privileged=self.privileged,
<ide> device_requests=self.device_requests,
<add> log_config=LogConfig(config=docker_log_config),
<ide> ),
<ide> image=self.image,
<ide> user=self.user,
<ide><path>tests/providers/docker/operators/test_docker.py
<ide>
<ide> try:
<ide> from docker import APIClient
<del> from docker.types import DeviceRequest, Mount
<add> from docker.types import DeviceRequest, LogConfig, Mount
<ide>
<ide> from airflow.providers.docker.hooks.docker import DockerHook
<ide> from airflow.providers.docker.operators.docker import DockerOperator
<ide> def test_execute(self):
<ide> container_name='test_container',
<ide> tty=True,
<ide> device_requests=[DeviceRequest(count=-1, capabilities=[['gpu']])],
<add> log_opts_max_file='5',
<add> log_opts_max_size='10m',
<ide> )
<ide> operator.execute(None)
<ide>
<ide> def test_execute(self):
<ide> extra_hosts=None,
<ide> privileged=False,
<ide> device_requests=[DeviceRequest(count=-1, capabilities=[['gpu']])],
<add> log_config=LogConfig(config={'max-size': '10m', 'max-file': '5'}),
<ide> )
<ide> self.tempdir_mock.assert_called_once_with(dir='/host/airflow', prefix='airflowtmp')
<ide> self.client_mock.images.assert_called_once_with(name='ubuntu:latest')
<ide> def test_execute_no_temp_dir(self):
<ide> extra_hosts=None,
<ide> privileged=False,
<ide> device_requests=None,
<add> log_config=LogConfig(config={}),
<ide> )
<ide> self.tempdir_mock.assert_not_called()
<ide> self.client_mock.images.assert_called_once_with(name='ubuntu:latest')
<ide> def test_execute_fallback_temp_dir(self):
<ide> extra_hosts=None,
<ide> privileged=False,
<ide> device_requests=None,
<add> log_config=LogConfig(config={}),
<ide> ),
<ide> call(
<ide> mounts=[
<ide> def test_execute_fallback_temp_dir(self):
<ide> extra_hosts=None,
<ide> privileged=False,
<ide> device_requests=None,
<add> log_config=LogConfig(config={}),
<ide> ),
<ide> ]
<ide> ) | 2 |
Go | Go | fix concurrent createnetwork in bridge driver | 7d466c6600fbe07636e763799d0d806ce35a90a2 | <ide><path>libnetwork/drivers/bridge/bridge.go
<ide> const (
<ide> DefaultGatewayV6AuxKey = "DefaultGatewayIPv6"
<ide> )
<ide>
<add>type defaultBridgeNetworkConflict struct {
<add> ID string
<add>}
<add>
<add>func (d defaultBridgeNetworkConflict) Error() string {
<add> return fmt.Sprintf("Stale default bridge network %s", d.ID)
<add>}
<add>
<ide> type iptableCleanFunc func() error
<ide> type iptablesCleanFuncs []iptableCleanFunc
<ide>
<ide> type driver struct {
<ide> networks map[string]*bridgeNetwork
<ide> store datastore.DataStore
<ide> nlh *netlink.Handle
<add> configNetwork sync.Mutex
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) err
<ide> return nil
<ide> }
<ide>
<del>// Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
<del>func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
<del> for _, nw := range others {
<del>
<del> nw.Lock()
<del> nwID := nw.id
<del> nwConfig := nw.config
<del> nwBridge := nw.bridge
<del> nw.Unlock()
<del>
<del> if nwID == id {
<del> continue
<del> }
<del> // Verify the name (which may have been set by newInterface()) does not conflict with
<del> // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
<del> // Basically we are checking if the two original configs were both empty.
<del> if nwConfig.BridgeName == c.BridgeName {
<del> return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
<del> }
<del> // If this network config specifies the AddressIPv4, we need
<del> // to make sure it does not conflict with any previously allocated
<del> // bridges. This could not be completely caught by the config conflict
<del> // check, because networks which config does not specify the AddressIPv4
<del> // get their address and subnet selected by the driver (see electBridgeIPv4())
<del> if c.AddressIPv4 != nil && nwBridge.bridgeIPv4 != nil {
<del> if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
<del> c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
<del> return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
<del> }
<del> }
<del> }
<del>
<del> return nil
<del>}
<del>
<ide> func (d *driver) configure(option map[string]interface{}) error {
<ide> var (
<ide> config *configuration
<ide> func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo d
<ide> return err
<ide> }
<ide>
<del> err = config.processIPAM(id, ipV4Data, ipV6Data)
<del> if err != nil {
<add> if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil {
<ide> return err
<ide> }
<ide>
<add> // start the critical section, from this point onward we are dealing with the list of networks
<add> // so to be consistent we cannot allow that the list changes
<add> d.configNetwork.Lock()
<add> defer d.configNetwork.Unlock()
<add>
<add> // check network conflicts
<add> if err = d.checkConflict(config); err != nil {
<add> nerr, ok := err.(defaultBridgeNetworkConflict)
<add> if !ok {
<add> return err
<add> }
<add> // Got a conflict with a stale default network, clean that up and continue
<add> logrus.Warn(nerr)
<add> d.deleteNetwork(nerr.ID)
<add> }
<add>
<add> // there is no conflict, now create the network
<ide> if err = d.createNetwork(config); err != nil {
<ide> return err
<ide> }
<ide>
<ide> return d.storeUpdate(config)
<ide> }
<ide>
<del>func (d *driver) createNetwork(config *networkConfiguration) error {
<del> var err error
<del>
<del> defer osl.InitOSContext()()
<del>
<add>func (d *driver) checkConflict(config *networkConfiguration) error {
<ide> networkList := d.getNetworks()
<del> for i, nw := range networkList {
<add> for _, nw := range networkList {
<ide> nw.Lock()
<ide> nwConfig := nw.config
<ide> nw.Unlock()
<ide> if err := nwConfig.Conflicts(config); err != nil {
<ide> if config.DefaultBridge {
<ide> // We encountered and identified a stale default network
<del> // We must delete it as libnetwork is the source of thruth
<add> // We must delete it as libnetwork is the source of truth
<ide> // The default network being created must be the only one
<ide> // This can happen only from docker 1.12 on ward
<del> logrus.Infof("Removing stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
<del> if err := d.DeleteNetwork(nwConfig.ID); err != nil {
<del> logrus.Warnf("Failed to remove stale default network: %s (%s): %v. Will remove from store.", nwConfig.ID, nwConfig.BridgeName, err)
<del> d.storeDelete(nwConfig)
<del> }
<del> networkList = append(networkList[:i], networkList[i+1:]...)
<del> } else {
<del> return types.ForbiddenErrorf("cannot create network %s (%s): conflicts with network %s (%s): %s",
<del> config.ID, config.BridgeName, nwConfig.ID, nwConfig.BridgeName, err.Error())
<add> logrus.Infof("Found stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
<add> return defaultBridgeNetworkConflict{nwConfig.ID}
<ide> }
<add>
<add> return types.ForbiddenErrorf("cannot create network %s (%s): conflicts with network %s (%s): %s",
<add> config.ID, config.BridgeName, nwConfig.ID, nwConfig.BridgeName, err.Error())
<ide> }
<ide> }
<add> return nil
<add>}
<add>
<add>func (d *driver) createNetwork(config *networkConfiguration) error {
<add> var err error
<add>
<add> defer osl.InitOSContext()()
<add>
<add> networkList := d.getNetworks()
<add>
<add> // Initialize handle when needed
<add> d.Lock()
<add> if d.nlh == nil {
<add> d.nlh = ns.NlHandle()
<add> }
<add> d.Unlock()
<add>
<add> // Create or retrieve the bridge L3 interface
<add> bridgeIface, err := newInterface(d.nlh, config)
<add> if err != nil {
<add> return err
<add> }
<ide>
<ide> // Create and set network handler in driver
<ide> network := &bridgeNetwork{
<ide> id: config.ID,
<ide> endpoints: make(map[string]*bridgeEndpoint),
<ide> config: config,
<ide> portMapper: portmapper.New(d.config.UserlandProxyPath),
<add> bridge: bridgeIface,
<ide> driver: d,
<ide> }
<ide>
<ide> func (d *driver) createNetwork(config *networkConfiguration) error {
<ide> }
<ide> }()
<ide>
<del> // Initialize handle when needed
<del> d.Lock()
<del> if d.nlh == nil {
<del> d.nlh = ns.NlHandle()
<del> }
<del> d.Unlock()
<del>
<del> // Create or retrieve the bridge L3 interface
<del> bridgeIface, err := newInterface(d.nlh, config)
<del> if err != nil {
<del> return err
<del> }
<del> network.bridge = bridgeIface
<del>
<del> // Verify the network configuration does not conflict with previously installed
<del> // networks. This step is needed now because driver might have now set the bridge
<del> // name on this config struct. And because we need to check for possible address
<del> // conflicts, so we need to check against operationa lnetworks.
<del> if err = config.conflictsWithNetworks(config.ID, networkList); err != nil {
<del> return err
<del> }
<del>
<add> // Add inter-network communication rules.
<ide> setupNetworkIsolationRules := func(config *networkConfiguration, i *bridgeInterface) error {
<ide> if err := network.isolateNetwork(networkList, true); err != nil {
<del> if err := network.isolateNetwork(networkList, false); err != nil {
<add> if err = network.isolateNetwork(networkList, false); err != nil {
<ide> logrus.Warnf("Failed on removing the inter-network iptables rules on cleanup: %v", err)
<ide> }
<ide> return err
<ide> }
<add> // register the cleanup function
<ide> network.registerIptCleanFunc(func() error {
<ide> nwList := d.getNetworks()
<ide> return network.isolateNetwork(nwList, false)
<ide> func (d *driver) createNetwork(config *networkConfiguration) error {
<ide>
<ide> // Apply the prepared list of steps, and abort at the first error.
<ide> bridgeSetup.queueStep(setupDeviceUp)
<del> if err = bridgeSetup.apply(); err != nil {
<del> return err
<del> }
<del>
<del> return nil
<add> return bridgeSetup.apply()
<ide> }
<ide>
<ide> func (d *driver) DeleteNetwork(nid string) error {
<add>
<add> d.configNetwork.Lock()
<add> defer d.configNetwork.Unlock()
<add>
<add> return d.deleteNetwork(nid)
<add>}
<add>
<add>func (d *driver) deleteNetwork(nid string) error {
<ide> var err error
<ide>
<ide> defer osl.InitOSContext()()
<del>
<ide> // Get network handler and remove it from driver
<ide> d.Lock()
<ide> n, ok := d.networks[nid]
<ide> func (d *driver) DeleteNetwork(nid string) error {
<ide> }
<ide> }()
<ide>
<del> // Sanity check
<del> if n == nil {
<del> err = driverapi.ErrNoNetwork(nid)
<del> return err
<del> }
<del>
<ide> switch config.BridgeIfaceCreator {
<ide> case ifaceCreatedByLibnetwork, ifaceCreatorUnknown:
<ide> // We only delete the bridge if it was created by the bridge driver and
<ide><path>libnetwork/drivers/bridge/bridge_test.go
<ide> import (
<ide> "fmt"
<ide> "net"
<ide> "regexp"
<add> "strconv"
<ide> "testing"
<ide>
<ide> "github.com/docker/libnetwork/driverapi"
<ide> func TestCreateWithExistingBridge(t *testing.T) {
<ide> t.Fatal("Deleting bridge network that using existing bridge interface unexpectedly deleted the bridge interface")
<ide> }
<ide> }
<add>
<add>func TestCreateParallel(t *testing.T) {
<add> if !testutils.IsRunningInContainer() {
<add> defer testutils.SetupTestOSContext(t)()
<add> }
<add>
<add> d := newDriver()
<add>
<add> if err := d.configure(nil); err != nil {
<add> t.Fatalf("Failed to setup driver config: %v", err)
<add> }
<add>
<add> ch := make(chan error, 100)
<add> for i := 0; i < 100; i++ {
<add> go func(name string, ch chan<- error) {
<add> config := &networkConfiguration{BridgeName: name}
<add> genericOption := make(map[string]interface{})
<add> genericOption[netlabel.GenericData] = config
<add> if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err != nil {
<add> ch <- fmt.Errorf("failed to create %s", name)
<add> return
<add> }
<add> if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err == nil {
<add> ch <- fmt.Errorf("failed was able to create overlap %s", name)
<add> return
<add> }
<add> ch <- nil
<add> }("net"+strconv.Itoa(i), ch)
<add> }
<add> // wait for the go routines
<add> var success int
<add> for i := 0; i < 100; i++ {
<add> val := <-ch
<add> if val == nil {
<add> success++
<add> }
<add> }
<add> if success != 1 {
<add> t.Fatalf("Success should be 1 instead: %d", success)
<add> }
<add>}
<ide><path>libnetwork/drivers/bridge/setup_firewalld.go
<ide> func (n *bridgeNetwork) setupFirewalld(config *networkConfiguration, i *bridgeIn
<ide> d.Unlock()
<ide>
<ide> // Sanity check.
<del> if driverConfig.EnableIPTables == false {
<add> if !driverConfig.EnableIPTables {
<ide> return IPTableCfgError(config.BridgeName)
<ide> }
<ide> | 3 |
PHP | PHP | add displayable value to required_unless | 39cbd0066c3382fca83a06c34c213266cfe34e35 | <ide><path>src/Illuminate/Validation/Concerns/ReplacesAttributes.php
<ide> protected function replaceRequiredIf($message, $attribute, $rule, $parameters)
<ide> */
<ide> protected function replaceRequiredUnless($message, $attribute, $rule, $parameters)
<ide> {
<del> $other = $this->getDisplayableAttribute(array_shift($parameters));
<add> $other = $this->getDisplayableAttribute($parameters[0]);
<ide>
<del> return str_replace([':other', ':values'], [$other, implode(', ', $parameters)], $message);
<add> $values = [];
<add> foreach (array_slice($parameters, 1) as $value) {
<add> $values[] = $this->getDisplayableValue($parameters[0], $value);
<add> }
<add>
<add> return str_replace([':other', ':values'], [$other, implode(', ', $values)], $message);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testDisplayableValuesAreReplaced()
<ide> $v->messages()->setFormat(':message');
<ide> $this->assertEquals('The bar field is required when color is red.', $v->messages()->first('bar'));
<ide>
<add> //required_unless:foo,bar
<add> $trans = $this->getIlluminateArrayTranslator();
<add> $trans->addLines(['validation.required_unless' => 'The :attribute field is required unless :other is in :values.'], 'en');
<add> $trans->addLines(['validation.values.color.1' => 'red'], 'en');
<add> $v = new Validator($trans, ['color' => '2', 'bar' => ''], ['bar' => 'RequiredUnless:color,1']);
<add> $this->assertFalse($v->passes());
<add> $v->messages()->setFormat(':message');
<add> $this->assertEquals('The bar field is required unless color is in red.', $v->messages()->first('bar'));
<add>
<ide> //in:foo,bar,...
<ide> $trans = $this->getIlluminateArrayTranslator();
<ide> $trans->addLines(['validation.in' => ':attribute must be included in :values.'], 'en'); | 2 |
Javascript | Javascript | fix src/locale (missing local variables) | ae32797f323b2bb331c0b770d1ab94c84424605d | <ide><path>src/locale/ar-sa.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '١',
<add> '2': '٢',
<add> '3': '٣',
<add> '4': '٤',
<add> '5': '٥',
<add> '6': '٦',
<add> '7': '٧',
<add> '8': '٨',
<add> '9': '٩',
<add> '0': '٠'
<add>}, numberMap = {
<add> '١': '1',
<add> '٢': '2',
<add> '٣': '3',
<add> '٤': '4',
<add> '٥': '5',
<add> '٦': '6',
<add> '٧': '7',
<add> '٨': '8',
<add> '٩': '9',
<add> '٠': '0'
<add>};
<add>
<ide> export default moment.defineLocale('ar-sa', {
<ide> months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
<ide> monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
<ide><path>src/locale/ar.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '١',
<add> '2': '٢',
<add> '3': '٣',
<add> '4': '٤',
<add> '5': '٥',
<add> '6': '٦',
<add> '7': '٧',
<add> '8': '٨',
<add> '9': '٩',
<add> '0': '٠'
<add>}, numberMap = {
<add> '١': '1',
<add> '٢': '2',
<add> '٣': '3',
<add> '٤': '4',
<add> '٥': '5',
<add> '٦': '6',
<add> '٧': '7',
<add> '٨': '8',
<add> '٩': '9',
<add> '٠': '0'
<add>}, pluralForm = function (n) {
<add> return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
<add>}, plurals = {
<add> s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
<add> m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
<add> h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
<add> d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
<add> M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
<add> y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
<add>}, pluralize = function (u) {
<add> return function (number, withoutSuffix, string, isFuture) {
<add> var f = pluralForm(number),
<add> str = plurals[u][pluralForm(number)];
<add> if (f === 2) {
<add> str = str[withoutSuffix ? 0 : 1];
<add> }
<add> return str.replace(/%d/i, number);
<add> };
<add>}, months = [
<add> 'كانون الثاني يناير',
<add> 'شباط فبراير',
<add> 'آذار مارس',
<add> 'نيسان أبريل',
<add> 'أيار مايو',
<add> 'حزيران يونيو',
<add> 'تموز يوليو',
<add> 'آب أغسطس',
<add> 'أيلول سبتمبر',
<add> 'تشرين الأول أكتوبر',
<add> 'تشرين الثاني نوفمبر',
<add> 'كانون الأول ديسمبر'
<add>];
<add>
<ide> export default moment.defineLocale('ar', {
<ide> months : months,
<ide> monthsShort : months,
<ide><path>src/locale/az.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var suffixes = {
<add> 1: '-inci',
<add> 5: '-inci',
<add> 8: '-inci',
<add> 70: '-inci',
<add> 80: '-inci',
<add> 2: '-nci',
<add> 7: '-nci',
<add> 20: '-nci',
<add> 50: '-nci',
<add> 3: '-üncü',
<add> 4: '-üncü',
<add> 100: '-üncü',
<add> 6: '-ncı',
<add> 9: '-uncu',
<add> 10: '-uncu',
<add> 30: '-uncu',
<add> 60: '-ıncı',
<add> 90: '-ıncı'
<add>};
<add>
<ide> export default moment.defineLocale('az', {
<ide> months : 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'),
<ide> monthsShort : 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),
<ide><path>src/locale/be.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function plural(word, num) {
<add> var forms = word.split('_');
<add> return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
<add>}
<add>function relativeTimeWithPlural(number, withoutSuffix, key) {
<add> var format = {
<add> 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',
<add> 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',
<add> 'dd': 'дзень_дні_дзён',
<add> 'MM': 'месяц_месяцы_месяцаў',
<add> 'yy': 'год_гады_гадоў'
<add> };
<add> if (key === 'm') {
<add> return withoutSuffix ? 'хвіліна' : 'хвіліну';
<add> }
<add> else if (key === 'h') {
<add> return withoutSuffix ? 'гадзіна' : 'гадзіну';
<add> }
<add> else {
<add> return number + ' ' + plural(format[key], +number);
<add> }
<add>}
<add>function monthsCaseReplace(m, format) {
<add> var months = {
<add> 'nominative': 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_'),
<add> 'accusative': 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_')
<add> },
<add> nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return months[nounCase][m.month()];
<add>}
<add>function weekdaysCaseReplace(m, format) {
<add> var weekdays = {
<add> 'nominative': 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),
<add> 'accusative': 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_')
<add> },
<add> nounCase = (/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return weekdays[nounCase][m.day()];
<add>}
<add>
<ide> export default moment.defineLocale('be', {
<ide> months : monthsCaseReplace,
<ide> monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),
<ide><path>src/locale/bn.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '১',
<add> '2': '২',
<add> '3': '৩',
<add> '4': '৪',
<add> '5': '৫',
<add> '6': '৬',
<add> '7': '৭',
<add> '8': '৮',
<add> '9': '৯',
<add> '0': '০'
<add>},
<add>numberMap = {
<add> '১': '1',
<add> '২': '2',
<add> '৩': '3',
<add> '৪': '4',
<add> '৫': '5',
<add> '৬': '6',
<add> '৭': '7',
<add> '৮': '8',
<add> '৯': '9',
<add> '০': '0'
<add>};
<add>
<ide> export default moment.defineLocale('bn', {
<ide> months : 'জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
<ide> monthsShort : 'জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্'.split('_'),
<ide><path>src/locale/bo.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '༡',
<add> '2': '༢',
<add> '3': '༣',
<add> '4': '༤',
<add> '5': '༥',
<add> '6': '༦',
<add> '7': '༧',
<add> '8': '༨',
<add> '9': '༩',
<add> '0': '༠'
<add>},
<add>numberMap = {
<add> '༡': '1',
<add> '༢': '2',
<add> '༣': '3',
<add> '༤': '4',
<add> '༥': '5',
<add> '༦': '6',
<add> '༧': '7',
<add> '༨': '8',
<add> '༩': '9',
<add> '༠': '0'
<add>};
<add>
<ide> export default moment.defineLocale('bo', {
<ide> months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
<ide> monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
<ide><path>src/locale/br.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function relativeTimeWithMutation(number, withoutSuffix, key) {
<add> var format = {
<add> 'mm': 'munutenn',
<add> 'MM': 'miz',
<add> 'dd': 'devezh'
<add> };
<add> return number + ' ' + mutation(format[key], number);
<add>}
<add>function specialMutationForYears(number) {
<add> switch (lastNumber(number)) {
<add> case 1:
<add> case 3:
<add> case 4:
<add> case 5:
<add> case 9:
<add> return number + ' bloaz';
<add> default:
<add> return number + ' vloaz';
<add> }
<add>}
<add>function lastNumber(number) {
<add> if (number > 9) {
<add> return lastNumber(number % 10);
<add> }
<add> return number;
<add>}
<add>function mutation(text, number) {
<add> if (number === 2) {
<add> return softMutation(text);
<add> }
<add> return text;
<add>}
<add>function softMutation(text) {
<add> var mutationTable = {
<add> 'm': 'v',
<add> 'b': 'v',
<add> 'd': 'z'
<add> };
<add> if (mutationTable[text.charAt(0)] === undefined) {
<add> return text;
<add> }
<add> return mutationTable[text.charAt(0)] + text.substring(1);
<add>}
<add>
<ide> export default moment.defineLocale('br', {
<ide> months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),
<ide> monthsShort : 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),
<ide><path>src/locale/bs.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function translate(number, withoutSuffix, key) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 'm':
<add> return withoutSuffix ? 'jedna minuta' : 'jedne minute';
<add> case 'mm':
<add> if (number === 1) {
<add> result += 'minuta';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'minute';
<add> } else {
<add> result += 'minuta';
<add> }
<add> return result;
<add> case 'h':
<add> return withoutSuffix ? 'jedan sat' : 'jednog sata';
<add> case 'hh':
<add> if (number === 1) {
<add> result += 'sat';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'sata';
<add> } else {
<add> result += 'sati';
<add> }
<add> return result;
<add> case 'dd':
<add> if (number === 1) {
<add> result += 'dan';
<add> } else {
<add> result += 'dana';
<add> }
<add> return result;
<add> case 'MM':
<add> if (number === 1) {
<add> result += 'mjesec';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'mjeseca';
<add> } else {
<add> result += 'mjeseci';
<add> }
<add> return result;
<add> case 'yy':
<add> if (number === 1) {
<add> result += 'godina';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'godine';
<add> } else {
<add> result += 'godina';
<add> }
<add> return result;
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('bs', {
<ide> months : 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),
<ide> monthsShort : 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),
<ide><path>src/locale/cs.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
<add> monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_');
<add>function plural(n) {
<add> return (n > 1) && (n < 5) && (~~(n / 10) !== 1);
<add>}
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 's': // a few seconds / in a few seconds / a few seconds ago
<add> return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami';
<add> case 'm': // a minute / in a minute / a minute ago
<add> return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou');
<add> case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'minuty' : 'minut');
<add> } else {
<add> return result + 'minutami';
<add> }
<add> break;
<add> case 'h': // an hour / in an hour / an hour ago
<add> return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
<add> case 'hh': // 9 hours / in 9 hours / 9 hours ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'hodiny' : 'hodin');
<add> } else {
<add> return result + 'hodinami';
<add> }
<add> break;
<add> case 'd': // a day / in a day / a day ago
<add> return (withoutSuffix || isFuture) ? 'den' : 'dnem';
<add> case 'dd': // 9 days / in 9 days / 9 days ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'dny' : 'dní');
<add> } else {
<add> return result + 'dny';
<add> }
<add> break;
<add> case 'M': // a month / in a month / a month ago
<add> return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem';
<add> case 'MM': // 9 months / in 9 months / 9 months ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'měsíce' : 'měsíců');
<add> } else {
<add> return result + 'měsíci';
<add> }
<add> break;
<add> case 'y': // a year / in a year / a year ago
<add> return (withoutSuffix || isFuture) ? 'rok' : 'rokem';
<add> case 'yy': // 9 years / in 9 years / 9 years ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'roky' : 'let');
<add> } else {
<add> return result + 'lety';
<add> }
<add> break;
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('cs', {
<ide> months : months,
<ide> monthsShort : monthsShort,
<ide><path>src/locale/de-at.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function processRelativeTime(number, withoutSuffix, key, isFuture) {
<add> var format = {
<add> 'm': ['eine Minute', 'einer Minute'],
<add> 'h': ['eine Stunde', 'einer Stunde'],
<add> 'd': ['ein Tag', 'einem Tag'],
<add> 'dd': [number + ' Tage', number + ' Tagen'],
<add> 'M': ['ein Monat', 'einem Monat'],
<add> 'MM': [number + ' Monate', number + ' Monaten'],
<add> 'y': ['ein Jahr', 'einem Jahr'],
<add> 'yy': [number + ' Jahre', number + ' Jahren']
<add> };
<add> return withoutSuffix ? format[key][0] : format[key][1];
<add>}
<add>
<ide> export default moment.defineLocale('de-at', {
<ide> months : 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
<ide> monthsShort : 'Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
<ide><path>src/locale/de.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function processRelativeTime(number, withoutSuffix, key, isFuture) {
<add> var format = {
<add> 'm': ['eine Minute', 'einer Minute'],
<add> 'h': ['eine Stunde', 'einer Stunde'],
<add> 'd': ['ein Tag', 'einem Tag'],
<add> 'dd': [number + ' Tage', number + ' Tagen'],
<add> 'M': ['ein Monat', 'einem Monat'],
<add> 'MM': [number + ' Monate', number + ' Monaten'],
<add> 'y': ['ein Jahr', 'einem Jahr'],
<add> 'yy': [number + ' Jahre', number + ' Jahren']
<add> };
<add> return withoutSuffix ? format[key][0] : format[key][1];
<add>}
<add>
<ide> export default moment.defineLocale('de', {
<ide> months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
<ide> monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
<ide><path>src/locale/es.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
<add> monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');
<add>
<ide> export default moment.defineLocale('es', {
<ide> months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
<ide> monthsShort : function (m, format) {
<ide><path>src/locale/et.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function processRelativeTime(number, withoutSuffix, key, isFuture) {
<add> var format = {
<add> 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'],
<add> 'm' : ['ühe minuti', 'üks minut'],
<add> 'mm': [number + ' minuti', number + ' minutit'],
<add> 'h' : ['ühe tunni', 'tund aega', 'üks tund'],
<add> 'hh': [number + ' tunni', number + ' tundi'],
<add> 'd' : ['ühe päeva', 'üks päev'],
<add> 'M' : ['kuu aja', 'kuu aega', 'üks kuu'],
<add> 'MM': [number + ' kuu', number + ' kuud'],
<add> 'y' : ['ühe aasta', 'aasta', 'üks aasta'],
<add> 'yy': [number + ' aasta', number + ' aastat']
<add> };
<add> if (withoutSuffix) {
<add> return format[key][2] ? format[key][2] : format[key][1];
<add> }
<add> return isFuture ? format[key][0] : format[key][1];
<add>}
<add>
<ide> export default moment.defineLocale('et', {
<ide> months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),
<ide> monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),
<ide><path>src/locale/fa.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '۱',
<add> '2': '۲',
<add> '3': '۳',
<add> '4': '۴',
<add> '5': '۵',
<add> '6': '۶',
<add> '7': '۷',
<add> '8': '۸',
<add> '9': '۹',
<add> '0': '۰'
<add>}, numberMap = {
<add> '۱': '1',
<add> '۲': '2',
<add> '۳': '3',
<add> '۴': '4',
<add> '۵': '5',
<add> '۶': '6',
<add> '۷': '7',
<add> '۸': '8',
<add> '۹': '9',
<add> '۰': '0'
<add>};
<add>
<ide> export default moment.defineLocale('fa', {
<ide> months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
<ide> monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
<ide><path>src/locale/fi.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
<add> numbersFuture = [
<add> 'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden',
<add> numbersPast[7], numbersPast[8], numbersPast[9]
<add> ];
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var result = '';
<add> switch (key) {
<add> case 's':
<add> return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';
<add> case 'm':
<add> return isFuture ? 'minuutin' : 'minuutti';
<add> case 'mm':
<add> result = isFuture ? 'minuutin' : 'minuuttia';
<add> break;
<add> case 'h':
<add> return isFuture ? 'tunnin' : 'tunti';
<add> case 'hh':
<add> result = isFuture ? 'tunnin' : 'tuntia';
<add> break;
<add> case 'd':
<add> return isFuture ? 'päivän' : 'päivä';
<add> case 'dd':
<add> result = isFuture ? 'päivän' : 'päivää';
<add> break;
<add> case 'M':
<add> return isFuture ? 'kuukauden' : 'kuukausi';
<add> case 'MM':
<add> result = isFuture ? 'kuukauden' : 'kuukautta';
<add> break;
<add> case 'y':
<add> return isFuture ? 'vuoden' : 'vuosi';
<add> case 'yy':
<add> result = isFuture ? 'vuoden' : 'vuotta';
<add> break;
<add> }
<add> result = verbalNumber(number, isFuture) + ' ' + result;
<add> return result;
<add>}
<add>function verbalNumber(number, isFuture) {
<add> return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number;
<add>}
<add>
<ide> export default moment.defineLocale('fi', {
<ide> months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),
<ide> monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),
<ide><path>src/locale/fy.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),
<add> monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');
<add>
<ide> export default moment.defineLocale('fy', {
<ide> months : 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'),
<ide> monthsShort : function (m, format) {
<ide><path>src/locale/hi.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '१',
<add> '2': '२',
<add> '3': '३',
<add> '4': '४',
<add> '5': '५',
<add> '6': '६',
<add> '7': '७',
<add> '8': '८',
<add> '9': '९',
<add> '0': '०'
<add>},
<add>numberMap = {
<add> '१': '1',
<add> '२': '2',
<add> '३': '3',
<add> '४': '4',
<add> '५': '5',
<add> '६': '6',
<add> '७': '7',
<add> '८': '8',
<add> '९': '9',
<add> '०': '0'
<add>};
<add>
<ide> export default moment.defineLocale('hi', {
<ide> months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'),
<ide> monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),
<ide><path>src/locale/hr.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function translate(number, withoutSuffix, key) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 'm':
<add> return withoutSuffix ? 'jedna minuta' : 'jedne minute';
<add> case 'mm':
<add> if (number === 1) {
<add> result += 'minuta';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'minute';
<add> } else {
<add> result += 'minuta';
<add> }
<add> return result;
<add> case 'h':
<add> return withoutSuffix ? 'jedan sat' : 'jednog sata';
<add> case 'hh':
<add> if (number === 1) {
<add> result += 'sat';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'sata';
<add> } else {
<add> result += 'sati';
<add> }
<add> return result;
<add> case 'dd':
<add> if (number === 1) {
<add> result += 'dan';
<add> } else {
<add> result += 'dana';
<add> }
<add> return result;
<add> case 'MM':
<add> if (number === 1) {
<add> result += 'mjesec';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'mjeseca';
<add> } else {
<add> result += 'mjeseci';
<add> }
<add> return result;
<add> case 'yy':
<add> if (number === 1) {
<add> result += 'godina';
<add> } else if (number === 2 || number === 3 || number === 4) {
<add> result += 'godine';
<add> } else {
<add> result += 'godina';
<add> }
<add> return result;
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('hr', {
<ide> months : 'sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_'),
<ide> monthsShort : 'sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'),
<ide><path>src/locale/hu.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var num = number,
<add> suffix;
<add> switch (key) {
<add> case 's':
<add> return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce';
<add> case 'm':
<add> return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce');
<add> case 'mm':
<add> return num + (isFuture || withoutSuffix ? ' perc' : ' perce');
<add> case 'h':
<add> return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája');
<add> case 'hh':
<add> return num + (isFuture || withoutSuffix ? ' óra' : ' órája');
<add> case 'd':
<add> return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja');
<add> case 'dd':
<add> return num + (isFuture || withoutSuffix ? ' nap' : ' napja');
<add> case 'M':
<add> return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
<add> case 'MM':
<add> return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
<add> case 'y':
<add> return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve');
<add> case 'yy':
<add> return num + (isFuture || withoutSuffix ? ' év' : ' éve');
<add> }
<add> return '';
<add>}
<add>function week(isFuture) {
<add> return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]';
<add>}
<add>
<ide> export default moment.defineLocale('hu', {
<ide> months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'),
<ide> monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'),
<ide><path>src/locale/hy-am.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function monthsCaseReplace(m, format) {
<add> var months = {
<add> 'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'),
<add> 'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_')
<add> },
<add> nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return months[nounCase][m.month()];
<add>}
<add>function monthsShortCaseReplace(m, format) {
<add> var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_');
<add> return monthsShort[m.month()];
<add>}
<add>function weekdaysCaseReplace(m, format) {
<add> var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_');
<add> return weekdays[m.day()];
<add>}
<add>
<ide> export default moment.defineLocale('hy-am', {
<ide> months : monthsCaseReplace,
<ide> monthsShort : monthsShortCaseReplace,
<ide><path>src/locale/is.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function plural(n) {
<add> if (n % 100 === 11) {
<add> return true;
<add> } else if (n % 10 === 1) {
<add> return false;
<add> }
<add> return true;
<add>}
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 's':
<add> return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum';
<add> case 'm':
<add> return withoutSuffix ? 'mínúta' : 'mínútu';
<add> case 'mm':
<add> if (plural(number)) {
<add> return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum');
<add> } else if (withoutSuffix) {
<add> return result + 'mínúta';
<add> }
<add> return result + 'mínútu';
<add> case 'hh':
<add> if (plural(number)) {
<add> return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum');
<add> }
<add> return result + 'klukkustund';
<add> case 'd':
<add> if (withoutSuffix) {
<add> return 'dagur';
<add> }
<add> return isFuture ? 'dag' : 'degi';
<add> case 'dd':
<add> if (plural(number)) {
<add> if (withoutSuffix) {
<add> return result + 'dagar';
<add> }
<add> return result + (isFuture ? 'daga' : 'dögum');
<add> } else if (withoutSuffix) {
<add> return result + 'dagur';
<add> }
<add> return result + (isFuture ? 'dag' : 'degi');
<add> case 'M':
<add> if (withoutSuffix) {
<add> return 'mánuður';
<add> }
<add> return isFuture ? 'mánuð' : 'mánuði';
<add> case 'MM':
<add> if (plural(number)) {
<add> if (withoutSuffix) {
<add> return result + 'mánuðir';
<add> }
<add> return result + (isFuture ? 'mánuði' : 'mánuðum');
<add> } else if (withoutSuffix) {
<add> return result + 'mánuður';
<add> }
<add> return result + (isFuture ? 'mánuð' : 'mánuði');
<add> case 'y':
<add> return withoutSuffix || isFuture ? 'ár' : 'ári';
<add> case 'yy':
<add> if (plural(number)) {
<add> return result + (withoutSuffix || isFuture ? 'ár' : 'árum');
<add> }
<add> return result + (withoutSuffix || isFuture ? 'ár' : 'ári');
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('is', {
<ide> months : 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'),
<ide> monthsShort : 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),
<ide><path>src/locale/ka.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function monthsCaseReplace(m, format) {
<add> var months = {
<add> 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'),
<add> 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_')
<add> },
<add> nounCase = (/D[oD] *MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return months[nounCase][m.month()];
<add>}
<add>function weekdaysCaseReplace(m, format) {
<add> var weekdays = {
<add> 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'),
<add> 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_')
<add> },
<add> nounCase = (/(წინა|შემდეგ)/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return weekdays[nounCase][m.day()];
<add>}
<add>
<ide> export default moment.defineLocale('ka', {
<ide> months : monthsCaseReplace,
<ide> monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),
<ide><path>src/locale/lb.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function processRelativeTime(number, withoutSuffix, key, isFuture) {
<add> var format = {
<add> 'm': ['eng Minutt', 'enger Minutt'],
<add> 'h': ['eng Stonn', 'enger Stonn'],
<add> 'd': ['een Dag', 'engem Dag'],
<add> 'M': ['ee Mount', 'engem Mount'],
<add> 'y': ['ee Joer', 'engem Joer']
<add> };
<add> return withoutSuffix ? format[key][0] : format[key][1];
<add>}
<add>function processFutureTime(string) {
<add> var number = string.substr(0, string.indexOf(' '));
<add> if (eifelerRegelAppliesToNumber(number)) {
<add> return 'a ' + string;
<add> }
<add> return 'an ' + string;
<add>}
<add>function processPastTime(string) {
<add> var number = string.substr(0, string.indexOf(' '));
<add> if (eifelerRegelAppliesToNumber(number)) {
<add> return 'viru ' + string;
<add> }
<add> return 'virun ' + string;
<add>}
<add>/**
<add> * Returns true if the word before the given number loses the '-n' ending.
<add> * e.g. 'an 10 Deeg' but 'a 5 Deeg'
<add> *
<add> * @param number {integer}
<add> * @returns {boolean}
<add> */
<add>function eifelerRegelAppliesToNumber(number) {
<add> number = parseInt(number, 10);
<add> if (isNaN(number)) {
<add> return false;
<add> }
<add> if (number < 0) {
<add> // Negative Number --> always true
<add> return true;
<add> } else if (number < 10) {
<add> // Only 1 digit
<add> if (4 <= number && number <= 7) {
<add> return true;
<add> }
<add> return false;
<add> } else if (number < 100) {
<add> // 2 digits
<add> var lastDigit = number % 10, firstDigit = number / 10;
<add> if (lastDigit === 0) {
<add> return eifelerRegelAppliesToNumber(firstDigit);
<add> }
<add> return eifelerRegelAppliesToNumber(lastDigit);
<add> } else if (number < 10000) {
<add> // 3 or 4 digits --> recursively check first digit
<add> while (number >= 10) {
<add> number = number / 10;
<add> }
<add> return eifelerRegelAppliesToNumber(number);
<add> } else {
<add> // Anything larger than 4 digits: recursively check first n-3 digits
<add> number = number / 1000;
<add> return eifelerRegelAppliesToNumber(number);
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('lb', {
<ide> months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
<ide> monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
<ide><path>src/locale/lt.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var units = {
<add> 'm' : 'minutė_minutės_minutę',
<add> 'mm': 'minutės_minučių_minutes',
<add> 'h' : 'valanda_valandos_valandą',
<add> 'hh': 'valandos_valandų_valandas',
<add> 'd' : 'diena_dienos_dieną',
<add> 'dd': 'dienos_dienų_dienas',
<add> 'M' : 'mėnuo_mėnesio_mėnesį',
<add> 'MM': 'mėnesiai_mėnesių_mėnesius',
<add> 'y' : 'metai_metų_metus',
<add> 'yy': 'metai_metų_metus'
<add>},
<add>weekDays = 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_');
<add>function translateSeconds(number, withoutSuffix, key, isFuture) {
<add> if (withoutSuffix) {
<add> return 'kelios sekundės';
<add> } else {
<add> return isFuture ? 'kelių sekundžių' : 'kelias sekundes';
<add> }
<add>}
<add>function translateSingular(number, withoutSuffix, key, isFuture) {
<add> return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]);
<add>}
<add>function special(number) {
<add> return number % 10 === 0 || (number > 10 && number < 20);
<add>}
<add>function forms(key) {
<add> return units[key].split('_');
<add>}
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var result = number + ' ';
<add> if (number === 1) {
<add> return result + translateSingular(number, withoutSuffix, key[0], isFuture);
<add> } else if (withoutSuffix) {
<add> return result + (special(number) ? forms(key)[1] : forms(key)[0]);
<add> } else {
<add> if (isFuture) {
<add> return result + forms(key)[1];
<add> } else {
<add> return result + (special(number) ? forms(key)[1] : forms(key)[2]);
<add> }
<add> }
<add>}
<add>function relativeWeekDay(moment, format) {
<add> var nominative = format.indexOf('dddd HH:mm') === -1,
<add> weekDay = weekDays[moment.day()];
<add> return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + 'į';
<add>}
<add>
<ide> export default moment.defineLocale('lt', {
<ide> months : 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),
<ide> monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),
<ide><path>src/locale/lv.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var units = {
<add> 'mm': 'minūti_minūtes_minūte_minūtes',
<add> 'hh': 'stundu_stundas_stunda_stundas',
<add> 'dd': 'dienu_dienas_diena_dienas',
<add> 'MM': 'mēnesi_mēnešus_mēnesis_mēneši',
<add> 'yy': 'gadu_gadus_gads_gadi'
<add>};
<add>function format(word, number, withoutSuffix) {
<add> var forms = word.split('_');
<add> if (withoutSuffix) {
<add> return number % 10 === 1 && number !== 11 ? forms[2] : forms[3];
<add> } else {
<add> return number % 10 === 1 && number !== 11 ? forms[0] : forms[1];
<add> }
<add>}
<add>function relativeTimeWithPlural(number, withoutSuffix, key) {
<add> return number + ' ' + format(units[key], number, withoutSuffix);
<add>}
<add>
<ide> export default moment.defineLocale('lv', {
<ide> months : 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'),
<ide> monthsShort : 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'),
<ide><path>src/locale/mr.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '१',
<add> '2': '२',
<add> '3': '३',
<add> '4': '४',
<add> '5': '५',
<add> '6': '६',
<add> '7': '७',
<add> '8': '८',
<add> '9': '९',
<add> '0': '०'
<add>},
<add>numberMap = {
<add> '१': '1',
<add> '२': '2',
<add> '३': '3',
<add> '४': '4',
<add> '५': '5',
<add> '६': '6',
<add> '७': '7',
<add> '८': '8',
<add> '९': '9',
<add> '०': '0'
<add>};
<add>
<ide> export default moment.defineLocale('mr', {
<ide> months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),
<ide> monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),
<ide><path>src/locale/my.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '၁',
<add> '2': '၂',
<add> '3': '၃',
<add> '4': '၄',
<add> '5': '၅',
<add> '6': '၆',
<add> '7': '၇',
<add> '8': '၈',
<add> '9': '၉',
<add> '0': '၀'
<add>}, numberMap = {
<add> '၁': '1',
<add> '၂': '2',
<add> '၃': '3',
<add> '၄': '4',
<add> '၅': '5',
<add> '၆': '6',
<add> '၇': '7',
<add> '၈': '8',
<add> '၉': '9',
<add> '၀': '0'
<add>};
<add>
<ide> export default moment.defineLocale('my', {
<ide> months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'),
<ide> monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'),
<ide><path>src/locale/ne.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var symbolMap = {
<add> '1': '१',
<add> '2': '२',
<add> '3': '३',
<add> '4': '४',
<add> '5': '५',
<add> '6': '६',
<add> '7': '७',
<add> '8': '८',
<add> '9': '९',
<add> '0': '०'
<add>},
<add>numberMap = {
<add> '१': '1',
<add> '२': '2',
<add> '३': '3',
<add> '४': '4',
<add> '५': '5',
<add> '६': '6',
<add> '७': '7',
<add> '८': '8',
<add> '९': '9',
<add> '०': '0'
<add>};
<add>
<ide> export default moment.defineLocale('ne', {
<ide> months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'),
<ide> monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'),
<ide><path>src/locale/nl.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
<add> monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');
<add>
<ide> export default moment.defineLocale('nl', {
<ide> months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
<ide> monthsShort : function (m, format) {
<ide><path>src/locale/pl.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),
<add> monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_');
<add>function plural(n) {
<add> return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1);
<add>}
<add>function translate(number, withoutSuffix, key) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 'm':
<add> return withoutSuffix ? 'minuta' : 'minutę';
<add> case 'mm':
<add> return result + (plural(number) ? 'minuty' : 'minut');
<add> case 'h':
<add> return withoutSuffix ? 'godzina' : 'godzinę';
<add> case 'hh':
<add> return result + (plural(number) ? 'godziny' : 'godzin');
<add> case 'MM':
<add> return result + (plural(number) ? 'miesiące' : 'miesięcy');
<add> case 'yy':
<add> return result + (plural(number) ? 'lata' : 'lat');
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('pl', {
<ide> months : function (momentToFormat, format) {
<ide> if (/D MMMM/.test(format)) {
<ide><path>src/locale/ro.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function relativeTimeWithPlural(number, withoutSuffix, key) {
<add> var format = {
<add> 'mm': 'minute',
<add> 'hh': 'ore',
<add> 'dd': 'zile',
<add> 'MM': 'luni',
<add> 'yy': 'ani'
<add> },
<add> separator = ' ';
<add> if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) {
<add> separator = ' de ';
<add> }
<add> return number + separator + format[key];
<add>}
<add>
<ide> export default moment.defineLocale('ro', {
<ide> months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),
<ide> monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),
<ide><path>src/locale/ru.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function plural(word, num) {
<add> var forms = word.split('_');
<add> return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
<add>}
<add>function relativeTimeWithPlural(number, withoutSuffix, key) {
<add> var format = {
<add> 'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут',
<add> 'hh': 'час_часа_часов',
<add> 'dd': 'день_дня_дней',
<add> 'MM': 'месяц_месяца_месяцев',
<add> 'yy': 'год_года_лет'
<add> };
<add> if (key === 'm') {
<add> return withoutSuffix ? 'минута' : 'минуту';
<add> }
<add> else {
<add> return number + ' ' + plural(format[key], +number);
<add> }
<add>}
<add>function monthsCaseReplace(m, format) {
<add> var months = {
<add> 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
<add> 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_')
<add> },
<add> nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return months[nounCase][m.month()];
<add>}
<add>function monthsShortCaseReplace(m, format) {
<add> var monthsShort = {
<add> 'nominative': 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
<add> 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_')
<add> },
<add> nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return monthsShort[nounCase][m.month()];
<add>}
<add>function weekdaysCaseReplace(m, format) {
<add> var weekdays = {
<add> 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),
<add> 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_')
<add> },
<add> nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return weekdays[nounCase][m.day()];
<add>}
<add>
<ide> export default moment.defineLocale('ru', {
<ide> months : monthsCaseReplace,
<ide> monthsShort : monthsShortCaseReplace,
<ide><path>src/locale/sk.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
<add> monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_');
<add>function plural(n) {
<add> return (n > 1) && (n < 5);
<add>}
<add>function translate(number, withoutSuffix, key, isFuture) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 's': // a few seconds / in a few seconds / a few seconds ago
<add> return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami';
<add> case 'm': // a minute / in a minute / a minute ago
<add> return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou');
<add> case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'minúty' : 'minút');
<add> } else {
<add> return result + 'minútami';
<add> }
<add> break;
<add> case 'h': // an hour / in an hour / an hour ago
<add> return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
<add> case 'hh': // 9 hours / in 9 hours / 9 hours ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'hodiny' : 'hodín');
<add> } else {
<add> return result + 'hodinami';
<add> }
<add> break;
<add> case 'd': // a day / in a day / a day ago
<add> return (withoutSuffix || isFuture) ? 'deň' : 'dňom';
<add> case 'dd': // 9 days / in 9 days / 9 days ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'dni' : 'dní');
<add> } else {
<add> return result + 'dňami';
<add> }
<add> break;
<add> case 'M': // a month / in a month / a month ago
<add> return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom';
<add> case 'MM': // 9 months / in 9 months / 9 months ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'mesiace' : 'mesiacov');
<add> } else {
<add> return result + 'mesiacmi';
<add> }
<add> break;
<add> case 'y': // a year / in a year / a year ago
<add> return (withoutSuffix || isFuture) ? 'rok' : 'rokom';
<add> case 'yy': // 9 years / in 9 years / 9 years ago
<add> if (withoutSuffix || isFuture) {
<add> return result + (plural(number) ? 'roky' : 'rokov');
<add> } else {
<add> return result + 'rokmi';
<add> }
<add> break;
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('sk', {
<ide> months : months,
<ide> monthsShort : monthsShort,
<ide><path>src/locale/sl.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function translate(number, withoutSuffix, key) {
<add> var result = number + ' ';
<add> switch (key) {
<add> case 'm':
<add> return withoutSuffix ? 'ena minuta' : 'eno minuto';
<add> case 'mm':
<add> if (number === 1) {
<add> result += 'minuta';
<add> } else if (number === 2) {
<add> result += 'minuti';
<add> } else if (number === 3 || number === 4) {
<add> result += 'minute';
<add> } else {
<add> result += 'minut';
<add> }
<add> return result;
<add> case 'h':
<add> return withoutSuffix ? 'ena ura' : 'eno uro';
<add> case 'hh':
<add> if (number === 1) {
<add> result += 'ura';
<add> } else if (number === 2) {
<add> result += 'uri';
<add> } else if (number === 3 || number === 4) {
<add> result += 'ure';
<add> } else {
<add> result += 'ur';
<add> }
<add> return result;
<add> case 'dd':
<add> if (number === 1) {
<add> result += 'dan';
<add> } else {
<add> result += 'dni';
<add> }
<add> return result;
<add> case 'MM':
<add> if (number === 1) {
<add> result += 'mesec';
<add> } else if (number === 2) {
<add> result += 'meseca';
<add> } else if (number === 3 || number === 4) {
<add> result += 'mesece';
<add> } else {
<add> result += 'mesecev';
<add> }
<add> return result;
<add> case 'yy':
<add> if (number === 1) {
<add> result += 'leto';
<add> } else if (number === 2) {
<add> result += 'leti';
<add> } else if (number === 3 || number === 4) {
<add> result += 'leta';
<add> } else {
<add> result += 'let';
<add> }
<add> return result;
<add> }
<add>}
<add>
<ide> export default moment.defineLocale('sl', {
<ide> months : 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'),
<ide> monthsShort : 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'),
<ide><path>src/locale/sr-cyrl.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var translator = {
<add> words: { //Different grammatical cases
<add> m: ['један минут', 'једне минуте'],
<add> mm: ['минут', 'минуте', 'минута'],
<add> h: ['један сат', 'једног сата'],
<add> hh: ['сат', 'сата', 'сати'],
<add> dd: ['дан', 'дана', 'дана'],
<add> MM: ['месец', 'месеца', 'месеци'],
<add> yy: ['година', 'године', 'година']
<add> },
<add> correctGrammaticalCase: function (number, wordKey) {
<add> return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
<add> },
<add> translate: function (number, withoutSuffix, key) {
<add> var wordKey = translator.words[key];
<add> if (key.length === 1) {
<add> return withoutSuffix ? wordKey[0] : wordKey[1];
<add> } else {
<add> return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
<add> }
<add> }
<add>};
<add>
<ide> export default moment.defineLocale('sr-cyrl', {
<ide> months: ['јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар'],
<ide> monthsShort: ['јан.', 'феб.', 'мар.', 'апр.', 'мај', 'јун', 'јул', 'авг.', 'сеп.', 'окт.', 'нов.', 'дец.'],
<ide><path>src/locale/sr.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var translator = {
<add> words: { //Different grammatical cases
<add> m: ['jedan minut', 'jedne minute'],
<add> mm: ['minut', 'minute', 'minuta'],
<add> h: ['jedan sat', 'jednog sata'],
<add> hh: ['sat', 'sata', 'sati'],
<add> dd: ['dan', 'dana', 'dana'],
<add> MM: ['mesec', 'meseca', 'meseci'],
<add> yy: ['godina', 'godine', 'godina']
<add> },
<add> correctGrammaticalCase: function (number, wordKey) {
<add> return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
<add> },
<add> translate: function (number, withoutSuffix, key) {
<add> var wordKey = translator.words[key];
<add> if (key.length === 1) {
<add> return withoutSuffix ? wordKey[0] : wordKey[1];
<add> } else {
<add> return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
<add> }
<add> }
<add>};
<add>
<ide> export default moment.defineLocale('sr', {
<ide> months: ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'],
<ide> monthsShort: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'],
<ide><path>src/locale/ta.js
<ide> export default moment.defineLocale('ta', {
<ide> y : 'ஒரு வருடம்',
<ide> yy : '%d ஆண்டுகள்'
<ide> },
<del> preparse: function (string) {
<del> return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) {
<del> return numberMap[match];
<del> });
<del> },
<del> postformat: function (string) {
<del> return string.replace(/\d/g, function (match) {
<del> return symbolMap[match];
<del> });
<del> },*/
<ide> ordinalParse: /\d{1,2}வது/,
<ide> ordinal : function (number) {
<ide> return number + 'வது';
<ide><path>src/locale/tr.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>var suffixes = {
<add> 1: '\'inci',
<add> 5: '\'inci',
<add> 8: '\'inci',
<add> 70: '\'inci',
<add> 80: '\'inci',
<add> 2: '\'nci',
<add> 7: '\'nci',
<add> 20: '\'nci',
<add> 50: '\'nci',
<add> 3: '\'üncü',
<add> 4: '\'üncü',
<add> 100: '\'üncü',
<add> 6: '\'ncı',
<add> 9: '\'uncu',
<add> 10: '\'uncu',
<add> 30: '\'uncu',
<add> 60: '\'ıncı',
<add> 90: '\'ıncı'
<add>};
<add>
<ide> export default moment.defineLocale('tr', {
<ide> months : 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'),
<ide> monthsShort : 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'),
<ide><path>src/locale/uk.js
<ide>
<ide> import moment from "../moment";
<ide>
<add>function plural(word, num) {
<add> var forms = word.split('_');
<add> return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
<add>}
<add>function relativeTimeWithPlural(number, withoutSuffix, key) {
<add> var format = {
<add> 'mm': 'хвилина_хвилини_хвилин',
<add> 'hh': 'година_години_годин',
<add> 'dd': 'день_дні_днів',
<add> 'MM': 'місяць_місяці_місяців',
<add> 'yy': 'рік_роки_років'
<add> };
<add> if (key === 'm') {
<add> return withoutSuffix ? 'хвилина' : 'хвилину';
<add> }
<add> else if (key === 'h') {
<add> return withoutSuffix ? 'година' : 'годину';
<add> }
<add> else {
<add> return number + ' ' + plural(format[key], +number);
<add> }
<add>}
<add>function monthsCaseReplace(m, format) {
<add> var months = {
<add> 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'),
<add> 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_')
<add> },
<add> nounCase = (/D[oD]? *MMMM?/).test(format) ?
<add> 'accusative' :
<add> 'nominative';
<add> return months[nounCase][m.month()];
<add>}
<add>function weekdaysCaseReplace(m, format) {
<add> var weekdays = {
<add> 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'),
<add> 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'),
<add> 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_')
<add> },
<add> nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ?
<add> 'accusative' :
<add> ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ?
<add> 'genitive' :
<add> 'nominative');
<add> return weekdays[nounCase][m.day()];
<add>}
<add>function processHoursFunction(str) {
<add> return function () {
<add> return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT';
<add> };
<add>}
<add>
<ide> export default moment.defineLocale('uk', {
<ide> months : monthsCaseReplace,
<ide> monthsShort : 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), | 39 |
Javascript | Javascript | use mustnotcall() in test-stream2-objects | 64ded9f9bca71a2b230a9c114964ccfc258db98f | <ide><path>test/parallel/test-stream2-objects.js
<ide> function toArray(callback) {
<ide>
<ide> function fromArray(list) {
<ide> const r = new Readable({ objectMode: true });
<del> r._read = common.noop;
<add> r._read = common.mustNotCall();
<ide> list.forEach(function(chunk) {
<ide> r.push(chunk);
<ide> });
<ide> test('can read strings as objects', function(t) {
<ide> const r = new Readable({
<ide> objectMode: true
<ide> });
<del> r._read = common.noop;
<add> r._read = common.mustNotCall();
<ide> const list = ['one', 'two', 'three'];
<ide> list.forEach(function(str) {
<ide> r.push(str);
<ide> test('read(0) for object streams', function(t) {
<ide> const r = new Readable({
<ide> objectMode: true
<ide> });
<del> r._read = common.noop;
<add> r._read = common.mustNotCall();
<ide>
<ide> r.push('foobar');
<ide> r.push(null);
<ide> test('falsey values', function(t) {
<ide> const r = new Readable({
<ide> objectMode: true
<ide> });
<del> r._read = common.noop;
<add> r._read = common.mustNotCall();
<ide>
<ide> r.push(false);
<ide> r.push(0);
<ide> test('high watermark push', function(t) {
<ide> highWaterMark: 6,
<ide> objectMode: true
<ide> });
<del> r._read = common.noop;
<add> r._read = common.mustNotCall();
<ide> for (let i = 0; i < 6; i++) {
<ide> const bool = r.push(i);
<ide> assert.strictEqual(bool, i !== 5); | 1 |
PHP | PHP | remove unused path | fc7bad49e8ecf6cf3dc70adc152e4cdbd2dc94ec | <ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php
<ide> protected function setAppDirectoryNamespace()
<ide> {
<ide> $files = Finder::create()
<ide> ->in($this->laravel['path'])
<del> ->exclude($this->laravel['path'].'/Http/Views')
<ide> ->name('*.php');
<ide>
<ide> foreach ($files as $file) | 1 |
PHP | PHP | add passthru methods to eloquent builder | 2996da8d616aa648ac7646001d318928ae4a41f6 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> class Builder
<ide> protected $passthru = [
<ide> 'insert', 'insertOrIgnore', 'insertGetId', 'insertUsing', 'getBindings', 'toSql', 'dump', 'dd',
<ide> 'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'average', 'sum', 'getConnection', 'raw', 'getGrammar',
<add> 'newQuery', 'getProcessor', 'implode', 'aggregate', 'numericAggregate',
<ide> ];
<ide>
<ide> /** | 1 |
Java | Java | improve encoder javadoc | d51005fbbeaf6e84f94a2f9d491d705119898572 | <ide><path>spring-core/src/main/java/org/springframework/core/codec/Encoder.java
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> /**
<ide> * Encode a stream of Objects of type {@code T} into a {@link DataBuffer}
<ide> * output stream.
<del> * @param inputStream the input stream of Objects to encode
<add> * @param inputStream the input stream of Objects to encode. If the input should be
<add> * encoded as a single value rather than as a stream of elements, an instance of
<add> * {@link Mono} should be used.
<ide> * @param bufferFactory for creating output stream {@code DataBuffer}'s
<ide> * @param elementType the expected type of elements in the input stream;
<ide> * this type must have been previously passed to the {@link #canEncode} | 1 |
Mixed | Python | add kannada support | a78db10941d0818b0077d1fb6d1795d9ebb34f99 | <ide><path>.github/contributors/akki2825.md
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Akhilesh K R |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2019-02-12 |
<add>| GitHub username | akki2825 |
<add>| Website (optional) | |
<ide><path>spacy/lang/kn/__init__.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from .stop_words import STOP_WORDS
<add>from .lex_attrs import LEX_ATTRS
<add>
<add>from ..norm_exceptions import BASE_NORMS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>
<add>
<add>class KannadaDefaults(Language.Defaults):
<add> stop_words = STOP_WORDS
<add>
<add>
<add>class Kannada(Language):
<add> lang = 'kn'
<add> Defaults = KannadaDefaults
<add>
<add>
<add>__all__ = ['Kannada']
<ide><path>spacy/lang/kn/stop_words.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add># Stop words
<add>
<add>STOP_WORD = set("""
<add>ಈ
<add>ಮತ್ತು
<add>ಹಾಗೂ
<add>ಅವರು
<add>ಅವರ
<add>ಬಗ್ಗೆ
<add>ಎಂಬ
<add>ಆದರೆ
<add>ಅವರನ್ನು
<add>ಆದರೆ
<add>ತಮ್ಮ
<add>ಒಂದು
<add>ಎಂದರು
<add>ಮೇಲೆ
<add>ಹೇಳಿದರು
<add>ಸೇರಿದಂತೆ
<add>ಬಳಿಕ
<add>ಆ
<add>ಯಾವುದೇ
<add>ಅವರಿಗೆ
<add>ನಡೆದ
<add>ಕುರಿತು
<add>ಇದು
<add>ಅವರು
<add>ಕಳೆದ
<add>ಇದೇ
<add>ತಿಳಿಸಿದರು
<add>ಹೀಗಾಗಿ
<add>ಕೂಡ
<add>ತನ್ನ
<add>ತಿಳಿಸಿದ್ದಾರೆ
<add>ನಾನು
<add>ಹೇಳಿದ್ದಾರೆ
<add>ಈಗ
<add>ಎಲ್ಲ
<add>ನನ್ನ
<add>ನಮ್ಮ
<add>ಈಗಾಗಲೇ
<add>ಇದಕ್ಕೆ
<add>ಹಲವು
<add>ಇದೆ
<add>ಮತ್ತೆ
<add>ಮಾಡುವ
<add>ನೀಡಿದರು
<add>ನಾವು
<add>ನೀಡಿದ
<add>ಇದರಿಂದ
<add>ಅದು
<add>ಇದನ್ನು
<add>ನೀಡಿದ್ದಾರೆ
<add>ಅದನ್ನು
<add>ಇಲ್ಲಿ
<add>ಆಗ
<add>ಬಂದಿದೆ.
<add>ಅದೇ
<add>ಇರುವ
<add>ಅಲ್ಲದೆ
<add>ಕೆಲವು
<add>ನೀಡಿದೆ
<add>ಇದರ
<add>ಇನ್ನು
<add>ನಡೆದಿದೆ
<add>""".split()) | 3 |
Mixed | Ruby | remove xml parser from actiondispatch | c9909db9f2f81575ef2ea2ed3b4e8743c8d6f1b9 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Remove support for parsing XML parameters from request. If you still want to parse XML
<add> parameters, please install `actionpack-xml_parser' gem.
<add>
<add> *Prem Sichanugrist*
<add>
<ide> * Fix `time_zone_options_for_select` to call `dup` on the returned TimeZone array.
<del>
<add>
<ide> Previously if you supplied :priority_zones options to `time_zone_options_for_select`
<ide> the memoized ActiveSupport::TimeZone.all array would be mutated. Calling
<ide> `dup` prevents mutation of the main TimeZones array.
<del>
<add>
<ide> *Brian McManus*
<del>
<add>
<ide> * Remove support for parsing YAML parameters from request.
<ide>
<ide> *Aaron Patterson*
<ide><path>actionpack/lib/action_dispatch/middleware/params_parser.rb
<ide> def initialize(message, original_exception)
<ide> end
<ide> end
<ide>
<del> DEFAULT_PARSERS = {
<del> Mime::XML => :xml_simple,
<del> Mime::JSON => :json
<del> }
<add> DEFAULT_PARSERS = { Mime::JSON => :json }
<ide>
<ide> def initialize(app, parsers = {})
<ide> @app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
<ide> def parse_formatted_parameters(env)
<ide>
<ide> return false if request.content_length.zero?
<ide>
<del> mime_type = content_type_from_legacy_post_data_format_header(env) ||
<del> request.content_mime_type
<del>
<del> strategy = @parsers[mime_type]
<add> strategy = @parsers[request.content_mime_type]
<ide>
<ide> return false unless strategy
<ide>
<ide> case strategy
<ide> when Proc
<ide> strategy.call(request.raw_post)
<del> when :xml_simple, :xml_node
<del> data = request.deep_munge(Hash.from_xml(request.body.read) || {})
<del> data.with_indifferent_access
<ide> when :json
<ide> data = ActiveSupport::JSON.decode(request.body)
<ide> data = {:_json => data} unless data.is_a?(Hash)
<ide> request.deep_munge(data).with_indifferent_access
<ide> else
<ide> false
<ide> end
<del> rescue Exception => e # YAML, XML or Ruby code block errors
<add> rescue Exception => e # JSON or Ruby code block errors
<ide> logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
<ide>
<ide> raise ParseError.new(e.message, e)
<ide> end
<ide>
<del> def content_type_from_legacy_post_data_format_header(env)
<del> if x_post_format = env['HTTP_X_POST_DATA_FORMAT']
<del> case x_post_format.to_s.downcase
<del> when 'yaml' then return Mime::YAML
<del> when 'xml' then return Mime::XML
<del> end
<del> end
<del>
<del> nil
<del> end
<del>
<ide> def logger(env)
<ide> env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
<ide> end
<ide><path>actionpack/test/controller/webservice_test.rb
<ide> def test_check_parameters
<ide> end
<ide> end
<ide>
<del> def test_post_xml
<add> def test_post_json
<ide> with_test_route_set do
<del> post "/", '<entry attributed="true"><summary>content...</summary></entry>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<add> post "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
<ide>
<ide> assert_equal 'entry', @controller.response.body
<ide> assert @controller.params.has_key?(:entry)
<ide> assert_equal 'content...', @controller.params["entry"]['summary']
<del> assert_equal 'true', @controller.params["entry"]['attributed']
<ide> end
<ide> end
<ide>
<del> def test_put_xml
<add> def test_put_json
<ide> with_test_route_set do
<del> put "/", '<entry attributed="true"><summary>content...</summary></entry>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<add> put "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
<ide>
<ide> assert_equal 'entry', @controller.response.body
<ide> assert @controller.params.has_key?(:entry)
<ide> assert_equal 'content...', @controller.params["entry"]['summary']
<del> assert_equal 'true', @controller.params["entry"]['attributed']
<ide> end
<ide> end
<ide>
<del> def test_put_xml_using_a_type_node
<add> def test_register_and_use_json_simple
<ide> with_test_route_set do
<del> put "/", '<type attributed="true"><summary>content...</summary></type>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> assert_equal 'type', @controller.response.body
<del> assert @controller.params.has_key?(:type)
<del> assert_equal 'content...', @controller.params["type"]['summary']
<del> assert_equal 'true', @controller.params["type"]['attributed']
<del> end
<del> end
<del>
<del> def test_put_xml_using_a_type_node_and_attribute
<del> with_test_route_set do
<del> put "/", '<type attributed="true"><summary type="boolean">false</summary></type>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> assert_equal 'type', @controller.response.body
<del> assert @controller.params.has_key?(:type)
<del> assert_equal false, @controller.params["type"]['summary']
<del> assert_equal 'true', @controller.params["type"]['attributed']
<del> end
<del> end
<del>
<del> def test_post_xml_using_a_type_node
<del> with_test_route_set do
<del> post "/", '<font attributed="true"><type>arial</type></font>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> assert_equal 'font', @controller.response.body
<del> assert @controller.params.has_key?(:font)
<del> assert_equal 'arial', @controller.params['font']['type']
<del> assert_equal 'true', @controller.params["font"]['attributed']
<del> end
<del> end
<del>
<del> def test_post_xml_using_a_root_node_named_type
<del> with_test_route_set do
<del> post "/", '<type type="integer">33</type>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> assert @controller.params.has_key?(:type)
<del> assert_equal 33, @controller.params['type']
<del> end
<del> end
<del>
<del> def test_post_xml_using_an_attributted_node_named_type
<del> with_test_route_set do
<del> with_params_parsers Mime::XML => Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } do
<del> post "/", '<request><type type="string">Arial,12</type><z>3</z></request>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> assert_equal 'type, z', @controller.response.body
<del> assert @controller.params.has_key?(:type)
<del> assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect
<del> assert_equal '3', @controller.params['z'], @controller.params.inspect
<del> end
<del> end
<del> end
<del>
<del> def test_post_xml_using_a_disallowed_type_attribute
<del> $stderr = StringIO.new
<del> with_test_route_set do
<del> post '/', '<foo type="symbol">value</foo>', 'CONTENT_TYPE' => 'application/xml'
<del> assert_response 500
<del>
<del> post '/', '<foo type="yaml">value</foo>', 'CONTENT_TYPE' => 'application/xml'
<del> assert_response 500
<del> end
<del> ensure
<del> $stderr = STDERR
<del> end
<del>
<del> def test_register_and_use_xml_simple
<del> with_test_route_set do
<del> with_params_parsers Mime::XML => Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } do
<del> post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>',
<del> {'CONTENT_TYPE' => 'application/xml'}
<add> with_params_parsers Mime::JSON => Proc.new { |data| JSON.parse(data)['request'].with_indifferent_access } do
<add> post "/", '{"request":{"summary":"content...","title":"JSON"}}',
<add> 'CONTENT_TYPE' => 'application/json'
<ide>
<ide> assert_equal 'summary, title', @controller.response.body
<ide> assert @controller.params.has_key?(:summary)
<ide> assert @controller.params.has_key?(:title)
<ide> assert_equal 'content...', @controller.params["summary"]
<del> assert_equal 'SimpleXml', @controller.params["title"]
<add> assert_equal 'JSON', @controller.params["title"]
<ide> end
<ide> end
<ide> end
<ide>
<del> def test_use_xml_ximple_with_empty_request
<add> def test_use_json_with_empty_request
<ide> with_test_route_set do
<del> assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} }
<add> assert_nothing_raised { post "/", "", 'CONTENT_TYPE' => 'application/json' }
<ide> assert_equal '', @controller.response.body
<ide> end
<ide> end
<ide>
<del> def test_dasherized_keys_as_xml
<del> with_test_route_set do
<del> post "/?full=1", "<first-key>\n<sub-key>...</sub-key>\n</first-key>",
<del> {'CONTENT_TYPE' => 'application/xml'}
<del> assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body
<del> assert_equal "...", @controller.params[:first_key][:sub_key]
<del> end
<del> end
<del>
<del> def test_typecast_as_xml
<del> with_test_route_set do
<del> xml = <<-XML
<del> <data>
<del> <a type="integer">15</a>
<del> <b type="boolean">false</b>
<del> <c type="boolean">true</c>
<del> <d type="date">2005-03-17</d>
<del> <e type="datetime">2005-03-17T21:41:07Z</e>
<del> <f>unparsed</f>
<del> <g type="integer">1</g>
<del> <g>hello</g>
<del> <g type="date">1974-07-25</g>
<del> </data>
<del> XML
<del> post "/", xml, {'CONTENT_TYPE' => 'application/xml'}
<del>
<del> params = @controller.params
<del> assert_equal 15, params[:data][:a]
<del> assert_equal false, params[:data][:b]
<del> assert_equal true, params[:data][:c]
<del> assert_equal Date.new(2005,3,17), params[:data][:d]
<del> assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e]
<del> assert_equal "unparsed", params[:data][:f]
<del> assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g]
<del> end
<del> end
<del>
<del> def test_entities_unescaped_as_xml_simple
<add> def test_dasherized_keys_as_json
<ide> with_test_route_set do
<del> xml = <<-XML
<del> <data><foo "bar's" & friends></data>
<del> XML
<del> post "/", xml, {'CONTENT_TYPE' => 'application/xml'}
<del> assert_equal %(<foo "bar's" & friends>), @controller.params[:data]
<add> post "/?full=1", '{"first-key":{"sub-key":"..."}}', 'CONTENT_TYPE' => 'application/json'
<add> assert_equal 'action, controller, first-key(sub-key), full', @controller.response.body
<add> assert_equal "...", @controller.params['first-key']['sub-key']
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/dispatch/request/xml_params_parsing_test.rb
<del>require 'abstract_unit'
<del>
<del>class XmlParamsParsingTest < ActionDispatch::IntegrationTest
<del> class TestController < ActionController::Base
<del> class << self
<del> attr_accessor :last_request_parameters
<del> end
<del>
<del> def parse
<del> self.class.last_request_parameters = request.request_parameters
<del> head :ok
<del> end
<del> end
<del>
<del> def teardown
<del> TestController.last_request_parameters = nil
<del> end
<del>
<del> test "parses a strict rack.input" do
<del> class Linted
<del> undef call if method_defined?(:call)
<del> def call(env)
<del> bar = env['action_dispatch.request.request_parameters']['foo']
<del> result = "<ok>#{bar}</ok>"
<del> [200, {"Content-Type" => "application/xml", "Content-Length" => result.length.to_s}, [result]]
<del> end
<del> end
<del> req = Rack::MockRequest.new(ActionDispatch::ParamsParser.new(Linted.new))
<del> resp = req.post('/', "CONTENT_TYPE" => "application/xml", :input => "<foo>bar</foo>", :lint => true)
<del> assert_equal "<ok>bar</ok>", resp.body
<del> end
<del>
<del> def assert_parses(expected, xml)
<del> with_test_routing do
<del> post "/parse", xml, default_headers
<del> assert_response :ok
<del> assert_equal(expected, TestController.last_request_parameters)
<del> end
<del> end
<del>
<del> test "nils are stripped from collections" do
<del> assert_parses(
<del> {"hash" => { "person" => nil} },
<del> "<hash><person type=\"array\"><person nil=\"true\"/></person></hash>")
<del> assert_parses(
<del> {"hash" => { "person" => ['foo']} },
<del> "<hash><person type=\"array\"><person>foo</person><person nil=\"true\"/></person>\n</hash>")
<del> end
<del>
<del> test "parses hash params" do
<del> with_test_routing do
<del> xml = "<person><name>David</name></person>"
<del> post "/parse", xml, default_headers
<del> assert_response :ok
<del> assert_equal({"person" => {"name" => "David"}}, TestController.last_request_parameters)
<del> end
<del> end
<del>
<del> test "parses single file" do
<del> with_test_routing do
<del> xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{::Base64.encode64('ABC')}</avatar></person>"
<del> post "/parse", xml, default_headers
<del> assert_response :ok
<del>
<del> person = TestController.last_request_parameters
<del> assert_equal "image/jpg", person['person']['avatar'].content_type
<del> assert_equal "me.jpg", person['person']['avatar'].original_filename
<del> assert_equal "ABC", person['person']['avatar'].read
<del> end
<del> end
<del>
<del> test "logs error if parsing unsuccessful" do
<del> with_test_routing do
<del> output = StringIO.new
<del> xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{::Base64.encode64('ABC')}</avatar></pineapple>"
<del> post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => ActiveSupport::Logger.new(output))
<del> assert_response :error
<del> output.rewind && err = output.read
<del> assert err =~ /Error occurred while parsing request parameters/
<del> end
<del> end
<del>
<del> test "occurring a parse error if parsing unsuccessful" do
<del> with_test_routing do
<del> begin
<del> $stderr = StringIO.new # suppress the log
<del> xml = "<person><name>David</name></pineapple>"
<del> exception = assert_raise(ActionDispatch::ParamsParser::ParseError) { post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => false) }
<del> assert_equal REXML::ParseException, exception.original_exception.class
<del> assert_equal exception.original_exception.message, exception.message
<del> ensure
<del> $stderr = STDERR
<del> end
<del> end
<del> end
<del>
<del> test "parses multiple files" do
<del> xml = <<-end_body
<del> <person>
<del> <name>David</name>
<del> <avatars>
<del> <avatar type='file' name='me.jpg' content_type='image/jpg'>#{::Base64.encode64('ABC')}</avatar>
<del> <avatar type='file' name='you.gif' content_type='image/gif'>#{::Base64.encode64('DEF')}</avatar>
<del> </avatars>
<del> </person>
<del> end_body
<del>
<del> with_test_routing do
<del> post "/parse", xml, default_headers
<del> assert_response :ok
<del> end
<del>
<del> person = TestController.last_request_parameters
<del>
<del> assert_equal "image/jpg", person['person']['avatars']['avatar'].first.content_type
<del> assert_equal "me.jpg", person['person']['avatars']['avatar'].first.original_filename
<del> assert_equal "ABC", person['person']['avatars']['avatar'].first.read
<del>
<del> assert_equal "image/gif", person['person']['avatars']['avatar'].last.content_type
<del> assert_equal "you.gif", person['person']['avatars']['avatar'].last.original_filename
<del> assert_equal "DEF", person['person']['avatars']['avatar'].last.read
<del> end
<del>
<del> private
<del> def with_test_routing
<del> with_routing do |set|
<del> set.draw do
<del> post ':action', :to => ::XmlParamsParsingTest::TestController
<del> end
<del> yield
<del> end
<del> end
<del>
<del> def default_headers
<del> {'CONTENT_TYPE' => 'application/xml'}
<del> end
<del>end
<del>
<del>class LegacyXmlParamsParsingTest < XmlParamsParsingTest
<del> private
<del> def default_headers
<del> {'HTTP_X_POST_DATA_FORMAT' => 'xml'}
<del> end
<del>end
<del>
<del>class RootLessXmlParamsParsingTest < ActionDispatch::IntegrationTest
<del> class TestController < ActionController::Base
<del> wrap_parameters :person, :format => :xml
<del>
<del> class << self
<del> attr_accessor :last_request_parameters
<del> end
<del>
<del> def parse
<del> self.class.last_request_parameters = request.request_parameters
<del> head :ok
<del> end
<del> end
<del>
<del> def teardown
<del> TestController.last_request_parameters = nil
<del> end
<del>
<del> test "parses hash params" do
<del> with_test_routing do
<del> xml = "<name>David</name>"
<del> post "/parse", xml, {'CONTENT_TYPE' => 'application/xml'}
<del> assert_response :ok
<del> assert_equal({"name" => "David", "person" => {"name" => "David"}}, TestController.last_request_parameters)
<del> end
<del> end
<del>
<del> private
<del> def with_test_routing
<del> with_routing do |set|
<del> set.draw do
<del> post ':action', :to => ::RootLessXmlParamsParsingTest::TestController
<del> end
<del> yield
<del> end
<del> end
<del>end
<ide><path>guides/source/action_controller_overview.md
<ide> When this form is submitted, the value of `params[:client]` will be `{"name" =>
<ide>
<ide> Note that the `params` hash is actually an instance of `ActiveSupport::HashWithIndifferentAccess`, which acts like a hash that lets you use symbols and strings interchangeably as keys.
<ide>
<del>### JSON/XML parameters
<add>### JSON parameters
<ide>
<del>If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into `params` hash, which you'll be able to access like you would normally do with form data.
<add>If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON format. Rails will automatically convert your parameters into `params` hash, which you'll be able to access like you would normally do with form data.
<ide>
<ide> So for example, if you are sending this JSON parameter:
<ide>
<ide> So for example, if you are sending this JSON parameter:
<ide>
<ide> You'll get `params[:company]` as `{ :name => "acme", "address" => "123 Carrot Street" }`.
<ide>
<del>Also, if you've turned on `config.wrap_parameters` in your initializer or calling `wrap_parameters` in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
<add>Also, if you've turned on `config.wrap_parameters` in your initializer or calling `wrap_parameters` in your controller, you can safely omit the root element in the JSON parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
<ide>
<ide> ```json
<ide> { "name": "acme", "address": "123 Carrot Street" }
<ide> And assume that you're sending the data to `CompaniesController`, it would then
<ide>
<ide> You can customize the name of the key or specific parameters you want to wrap by consulting the [API documentation](http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html)
<ide>
<add>NOTE: A support for parsing XML parameters has been extracted into a gem named `actionpack-xml_parser`
<add>
<ide> ### Routing Parameters
<ide>
<ide> The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL: | 5 |
Javascript | Javascript | use options object for nodetemplateplugin | b296e5a08c71208b979d3d4e4e6e7730377865ec | <ide><path>lib/WebpackOptionsApply.js
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> var NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
<ide> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<ide> compiler.apply(
<del> new NodeTemplatePlugin(options.output, options.target === "async-node"),
<add> new NodeTemplatePlugin(options.target === "async-node"),
<ide> new FunctionModulePlugin(options.output),
<ide> new NodeTargetPlugin(),
<ide> new LoaderTargetPlugin("node")
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<ide> var ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(
<del> new NodeTemplatePlugin(options.output, true),
<add> new NodeTemplatePlugin(true),
<ide> new FunctionModulePlugin(options.output),
<ide> new NodeTargetPlugin(),
<ide> new ExternalsPlugin("commonjs", [
<ide><path>lib/node/NodeTemplatePlugin.js
<ide> var NodeMainTemplatePlugin = require("./NodeMainTemplatePlugin");
<ide> var NodeChunkTemplatePlugin = require("./NodeChunkTemplatePlugin");
<ide> var NodeHotUpdateChunkTemplatePlugin = require("./NodeHotUpdateChunkTemplatePlugin");
<ide>
<del>function NodeTemplatePlugin(options, asyncChunkLoading) {
<del> // TODO remove options parameter
<del> this.options = options;
<del> this.asyncChunkLoading = asyncChunkLoading;
<add>function NodeTemplatePlugin(options) {
<add> options = options || {};
<add> this.asyncChunkLoading = options.asyncChunkLoading;
<ide> }
<ide> module.exports = NodeTemplatePlugin;
<ide> NodeTemplatePlugin.prototype.apply = function(compiler) { | 2 |
Ruby | Ruby | check cellar access | b1514c1c40390b2238f378ff132b76e2e8a744ef | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_access_cache
<ide> end
<ide> end
<ide>
<add>def check_access_cellar
<add> if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real?
<add> <<-EOS.undent
<add> #{HOMEBREW_CELLAR} isn't writable.
<add> You should `chown` #{HOMEBREW_CELLAR}
<add> EOS
<add> end
<add>end
<add>
<ide> def check_ruby_version
<ide> ruby_version = MacOS.version >= "10.9" ? "2.0" : "1.8"
<ide> if RUBY_VERSION[/\d\.\d/] != ruby_version then <<-EOS.undent | 1 |
Python | Python | fix pytorch/tf auto tests | db2644b9eb948b62c282c1ba25f8f44a17615b93 | <ide><path>src/transformers/modeling_tf_pytorch_utils.py
<ide> def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove="",
<ide> #####################
<ide>
<ide>
<del>def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False):
<add>def load_pytorch_checkpoint_in_tf2_model(
<add> tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
<add>):
<ide> """Load pytorch checkpoints in a TF 2.0 model"""
<ide> try:
<ide> import tensorflow as tf # noqa: F401
<ide> def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_i
<ide> logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters")
<ide>
<ide> return load_pytorch_weights_in_tf2_model(
<del> tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys
<add> tf_model,
<add> pt_state_dict,
<add> tf_inputs=tf_inputs,
<add> allow_missing_keys=allow_missing_keys,
<add> output_loading_info=output_loading_info,
<ide> )
<ide>
<ide>
<ide> def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_mi
<ide> )
<ide>
<ide>
<del>def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False):
<add>def load_pytorch_weights_in_tf2_model(
<add> tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
<add>):
<ide> """Load pytorch state_dict in a TF 2.0 model."""
<ide> try:
<ide> import tensorflow as tf # noqa: F401
<ide> def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, a
<ide> f"you can already use {tf_model.__class__.__name__} for predictions without further training."
<ide> )
<ide>
<add> if output_loading_info:
<add> loading_info = {"missing_keys": missing_keys, "unexpected_keys": unexpected_keys}
<add> return tf_model, loading_info
<add>
<ide> return tf_model
<ide>
<ide>
<ide> def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, a
<ide> #####################
<ide>
<ide>
<del>def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False):
<add>def load_tf2_checkpoint_in_pytorch_model(
<add> pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
<add>):
<ide> """
<ide> Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
<ide> https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
<ide> def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs
<ide>
<ide> load_tf_weights(tf_model, tf_checkpoint_path)
<ide>
<del> return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys)
<add> return load_tf2_model_in_pytorch_model(
<add> pt_model, tf_model, allow_missing_keys=allow_missing_keys, output_loading_info=output_loading_info
<add> )
<ide>
<ide>
<del>def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False):
<add>def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False, output_loading_info=False):
<ide> """Load TF 2.0 model in a pytorch model"""
<ide> weights = tf_model.weights
<ide>
<del> return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys)
<add> return load_tf2_weights_in_pytorch_model(
<add> pt_model, weights, allow_missing_keys=allow_missing_keys, output_loading_info=output_loading_info
<add> )
<ide>
<ide>
<del>def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False):
<add>def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False, output_loading_info=False):
<ide> """Load TF2.0 symbolic weights in a PyTorch model"""
<ide> try:
<ide> import tensorflow as tf # noqa: F401
<ide> def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=F
<ide>
<ide> logger.info(f"Weights or buffers not loaded from TF 2.0 model: {all_tf_weights}")
<ide>
<add> if output_loading_info:
<add> loading_info = {"missing_keys": missing_keys, "unexpected_keys": unexpected_keys}
<add> return pt_model, loading_info
<add>
<ide> return pt_model
<ide><path>src/transformers/modeling_tf_utils.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model
<ide>
<ide> # Load from a PyTorch checkpoint
<del> return load_pytorch_checkpoint_in_tf2_model(model, resolved_archive_file, allow_missing_keys=True)
<add> return load_pytorch_checkpoint_in_tf2_model(
<add> model, resolved_archive_file, allow_missing_keys=True, output_loading_info=output_loading_info
<add> )
<ide>
<ide> # we might need to extend the variable scope for composite models
<ide> if load_weight_prefix is not None:
<ide><path>src/transformers/modeling_utils.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> is_sharded = False
<ide> sharded_metadata = None
<ide> # Load model
<add> loading_info = None
<add>
<ide> if pretrained_model_name_or_path is not None:
<ide> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<ide> if os.path.isdir(pretrained_model_name_or_path):
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> try:
<ide> from .modeling_tf_pytorch_utils import load_tf2_checkpoint_in_pytorch_model
<ide>
<del> model = load_tf2_checkpoint_in_pytorch_model(model, resolved_archive_file, allow_missing_keys=True)
<add> model, loading_info = load_tf2_checkpoint_in_pytorch_model(
<add> model, resolved_archive_file, allow_missing_keys=True, output_loading_info=True
<add> )
<ide> except ImportError:
<ide> logger.error(
<ide> "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed."
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> dispatch_model(model, device_map=device_map, offload_dir=offload_folder)
<ide>
<ide> if output_loading_info:
<del> loading_info = {
<del> "missing_keys": missing_keys,
<del> "unexpected_keys": unexpected_keys,
<del> "mismatched_keys": mismatched_keys,
<del> "error_msgs": error_msgs,
<del> }
<add> if loading_info is None:
<add> loading_info = {
<add> "missing_keys": missing_keys,
<add> "unexpected_keys": unexpected_keys,
<add> "mismatched_keys": mismatched_keys,
<add> "error_msgs": error_msgs,
<add> }
<ide> return model, loading_info
<ide>
<ide> return model | 3 |
Text | Text | fix typos in handle scope descriptions | 1786504afa068b2b6591f23799dadd4e867cc529 | <ide><path>doc/api/n-api.md
<ide> NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API open a new scope.
<add>This API opens a new scope.
<ide>
<ide> #### napi_close_handle_scope
<ide> <!-- YAML
<ide> NAPI_EXTERN napi_status
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API open a new scope from which one object can be promoted
<add>This API opens a new scope from which one object can be promoted
<ide> to the outer scope.
<ide>
<ide> #### napi_close_escapable_handle_scope | 1 |
Go | Go | return container exit code with start -a/-i | 65edb07065e9e8a08090a4ac88cf449b7faaff09 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdStart(args ...string) error {
<ide> return fmt.Errorf("You cannot start and attach multiple containers at once.")
<ide> }
<ide>
<del> steam, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
<add> stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> env := engine.Env{}
<del> if err := env.Decode(steam); err != nil {
<add> if err := env.Decode(stream); err != nil {
<ide> return err
<ide> }
<ide> config := env.GetSubEnv("Config")
<ide> func (cli *DockerCli) CmdStart(args ...string) error {
<ide> log.Errorf("Error monitoring TTY size: %s", err)
<ide> }
<ide> }
<del> return <-cErr
<add> if attchErr := <-cErr; attchErr != nil {
<add> return attchErr
<add> }
<add> _, status, err := getExitCode(cli, cmd.Arg(0))
<add> if err != nil {
<add> return err
<add> }
<add> if status != 0 {
<add> return &utils.StatusError{StatusCode: status}
<add> }
<ide> }
<ide> return nil
<ide> }
<ide><path>integration-cli/docker_cli_start_test.go
<ide> package main
<ide>
<ide> import (
<add> "fmt"
<ide> "os/exec"
<add> "strings"
<ide> "testing"
<ide> "time"
<ide> )
<ide> func TestStartAttachReturnsOnError(t *testing.T) {
<ide>
<ide> logDone("start - error on start with attach exits")
<ide> }
<add>
<add>// gh#8555: Exit code should be passed through when using start -a
<add>func TestStartAttachCorrectExitCode(t *testing.T) {
<add> defer deleteAllContainers()
<add>
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", "sleep 2; exit 1")
<add> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<add> if err != nil {
<add> t.Fatalf("failed to run container: %v, output: %q", err, out)
<add> }
<add>
<add> out = stripTrailingCharacters(out)
<add>
<add> // make sure the container has exited before trying the "start -a"
<add> waitCmd := exec.Command(dockerBinary, "wait", out)
<add> if out, _, err = runCommandWithOutput(waitCmd); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> startCmd := exec.Command(dockerBinary, "start", "-a", out)
<add> startOut, exitCode, err := runCommandWithOutput(startCmd)
<add> if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
<add> t.Fatalf("start command failed unexpectedly with error: %v, output: %q", err, startOut)
<add> }
<add> if exitCode != 1 {
<add> t.Fatalf("start -a did not respond with proper exit code: expected 1, got %d", exitCode)
<add> }
<add>
<add> logDone("start - correct exit code returned with -a")
<add>} | 2 |
Text | Text | remove ref to data-react-id | 83a978d5dd9c0ded959e9d6fa5757030eac2d63d | <ide><path>docs/recipes/ServerRendering.md
<ide> hydrate(
<ide>
<ide> You can set up your build tool of choice (Webpack, Browserify, etc.) to compile a bundle file into `static/bundle.js`.
<ide>
<del>When the page loads, the bundle file will be started up and [`ReactDOM.hydrate()`](https://reactjs.org/docs/react-dom.html#hydrate) will hook into the `data-react-id` attributes from the server-rendered HTML. This will connect our newly-started React instance to the virtual DOM used on the server. Since we have the same initial state for our Redux store and used the same code for all our view components, the result will be the same real DOM.
<add>When the page loads, the bundle file will be started up and [`ReactDOM.hydrate()`](https://reactjs.org/docs/react-dom.html#hydrate) will reuse the server-rendered HTML. This will connect our newly-started React instance to the virtual DOM used on the server. Since we have the same initial state for our Redux store and used the same code for all our view components, the result will be the same real DOM.
<ide>
<ide> And that's it! That is all we need to do to implement server side rendering.
<ide> | 1 |
PHP | PHP | fix return type | ff69df0a028747f4361ef2b4615b2b03a719dbca | <ide><path>src/Controller/Component/PaginatorComponent.php
<ide> public function implementedEvents()
<ide> *
<ide> * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate.
<ide> * @param array $settings The settings/configuration used for pagination.
<del> * @return array Query results
<add> * @return \Cake\Datasource\ResultSetInterface Query results
<ide> * @throws \Cake\Network\Exception\NotFoundException
<ide> */
<ide> public function paginate($object, array $settings = []) | 1 |
Text | Text | correct typos in various docs | 8f87080fcd05cdd9cddccf055c68f1da30fc7332 | <ide><path>doc/api/crypto.md
<ide> otherwise `err` will be `null`. By default, the successfully generated
<ide> thrown if any of the input arguments specify invalid values or types.
<ide>
<ide> If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
<del>please specify a `digest` explicitely.
<add>please specify a `digest` explicitly.
<ide>
<ide> The `iterations` argument must be a number set as high as possible. The
<ide> higher the number of iterations, the more secure the derived key will be,
<ide> If an error occurs an `Error` will be thrown, otherwise the derived key will be
<ide> returned as a [`Buffer`][].
<ide>
<ide> If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
<del>please specify a `digest` explicitely.
<add>please specify a `digest` explicitly.
<ide>
<ide> The `iterations` argument must be a number set as high as possible. The
<ide> higher the number of iterations, the more secure the derived key will be,
<ide><path>doc/api/n-api.md
<ide> typedef void (*napi_finalize)(napi_env env,
<ide>
<ide> #### napi_async_execute_callback
<ide> Function pointer used with functions that support asynchronous
<del>operations. Callback functions must statisfy the following signature:
<add>operations. Callback functions must satisfy the following signature:
<ide>
<ide> ```C
<ide> typedef void (*napi_async_execute_callback)(napi_env env, void* data);
<ide> calls should be made in `napi_async_complete_callback` instead.
<ide>
<ide> #### napi_async_complete_callback
<ide> Function pointer used with functions that support asynchronous
<del>operations. Callback functions must statisfy the following signature:
<add>operations. Callback functions must satisfy the following signature:
<ide>
<ide> ```C
<ide> typedef void (*napi_async_complete_callback)(napi_env env,
<ide><path>doc/api/process.md
<ide> reports for the current process. Additional documentation is available in the
<ide> added: v11.8.0
<ide> -->
<ide>
<del>* `err` {Error} A custom error used for reporting the JavsScript stack.
<add>* `err` {Error} A custom error used for reporting the JavaScript stack.
<ide> * Returns: {string}
<ide>
<ide> Returns a JSON-formatted diagnostic report for the running process. The report's
<ide> added: v11.8.0
<ide> should be a relative path, that will be appended to the directory specified in
<ide> `process.report.setOptions`, or the current working directory of the Node.js
<ide> process, if unspecified.
<del>* `err` {Error} A custom error used for reporting the JavsScript stack.
<add>* `err` {Error} A custom error used for reporting the JavaScript stack.
<ide>
<ide> * Returns: {string} Returns the filename of the generated report.
<ide>
<ide><path>doc/api/v8.md
<ide> if a previous write has failed.
<ide> * `id` {integer} A 32-bit unsigned integer.
<ide> * `arrayBuffer` {ArrayBuffer} An `ArrayBuffer` instance.
<ide>
<del>Marks an `ArrayBuffer` as havings its contents transferred out of band.
<add>Marks an `ArrayBuffer` as having its contents transferred out of band.
<ide> Pass the corresponding `ArrayBuffer` in the deserializing context to
<ide> [`deserializer.transferArrayBuffer()`][].
<ide>
<ide> Deserializes a JavaScript value from the buffer and returns it.
<ide> * `id` {integer} A 32-bit unsigned integer.
<ide> * `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An `ArrayBuffer` instance.
<ide>
<del>Marks an `ArrayBuffer` as havings its contents transferred out of band.
<add>Marks an `ArrayBuffer` as having its contents transferred out of band.
<ide> Pass the corresponding `ArrayBuffer` in the serializing context to
<ide> [`serializer.transferArrayBuffer()`][] (or return the `id` from
<ide> [`serializer._getSharedArrayBufferId()`][] in the case of `SharedArrayBuffer`s). | 4 |
Text | Text | remove target size for ctc | bb28770aa1fb541b5a7cc0745b17ca4881bfade6 | <ide><path>GOVERNANCE.md
<ide> A guide for Collaborators is maintained in
<ide>
<ide> ## CTC Membership
<ide>
<del>CTC seats are not time-limited. There is no fixed size of the CTC.
<del>However, the expected target is between 6 and 12, to ensure adequate
<del>coverage of important areas of expertise, balanced with the ability to
<del>make decisions efficiently.
<add>CTC seats are not time-limited. There is no fixed size of the CTC. The CTC
<add>should be of such a size as to ensure adequate coverage of important areas of
<add>expertise balanced with the ability to make decisions efficiently.
<ide>
<ide> There is no specific set of requirements or qualifications for CTC
<ide> membership beyond these rules. | 1 |
Python | Python | allow subclasses in ndarray.__array_function__ | f7a82245fcd61a9b477d250d94951f33dfe2f097 | <ide><path>numpy/core/_methods.py
<ide> def _array_function(self, func, types, args, kwargs):
<ide> # TODO: rewrite this in C
<ide> # Cannot handle items that have __array_function__ other than our own.
<ide> for t in types:
<del> if t is not mu.ndarray:
<del> method = getattr(t, '__array_function__', _NDARRAY_ARRAY_FUNCTION)
<del> if method is not _NDARRAY_ARRAY_FUNCTION:
<del> return NotImplemented
<del>
<del> # Arguments contain no overrides, so we can safely call the
<del> # overloaded function again.
<del> return func(*args, **kwargs)
<add> if not issubclass(t, mu.ndarray) and hasattr(t, '__array_function__'):
<add> return NotImplemented
<add>
<add> # The regular implementation can handle this, so we call it directly.
<add> return func.__wrapped__(*args, **kwargs)
<ide><path>numpy/core/overrides.py
<ide> def get_overloaded_types_and_args(relevant_args):
<ide> overloaded_types = [arg_type]
<ide> overloaded_args = [arg]
<ide>
<del> # Short-cut for the common case of only ndarray.
<del> if overloaded_types == _NDARRAY_ONLY:
<del> return overloaded_types, []
<del>
<del> # Special handling for ndarray.__array_function__
<del> overloaded_args = [
<del> arg for arg in overloaded_args
<del> if type(arg).__array_function__ is not _NDARRAY_ARRAY_FUNCTION
<del> ]
<del>
<ide> return overloaded_types, overloaded_args
<ide>
<ide>
<ide> def array_function_implementation_or_override(
<ide> """
<ide> # Check for __array_function__ methods.
<ide> types, overloaded_args = get_overloaded_types_and_args(relevant_args)
<del> if not overloaded_args:
<add> # Short-cut for common cases: no overload or only ndarray overload
<add> # (directly or with subclasses that do not override __array_function__).
<add> if (not overloaded_args or types == _NDARRAY_ONLY or
<add> all(type(arg).__array_function__ is _NDARRAY_ARRAY_FUNCTION
<add> for arg in overloaded_args)):
<ide> return implementation(*args, **kwargs)
<ide>
<ide> # Call overrides
<ide><path>numpy/core/tests/test_overrides.py
<ide> def _return_not_implemented(self, *args, **kwargs):
<ide> return NotImplemented
<ide>
<ide>
<add># need to define this at the top level to test pickling
<add>@array_function_dispatch(lambda array: (array,))
<add>def dispatched_one_arg(array):
<add> """Docstring."""
<add> return 'original'
<add>
<add>
<add>@array_function_dispatch(lambda array1, array2: (array1, array2))
<add>def dispatched_two_arg(array1, array2):
<add> """Docstring."""
<add> return 'original'
<add>
<add>
<add>@requires_array_function
<ide> class TestGetOverloadedTypesAndArgs(object):
<ide>
<ide> def test_ndarray(self):
<ide> array = np.array(1)
<ide>
<ide> types, args = get_overloaded_types_and_args([array])
<ide> assert_equal(set(types), {np.ndarray})
<del> assert_equal(list(args), [])
<add> assert_equal(list(args), [array])
<ide>
<ide> types, args = get_overloaded_types_and_args([array, array])
<ide> assert_equal(len(types), 1)
<ide> assert_equal(set(types), {np.ndarray})
<del> assert_equal(list(args), [])
<add> assert_equal(list(args), [array])
<ide>
<ide> types, args = get_overloaded_types_and_args([array, 1])
<ide> assert_equal(set(types), {np.ndarray})
<del> assert_equal(list(args), [])
<add> assert_equal(list(args), [array])
<ide>
<ide> types, args = get_overloaded_types_and_args([1, array])
<ide> assert_equal(set(types), {np.ndarray})
<del> assert_equal(list(args), [])
<add> assert_equal(list(args), [array])
<ide>
<ide> def test_ndarray_subclasses(self):
<ide>
<ide> class NoOverrideSub(np.ndarray):
<ide>
<ide> types, args = get_overloaded_types_and_args([array, override_sub])
<ide> assert_equal(set(types), {np.ndarray, OverrideSub})
<del> assert_equal(list(args), [override_sub])
<add> assert_equal(list(args), [override_sub, array])
<ide>
<ide> types, args = get_overloaded_types_and_args([array, no_override_sub])
<ide> assert_equal(set(types), {np.ndarray, NoOverrideSub})
<del> assert_equal(list(args), [])
<add> assert_equal(list(args), [no_override_sub, array])
<ide>
<ide> types, args = get_overloaded_types_and_args(
<ide> [override_sub, no_override_sub])
<ide> assert_equal(set(types), {OverrideSub, NoOverrideSub})
<del> assert_equal(list(args), [override_sub])
<add> assert_equal(list(args), [override_sub, no_override_sub])
<ide>
<ide> def test_ndarray_and_duck_array(self):
<ide>
<ide> class Other(object):
<ide>
<ide> types, args = get_overloaded_types_and_args([other, array])
<ide> assert_equal(set(types), {np.ndarray, Other})
<del> assert_equal(list(args), [other])
<add> assert_equal(list(args), [other, array])
<ide>
<ide> types, args = get_overloaded_types_and_args([array, other])
<ide> assert_equal(set(types), {np.ndarray, Other})
<del> assert_equal(list(args), [other])
<add> assert_equal(list(args), [array, other])
<ide>
<ide> def test_ndarray_subclass_and_duck_array(self):
<ide>
<ide> class Other(object):
<ide> other = Other()
<ide>
<ide> assert_equal(_get_overloaded_args([array, subarray, other]),
<del> [subarray, other])
<add> [subarray, array, other])
<ide> assert_equal(_get_overloaded_args([array, other, subarray]),
<del> [subarray, other])
<add> [subarray, array, other])
<ide>
<ide> def test_many_duck_arrays(self):
<ide>
<ide> class D(object):
<ide> assert_equal(_get_overloaded_args([a, c, b]), [c, b, a])
<ide>
<ide>
<add>@requires_array_function
<ide> class TestNDArrayArrayFunction(object):
<ide>
<ide> def test_method(self):
<ide>
<del> class SubOverride(np.ndarray):
<add> class Other(object):
<ide> __array_function__ = _return_not_implemented
<ide>
<ide> class NoOverrideSub(np.ndarray):
<ide> pass
<ide>
<del> array = np.array(1)
<add> class OverrideSub(np.ndarray):
<add> __array_function__ = _return_not_implemented
<ide>
<del> def func():
<del> return 'original'
<add> array = np.array([1])
<add> other = Other()
<add> no_override_sub = array.view(NoOverrideSub)
<add> override_sub = array.view(OverrideSub)
<ide>
<del> result = array.__array_function__(
<del> func=func, types=(np.ndarray,), args=(), kwargs={})
<add> result = array.__array_function__(func=dispatched_two_arg,
<add> types=(np.ndarray,),
<add> args=(array, 1.), kwargs={})
<ide> assert_equal(result, 'original')
<ide>
<del> result = array.__array_function__(
<del> func=func, types=(np.ndarray, SubOverride), args=(), kwargs={})
<add> result = array.__array_function__(func=dispatched_two_arg,
<add> types=(np.ndarray, Other),
<add> args=(array, other), kwargs={})
<ide> assert_(result is NotImplemented)
<ide>
<del> result = array.__array_function__(
<del> func=func, types=(np.ndarray, NoOverrideSub), args=(), kwargs={})
<add> result = array.__array_function__(func=dispatched_two_arg,
<add> types=(np.ndarray, NoOverrideSub),
<add> args=(array, no_override_sub),
<add> kwargs={})
<ide> assert_equal(result, 'original')
<ide>
<add> result = array.__array_function__(func=dispatched_two_arg,
<add> types=(np.ndarray, OverrideSub),
<add> args=(array, override_sub),
<add> kwargs={})
<add> assert_equal(result, 'original')
<ide>
<del># need to define this at the top level to test pickling
<del>@array_function_dispatch(lambda array: (array,))
<del>def dispatched_one_arg(array):
<del> """Docstring."""
<del> return 'original'
<add> with assert_raises_regex(TypeError, 'no implementation found'):
<add> np.concatenate((array, other))
<add>
<add> expected = np.concatenate((array, array))
<add> result = np.concatenate((array, no_override_sub))
<add> assert_equal(result, expected.view(NoOverrideSub))
<add> result = np.concatenate((array, override_sub))
<add> assert_equal(result, expected.view(OverrideSub))
<ide>
<ide>
<ide> @requires_array_function | 3 |
Python | Python | add experimental warning | d9e848c1d646a47e4cff50555f7bff3ad8e4033c | <ide><path>src/transformers/models/gpt2/modeling_gpt2.py
<ide> class GPT2DoubleHeadsModelOutput(ModelOutput):
<ide> Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
<ide> """
<ide> PARALLELIZE_DOCSTRING = r"""
<add> This is an experimental feature and is a subject to change at a moment's notice.
<add>
<ide> Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
<ide> it will evenly distribute blocks across all devices.
<ide>
<ide><path>src/transformers/models/t5/modeling_t5.py
<ide> def load_tf_weights_in_t5(model, config, tf_checkpoint_path):
<ide> # - PreTrainedModel for the models (it-self a sub-class of torch.nn.Module)
<ide> ####################################################
<ide> PARALLELIZE_DOCSTRING = r"""
<add> This is an experimental feature and is a subject to change at a moment's notice.
<add>
<ide> Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
<ide> it will evenly distribute blocks across all devices.
<ide> | 2 |
PHP | PHP | move xmlexception under utility\error | a427c33cb9e1be23c824cf2fa11b0f3dc05889a5 | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<del>use Cake\Error;
<add>use Cake\Error\Exception;
<ide> use Cake\Event\Event;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Routing\Router;
<add>use Cake\Utility\Error\XmlException;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\Utility\Xml;
<ide>
<ide> public function convertXml($xml) {
<ide> return Xml::toArray($xml->data);
<ide> }
<ide> return Xml::toArray($xml);
<del> } catch (Error\XmlException $e) {
<add> } catch (XmlException $e) {
<ide> return array();
<ide> }
<ide> }
<ide> public function mapAlias($alias) {
<ide> */
<ide> public function addInputType($type, $handler) {
<ide> if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
<del> throw new Error\Exception('You must give a handler callback.');
<add> throw new Exception('You must give a handler callback.');
<ide> }
<ide> $this->_inputTypeMap[$type] = $handler;
<ide> }
<add><path>src/Utility/Error/XmlException.php
<del><path>src/Error/XmlException.php
<ide> * @since 3.0.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>namespace Cake\Error;
<add>namespace Cake\Utility\Error;
<add>
<add>use Cake\Error\Exception;
<ide>
<ide> /**
<ide> * Exception class for Xml. This exception will be thrown from Xml when it
<ide><path>src/Utility/Xml.php
<ide> namespace Cake\Utility;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Error;
<ide> use Cake\Network\Http\Client;
<add>use Cake\Utility\Error\XmlException;
<ide> use \DOMDocument;
<ide>
<ide> /**
<ide> class Xml {
<ide> * @param string|array $input XML string, a path to a file, a URL or an array
<ide> * @param string|array $options The options to use
<ide> * @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
<del> * @throws \Cake\Error\XmlException
<add> * @throws \Cake\Utility\Error\XmlException
<ide> */
<ide> public static function build($input, array $options = []) {
<ide> $defaults = array(
<ide> public static function build($input, array $options = []) {
<ide> $socket = new Client(['redirect' => 10]);
<ide> $response = $socket->get($input);
<ide> if (!$response->isOk()) {
<del> throw new Error\XmlException('XML cannot be read.');
<add> throw new XmlException('XML cannot be read.');
<ide> }
<ide> return static::_loadXml($response->body, $options);
<ide> } catch (Error\SocketException $e) {
<del> throw new Error\XmlException('XML cannot be read.');
<add> throw new XmlException('XML cannot be read.');
<ide> }
<ide> } elseif (!is_string($input)) {
<del> throw new Error\XmlException('Invalid input.');
<add> throw new XmlException('Invalid input.');
<ide> }
<del> throw new Error\XmlException('XML cannot be read.');
<add> throw new XmlException('XML cannot be read.');
<ide> }
<ide>
<ide> /**
<ide> public static function build($input, array $options = []) {
<ide> * @param string $input The input to load.
<ide> * @param array $options The options to use. See Xml::build()
<ide> * @return \SimpleXmlElement|\DOMDocument
<del> * @throws \Cake\Error\XmlException
<add> * @throws \Cake\Utility\Error\XmlException
<ide> */
<ide> protected static function _loadXml($input, $options) {
<ide> $hasDisable = function_exists('libxml_disable_entity_loader');
<ide> protected static function _loadXml($input, $options) {
<ide> }
<ide> libxml_use_internal_errors($internalErrors);
<ide> if ($xml === null) {
<del> throw new Error\XmlException('Xml cannot be read.');
<add> throw new XmlException('Xml cannot be read.');
<ide> }
<ide> return $xml;
<ide> }
<ide> protected static function _loadXml($input, $options) {
<ide> * @param array $input Array with data
<ide> * @param string|array $options The options to use
<ide> * @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
<del> * @throws \Cake\Error\XmlException
<add> * @throws \Cake\Utility\Error\XmlException
<ide> */
<ide> public static function fromArray(array $input, $options = array()) {
<del> if (count($input) !== 1) {
<del> throw new Error\XmlException('Invalid input.');
<add> if (!is_array($input) || count($input) !== 1) {
<add> throw new XmlException('Invalid input.');
<ide> }
<ide> $key = key($input);
<ide> if (is_int($key)) {
<del> throw new Error\XmlException('The key of input must be alphanumeric');
<add> throw new XmlException('The key of input must be alphanumeric');
<ide> }
<ide>
<ide> if (!is_array($options)) {
<ide> public static function fromArray(array $input, $options = array()) {
<ide> * @param array $data Array of data to append to the $node.
<ide> * @param string $format Either 'attribute' or 'tags'. This determines where nested keys go.
<ide> * @return void
<del> * @throws \Cake\Error\XmlException
<add> * @throws \Cake\Utility\Error\XmlException
<ide> */
<ide> protected static function _fromArray($dom, $node, &$data, $format) {
<ide> if (empty($data) || !is_array($data)) {
<ide> protected static function _fromArray($dom, $node, &$data, $format) {
<ide> }
<ide> } else {
<ide> if ($key[0] === '@') {
<del> throw new Error\XmlException('Invalid array');
<add> throw new XmlException('Invalid array');
<ide> }
<ide> if (is_numeric(implode('', array_keys($value)))) { // List
<ide> foreach ($value as $item) {
<ide> protected static function _fromArray($dom, $node, &$data, $format) {
<ide> }
<ide> }
<ide> } else {
<del> throw new Error\XmlException('Invalid array');
<add> throw new XmlException('Invalid array');
<ide> }
<ide> }
<ide> }
<ide> protected static function _createChild($data) {
<ide> *
<ide> * @param \SimpleXMLElement|\DOMDocument|\DOMNode $obj SimpleXMLElement, DOMDocument or DOMNode instance
<ide> * @return array Array representation of the XML structure.
<del> * @throws \Cake\Error\XmlException
<add> * @throws \Cake\Utility\Error\XmlException
<ide> */
<ide> public static function toArray($obj) {
<ide> if ($obj instanceof \DOMNode) {
<ide> $obj = simplexml_import_dom($obj);
<ide> }
<ide> if (!($obj instanceof \SimpleXMLElement)) {
<del> throw new Error\XmlException('The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.');
<add> throw new XmlException('The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.');
<ide> }
<ide> $result = array();
<ide> $namespaces = array_merge(array('' => ''), $obj->getNamespaces(true));
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<add>use Cake\Utility\Error\XmlException;
<ide> use Cake\Utility\Xml;
<ide>
<ide> /**
<ide> public function testBuildInvalidData($value) {
<ide> /**
<ide> * Test that building SimpleXmlElement with invalid XML causes the right exception.
<ide> *
<del> * @expectedException \Cake\Error\XmlException
<add> * @expectedException \Cake\Utility\Error\XmlException
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidDataSimpleXml() {
<ide> public static function invalidToArrayDataProvider() {
<ide> * testToArrayFail method
<ide> *
<ide> * @dataProvider invalidToArrayDataProvider
<del> * @expectedException \Cake\Error\XmlException
<add> * @expectedException \Cake\Utility\Error\XmlException
<ide> * @return void
<ide> */
<ide> public function testToArrayFail($value) { | 4 |
Ruby | Ruby | fix railtie to pass class when setting options | 4533bb7dcbdd6e0451395bc869d6c3603c6ff1df | <ide><path>actionpack/lib/system_testing/driver_adapter.rb
<ide> def driver
<ide> @driver ||= DriverAdapters.lookup(default_driver).new
<ide> end
<ide>
<del> def driver=(adapter: default_driver, settings: {})
<del> @driver = DriverAdapters.lookup(adapter).new(settings)
<add> def driver=(adapter)
<add> @driver = case adapter
<add> when Symbol
<add> DriverAdapters.lookup(adapter).new
<add> else
<add> adapter
<add> end
<add>
<add> @driver.call
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/system_testing/railtie.rb
<add>require 'system_test_case'
<add>
<ide> module SystemTesting
<ide> class Railtie < Rails::Railtie
<ide> config.system_testing = ActiveSupport::OrderedOptions.new
<ide>
<ide> initializer "system_testing.set_configs" do |app|
<ide> options = app.config.system_testing
<del> options.driver ||= {}
<add> options.driver ||= Rails::SystemTestCase.default_driver
<ide>
<ide> ActiveSupport.on_load(:system_testing) do
<ide> options.each { |k,v| send("#{k}=", v) }
<ide><path>actionpack/lib/system_testing/test_helper.rb
<ide> module TestHelper
<ide> end
<ide> end
<ide>
<del> def before_setup
<del> Base.driver.call
<del> super
<del> end
<del>
<ide> def after_teardown
<ide> Capybara.reset_sessions!
<ide> super | 3 |
Javascript | Javascript | fix duplication due to unsafe cache | 80b1e77705c1810ae7e95dea4453035da2ef652a | <ide><path>lib/Compilation.js
<ide> const byLocation = compareSelect(err => err.loc, compareLocations);
<ide>
<ide> const compareErrors = concatComparators(byModule, byLocation, byMessage);
<ide>
<del>/** @type {WeakMap<Dependency, Module & { restoreFromUnsafeCache: Function }>} */
<add>/** @type {WeakMap<Dependency, Module & { restoreFromUnsafeCache: Function } | null>} */
<ide> const unsafeCacheDependencies = new WeakMap();
<ide>
<del>/** @type {WeakMap<Module, object>} */
<add>/** @type {WeakMap<Module & { restoreFromUnsafeCache: Function }, object>} */
<ide> const unsafeCacheData = new WeakMap();
<ide>
<ide> class Compilation {
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> this.usedModuleIds = null;
<ide> /** @type {boolean} */
<ide> this.needAdditionalPass = false;
<del> /** @type {Set<Module>} */
<del> this._restoredUnsafeCacheEntries = new Set();
<add> /** @type {Set<Module & { restoreFromUnsafeCache: Function }>} */
<add> this._restoredUnsafeCacheModuleEntries = new Set();
<add> /** @type {Map<string, Module & { restoreFromUnsafeCache: Function }>} */
<add> this._restoredUnsafeCacheEntries = new Map();
<ide> /** @type {WeakSet<Module>} */
<ide> this.builtModules = new WeakSet();
<ide> /** @type {WeakSet<Module>} */
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> * @returns {void}
<ide> */
<ide> _processModuleDependencies(module, callback) {
<del> /**
<del> * @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>}
<del> */
<add> /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>} */
<ide> const sortedDependencies = [];
<ide>
<ide> /** @type {DependenciesBlock} */
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> /** @type {Dependency[]} */
<ide> let listCacheValue;
<ide>
<del> const unsafeRestoredModules = new Set();
<add> let inProgressSorting = 1;
<add> let inProgressTransitive = 1;
<add>
<add> const onDependenciesSorted = err => {
<add> if (err) return callback(err);
<add>
<add> // early exit without changing parallelism back and forth
<add> if (sortedDependencies.length === 0 && inProgressTransitive === 1) {
<add> return callback();
<add> }
<add>
<add> // This is nested so we need to allow one additional task
<add> this.processDependenciesQueue.increaseParallelism();
<add>
<add> for (const item of sortedDependencies) {
<add> inProgressTransitive++;
<add> this.handleModuleCreation(item, err => {
<add> // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
<add> // errors are created inside closures that keep a reference to the Compilation, so errors are
<add> // leaking the Compilation object.
<add> if (err && this.bail) {
<add> if (inProgressTransitive <= 0) return;
<add> inProgressTransitive = -1;
<add> // eslint-disable-next-line no-self-assign
<add> err.stack = err.stack;
<add> onTransitiveTasksFinished(err);
<add> return;
<add> }
<add> if (--inProgressTransitive === 0) onTransitiveTasksFinished();
<add> });
<add> }
<add> if (--inProgressTransitive === 0) onTransitiveTasksFinished();
<add> };
<add>
<add> const onTransitiveTasksFinished = err => {
<add> if (err) return callback(err);
<add> this.processDependenciesQueue.decreaseParallelism();
<add>
<add> return callback();
<add> };
<ide>
<ide> /**
<ide> * @param {Dependency} dep dependency
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> this.moduleGraph.setParents(dep, currentBlock, module, index);
<ide> if (this._unsafeCache) {
<ide> try {
<del> const cachedModule = unsafeCacheDependencies.get(dep);
<del> if (cachedModule === null) return;
<del> if (cachedModule !== undefined) {
<del> if (!this._restoredUnsafeCacheEntries.has(cachedModule)) {
<del> const data = unsafeCacheData.get(cachedModule);
<del> cachedModule.restoreFromUnsafeCache(
<del> data,
<del> this.params.normalModuleFactory,
<del> this.params
<add> const unsafeCachedModule = unsafeCacheDependencies.get(dep);
<add> if (unsafeCachedModule === null) return;
<add> if (unsafeCachedModule !== undefined) {
<add> if (
<add> this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule)
<add> ) {
<add> this._handleExistingModuleFromUnsafeCache(
<add> module,
<add> dep,
<add> unsafeCachedModule
<ide> );
<del> this._restoredUnsafeCacheEntries.add(cachedModule);
<del> if (!this.modules.has(cachedModule)) {
<del> this._handleNewModuleFromUnsafeCache(module, dep, cachedModule);
<del> unsafeRestoredModules.add(cachedModule);
<add> return;
<add> }
<add> const identifier = unsafeCachedModule.identifier();
<add> const cachedModule =
<add> this._restoredUnsafeCacheEntries.get(identifier);
<add> if (cachedModule !== undefined) {
<add> // update unsafe cache to new module
<add> unsafeCacheDependencies.set(dep, cachedModule);
<add> this._handleExistingModuleFromUnsafeCache(
<add> module,
<add> dep,
<add> cachedModule
<add> );
<add> return;
<add> }
<add> inProgressSorting++;
<add> this._modulesCache.get(identifier, null, (err, cachedModule) => {
<add> if (err) {
<add> if (inProgressSorting <= 0) return;
<add> inProgressSorting = -1;
<add> onDependenciesSorted(err);
<ide> return;
<ide> }
<del> }
<del> this._handleExistingModuleFromUnsafeCache(
<del> module,
<del> dep,
<del> cachedModule
<del> );
<add> try {
<add> if (!this._restoredUnsafeCacheEntries.has(identifier)) {
<add> const data = unsafeCacheData.get(cachedModule);
<add> if (data === undefined) {
<add> processDependencyForResolving(dep);
<add> if (--inProgressSorting === 0) onDependenciesSorted();
<add> return;
<add> }
<add> if (cachedModule !== unsafeCachedModule) {
<add> unsafeCacheDependencies.set(dep, cachedModule);
<add> }
<add> cachedModule.restoreFromUnsafeCache(
<add> data,
<add> this.params.normalModuleFactory,
<add> this.params
<add> );
<add> this._restoredUnsafeCacheEntries.set(
<add> identifier,
<add> cachedModule
<add> );
<add> this._restoredUnsafeCacheModuleEntries.add(cachedModule);
<add> if (!this.modules.has(cachedModule)) {
<add> inProgressTransitive++;
<add> this._handleNewModuleFromUnsafeCache(
<add> module,
<add> dep,
<add> cachedModule,
<add> err => {
<add> if (err) {
<add> if (inProgressTransitive <= 0) return;
<add> inProgressTransitive = -1;
<add> onTransitiveTasksFinished(err);
<add> }
<add> if (--inProgressTransitive === 0)
<add> return onTransitiveTasksFinished();
<add> }
<add> );
<add> if (--inProgressSorting === 0) onDependenciesSorted();
<add> return;
<add> }
<add> }
<add> if (unsafeCachedModule !== cachedModule) {
<add> unsafeCacheDependencies.set(dep, cachedModule);
<add> }
<add> this._handleExistingModuleFromUnsafeCache(
<add> module,
<add> dep,
<add> cachedModule
<add> ); // a3
<add> } catch (err) {
<add> if (inProgressSorting <= 0) return;
<add> inProgressSorting = -1;
<add> onDependenciesSorted(err);
<add> return;
<add> }
<add> if (--inProgressSorting === 0) onDependenciesSorted();
<add> });
<ide> return;
<ide> }
<ide> } catch (e) {
<ide> console.error(e);
<ide> }
<ide> }
<add> processDependencyForResolving(dep);
<add> };
<add>
<add> /**
<add> * @param {Dependency} dep dependency
<add> * @returns {void}
<add> */
<add> const processDependencyForResolving = dep => {
<ide> const resourceIdent = dep.getResourceIdentifier();
<ide> if (resourceIdent !== undefined && resourceIdent !== null) {
<ide> const category = dep.category;
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> return callback(e);
<ide> }
<ide>
<del> if (sortedDependencies.length === 0 && unsafeRestoredModules.size === 0) {
<del> callback();
<del> return;
<del> }
<del>
<del> // This is nested so we need to allow one additional task
<del> this.processDependenciesQueue.increaseParallelism();
<del>
<del> const processSortedDependency = (item, callback) => {
<del> this.handleModuleCreation(item, err => {
<del> // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
<del> // errors are created inside closures that keep a reference to the Compilation, so errors are
<del> // leaking the Compilation object.
<del> if (err && this.bail) {
<del> // eslint-disable-next-line no-self-assign
<del> err.stack = err.stack;
<del> return callback(err);
<del> }
<del> callback();
<del> });
<del> };
<del>
<del> const processUnsafeRestoredModule = (item, callback) => {
<del> this._handleModuleBuildAndDependencies(module, item, true, callback);
<del> };
<del>
<del> const finalCallback = err => {
<del> this.processDependenciesQueue.decreaseParallelism();
<del>
<del> return callback(err);
<del> };
<del>
<del> if (sortedDependencies.length === 0) {
<del> asyncLib.forEach(
<del> unsafeRestoredModules,
<del> processUnsafeRestoredModule,
<del> finalCallback
<del> );
<del> } else if (unsafeRestoredModules.size === 0) {
<del> asyncLib.forEach(
<del> sortedDependencies,
<del> processSortedDependency,
<del> finalCallback
<del> );
<del> } else {
<del> asyncLib.parallel(
<del> [
<del> cb =>
<del> asyncLib.forEach(
<del> unsafeRestoredModules,
<del> processUnsafeRestoredModule,
<del> cb
<del> ),
<del> cb =>
<del> asyncLib.forEach(sortedDependencies, processSortedDependency, cb)
<del> ],
<del> finalCallback
<del> );
<del> }
<add> if (--inProgressSorting === 0) onDependenciesSorted();
<ide> }
<ide>
<del> _handleNewModuleFromUnsafeCache(originModule, dependency, module) {
<add> _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) {
<ide> const moduleGraph = this.moduleGraph;
<ide>
<ide> moduleGraph.setResolvedModule(originModule, dependency, module);
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> this._modules.set(module.identifier(), module);
<ide> this.modules.add(module);
<ide> ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
<add>
<add> this._handleModuleBuildAndDependencies(
<add> originModule,
<add> module,
<add> true,
<add> callback
<add> );
<ide> }
<ide>
<ide> _handleExistingModuleFromUnsafeCache(originModule, dependency, module) {
<ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
<ide> /** @type {any} */ (module).restoreFromUnsafeCache &&
<ide> this._unsafeCachePredicate(module)
<ide> ) {
<add> const unsafeCacheableModule =
<add> /** @type {Module & { restoreFromUnsafeCache: Function }} */ (
<add> module
<add> );
<ide> for (let i = 0; i < dependencies.length; i++) {
<ide> const dependency = dependencies[i];
<ide> moduleGraph.setResolvedModule(
<ide> connectOrigin ? originModule : null,
<ide> dependency,
<del> module
<del> );
<del> unsafeCacheDependencies.set(
<del> dependency,
<del> /** @type {any} */ (module)
<add> unsafeCacheableModule
<ide> );
<add> unsafeCacheDependencies.set(dependency, unsafeCacheableModule);
<ide> }
<del> if (!unsafeCacheData.has(module)) {
<del> unsafeCacheData.set(module, module.getUnsafeCacheData());
<add> if (!unsafeCacheData.has(unsafeCacheableModule)) {
<add> unsafeCacheData.set(
<add> unsafeCacheableModule,
<add> unsafeCacheableModule.getUnsafeCacheData()
<add> );
<ide> }
<ide> } else {
<ide> applyFactoryResultDependencies();
<ide><path>test/WatchTestCases.template.js
<ide> const describeCases = config => {
<ide> srcPath: tempDirectory
<ide> });
<ide> }
<del> const applyConfig = options => {
<add> const applyConfig = (options, idx) => {
<ide> if (!options.mode) options.mode = "development";
<ide> if (!options.context) options.context = tempDirectory;
<ide> if (!options.entry) options.entry = "./index.js";
<ide> const describeCases = config => {
<ide> options.output.pathinfo = true;
<ide> if (!options.output.filename)
<ide> options.output.filename = "bundle.js";
<add> if (options.cache && options.cache.type === "filesystem") {
<add> const cacheDirectory = path.join(tempDirectory, ".cache");
<add> options.cache.cacheDirectory = cacheDirectory;
<add> options.cache.name = `config-${idx}`;
<add> }
<ide> if (config.experiments) {
<ide> if (!options.experiments) options.experiments = {};
<ide> for (const key of Object.keys(config.experiments)) {
<ide> const describeCases = config => {
<ide> if (Array.isArray(options)) {
<ide> options.forEach(applyConfig);
<ide> } else {
<del> applyConfig(options);
<add> applyConfig(options, 0);
<ide> }
<ide>
<ide> const state = {};
<ide> const describeCases = config => {
<ide> triggeringFilename = filename;
<ide> }
<ide> );
<del> const watching = compiler.watch(
<add> compiler.watch(
<ide> {
<ide> aggregateTimeout: 1000
<ide> },
<ide> const describeCases = config => {
<ide> done
<ide> )
<ide> ) {
<del> watching.close();
<add> compiler.close();
<ide> return;
<ide> }
<del> watching.close(done);
<add> compiler.close(done);
<ide> }
<ide> },
<ide> 45000
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/0/after.js
<add>export default 0;
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/0/index.js
<add>import "./unsafe-cache-root";
<add>
<add>it("should compile fine", () => {});
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/0/module.js
<add>export { default } from "./after";
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/0/unsafe-cache-root.js
<add>export default require.resolve("./module");
<add>export { default as module } from "./module";
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/1/alternative-path.js
<add>export default require.resolve("./module");
<add>export { default as module } from "./module";
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/1/index.js
<add>import id from "./alternative-path";
<add>
<add>it("should compile fine", () => {
<add> expect(id).toBe("./module.js");
<add>});
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/2/after.js
<add>export { default } from "./unsafe-cache-root";
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/2/index.js
<add>import id, { module } from "./alternative-path";
<add>
<add>it("should not duplicate modules", () => {
<add> expect(id).toBe("./module.js");
<add> expect(module).toBe("./module.js");
<add>});
<ide><path>test/watchCases/cache/unsafe-cache-duplicates/webpack.config.js
<add>const path = require("path");
<add>
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = (env, { srcPath }) => ({
<add> mode: "development",
<add> cache: {
<add> type: "filesystem",
<add> maxMemoryGenerations: Infinity,
<add> idleTimeout: 1
<add> },
<add> module: {
<add> unsafeCache: module => /module\.js/.test(module.resource)
<add> },
<add> plugins: [
<add> compiler => {
<add> compiler.cache.hooks.get.tap(
<add> {
<add> name: "webpack.config.js",
<add> stage: -1000
<add> },
<add> (identifier, etag) => {
<add> if (identifier.includes(path.join(srcPath, "module.js"))) {
<add> return null;
<add> }
<add> return;
<add> }
<add> );
<add> }
<add> ]
<add>}); | 11 |
Javascript | Javascript | revise comment + add non-bubbling event test | 1aae05c4364ca8553c62b46a8df70ebe8fa574f0 | <ide><path>packages/react-dom/src/__tests__/ReactDOMEventListener-test.js
<ide> describe('ReactDOMEventListener', () => {
<ide> document.body.removeChild(container);
<ide> }
<ide> });
<add>
<add> it('should bubble non-native bubbling events', () => {
<add> const container = document.createElement('div');
<add> const ref = React.createRef();
<add> const onPlay = jest.fn();
<add> const onScroll = jest.fn();
<add> const onCancel = jest.fn();
<add> const onClose = jest.fn();
<add> document.body.appendChild(container);
<add> try {
<add> ReactDOM.render(
<add> <div
<add> onPlay={onPlay}
<add> onScroll={onScroll}
<add> onCancel={onCancel}
<add> onClose={onClose}>
<add> <div
<add> ref={ref}
<add> onPlay={onPlay}
<add> onScroll={onScroll}
<add> onCancel={onCancel}
<add> onClose={onClose}
<add> />
<add> </div>,
<add> container,
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('play', {
<add> bubbles: false,
<add> }),
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('scroll', {
<add> bubbles: false,
<add> }),
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('cancel', {
<add> bubbles: false,
<add> }),
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('close', {
<add> bubbles: false,
<add> }),
<add> );
<add> // Regression test: ensure we still emulate bubbling with non-bubbling
<add> // media
<add> expect(onPlay).toHaveBeenCalledTimes(2);
<add> expect(onScroll).toHaveBeenCalledTimes(2);
<add> expect(onCancel).toHaveBeenCalledTimes(2);
<add> expect(onClose).toHaveBeenCalledTimes(2);
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<add> });
<ide> });
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> export const nonDelegatedEvents: Set<DOMTopLevelEventType> = new Set([
<ide> TOP_CLOSE,
<ide> TOP_INVALID,
<ide> // In order to reduce bytes, we insert the above array of media events
<del> // into this Set. Note: some events like "load" and "error" aren't
<del> // exclusively media events, but rather than duplicate them, we just
<del> // take them from the media events array.
<add> // into this Set. Note: the "error" event isn't an exclusive media event,
<add> // and can occur on other elements too. Rather than duplicate that event,
<add> // we just take it from the media events array.
<ide> ...mediaEventTypes,
<ide> ]);
<ide> | 2 |
PHP | PHP | change default value of property | 8a11965b20c60961e3864dd71e8799a6b6c78a11 | <ide><path>src/Routing/Route/Route.php
<ide> class Route
<ide> *
<ide> * @var bool
<ide> */
<del> protected $braceKeys = false;
<add> protected $braceKeys = true;
<ide>
<ide> /**
<ide> * Valid HTTP methods.
<ide> protected function _writeRoute(): void
<ide>
<ide> if (strpos($route, '{') !== false && strpos($route, '}') !== false) {
<ide> preg_match_all('/\{([a-z][a-z0-9-_]*)\}/i', $route, $namedElements);
<del> $this->braceKeys = true;
<ide> } else {
<ide> preg_match_all('/:([a-z0-9-_]+(?<![-_]))/i', $route, $namedElements);
<ide> $this->braceKeys = false; | 1 |
PHP | PHP | replace more strings with constants | 3383aacd9e1f1e812c828cdcb2b2f86853d416ce | <ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testCompareFieldsEqualTo()
<ide> 'other' => 'a value'
<ide> ]
<ide> ];
<del> $this->assertTrue(Validation::compareFields('a value', 'other', 'equalto', $context));
<add> $this->assertTrue(Validation::compareFields('a value', 'other', Validation::COMPARE_EQUAL, $context));
<ide>
<ide> $context = [
<ide> 'data' => [
<ide> 'other' => 'different'
<ide> ]
<ide> ];
<del> $this->assertFalse(Validation::compareFields('a value', 'other', 'equalto', $context));
<add> $this->assertFalse(Validation::compareFields('a value', 'other', Validation::COMPARE_EQUAL, $context));
<ide>
<ide> $context = [];
<del> $this->assertFalse(Validation::compareFields('a value', 'other', 'equalto', $context));
<add> $this->assertFalse(Validation::compareFields('a value', 'other', Validation::COMPARE_EQUAL, $context));
<ide> }
<ide>
<ide> /**
<ide> public function testCompareFieldsNotEqual()
<ide> 'other' => 'different'
<ide> ]
<ide> ];
<del> $this->assertTrue(Validation::compareFields('a value', 'other', 'notequal', $context));
<add> $this->assertTrue(Validation::compareFields('a value', 'other', Validation::COMPARE_NOT_EQUAL, $context));
<ide>
<ide> $context = [
<ide> 'data' => [
<ide> 'other' => 'a value'
<ide> ]
<ide> ];
<del> $this->assertFalse(Validation::compareFields('a value', 'other', 'notequal', $context));
<add> $this->assertFalse(Validation::compareFields('a value', 'other', Validation::COMPARE_NOT_EQUAL, $context));
<ide>
<ide> $context = [];
<del> $this->assertFalse(Validation::compareFields('a value', 'other', 'notequal', $context));
<add> $this->assertFalse(Validation::compareFields('a value', 'other', Validation::COMPARE_NOT_EQUAL, $context));
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | add `--adopt` switch | a715dec49d825da2c09da3e3fe83d7009a415cb8 | <ide><path>Library/Homebrew/cask/artifact/moved.rb
<ide> def summarize_installed
<ide>
<ide> private
<ide>
<del> def move(force: false, command: nil, **options)
<add> def move(adopt: false, force: false, verbose: false, command: nil, **options)
<add> unless source.exist?
<add> raise CaskError, "It seems the #{self.class.english_name} source '#{source}' is not there."
<add> end
<add>
<ide> if Utils.path_occupied?(target)
<add> if adopt
<add> ohai "Adopting existing #{self.class.english_name} at '#{target}'"
<add> same = command.run(
<add> "/usr/bin/diff",
<add> args: ["-rq", source, target],
<add> verbose: verbose,
<add> print_stdout: verbose,
<add> ).success?
<add>
<add> unless same
<add> raise CaskError,
<add> "It seems the existing #{self.class.english_name} is different from " \
<add> "the one being installed."
<add> end
<add>
<add> # Simulate moving the source to the target location
<add> source.rmtree
<add>
<add> return post_move(command)
<add> end
<add>
<ide> message = "It seems there is already #{self.class.english_article} " \
<ide> "#{self.class.english_name} at '#{target}'"
<ide> raise CaskError, "#{message}." unless force
<ide> def move(force: false, command: nil, **options)
<ide> delete(target, force: force, command: command, **options)
<ide> end
<ide>
<del> unless source.exist?
<del> raise CaskError, "It seems the #{self.class.english_name} source '#{source}' is not there."
<del> end
<del>
<ide> ohai "Moving #{self.class.english_name} '#{source.basename}' to '#{target}'"
<ide> if target.dirname.ascend.find(&:directory?).writable?
<ide> target.dirname.mkpath
<ide> def move(force: false, command: nil, **options)
<ide> command.run!("/bin/mv", args: [source, target], sudo: true)
<ide> end
<ide>
<add> post_move(command)
<add> end
<add>
<add> # Performs any actions necessary after the source has been moved to the target location.
<add> def post_move(command)
<ide> FileUtils.ln_sf target, source
<ide>
<ide> add_altname_metadata(target, source.basename, command: command)
<ide><path>Library/Homebrew/cask/cmd/install.rb
<ide> class Install < AbstractCommand
<ide> extend T::Sig
<ide>
<ide> OPTIONS = [
<add> [:switch, "--adopt", {
<add> description: "Adopt existing artifacts in the destination that are identical to those being installed. " \
<add> "Cannot be combined with --force.",
<add> }],
<ide> [:switch, "--skip-cask-deps", {
<ide> description: "Skip installing cask dependencies.",
<ide> }],
<ide> def run
<ide> binaries: args.binaries?,
<ide> verbose: args.verbose?,
<ide> force: args.force?,
<add> adopt: args.adopt?,
<ide> skip_cask_deps: args.skip_cask_deps?,
<ide> require_sha: args.require_sha?,
<ide> quarantine: args.quarantine?,
<ide> def self.install_casks(
<ide> *casks,
<ide> verbose: nil,
<ide> force: nil,
<add> adopt: nil,
<ide> binaries: nil,
<ide> skip_cask_deps: nil,
<ide> require_sha: nil,
<ide> def self.install_casks(
<ide> options = {
<ide> verbose: verbose,
<ide> force: force,
<add> adopt: adopt,
<ide> binaries: binaries,
<ide> skip_cask_deps: skip_cask_deps,
<ide> require_sha: require_sha,
<ide><path>Library/Homebrew/cask/cmd/reinstall.rb
<ide> def run
<ide> binaries: args.binaries?,
<ide> verbose: args.verbose?,
<ide> force: args.force?,
<add> adopt: args.adopt?,
<ide> skip_cask_deps: args.skip_cask_deps?,
<ide> require_sha: args.require_sha?,
<ide> quarantine: args.quarantine?,
<ide> def self.reinstall_casks(
<ide> *casks,
<ide> verbose: nil,
<ide> force: nil,
<add> adopt: nil,
<ide> skip_cask_deps: nil,
<ide> binaries: nil,
<ide> require_sha: nil,
<ide> def self.reinstall_casks(
<ide> binaries: binaries,
<ide> verbose: verbose,
<ide> force: force,
<add> adopt: adopt,
<ide> skip_cask_deps: skip_cask_deps,
<ide> require_sha: require_sha,
<ide> quarantine: quarantine,
<ide><path>Library/Homebrew/cask/cmd/upgrade.rb
<ide> class Upgrade < AbstractCommand
<ide> extend T::Sig
<ide>
<ide> OPTIONS = [
<add> [:switch, "--adopt", {
<add> description: "Adopt existing artifacts in the destination that are identical to those being installed. " \
<add> "Cannot be combined with --force.",
<add> }],
<ide> [:switch, "--skip-cask-deps", {
<ide> description: "Skip installing cask dependencies.",
<ide> }],
<ide> def run
<ide> casks: Cask,
<ide> args: Homebrew::CLI::Args,
<ide> force: T.nilable(T::Boolean),
<add> adopt: T.nilable(T::Boolean),
<ide> greedy: T.nilable(T::Boolean),
<ide> greedy_latest: T.nilable(T::Boolean),
<ide> greedy_auto_updates: T.nilable(T::Boolean),
<ide> def self.upgrade_casks(
<ide> *casks,
<ide> args:,
<ide> force: false,
<add> adopt: false,
<ide> greedy: false,
<ide> greedy_latest: false,
<ide> greedy_auto_updates: false,
<ide> def self.upgrade_casks(
<ide> upgradable_casks.each do |(old_cask, new_cask)|
<ide> upgrade_cask(
<ide> old_cask, new_cask,
<del> binaries: binaries, force: force, skip_cask_deps: skip_cask_deps, verbose: verbose,
<add> binaries: binaries, force: force, adopt: adopt, skip_cask_deps: skip_cask_deps, verbose: verbose,
<ide> quarantine: quarantine, require_sha: require_sha
<ide> )
<ide> rescue => e
<ide> def self.upgrade_casks(
<ide>
<ide> def self.upgrade_cask(
<ide> old_cask, new_cask,
<del> binaries:, force:, quarantine:, require_sha:, skip_cask_deps:, verbose:
<add> binaries:, force:, adopt:, quarantine:, require_sha:, skip_cask_deps:, verbose:
<ide> )
<ide> require "cask/installer"
<ide>
<ide> def self.upgrade_cask(
<ide> binaries: binaries,
<ide> verbose: verbose,
<ide> force: force,
<add> adopt: adopt,
<ide> skip_cask_deps: skip_cask_deps,
<ide> require_sha: require_sha,
<ide> upgrade: true,
<ide><path>Library/Homebrew/cask/installer.rb
<ide> class Installer
<ide>
<ide> extend Predicable
<ide>
<del> def initialize(cask, command: SystemCommand, force: false,
<add> def initialize(cask, command: SystemCommand, force: false, adopt: false,
<ide> skip_cask_deps: false, binaries: true, verbose: false,
<ide> zap: false, require_sha: false, upgrade: false,
<ide> installed_as_dependency: false, quarantine: true,
<ide> verify_download_integrity: true, quiet: false)
<ide> @cask = cask
<ide> @command = command
<ide> @force = force
<add> @adopt = adopt
<ide> @skip_cask_deps = skip_cask_deps
<ide> @binaries = binaries
<ide> @verbose = verbose
<ide> def initialize(cask, command: SystemCommand, force: false,
<ide> @quiet = quiet
<ide> end
<ide>
<del> attr_predicate :binaries?, :force?, :skip_cask_deps?, :require_sha?,
<add> attr_predicate :binaries?, :force?, :adopt?, :skip_cask_deps?, :require_sha?,
<ide> :reinstall?, :upgrade?, :verbose?, :zap?, :installed_as_dependency?,
<ide> :quarantine?, :quiet?
<ide>
<ide> def install_artifacts
<ide>
<ide> next if artifact.is_a?(Artifact::Binary) && !binaries?
<ide>
<del> artifact.install_phase(command: @command, verbose: verbose?, force: force?)
<add> artifact.install_phase(command: @command, verbose: verbose?, adopt: adopt?, force: force?)
<ide> already_installed_artifacts.unshift(artifact)
<ide> end
<ide>
<ide> def cask_and_formula_dependencies
<ide>
<ide> Installer.new(
<ide> cask_or_formula,
<add> adopt: adopt?,
<ide> binaries: binaries?,
<ide> verbose: verbose?,
<ide> installed_as_dependency: true,
<ide><path>Library/Homebrew/cmd/install.rb
<ide> def install_args
<ide>
<ide> conflicts "--ignore-dependencies", "--only-dependencies"
<ide> conflicts "--build-from-source", "--build-bottle", "--force-bottle"
<add> conflicts "--adopt", "--force"
<ide>
<ide> named_args [:formula, :cask], min: 1
<ide> end
<ide> def install
<ide> binaries: args.binaries?,
<ide> verbose: args.verbose?,
<ide> force: args.force?,
<add> adopt: args.adopt?,
<ide> require_sha: args.require_sha?,
<ide> skip_cask_deps: args.skip_cask_deps?,
<ide> quarantine: args.quarantine?,
<ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> def reinstall
<ide> binaries: args.binaries?,
<ide> verbose: args.verbose?,
<ide> force: args.force?,
<add> adopt: args.adopt?,
<ide> require_sha: args.require_sha?,
<ide> skip_cask_deps: args.skip_cask_deps?,
<ide> quarantine: args.quarantine?,
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_args
<ide> cask_options
<ide>
<ide> conflicts "--build-from-source", "--force-bottle"
<add> conflicts "--adopt", "--force"
<ide>
<ide> named_args [:outdated_formula, :outdated_cask]
<ide> end
<ide> def upgrade_outdated_casks(casks, args:)
<ide> Cask::Cmd::Upgrade.upgrade_casks(
<ide> *casks,
<ide> force: args.force?,
<add> adopt: args.adopt?,
<ide> greedy: args.greedy?,
<ide> greedy_latest: args.greedy_latest?,
<ide> greedy_auto_updates: args.greedy_auto_updates?,
<ide><path>Library/Homebrew/test/cask/artifact/app_spec.rb
<ide> describe Cask::Artifact::App, :cask do
<ide> let(:cask) { Cask::CaskLoader.load(cask_path("local-caffeine")) }
<ide> let(:command) { SystemCommand }
<add> let(:adopt) { false }
<ide> let(:force) { false }
<ide> let(:app) { cask.artifacts.find { |a| a.is_a?(described_class) } }
<ide>
<ide> let(:source_path) { cask.staged_path.join("Caffeine.app") }
<ide> let(:target_path) { cask.config.appdir.join("Caffeine.app") }
<ide>
<del> let(:install_phase) { app.install_phase(command: command, force: force) }
<add> let(:install_phase) { app.install_phase(command: command, adopt: adopt, force: force) }
<ide> let(:uninstall_phase) { app.uninstall_phase(command: command, force: force) }
<ide>
<ide> before do
<ide> expect(contents_path).not_to exist
<ide> end
<ide>
<add> describe "given the adopt option" do
<add> let(:adopt) { true }
<add>
<add> describe "when the target compares different from the source" do
<add> it "avoids clobbering the existing app" do
<add> stdout = <<~EOS
<add> ==> Adopting existing App at '#{target_path}'
<add> EOS
<add>
<add> expect { install_phase }
<add> .to output(stdout).to_stdout
<add> .and raise_error(
<add> Cask::CaskError,
<add> "It seems the existing App is different from the one being installed.",
<add> )
<add>
<add> expect(source_path).to be_a_directory
<add> expect(target_path).to be_a_directory
<add> expect(File.identical?(source_path, target_path)).to be false
<add>
<add> contents_path = target_path.join("Contents/Info.plist")
<add> expect(contents_path).not_to exist
<add> end
<add> end
<add>
<add> describe "when the target compares the same as the source" do
<add> before do
<add> target_path.delete
<add> FileUtils.cp_r source_path, target_path
<add> end
<add>
<add> it "adopts the existing app" do
<add> stdout = <<~EOS
<add> ==> Adopting existing App at '#{target_path}'
<add> EOS
<add>
<add> stderr = ""
<add>
<add> expect { install_phase }
<add> .to output(stdout).to_stdout
<add> .and output(stderr).to_stderr
<add>
<add> expect(source_path).to be_a_symlink
<add> expect(target_path).to be_a_directory
<add>
<add> contents_path = target_path.join("Contents/Info.plist")
<add> expect(contents_path).to exist
<add> end
<add> end
<add> end
<add>
<ide> describe "given the force option" do
<ide> let(:force) { true }
<ide> | 9 |
Ruby | Ruby | fix active support isolated build | 32ea85f1c232261214ccc155f75349654fb7ed74 | <ide><path>activesupport/test/message_encryptors_test.rb
<ide> # frozen_string_literal: true
<ide>
<add>require_relative "abstract_unit"
<ide> require_relative "rotation_coordinator_tests"
<ide>
<ide> class MessageEncryptorsTest < ActiveSupport::TestCase
<ide><path>activesupport/test/message_verifiers_test.rb
<ide> # frozen_string_literal: true
<ide>
<add>require_relative "abstract_unit"
<ide> require_relative "rotation_coordinator_tests"
<ide>
<ide> class MessageVerifiersTest < ActiveSupport::TestCase | 2 |
Python | Python | remove lock in fit_generator | 2f4eed1f0fb01e58791f02fbe1640869f13f876b | <ide><path>keras/engine/training.py
<ide> def generator_queue(generator, max_q_size=10,
<ide> if pickle_safe:
<ide> q = multiprocessing.Queue(maxsize=max_q_size)
<ide> _stop = multiprocessing.Event()
<del> lock = multiprocessing.Lock()
<ide> else:
<ide> q = queue.Queue()
<ide> _stop = threading.Event()
<del> lock = threading.Lock()
<ide>
<ide> try:
<ide> def data_generator_task():
<ide> while not _stop.is_set():
<ide> try:
<ide> if pickle_safe or q.qsize() < max_q_size:
<del> lock.acquire()
<ide> generator_output = next(generator)
<del> lock.release()
<ide> q.put(generator_output)
<ide> else:
<ide> time.sleep(wait_time) | 1 |
Ruby | Ruby | add newline if preinstall updated | 2682b59b7f9bf668d73ee36e073f6e2a823f57ef | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report
<ide> if !ARGV.include?("--preinstall") && !ENV["HOMEBREW_UPDATE_FAILED"]
<ide> puts "Already up-to-date."
<ide> end
<del> elsif hub.empty?
<del> puts "No changes to formulae."
<ide> else
<del> hub.dump
<del> hub.reporters.each(&:migrate_tap_migration)
<del> hub.reporters.each(&:migrate_formula_rename)
<del> Descriptions.update_cache(hub)
<add> if hub.empty?
<add> puts "No changes to formulae."
<add> else
<add> hub.dump
<add> hub.reporters.each(&:migrate_tap_migration)
<add> hub.reporters.each(&:migrate_formula_rename)
<add> Descriptions.update_cache(hub)
<add> end
<add> puts if ARGV.include?("--preinstall")
<ide> end
<ide>
<ide> link_manpages | 1 |
Javascript | Javascript | use es6 export in null-grammar.js | 782b07096452849e497bd7199a26b289e8f4e6df | <ide><path>src/null-grammar.js
<ide>
<ide> import {Disposable} from 'event-kit'
<ide>
<del>module.exports = Object.freeze({
<add>export default Object.freeze({
<ide> name: 'Null Grammar',
<ide> scopeName: 'text.plain',
<ide> onDidUpdate (callback) { | 1 |
Ruby | Ruby | add pax to allowlist | ed1324c9ca3115184b270baa8e46259a3490a6cc | <ide><path>Library/Homebrew/rubocops/uses_from_macos.rb
<ide> class ProvidedByMacos < FormulaCop
<ide> net-snmp
<ide> netcat
<ide> openldap
<add> pax
<ide> pcsc-lite
<ide> pod2man
<ide> rpcgen | 1 |
Ruby | Ruby | use pathname#rmtree instead of fileutils | daf8c26108bd34dfbcad05f321f0edb61fba13b3 | <ide><path>Library/Homebrew/cmd/cleanup.rb
<ide> def cleanup_formula f
<ide> puts "Would remove: #{keg}"
<ide> else
<ide> puts "Removing: #{keg}..."
<del> rm_rf keg
<add> keg.rmtree
<ide> end
<ide> else
<ide> opoo "Skipping (old) #{keg} due to it being linked" | 1 |
PHP | PHP | fix method signature of inherited method | 7101e3d232b8198d2a8a601175caf5581bbd16b9 | <ide><path>src/Illuminate/Database/Schema/Grammars/Grammar.php
<ide> public function wrapTable($table)
<ide> }
<ide>
<ide> /**
<del> * Wrap a value in keyword identifiers.
<del> *
<del> * @param string $value
<del> * @return string
<add> * {@inheritdoc}
<ide> */
<del> public function wrap($value)
<add> public function wrap($value, $prefixAlias = false)
<ide> {
<ide> if ($value instanceof Fluent) $value = $value->name;
<ide>
<del> return parent::wrap($value);
<add> return parent::wrap($value, $prefixAlias);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix problem with half | ac303eae46874e48854b60626b9db7a407688e3d | <ide><path>tests/test_modeling_bart.py
<ide> def test_tokenization(self):
<ide> @unittest.skipIf(torch_device == "cpu", "Cant do half precision")
<ide> def test_generate_fp16(self):
<ide> config, input_ids, batch_size = self._get_config_and_data(output_past=True)
<del> input_ids = input_ids.half()
<del> attention_mask = input_ids.ne(1).to(torch_device).half()
<add> input_ids = input_ids
<add> attention_mask = input_ids.ne(1).to(torch_device)
<ide> lm_model = BartForConditionalGeneration(config).eval().to(torch_device).half()
<ide> lm_model.generate(input_ids, attention_mask=attention_mask)
<ide> | 1 |
Text | Text | clarify weak keys text | 50a4e00143720ee707905c13aac26d45b1b549e7 | <ide><path>doc/api/crypto.md
<ide> it can be used to put the ECDH key pair into an inconsistent state.
<ide>
<ide> The `crypto` module still supports some algorithms which are already
<ide> compromised and are not currently recommended for use. The API also allows
<del>the use of ciphers and hashes with a small key size that are considered to be
<del>too weak for safe use.
<add>the use of ciphers and hashes with a small key size that are too weak for safe
<add>use.
<ide>
<ide> Users should take full responsibility for selecting the crypto
<ide> algorithm and key size according to their security requirements. | 1 |
Mixed | Python | update callback system | 54b999e661d4eca342d270115f4ef740ce979923 | <ide><path>docs/sources/callbacks.md
<ide> ## Usage of callbacks
<ide>
<del>A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training.
<add>A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callback (as the keyword argument `callbacks`) to the `.fit()` method of the `Sequential` model. The relevant methods of the callbacks will then be called at each stage of the training.
<ide>
<ide> ---
<ide>
<ide> keras.callbacks.Callback()
<ide> - __params__: dict. Training parameters (eg. verbosity, batch size, number of epochs...).
<ide> - __model__: `keras.models.Model`. Reference of the model being trained.
<ide> - __Methods__:
<del> - __on_train_begin__(): Method called at the beginning of training.
<del> - __on_train_end__(): Method called at the end of training.
<del> - __on_epoch_begin__(epoch): Method called at the beginning of epoch `epoch`.
<del> - __on_epoch_end__(epoch): Method called at the end of epoch `epoch`.
<del> - __on_batch_begin__(batch): Method called at the beginning of batch `batch`.
<del> - __on_batch_end__(batch): Method called at the end of batch `batch`.
<add> - __on_train_begin__(logs={}): Method called at the beginning of training.
<add> - __on_train_end__(logs={}): Method called at the end of training.
<add> - __on_epoch_begin__(epoch, logs={}): Method called at the beginning of epoch `epoch`.
<add> - __on_epoch_end__(epoch, logs={}): Method called at the end of epoch `epoch`.
<add> - __on_batch_begin__(batch, logs={}): Method called at the beginning of batch `batch`.
<add> - __on_batch_end__(batch, logs={}): Method called at the end of batch `batch`.
<add>
<add>The `logs` dictionary will contain keys for quantities relevant to the current batch or epoch. Currently, the `.fit()` method of the `Sequential` model class will include the following quantities in the `logs` that it passes to its callbacks:
<add>- __on_epoch_end__: logs optionally include `val_loss` (if validation is enabled in `fit`), and `val_accuracy` (if validation and accuracy monitoring are enabled).
<add>- __on_batch_begin__: logs include `size`, the number of samples in the current batch.
<add>- __on_batch_end__: logs include `loss`, and optionally `accuracy` (if accuracy monitoring is enabled).
<ide>
<ide> ---
<ide>
<ide>
<ide> ## Create a callback
<ide>
<del>You can create a custom callback by extending the base class `keras.callbacks.Callback`. A callback has access to its associated model through the class property `self.model`. Two properties of models will be of particular interest to callbacks: `self.model.epoch_history` and `self.model.batch_history`.
<add>You can create a custom callback by extending the base class `keras.callbacks.Callback`. A callback has access to its associated model through the class property `self.model`.
<ide>
<ide> Here's a simple example saving a list of losses over each batch during training:
<ide> ```python
<ide> class LossHistory(keras.callbacks.Callback):
<ide> def on_train_begin(self):
<ide> self.losses = []
<ide>
<del> def on_batch_end(self, batch):
<del> self.losses.append(self.model.batch_history.loss[-1])
<add> def on_batch_end(self, batch, logs={}):
<add> self.losses.append(logs.get('loss'))
<ide> ```
<ide>
<ide> ---
<ide> class LossHistory(keras.callbacks.Callback):
<ide> def on_train_begin(self):
<ide> self.losses = []
<ide>
<del> def on_batch_end(self, batch):
<del> self.losses.append(self.model.batch_history.loss[-1])
<add> def on_batch_end(self, batch, logs={}):
<add> self.losses.append(logs.get('loss'))
<ide>
<ide> model = Sequential()
<ide> model.add(Dense(784, 10, init='uniform'))
<ide><path>examples/reuters_mlp.py
<ide> python examples/reuters_mlp.py
<ide> '''
<ide>
<del>max_words = 10000
<add>max_words = 1000
<ide> batch_size = 32
<ide>
<ide> print("Loading data...")
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer='adam')
<ide>
<del>history = model.fit(X_train, Y_train, nb_epoch=3, batch_size=batch_size, verbose=1, show_accuracy=True, validation_split=0.1)
<del>print(history)
<del>score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=1, show_accuracy=True)
<add>history = model.fit(X_train, Y_train, nb_epoch=3, batch_size=batch_size, verbose=1, show_accuracy=False, validation_split=0.1)
<add>print(history.epoch)
<add>print(history.loss)
<add>print(history.accuracy)
<add>print(history.validation_loss)
<add>print(history.validation_accuracy)
<add>score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=1, show_accuracy=False)
<ide> print('Test score:', score[0])
<ide> print('Test accuracy:', score[1])
<ide><path>keras/callbacks.py
<ide> def _set_model(self, model):
<ide> for callback in self.callbacks:
<ide> callback._set_model(model)
<ide>
<del> def on_epoch_begin(self, epoch):
<add> def on_epoch_begin(self, epoch, logs={}):
<ide> for callback in self.callbacks:
<del> callback.on_epoch_begin(epoch)
<add> callback.on_epoch_begin(epoch, logs)
<ide> self._delta_t_batch = 0.
<ide> self._delta_ts_batch_begin = deque([], maxlen=self.queue_length)
<ide> self._delta_ts_batch_end = deque([], maxlen=self.queue_length)
<ide>
<del> def on_epoch_end(self, epoch):
<add> def on_epoch_end(self, epoch, logs={}):
<ide> for callback in self.callbacks:
<del> callback.on_epoch_end(epoch)
<add> callback.on_epoch_end(epoch, logs)
<ide>
<del> def on_batch_begin(self, batch):
<add> def on_batch_begin(self, batch, logs={}):
<ide> t_before_callbacks = time.time()
<ide> for callback in self.callbacks:
<del> callback.on_batch_begin(batch)
<add> callback.on_batch_begin(batch, logs)
<ide> self._delta_ts_batch_begin.append(time.time() - t_before_callbacks)
<ide> delta_t_median = np.median(self._delta_ts_batch_begin)
<ide> if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch \
<ide> def on_batch_begin(self, batch):
<ide> 'to the batch update (%f). Check your callbacks.' % delta_t_median)
<ide> self._t_enter_batch = time.time()
<ide>
<del> def on_batch_end(self, batch):
<add> def on_batch_end(self, batch, logs={}):
<ide> self._delta_t_batch = time.time() - self._t_enter_batch
<ide> t_before_callbacks = time.time()
<ide> for callback in self.callbacks:
<del> callback.on_batch_end(batch)
<add> callback.on_batch_end(batch, logs)
<ide> self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
<ide> delta_t_median = np.median(self._delta_ts_batch_end)
<ide> if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch \
<ide> and delta_t_median > 0.1:
<ide> warnings.warn('Method on_batch_end() is slow compared '
<ide> 'to the batch update (%f). Check your callbacks.' % delta_t_median)
<ide>
<del> def on_train_begin(self):
<add> def on_train_begin(self, logs={}):
<ide> for callback in self.callbacks:
<del> callback.on_train_begin()
<add> callback.on_train_begin(logs)
<ide>
<del> def on_train_end(self):
<add> def on_train_end(self, logs={}):
<ide> for callback in self.callbacks:
<del> callback.on_train_end()
<add> callback.on_train_end(logs)
<ide>
<ide>
<ide> class Callback(object):
<ide> def _set_params(self, params):
<ide> def _set_model(self, model):
<ide> self.model = model
<ide>
<del> def on_epoch_begin(self, epoch):
<add> def on_epoch_begin(self, epoch, logs={}):
<ide> pass
<ide>
<del> def on_epoch_end(self, epoch):
<add> def on_epoch_end(self, epoch, logs={}):
<ide> pass
<ide>
<del> def on_batch_begin(self, batch):
<add> def on_batch_begin(self, batch, logs={}):
<ide> pass
<ide>
<del> def on_batch_end(self, batch):
<add> def on_batch_end(self, batch, logs={}):
<ide> pass
<ide>
<del> def on_train_begin(self):
<add> def on_train_begin(self, logs={}):
<ide> pass
<ide>
<del> def on_train_end(self):
<add> def on_train_end(self, logs={}):
<ide> pass
<ide>
<ide> class BaseLogger(Callback):
<ide>
<del> def on_train_begin(self):
<add> def on_train_begin(self, logs={}):
<ide> self.verbose = self.params['verbose']
<ide>
<del> def on_epoch_begin(self, epoch):
<add> def on_epoch_begin(self, epoch, logs={}):
<ide> if self.verbose:
<ide> print('Epoch %d' % epoch)
<ide> self.progbar = Progbar(target=self.params['nb_sample'], \
<ide> verbose=self.verbose)
<ide> self.current = 0
<add> self.tot_loss = 0.
<add> self.tot_acc = 0.
<ide>
<del> def on_batch_begin(self, batch):
<del> self.log_values = []
<del>
<del> def on_batch_end(self, batch_index):
<del> self.current += self.model.batch_history['batch_size'][-1]
<del> # skip progbar update for the last batch; will be handled by on_epoch_end
<add> def on_batch_begin(self, batch, logs={}):
<ide> if self.current < self.params['nb_sample']:
<del> loss = self.model.batch_history['loss'][-1]
<del> self.log_values.append(('loss', loss))
<del> if self.params['show_accuracy']:
<del> accuracy = self.model.batch_history['accuracy'][-1]
<del> self.log_values.append(('acc.', accuracy))
<del> if self.verbose:
<del> self.progbar.update(self.current, self.log_values)
<add> self.log_values = []
<ide>
<del> def on_epoch_end(self, epoch):
<del> loss = self.model.batch_history['loss'][-1]
<del> self.log_values.append(('loss', loss))
<add> def on_batch_end(self, batch, logs={}):
<add> batch_size = logs.get('size', 0)
<add> self.current += batch_size
<ide>
<add> loss = logs.get('loss')
<add> self.log_values.append(('loss', loss))
<add> self.tot_loss += loss * batch_size
<ide> if self.params['show_accuracy']:
<del> accuracy = self.model.batch_history['accuracy'][-1]
<add> accuracy = logs.get('accuracy')
<ide> self.log_values.append(('acc.', accuracy))
<add> self.tot_acc += accuracy * batch_size
<add> # skip progbar update for the last batch; will be handled by on_epoch_end
<add> if self.verbose and self.current < self.params['nb_sample']:
<add> self.progbar.update(self.current, self.log_values)
<add>
<add> def on_epoch_end(self, epoch, logs={}):
<add> self.log_values.append(('loss', self.tot_loss / self.current))
<add> if self.params['show_accuracy']:
<add> self.log_values.append(('acc.', self.tot_acc / self.current))
<ide> if self.params['do_validation']:
<del> val_loss = self.model.epoch_history['val_loss'][-1]
<add> val_loss = logs.get('val_loss')
<ide> self.log_values.append(('val. loss', val_loss))
<ide> if self.params['show_accuracy']:
<del> val_acc = self.model.epoch_history['val_accuracy'][-1]
<add> val_acc = logs.get('val_accuracy')
<ide> self.log_values.append(('val. acc.', val_acc))
<ide> self.progbar.update(self.current, self.log_values)
<add>
<add>
<add>class History(Callback):
<add>
<add> def on_train_begin(self, logs={}):
<add> self.epoch = []
<add> self.loss = []
<add> if self.params['show_accuracy']:
<add> self.accuracy = []
<add> if self.params['do_validation']:
<add> self.validation_loss = []
<add> if self.params['show_accuracy']:
<add> self.validation_accuracy = []
<add>
<add> def on_epoch_begin(self, epoch, logs={}):
<add> self.seen = 0
<add> self.tot_loss = 0.
<add> self.tot_accuracy = 0.
<add>
<add> def on_batch_end(self, batch, logs={}):
<add> batch_size = logs.get('size', 0)
<add> self.seen += batch_size
<add> self.tot_loss += logs.get('loss', 0.) * batch_size
<add> if self.params['show_accuracy']:
<add> self.tot_accuracy += logs.get('accuracy', 0.) * batch_size
<add>
<add> def on_epoch_end(self, epoch, logs={}):
<add> val_loss = logs.get('val_loss')
<add> val_acc = logs.get('val_accuracy')
<add> self.epoch.append(epoch)
<add> self.loss.append(self.tot_loss / self.seen)
<add> if self.params['show_accuracy']:
<add> self.accuracy.append(self.tot_accuracy / self.seen)
<add> if self.params['do_validation']:
<add> self.validation_loss.append(val_loss)
<add> if self.params['show_accuracy']:
<add> self.validation_accuracy.append(val_acc)
<ide><path>keras/models.py
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> callbacks = cbks.CallbackList(callbacks)
<ide> if verbose:
<ide> callbacks.append(cbks.BaseLogger())
<add> callbacks.append(cbks.History())
<ide>
<ide> callbacks._set_model(self)
<ide> callbacks._set_params({
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> 'do_validation': do_validation,
<ide> 'show_accuracy': show_accuracy
<ide> })
<del> self.batch_history = {
<del> 'batch':[],
<del> 'batch_size':[],
<del> 'loss':[],
<del> 'accuracy':[],
<del> 'val_loss':[],
<del> 'val_accuracy':[],
<del> }
<del> self.epoch_history = {
<del> 'epoch':[],
<del> 'epoch_size':[],
<del> 'loss':[],
<del> 'accuracy':[],
<del> 'val_loss':[],
<del> 'val_accuracy':[],
<del> }
<ide> callbacks.on_train_begin()
<ide>
<ide> for epoch in range(nb_epoch):
<del> self.epoch_history['epoch'] = epoch
<ide> callbacks.on_epoch_begin(epoch)
<ide> if shuffle:
<ide> np.random.shuffle(index_array)
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> X_batch = slice_X(X, batch_ids)
<ide> y_batch = y[batch_ids]
<ide>
<del> self.batch_history['batch'].append(batch_index)
<del> self.batch_history['batch_size'].append(len(batch_ids))
<del> callbacks.on_batch_begin(batch_index)
<add> batch_logs = {}
<add> batch_logs['batch'] = batch_index
<add> batch_logs['size'] = len(batch_ids)
<add> callbacks.on_batch_begin(batch_index, batch_logs)
<ide>
<ide> ins = X_batch + [y_batch]
<ide> if show_accuracy:
<ide> loss, acc = self._train_with_acc(*ins)
<del> self.batch_history['accuracy'].append(acc)
<add> batch_logs['accuracy'] = acc
<ide> else:
<ide> loss = self._train(*ins)
<del> self.batch_history['loss'].append(loss)
<add> batch_logs['loss'] = loss
<ide>
<del> callbacks.on_batch_end(batch_index)
<add> callbacks.on_batch_end(batch_index, batch_logs)
<ide>
<ide> if batch_index == len(batches) - 1: # last batch
<ide> # validation
<add> epoch_logs = {}
<ide> if do_validation:
<ide> if show_accuracy:
<ide> val_loss, val_acc = self.evaluate(X_val, y_val, batch_size=batch_size, \
<ide> verbose=0, show_accuracy=True)
<del> self.epoch_history['val_accuracy'].append(val_acc)
<add> epoch_logs['val_accuracy'] = val_acc
<ide> else:
<ide> val_loss = self.evaluate(X_val, y_val, batch_size=batch_size, verbose=0)
<del> self.epoch_history['val_loss'].append(val_loss)
<add> epoch_logs['val_loss'] = val_loss
<ide>
<del> epoch_loss = sum(map(lambda x: x[0]*x[1], zip(self.batch_history['batch_size'], self.batch_history['loss']))) / len(y)
<del> self.epoch_history['loss'].append(epoch_loss)
<del> if show_accuracy:
<del> epoch_acc = sum(map(lambda x: x[0]*x[1], zip(self.batch_history['batch_size'], self.batch_history['accuracy']))) / len(y)
<del> self.epoch_history['accuracy'].append(epoch_acc)
<del> callbacks.on_epoch_end(epoch)
<add> callbacks.on_epoch_end(epoch, epoch_logs)
<ide>
<ide> callbacks.on_train_end()
<del> return self.epoch_history
<add> # return history
<add> return callbacks.callbacks[-1]
<ide>
<ide> def predict(self, X, batch_size=128, verbose=1):
<ide> X = standardize_X(X)
<ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<ide> if show_accuracy:
<ide> tot_acc = 0.
<ide> tot_score = 0.
<add> seen = 0
<ide>
<ide> batches = make_batches(len(y), batch_size)
<ide> if verbose:
<ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<ide> ins = X_batch + [y_batch]
<ide> if show_accuracy:
<ide> loss, acc = self._test_with_acc(*ins)
<del> tot_acc += acc
<add> tot_acc += acc * len(y_batch)
<ide> log_values = [('loss', loss), ('acc.', acc)]
<ide> else:
<ide> loss = self._test(*ins)
<ide> log_values = [('loss', loss)]
<del> tot_score += loss
<add> tot_score += loss * len(y_batch)
<add> seen += len(y_batch)
<ide>
<ide> # logging
<ide> if verbose:
<ide> progbar.update(batch_end, log_values)
<ide>
<ide> if show_accuracy:
<del> return tot_score/len(batches), tot_acc/len(batches)
<add> return tot_score / seen, tot_acc / seen
<ide> else:
<del> return tot_score/len(batches)
<add> return tot_score / seen
<ide>
<ide> def get_config(self, verbose=0):
<ide> layers = []
<ide><path>keras/utils/generic_utils.py
<ide> def update(self, current, values=[]):
<ide> '''
<ide> for k, v in values:
<ide> if k not in self.sum_values:
<del> self.sum_values[k] = [v * max(1, current-self.seen_so_far), current-self.seen_so_far]
<add> self.sum_values[k] = [v * (current-self.seen_so_far), current-self.seen_so_far]
<ide> self.unique_values.append(k)
<ide> else:
<ide> self.sum_values[k][0] += v * (current-self.seen_so_far) | 5 |
Javascript | Javascript | remove unused promiserejectioniserror | a8b5b63d4ea280275ede452f5e14b835e3eb7a3a | <ide><path>Libraries/promiseRejectionIsError.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @format
<del> * @flow strict
<del> */
<del>
<del>'use strict';
<del>
<del>require('./Promise'); // make sure the default rejection handler is installed
<del>const rejectionTracking = require('promise/setimmediate/rejection-tracking');
<del>
<del>module.exports = () => {
<del> rejectionTracking.enable({
<del> allRejections: true,
<del> onUnhandled: (id, error) => {
<del> console.error(error);
<del> },
<del> onHandled: () => {},
<del> });
<del>}; | 1 |
Python | Python | update concat_v2 to be concat to match 1.0 final | 634479399664e6a908e6e68ef13ffabf0b49f33e | <ide><path>resnet/cifar_input.py
<ide> def build_input(dataset, data_path, batch_size, mode):
<ide> labels = tf.reshape(labels, [batch_size, 1])
<ide> indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1])
<ide> labels = tf.sparse_to_dense(
<del> tf.concat_v2(values=[indices, labels], axis=1),
<add> tf.concat(values=[indices, labels], axis=1),
<ide> [batch_size, num_classes], 1.0, 0.0)
<ide>
<ide> assert len(images.get_shape()) == 4
<ide><path>tutorials/rnn/ptb/ptb_word_lm.py
<ide> def attn_cell():
<ide> (cell_output, state) = cell(inputs[:, time_step, :], state)
<ide> outputs.append(cell_output)
<ide>
<del> output = tf.reshape(tf.concat_v2(outputs, 1), [-1, size])
<add> output = tf.reshape(tf.concat(outputs, 1), [-1, size])
<ide> softmax_w = tf.get_variable(
<ide> "softmax_w", [size, vocab_size], dtype=data_type())
<ide> softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type()) | 2 |
Text | Text | improve the test common documentation | 5ffb5b6fce376fa08be1af7552ce6d6c9e80bc56 | <ide><path>test/common/README.md
<ide> The `common` module is used by tests for consistency across repeated
<ide> tasks.
<ide>
<ide> ### allowGlobals(...whitelist)
<del>* `whitelist` [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Array of Globals
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>* `whitelist` [<Array>] Array of Globals
<add>* return [<Array>]
<ide>
<ide> Takes `whitelist` and concats that with predefined `knownGlobals`.
<ide>
<ide> ### arrayStream
<ide> A stream to push an array into a REPL
<ide>
<ide> ### busyLoop(time)
<del>* `time` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>* `time` [<Number>]
<ide>
<ide> Blocks for `time` amount of time.
<ide>
<ide> no unexpected rejections occur, because currently they result in silent
<ide> failures.
<ide>
<ide> ### ddCommand(filename, kilobytes)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* return [<Object>]
<ide>
<ide> Platform normalizes the `dd` command
<ide>
<ide> ### enoughTestMem
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Check if there is more than 1gb of total memory.
<ide>
<ide> ### expectsError([fn, ]settings[, exact])
<del>* `fn` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<del>* `settings` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* `fn` [<Function>]
<add>* `settings` [<Object>]
<ide> with the following optional properties:
<del> * `code` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add> * `code` [<String>]
<ide> expected error must have this value for its `code` property
<del> * `type` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add> * `type` [<Function>]
<ide> expected error must be an instance of `type`
<del> * `message` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del> or [<RegExp>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
<add> * `message` [<String>]
<add> or [<RegExp>]
<ide> if a string is provided for `message`, expected error must have it for its
<ide> `message` property; if a regular expression is provided for `message`, the
<ide> regular expression must match the `message` property of the expected error
<del>* `exact` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1
<add>* `exact` [<Number>] default = 1
<ide>
<ide> * return function suitable for use as a validation function passed as the second
<del> argument to e.g. `assert.throws()`. If the returned function has not been called
<del> exactly `exact` number of times when the test is complete, then the test will
<del> fail.
<add> argument to e.g. `assert.throws()`. If the returned function has not been
<add> called exactly `exact` number of times when the test is complete, then the
<add> test will fail.
<ide>
<ide> If `fn` is provided, it will be passed to `assert.throws` as first argument.
<ide>
<ide> The expected error should be [subclassed by the `internal/errors` module](https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md#api).
<ide>
<ide> ### expectWarning(name, expected)
<del>* `name` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* `expected` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>* `name` [<String>]
<add>* `expected` [<String>] | [<Array>]
<ide>
<ide> Tests whether `name` and `expected` are part of a raised warning.
<ide>
<ide> ### fileExists(pathname)
<del>* pathname [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* pathname [<String>]
<add>* return [<Boolean>]
<ide>
<ide> Checks if `pathname` exists
<ide>
<ide> ### fixturesDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Path to the 'fixtures' directory.
<ide>
<ide> ### getArrayBufferViews(buf)
<del>* `buf` [<Buffer>](https://nodejs.org/api/buffer.html#buffer_class_buffer)
<del>* return [<ArrayBufferView[]>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)
<add>* `buf` [<Buffer>]
<add>* return [<ArrayBufferView[]>]
<ide>
<ide> Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
<ide>
<ide> ### globalCheck
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Turn this off if the test should not check for global leaks.
<ide>
<ide> ### hasCrypto
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks for 'openssl'.
<ide>
<ide> ### hasFipsCrypto
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks `hasCrypto` and `crypto` with fips.
<ide>
<ide> ### hasIntl
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks if [internationalization] is supported.
<ide>
<ide> ### hasSmallICU
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks `hasIntl` and `small-icu` is supported.
<ide>
<ide> ### hasIPv6
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks whether `IPv6` is supported on this platform.
<ide>
<ide> ### hasMultiLocalhost
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks if there are multiple localhosts available.
<ide>
<ide> ### hijackStderr(listener)
<del>* `listener` [<Function>][MDN-Function]: a listener with a single parameter called `data`.
<add>* `listener` [<Function>]: a listener with a single parameter
<add> called `data`.
<ide>
<ide> Eavesdrop to `process.stderr.write` calls. Once `process.stderr.write` is
<ide> called, `listener` will also be called and the `data` of `write` function will
<ide> be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
<ide> the number of calls.
<ide>
<ide> ### hijackStdout(listener)
<del>* `listener` [<Function>][MDN-Function]: a listener with a single parameter called `data`.
<add>* `listener` [<Function>]: a listener with a single parameter
<add> called `data`.
<ide>
<ide> Eavesdrop to `process.stdout.write` calls. Once `process.stdout.write` is
<ide> called, `listener` will also be called and the `data` of `write` function will
<ide> be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
<ide> the number of calls.
<ide>
<ide> ### inFreeBSDJail
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks whether free BSD Jail is true or false.
<ide>
<ide> ### isAix
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Advanced Interactive eXecutive (AIX).
<ide>
<ide> ### isAlive(pid)
<del>* `pid` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* `pid` [<Number>]
<add>* return [<Boolean>]
<ide>
<ide> Attempts to 'kill' `pid`
<ide>
<ide> ### isFreeBSD
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Free BSD.
<ide>
<ide> ### isLinux
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Linux.
<ide>
<ide> ### isLinuxPPCBE
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Linux on PowerPC.
<ide>
<ide> ### isOSX
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for macOS.
<ide>
<ide> ### isSunOS
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for SunOS.
<ide>
<ide> ### isWindows
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Windows.
<ide>
<ide> ### isWOW64
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Platform check for Windows 32-bit on Windows 64-bit.
<ide>
<ide> ### leakedGlobals
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>* return [<Array>]
<ide>
<ide> Checks whether any globals are not on the `knownGlobals` list.
<ide>
<ide> ### localhostIPv4
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Gets IP of localhost
<ide>
<ide> ### localIPv6Hosts
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>* return [<Array>]
<ide>
<ide> Array of IPV6 hosts.
<ide>
<ide> ### mustCall([fn][, exact])
<del>* `fn` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) default = () => {}
<del>* `exact` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1
<del>* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add>* `fn` [<Function>] default = () => {}
<add>* `exact` [<Number>] default = 1
<add>* return [<Function>]
<ide>
<ide> Returns a function that calls `fn`. If the returned function has not been called
<ide> exactly `exact` number of times when the test is complete, then the test will
<ide> fail.
<ide> If `fn` is not provided, an empty function will be used.
<ide>
<ide> ### mustCallAtLeast([fn][, minimum])
<del>* `fn` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) default = () => {}
<del>* `minimum` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1
<del>* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add>* `fn` [<Function>] default = () => {}
<add>* `minimum` [<Number>] default = 1
<add>* return [<Function>]
<ide>
<ide> Returns a function that calls `fn`. If the returned function has not been called
<ide> at least `minimum` number of times when the test is complete, then the test will
<ide> fail.
<ide> If `fn` is not provided, an empty function will be used.
<ide>
<ide> ### mustNotCall([msg])
<del>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) default = 'function should not have been called'
<del>* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add>* `msg` [<String>] default = 'function should not have been called'
<add>* return [<Function>]
<ide>
<del>Returns a function that triggers an `AssertionError` if it is invoked. `msg` is used as the error message for the `AssertionError`.
<add>Returns a function that triggers an `AssertionError` if it is invoked. `msg` is
<add>used as the error message for the `AssertionError`.
<ide>
<ide> ### nodeProcessAborted(exitCode, signal)
<del>* `exitCode` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* `signal` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* `exitCode` [<Number>]
<add>* `signal` [<String>]
<add>* return [<Boolean>]
<ide>
<del>Returns `true` if the exit code `exitCode` and/or signal name `signal` represent the exit code and/or signal name of a node process that aborted, `false` otherwise.
<add>Returns `true` if the exit code `exitCode` and/or signal name `signal` represent
<add>the exit code and/or signal name of a node process that aborted, `false`
<add>otherwise.
<ide>
<ide> ### opensslCli
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>* return [<Boolean>]
<ide>
<ide> Checks whether 'opensslCli' is supported.
<ide>
<ide> ### platformTimeout(ms)
<del>* `ms` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>* `ms` [<Number>]
<add>* return [<Number>]
<ide>
<ide> Platform normalizes timeout.
<ide>
<ide> ### PIPE
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Path to the test sock.
<ide>
<ide> ### PORT
<del>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = `12346`
<add>* return [<Number>] default = `12346`
<ide>
<ide> Port tests are running on.
<ide>
<ide> ### printSkipMessage(msg)
<del>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* `msg` [<String>]
<ide>
<ide> Logs '1..0 # Skipped: ' + `msg`
<ide>
<ide> ### refreshTmpDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Deletes the 'tmp' dir and recreates it
<ide>
<ide> Restore the original `process.stderr.write`.
<ide> Restore the original `process.stdout.write`.
<ide>
<ide> ### rootDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Path to the 'root' directory. either `/` or `c:\\` (windows)
<ide>
<ide> ### skip(msg)
<del>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* `msg` [<String>]
<ide>
<ide> Logs '1..0 # Skipped: ' + `msg` and exits with exit code `0`.
<ide>
<ide> ### spawnPwd(options)
<del>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* `options` [<Object>]
<add>* return [<Object>]
<ide>
<ide> Platform normalizes the `pwd` command.
<ide>
<ide> ### spawnSyncPwd(options)
<del>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* `options` [<Object>]
<add>* return [<Object>]
<ide>
<ide> Synchronous version of `spawnPwd`.
<ide>
<ide> ### tmpDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> The realpath of the 'tmp' directory.
<ide>
<ide> ### tmpDirName
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<String>]
<ide>
<ide> Name of the temp directory used by tests.
<ide>
<ide> Node.js
<ide> implementation with tests from
<ide> [W3C Web Platform Tests](https://github.com/w3c/web-platform-tests).
<ide>
<del>[MDN-Function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Normal_objects_and_functions
<add>[<Array>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
<add>[<ArrayBufferView[]>]: https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView
<add>[<Boolean>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type
<add>[<Buffer>]: https://nodejs.org/api/buffer.html#buffer_class_buffer
<add>[<Function>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
<add>[<Number>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
<add>[<Object>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
<add>[<RegExp>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
<add>[<String>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type
<ide> [internationalization]: https://github.com/nodejs/node/wiki/Intl | 1 |
Text | Text | use h4 for individual methods in apm api doc | e6229f614584c79b6ac1a4cf064f2a3dec7ea266 | <ide><path>docs/apm-rest-api.md
<ide> All requests that take parameters require `application/json`.
<ide>
<ide> ### Packages
<ide>
<del>**GET** /api/packages
<add>#### GET /api/packages
<ide>
<ide> Returns a list of all packages in the following format:
<ide> ```json
<ide> Returns a list of all packages in the following format:
<ide> ]
<ide> ```
<ide>
<del>**GET** /api/packages/:package_name
<add>#### GET /api/packages/:package_name
<ide>
<ide> Returns package details and versions for a single package
<ide>
<ide> Returns:
<ide> }
<ide> ```
<ide>
<del>**POST** /api/packages
<add>#### POST /api/packages
<ide>
<ide> Create a new package; requires authentication.
<ide>
<ide> Returns:
<ide> - **409** - A package by that name already exists
<ide>
<ide>
<del>**DELETE** /api/packages/:package_name
<add>#### DELETE /api/packages/:package_name
<ide>
<ide> Delete a package; requires authentication.
<ide>
<ide> Returns:
<ide>
<ide> ### Package Versions
<ide>
<del>**GET** /api/packages/:package_name/versions/:version_name
<add>#### GET /api/packages/:package_name/versions/:version_name
<ide>
<ide> Returns `package.json` with `dist` key added for e.g. tarball download:
<ide>
<ide> Returns `package.json` with `dist` key added for e.g. tarball download:
<ide>
<ide> ### Creating a new package version
<ide>
<del>**POST** /api/packages/:package_name/versions
<add>#### POST /api/packages/:package_name/versions
<ide>
<ide> Creates a new package version from a git tag; requires authentication.
<ide>
<ide> Creates a new package version from a git tag; requires authentication.
<ide>
<ide> ### Delete a version
<ide>
<del>**DELETE** /api/packages/:package_name/versions/:version_name
<add>#### DELETE /api/packages/:package_name/versions/:version_name
<ide>
<ide> Deletes a package version; requires authentication.
<ide>
<ide> Returns 204 No Content
<ide>
<ide> ### Atom updates
<ide>
<del>**GET** /api/updates
<add>#### GET /api/updates
<ide>
<ide> Atom update feed, following the format expected by [Squirrel](https://github.com/Squirrel/).
<ide> | 1 |
Text | Text | fix broken changelog markup [ci skip] | 5df4efd2fd08dfdf8583bcb6a4322aa5997c18e1 | <ide><path>actionpack/CHANGELOG.md
<ide> There is no controller instance when using a redirect route or a
<ide> mounted rack application so pass the request object as the context
<ide> when resolving dynamic CSP sources in this scenario.
<del>
<add>
<ide> Fixes #34200.
<del>
<add>
<ide> *Andrew White*
<ide>
<ide> * Apply mapping to symbols returned from dynamic CSP sources
<ide> would be converted to a string implicity, e.g:
<ide>
<ide> policy.default_src -> { :self }
<del>
<add>
<ide> would generate the header:
<ide>
<ide> Content-Security-Policy: default-src self
<ide><path>actionview/CHANGELOG.md
<ide> *Eileen M. Uchitelle*, *Aaron Patterson*
<ide>
<ide> * Respect the `only_path` option passed to `url_for` when the options are passed in as an array
<del>
<add>
<ide> Fixes #33237.
<ide>
<ide> *Joel Ambass*
<ide><path>activerecord/CHANGELOG.md
<del>Adds support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`.
<add>* Adds support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`.
<ide>
<ide> *Gannon McGibbon*
<ide> | 3 |
Mixed | Javascript | add eventemitter.on to async iterate over events | 38a593b0f3bc4fa52ed9216d75a98bbf7ab5bd9e | <ide><path>doc/api/events.md
<ide> Value: `Symbol.for('nodejs.rejection')`
<ide>
<ide> See how to write a custom [rejection handler][rejection].
<ide>
<add>## events.on(emitter, eventName)
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `emitter` {EventEmitter}
<add>* `eventName` {string|symbol} The name of the event being listened for
<add>* Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`
<add>
<add>```js
<add>const { on, EventEmitter } = require('events');
<add>
<add>(async () => {
<add> const ee = new EventEmitter();
<add>
<add> // Emit later on
<add> process.nextTick(() => {
<add> ee.emit('foo', 'bar');
<add> ee.emit('foo', 42);
<add> });
<add>
<add> for await (const event of on(ee, 'foo')) {
<add> // The execution of this inner block is synchronous and it
<add> // processes one event at a time (even with await). Do not use
<add> // if concurrent execution is required.
<add> console.log(event); // prints ['bar'] [42]
<add> }
<add>})();
<add>```
<add>
<add>Returns an `AsyncIterator` that iterates `eventName` events. It will throw
<add>if the `EventEmitter` emits `'error'`. It removes all listeners when
<add>exiting the loop. The `value` returned by each iteration is an array
<add>composed of the emitted event arguments.
<add>
<ide> [WHATWG-EventTarget]: https://dom.spec.whatwg.org/#interface-eventtarget
<ide> [`--trace-warnings`]: cli.html#cli_trace_warnings
<ide> [`EventEmitter.defaultMaxListeners`]: #events_eventemitter_defaultmaxlisteners
<ide><path>lib/events.js
<ide> const {
<ide> ObjectCreate,
<ide> ObjectDefineProperty,
<ide> ObjectGetPrototypeOf,
<add> ObjectSetPrototypeOf,
<ide> ObjectKeys,
<ide> Promise,
<add> PromiseReject,
<add> PromiseResolve,
<ide> ReflectApply,
<ide> ReflectOwnKeys,
<ide> Symbol,
<ide> SymbolFor,
<add> SymbolAsyncIterator
<ide> } = primordials;
<ide> const kRejection = SymbolFor('nodejs.rejection');
<ide>
<ide> function EventEmitter(opts) {
<ide> }
<ide> module.exports = EventEmitter;
<ide> module.exports.once = once;
<add>module.exports.on = on;
<ide>
<ide> // Backwards-compat with node 0.10.x
<ide> EventEmitter.EventEmitter = EventEmitter;
<ide> function once(emitter, name) {
<ide> emitter.once(name, eventListener);
<ide> });
<ide> }
<add>
<add>const AsyncIteratorPrototype = ObjectGetPrototypeOf(
<add> ObjectGetPrototypeOf(async function* () {}).prototype);
<add>
<add>function createIterResult(value, done) {
<add> return { value, done };
<add>}
<add>
<add>function on(emitter, event) {
<add> const unconsumedEvents = [];
<add> const unconsumedPromises = [];
<add> let error = null;
<add> let finished = false;
<add>
<add> const iterator = ObjectSetPrototypeOf({
<add> next() {
<add> // First, we consume all unread events
<add> const value = unconsumedEvents.shift();
<add> if (value) {
<add> return PromiseResolve(createIterResult(value, false));
<add> }
<add>
<add> // Then we error, if an error happened
<add> // This happens one time if at all, because after 'error'
<add> // we stop listening
<add> if (error) {
<add> const p = PromiseReject(error);
<add> // Only the first element errors
<add> error = null;
<add> return p;
<add> }
<add>
<add> // If the iterator is finished, resolve to done
<add> if (finished) {
<add> return PromiseResolve(createIterResult(undefined, true));
<add> }
<add>
<add> // Wait until an event happens
<add> return new Promise(function(resolve, reject) {
<add> unconsumedPromises.push({ resolve, reject });
<add> });
<add> },
<add>
<add> return() {
<add> emitter.removeListener(event, eventHandler);
<add> emitter.removeListener('error', errorHandler);
<add> finished = true;
<add>
<add> for (const promise of unconsumedPromises) {
<add> promise.resolve(createIterResult(undefined, true));
<add> }
<add>
<add> return PromiseResolve(createIterResult(undefined, true));
<add> },
<add>
<add> throw(err) {
<add> if (!err || !(err instanceof Error)) {
<add> throw new ERR_INVALID_ARG_TYPE('EventEmitter.AsyncIterator',
<add> 'Error', err);
<add> }
<add> error = err;
<add> emitter.removeListener(event, eventHandler);
<add> emitter.removeListener('error', errorHandler);
<add> },
<add>
<add> [SymbolAsyncIterator]() {
<add> return this;
<add> }
<add> }, AsyncIteratorPrototype);
<add>
<add> emitter.on(event, eventHandler);
<add> emitter.on('error', errorHandler);
<add>
<add> return iterator;
<add>
<add> function eventHandler(...args) {
<add> const promise = unconsumedPromises.shift();
<add> if (promise) {
<add> promise.resolve(createIterResult(args, false));
<add> } else {
<add> unconsumedEvents.push(args);
<add> }
<add> }
<add>
<add> function errorHandler(err) {
<add> finished = true;
<add>
<add> const toError = unconsumedPromises.shift();
<add>
<add> if (toError) {
<add> toError.reject(err);
<add> } else {
<add> // The next time we call next()
<add> error = err;
<add> }
<add>
<add> iterator.return();
<add> }
<add>}
<ide><path>test/parallel/test-event-on-async-iterator.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { on, EventEmitter } = require('events');
<add>
<add>async function basic() {
<add> const ee = new EventEmitter();
<add> process.nextTick(() => {
<add> ee.emit('foo', 'bar');
<add> // 'bar' is a spurious event, we are testing
<add> // that it does not show up in the iterable
<add> ee.emit('bar', 24);
<add> ee.emit('foo', 42);
<add> });
<add>
<add> const iterable = on(ee, 'foo');
<add>
<add> const expected = [['bar'], [42]];
<add>
<add> for await (const event of iterable) {
<add> const current = expected.shift();
<add>
<add> assert.deepStrictEqual(current, event);
<add>
<add> if (expected.length === 0) {
<add> break;
<add> }
<add> }
<add> assert.strictEqual(ee.listenerCount('foo'), 0);
<add> assert.strictEqual(ee.listenerCount('error'), 0);
<add>}
<add>
<add>async function error() {
<add> const ee = new EventEmitter();
<add> const _err = new Error('kaboom');
<add> process.nextTick(() => {
<add> ee.emit('error', _err);
<add> });
<add>
<add> const iterable = on(ee, 'foo');
<add> let looped = false;
<add> let thrown = false;
<add>
<add> try {
<add> // eslint-disable-next-line no-unused-vars
<add> for await (const event of iterable) {
<add> looped = true;
<add> }
<add> } catch (err) {
<add> thrown = true;
<add> assert.strictEqual(err, _err);
<add> }
<add> assert.strictEqual(thrown, true);
<add> assert.strictEqual(looped, false);
<add>}
<add>
<add>async function errorDelayed() {
<add> const ee = new EventEmitter();
<add> const _err = new Error('kaboom');
<add> process.nextTick(() => {
<add> ee.emit('foo', 42);
<add> ee.emit('error', _err);
<add> });
<add>
<add> const iterable = on(ee, 'foo');
<add> const expected = [[42]];
<add> let thrown = false;
<add>
<add> try {
<add> for await (const event of iterable) {
<add> const current = expected.shift();
<add> assert.deepStrictEqual(current, event);
<add> }
<add> } catch (err) {
<add> thrown = true;
<add> assert.strictEqual(err, _err);
<add> }
<add> assert.strictEqual(thrown, true);
<add> assert.strictEqual(ee.listenerCount('foo'), 0);
<add> assert.strictEqual(ee.listenerCount('error'), 0);
<add>}
<add>
<add>async function throwInLoop() {
<add> const ee = new EventEmitter();
<add> const _err = new Error('kaboom');
<add>
<add> process.nextTick(() => {
<add> ee.emit('foo', 42);
<add> });
<add>
<add> try {
<add> for await (const event of on(ee, 'foo')) {
<add> assert.deepStrictEqual(event, [42]);
<add> throw _err;
<add> }
<add> } catch (err) {
<add> assert.strictEqual(err, _err);
<add> }
<add>
<add> assert.strictEqual(ee.listenerCount('foo'), 0);
<add> assert.strictEqual(ee.listenerCount('error'), 0);
<add>}
<add>
<add>async function next() {
<add> const ee = new EventEmitter();
<add> const iterable = on(ee, 'foo');
<add>
<add> process.nextTick(function() {
<add> ee.emit('foo', 'bar');
<add> ee.emit('foo', 42);
<add> iterable.return();
<add> });
<add>
<add> const results = await Promise.all([
<add> iterable.next(),
<add> iterable.next(),
<add> iterable.next()
<add> ]);
<add>
<add> assert.deepStrictEqual(results, [{
<add> value: ['bar'],
<add> done: false
<add> }, {
<add> value: [42],
<add> done: false
<add> }, {
<add> value: undefined,
<add> done: true
<add> }]);
<add>
<add> assert.deepStrictEqual(await iterable.next(), {
<add> value: undefined,
<add> done: true
<add> });
<add>}
<add>
<add>async function nextError() {
<add> const ee = new EventEmitter();
<add> const iterable = on(ee, 'foo');
<add> const _err = new Error('kaboom');
<add> process.nextTick(function() {
<add> ee.emit('error', _err);
<add> });
<add> const results = await Promise.allSettled([
<add> iterable.next(),
<add> iterable.next(),
<add> iterable.next()
<add> ]);
<add> assert.deepStrictEqual(results, [{
<add> status: 'rejected',
<add> reason: _err
<add> }, {
<add> status: 'fulfilled',
<add> value: {
<add> value: undefined,
<add> done: true
<add> }
<add> }, {
<add> status: 'fulfilled',
<add> value: {
<add> value: undefined,
<add> done: true
<add> }
<add> }]);
<add> assert.strictEqual(ee.listeners('error').length, 0);
<add>}
<add>
<add>async function iterableThrow() {
<add> const ee = new EventEmitter();
<add> const iterable = on(ee, 'foo');
<add>
<add> process.nextTick(() => {
<add> ee.emit('foo', 'bar');
<add> ee.emit('foo', 42); // lost in the queue
<add> iterable.throw(_err);
<add> });
<add>
<add> const _err = new Error('kaboom');
<add> let thrown = false;
<add>
<add> assert.throws(() => {
<add> // No argument
<add> iterable.throw();
<add> }, {
<add> message: 'The "EventEmitter.AsyncIterator" property must be' +
<add> ' an instance of Error. Received undefined',
<add> name: 'TypeError'
<add> });
<add>
<add> const expected = [['bar'], [42]];
<add>
<add> try {
<add> for await (const event of iterable) {
<add> assert.deepStrictEqual(event, expected.shift());
<add> }
<add> } catch (err) {
<add> thrown = true;
<add> assert.strictEqual(err, _err);
<add> }
<add> assert.strictEqual(thrown, true);
<add> assert.strictEqual(expected.length, 0);
<add> assert.strictEqual(ee.listenerCount('foo'), 0);
<add> assert.strictEqual(ee.listenerCount('error'), 0);
<add>}
<add>
<add>async function run() {
<add> const funcs = [
<add> basic,
<add> error,
<add> errorDelayed,
<add> throwInLoop,
<add> next,
<add> nextError,
<add> iterableThrow
<add> ];
<add>
<add> for (const fn of funcs) {
<add> await fn();
<add> }
<add>}
<add>
<add>run().then(common.mustCall()); | 3 |
PHP | PHP | add error message when a table has no primary key | f0f52b4af6cab46cb134911fe1aea4629ae63e22 | <ide><path>src/ORM/Table.php
<ide> protected function _processSave($entity, $options) {
<ide> * @param array $data The actual data that needs to be saved
<ide> * @return \Cake\Datasource\EntityInterface|bool
<ide> * @throws \RuntimeException if not all the primary keys where supplied or could
<del> * be generated when the table has composite primary keys
<add> * be generated when the table has composite primary keys. Or when the table has no primary key.
<ide> */
<ide> protected function _insert($entity, $data) {
<ide> $primary = (array)$this->primaryKey();
<add> if (empty($primary)) {
<add> $msg = sprintf(
<add> 'Cannot insert row in "%s", it has no primary key.',
<add> $this->table()
<add> );
<add> throw new \RuntimeException($msg);
<add> }
<ide> $keys = array_fill(0, count($primary), null);
<ide> $id = (array)$this->_newId($primary) + $keys;
<ide> $primary = array_combine($primary, $id);
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testAfterSaveNotCalled() {
<ide> $this->assertFalse($called);
<ide> }
<ide>
<add>/**
<add> * Test that you cannot save rows without a primary key.
<add> *
<add> * @group save
<add> * @expectedException \RuntimeException
<add> * @expectedExceptionMessage Cannot insert row in "users", it has no primary key
<add> * @return void
<add> */
<add> public function testSaveNewErrorOnNoPrimaryKey() {
<add> $entity = new \Cake\ORM\Entity();
<add> $table = TableRegistry::get('users', [
<add> 'schema' => [
<add> 'id' => ['type' => 'integer'],
<add> 'username' => ['type' => 'string'],
<add> ]
<add> ]);
<add> $table->save($entity);
<add> }
<add>
<ide> /**
<ide> * Tests that save is wrapped around a transaction
<ide> * | 2 |
Javascript | Javascript | remove unused uniform | 32955b5cc13cdd1aef074dbade9139e908136b6b | <ide><path>examples/js/objects/Water.js
<ide> THREE.Water = function ( width, height, options ) {
<ide> time: { value: 0.0 },
<ide> size: { value: 1.0 },
<ide> distortionScale: { value: 20.0 },
<del> noiseScale: { value: 1.0 },
<ide> textureMatrix: { value: new THREE.Matrix4() },
<ide> sunColor: { value: new THREE.Color( 0x7F7F7F ) },
<ide> sunDirection: { value: new THREE.Vector3( 0.70707, 0.70707, 0 ) }, | 1 |
Javascript | Javascript | improve core.openemptyeditoronstart description | 6472f069afb9d6a2b3cd4a64b589c7b372e877cf | <ide><path>src/config-schema.js
<ide> const configSchema = {
<ide> ]
<ide> },
<ide> openEmptyEditorOnStart: {
<del> description: 'Automatically open an empty editor on startup.',
<add> description: 'When checked opens an untitled editor on _File > New Window_; otherwise no buffer is opened.',
<ide> type: 'boolean',
<ide> default: true
<ide> }, | 1 |
Python | Python | add timing to spacy evaluate command | 02586a52431865a165439098bff8482cae96397a | <ide><path>spacy/__init__.py
<ide> from .cli.info import info as cli_info
<ide> from .glossary import explain
<ide> from .deprecated import resolve_load_name
<del>from .about import __version__
<add>#from .about import __version__
<ide> from . import util
<ide>
<ide> | 1 |
Text | Text | add command line $ tip for new programmers | e8bdbef00a26fd469c255cd5cfb4b3c71278beb4 | <ide><path>guides/source/migrations.md
<ide> adding these columns will also be created. For example, running
<ide> $ rails generate model Product name:string description:text
<ide> ```
<ide>
<add>TIP: All lines starting with a dollar sign `$` are intended to be run on the command line.
<add>
<ide> will create a migration that looks like this
<ide>
<ide> ```ruby | 1 |
PHP | PHP | add tests for cacheoverlappingstrategy | 781d4c03b2cf56ee6b90d68e8a5766496b91799c | <ide><path>tests/Console/Scheduling/CacheOverlappingStrategyTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Console\Scheduling;
<add>
<add>use Illuminate\Console\Scheduling\CacheOverlappingStrategy;
<add>use Illuminate\Console\Scheduling\Event;
<add>use PHPUnit\Framework\TestCase;
<add>use Mockery as m;
<add>
<add>class CacheOverlappingStrategyTest extends TestCase
<add>{
<add> /**
<add> * @var CacheOverlappingStrategy
<add> */
<add> protected $cacheOverlappingStrategy;
<add>
<add> /**
<add> * @var \Illuminate\Contracts\Cache\Repository
<add> */
<add> protected $cacheRepository;
<add>
<add> public function setUp()
<add> {
<add> parent::setUp();
<add>
<add> $this->cacheRepository = m::mock('Illuminate\Contracts\Cache\Repository');
<add> $this->cacheOverlappingStrategy = new CacheOverlappingStrategy($this->cacheRepository);
<add> }
<add>
<add> public function testPreventOverlap()
<add> {
<add> $cacheOverlappingStrategy = $this->cacheOverlappingStrategy;
<add>
<add> $this->cacheRepository->shouldReceive('put');
<add>
<add> $event = new Event($this->cacheOverlappingStrategy, 'command');
<add>
<add> $cacheOverlappingStrategy->prevent($event);
<add> }
<add>
<add> public function testOverlapsForNonRunningTask()
<add> {
<add> $cacheOverlappingStrategy = $this->cacheOverlappingStrategy;
<add>
<add> $this->cacheRepository->shouldReceive('has')->andReturn(false);
<add>
<add> $event = new Event($this->cacheOverlappingStrategy, 'command');
<add>
<add> $this->assertFalse($cacheOverlappingStrategy->overlaps($event));
<add> }
<add>
<add> public function testOverlapsForRunningTask()
<add> {
<add> $cacheOverlappingStrategy = $this->cacheOverlappingStrategy;
<add>
<add> $this->cacheRepository->shouldReceive('has')->andReturn(true);
<add>
<add> $event = new Event($this->cacheOverlappingStrategy, 'command');
<add>
<add> $this->assertTrue($cacheOverlappingStrategy->overlaps($event));
<add> }
<add>
<add> public function testResetOverlap()
<add> {
<add> $cacheOverlappingStrategy = $this->cacheOverlappingStrategy;
<add>
<add> $this->cacheRepository->shouldReceive('forget');
<add>
<add> $event = new Event($this->cacheOverlappingStrategy, 'command');
<add>
<add> $cacheOverlappingStrategy->reset($event);
<add> }
<add>} | 1 |
Python | Python | reduce false-positives when detecting sqlite usage | e81ec7c6ad227897948ace6b06991c7553129072 | <ide><path>airflow/settings.py
<ide> def prepare_engine_args(disable_connection_pool=False):
<ide> if disable_connection_pool or not pool_connections:
<ide> engine_args['poolclass'] = NullPool
<ide> log.debug("settings.prepare_engine_args(): Using NullPool")
<del> elif 'sqlite' not in SQL_ALCHEMY_CONN:
<add> elif not SQL_ALCHEMY_CONN.startswith('sqlite'):
<ide> # Pool size engine args not supported by sqlite.
<ide> # If no config value is defined for the pool size, select a reasonable value.
<ide> # 0 means no limit, which could lead to exceeding the Database connection limit.
<ide><path>airflow/utils/dag_processing.py
<ide> def __init__(
<ide> os.set_blocking(self._signal_conn.fileno(), False)
<ide>
<ide> self._parallelism = conf.getint('scheduler', 'parsing_processes')
<del> if 'sqlite' in conf.get('core', 'sql_alchemy_conn') and self._parallelism > 1:
<add> if conf.get('core', 'sql_alchemy_conn').startswith('sqlite') and self._parallelism > 1:
<ide> self.log.warning(
<ide> "Because we cannot use more than 1 thread (parsing_processes = "
<ide> "%d ) when using sqlite. So we set parallelism to 1.", | 2 |
Python | Python | allow partial content on bytesio | b570bf699c162e3223043582179db1c67b0a4c74 | <ide><path>flask/helpers.py
<ide> :copyright: © 2010 by the Pallets team.
<ide> :license: BSD, see LICENSE for more details.
<ide> """
<del>
<add>import io
<ide> import os
<ide> import socket
<ide> import sys
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide>
<ide> .. versionchanged:: 1.1
<ide> Filenames may be a `PathLike` object.
<add> .. versionadded:: 1.1
<add> Partial content supports ``BytesIO``.
<ide>
<ide> :param filename_or_fp: the filename of the file to send.
<ide> This is relative to the :attr:`~Flask.root_path`
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide> mtime = os.path.getmtime(filename)
<ide> fsize = os.path.getsize(filename)
<ide> headers['Content-Length'] = fsize
<add> elif isinstance(file, io.BytesIO):
<add> try:
<add> fsize = file.getbuffer().nbytes
<add> except AttributeError:
<add> fsize = len(file.getvalue())
<add> headers['Content-Length'] = fsize
<ide> data = wrap_file(request.environ, file)
<ide>
<ide> rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
<ide><path>tests/test_helpers.py
<ide> """
<ide>
<ide> import datetime
<add>import io
<ide> import os
<ide> import uuid
<ide>
<ide> def index():
<ide> assert rv.status_code == 200
<ide> rv.close()
<ide>
<add> @pytest.mark.skipif(
<add> not callable(getattr(Range, 'to_content_range_header', None)),
<add> reason="not implemented within werkzeug"
<add> )
<add> def test_send_file_range_request_bytesio(self, app, client):
<add> @app.route('/')
<add> def index():
<add> file = io.BytesIO(b'somethingsomething')
<add> return flask.send_file(
<add> file, attachment_filename='filename', conditional=True
<add> )
<add>
<add> rv = client.get('/', headers={'Range': 'bytes=4-15'})
<add> assert rv.status_code == 206
<add> assert rv.data == b'somethingsomething'[4:16]
<add> rv.close()
<add>
<ide> @pytest.mark.skipif(
<ide> not callable(getattr(Range, 'to_content_range_header', None)),
<ide> reason="not implemented within werkzeug" | 2 |
Text | Text | add openverse to inthewild.md | a2dd000bad25dcb4ced8ae052e7007078f5910e2 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [Open Knowledge International](https://okfn.org) [@vitorbaptista](https://github.com/vitorbaptista)
<ide> 1. [Opensignal](https://www.opensignal.com) [@harrisjoseph](https://github.com/harrisjoseph)
<ide> 1. [OpenSlate](https://openslate.com) [@marcusianlevine](https://github.com/marcusianlevine)
<add>1. [Openverse](https://wordpress.org/openverse)
<ide> 1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@fhoda](https://github.com/fhoda), [@ianstanton](https://github.com/ianstanton), [@nilaybhatt](https://github.com/NilayBhatt),[@hiteshrd](https://github.com/hiteshrd)]
<ide> 1. [Opus Interactive](https://www.opusinteractive.com/) [[@Opus-Interactive](https://github.com/Opus-Interactive)]
<ide> 1. [OrangeBank](https://www.orangebank.fr/) [[@HamzaBoukraa](https://github.com/HamzaBoukraa)] | 1 |
Javascript | Javascript | combine slug utils into one module | 9c2f1ffd820f85f6eda7080c41e5e214f74b3d4a | <ide><path>api-server/common/utils/index.js
<ide> export {
<ide> renderSignInEmail
<ide> } from './auth';
<ide>
<del>export function dashify(str) {
<del> return ('' + str)
<del> .toLowerCase()
<del> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-.]/gi, '')
<del> .replace(/:/g, '');
<del>}
<del>// todo: unify with server/utils/index.js:dasherize
<del>const dasherize = dashify;
<del>export { dasherize };
<del>
<ide> export const fixCompletedChallengeItem = obj =>
<ide> pick(obj, [
<ide> 'id',
<ide><path>api-server/server/boot/challenge.js
<ide> import isURL from 'validator/lib/isURL';
<ide> import { homeLocation } from '../../../config/env';
<ide>
<ide> import { ifNoUserSend } from '../utils/middleware';
<del>import { dasherize } from '../utils';
<add>import { dasherize } from '../../../utils/slugs';
<ide> import _pathMigrations from '../resources/pathMigration.json';
<ide> import { fixCompletedChallengeItem } from '../../common/utils';
<ide>
<ide><path>api-server/server/boot/commit.js
<ide> import { homeLocation } from '../../../config/env';
<ide> import nonprofits from '../utils/commit.json';
<ide> import { commitGoals, completeCommitment$ } from '../utils/commit';
<ide>
<del>import { unDasherize } from '../utils';
<add>import { unDasherize } from '../../../utils/slugs';
<ide>
<ide> import { observeQuery, saveInstance } from '../utils/rx';
<ide>
<ide><path>api-server/server/utils/index.js
<del>exports.dasherize = function dasherize(name) {
<del> return ('' + name)
<del> .toLowerCase()
<del> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-.]/gi, '')
<del> .replace(/:/g, '');
<del>};
<del>
<del>exports.nameify = function nameify(str) {
<del> return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '').replace(/:/g, '');
<del>};
<del>
<del>exports.unDasherize = function unDasherize(name) {
<del> return (
<del> ('' + name)
<del> // replace dash with space
<del> .replace(/-/g, ' ')
<del> // strip nonalphanumarics chars except whitespace
<del> .replace(/[^a-zA-Z\d\s]/g, '')
<del> .trim()
<del> );
<del>};
<del>
<ide> exports.addPlaceholderImage = function addPlaceholderImage(name) {
<ide> return `https://example.com/${name}.png`;
<ide> };
<ide><path>api-server/server/utils/map.js
<ide> import _ from 'lodash';
<ide> import { Observable } from 'rx';
<ide>
<del>import { unDasherize, nameify } from '../utils';
<add>import { unDasherize, nameify } from '../../../utils/slugs';
<ide> import {
<ide> addNameIdMap as _addNameIdToMap,
<ide> checkMapData,
<ide><path>client/gatsby-node.js
<ide> require('dotenv').config();
<ide>
<ide> const { createFilePath } = require('gatsby-source-filesystem');
<ide>
<del>const { dasherize } = require('./utils');
<add>const { dasherize } = require('../utils/slugs');
<ide> const { blockNameify } = require('./utils/blockNameify');
<ide> const {
<ide> createChallengePages,
<ide><path>client/src/templates/Challenges/classic/Show.js
<ide> import Hotkeys from '../components/Hotkeys';
<ide> import { getGuideUrl } from '../utils';
<ide> import { challengeTypes } from '../../../../utils/challengeTypes';
<ide> import { ChallengeNode } from '../../../redux/propTypes';
<del>import { dasherize } from '../../../../utils';
<add>import { dasherize } from '../../../../../utils/slugs';
<ide> import {
<ide> createFiles,
<ide> challengeFilesSelector,
<ide><path>client/src/templates/Challenges/components/CompletionModal.js
<ide> import { Button, Modal } from '@freecodecamp/react-bootstrap';
<ide> import ga from '../../../analytics';
<ide> import GreenPass from '../../../assets/icons/GreenPass';
<ide>
<del>import { dasherize } from '../../../../utils';
<add>import { dasherize } from '../../../../../utils/slugs';
<ide>
<ide> import './completion-modal.css';
<ide>
<ide><path>client/utils/buildChallenges.js
<ide> const {
<ide> createChallenge,
<ide> getChallengesDirForLang
<ide> } = require('../../curriculum/getChallenges');
<del>const utils = require('./');
<add>const { dasherize, nameify } = require('../../utils/slugs');
<ide> const { locale } = require('../config/env.json');
<ide> const { blockNameify } = require('./blockNameify');
<ide>
<del>const dasherize = utils.dasherize;
<del>const nameify = utils.nameify;
<del>
<ide> const arrToString = arr =>
<ide> Array.isArray(arr) ? arr.join('\n') : _.toString(arr);
<ide>
<ide><path>client/utils/gatsby/challengePageCreator.js
<ide> const path = require('path');
<del>const { dasherize } = require('..');
<add>const { dasherize } = require('../../../utils/slugs');
<ide>
<ide> const { viewTypes } = require('../challengeTypes');
<ide>
<ide><path>client/utils/index.js
<del>exports.dasherize = function dasherize(name) {
<del> return ('' + name)
<del> .toLowerCase()
<del> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-.]/gi, '');
<del>};
<del>
<del>exports.nameify = function nameify(str) {
<del> return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '').replace(/:/g, '');
<del>};
<del>
<del>exports.unDasherize = function unDasherize(name) {
<del> return (
<del> ('' + name)
<del> // replace dash with space
<del> .replace(/-/g, ' ')
<del> // strip nonalphanumarics chars except whitespace
<del> .replace(/[^a-zA-Z\d\s]/g, '')
<del> .trim()
<del> );
<del>};
<del>
<ide> exports.descriptionRegex = /<blockquote|<ol|<h4|<table/;
<ide>
<ide> exports.isBrowser = function isBrowser() {
<ide><path>curriculum/getChallenges.js
<ide> const { findIndex } = require('lodash');
<ide> const readDirP = require('readdirp-walk');
<ide> const { parseMarkdown } = require('@freecodecamp/challenge-md-parser');
<ide>
<del>const { dasherize } = require('./utils');
<add>const { dasherize } = require('../utils/slugs');
<ide>
<ide> const challengesDir = path.resolve(__dirname, './challenges');
<ide> const metaDir = path.resolve(challengesDir, '_meta');
<ide><path>curriculum/index.js
<ide> const adler32 = require('adler32');
<ide> const Rx = require('rx');
<ide> const _ = require('lodash');
<ide> const createDebugger = require('debug');
<del>const utils = require('../server/utils');
<add>const { dasherize, nameify } = require('../utils/slugs');
<ide> const getChallenges = require('./getChallenges');
<ide> const { validateChallenge } = require('./schema/challengeSchema');
<ide> const app = require('../server/server');
<ide> const log = createDebugger('fcc:seed');
<ide> // this may be brittle
<ide> log.enabled = true;
<ide>
<del>const dasherize = utils.dasherize;
<del>const nameify = utils.nameify;
<ide> const Observable = Rx.Observable;
<ide> const Challenge = app.models.Challenge;
<ide>
<ide><path>curriculum/utils.js
<ide> const path = require('path');
<ide> require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
<ide>
<del>exports.dasherize = function dasherize(name) {
<del> return ('' + name)
<del> .toLowerCase()
<del> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-\.]/gi, '')
<del> .replace(/\:/g, '');
<del>};
<del>
<ide> const supportedLangs = [
<ide> 'arabic',
<ide> 'chinese',
<ide><path>tools/scripts/ci/md-testing-utils.js
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide> const matter = require('gray-matter');
<del>const { dasherize } = require('../../../client/utils');
<add>const { dasherize } = require('../../../utils/slugs');
<ide>
<ide> const pass = true;
<ide>
<ide><path>tools/scripts/seed/createPathMigrationMap.js
<ide> const { flatten } = require('lodash');
<ide>
<del>const { dasherize } = require('../../../api-server/server/utils');
<add>const { dasherize } = require('../../../utils/slugs');
<ide>
<ide> function createPathMigrationMap(curriculum) {
<ide> return Object.keys(curriculum)
<ide><path>utils/slugs.js
<add>exports.dasherize = function dasherize(name) {
<add> return ('' + name)
<add> .toLowerCase()
<add> .replace(/\s/g, '-')
<add> .replace(/[^a-z0-9\-.]/gi, '');
<add>};
<add>
<add>exports.nameify = function nameify(str) {
<add> return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '');
<add>};
<add>
<add>exports.unDasherize = function unDasherize(name) {
<add> return (
<add> ('' + name)
<add> // replace dash with space
<add> .replace(/-/g, ' ')
<add> // strip nonalphanumarics chars except whitespace
<add> .replace(/[^a-zA-Z\d\s]/g, '')
<add> .trim()
<add> );
<add>}; | 17 |
Javascript | Javascript | add a constant declaration for `net` | 4126441013bb569c19417f4a23c5f6b3bc38ef2b | <ide><path>benchmark/idle_server.js
<del>net = require('net');
<del>connections = 0;
<add>'use strict';
<ide>
<add>const net = require('net');
<add>var connections = 0;
<ide> var errors = 0;
<ide>
<del>server = net.Server(function (socket) {
<add>var server = net.Server(function (socket) {
<ide>
<ide> socket.on('error', function () {
<del> errors++;
<add> errors++;
<ide> });
<ide>
<ide> });
<ide> setInterval(function () {
<ide> console.log("SERVER %d errors: %d", process.pid, errors);
<ide> }
<ide> }, 1000);
<del> | 1 |
Ruby | Ruby | use github api to generate release notes | 4f1bbf003ad1ad3523cdc59a04d49e0973d05090 | <ide><path>Library/Homebrew/dev-cmd/release.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "cli/parser"
<del>require "release_notes"
<ide>
<ide> module Homebrew
<ide> extend T::Sig
<ide> def release
<ide> if args.major? || args.minor?
<ide> latest_major_minor_version = "#{latest_version.major}.#{latest_version.minor.to_i}.0"
<ide> ohai "Release notes since #{latest_major_minor_version} for #{new_version} blog post:"
<del> # release notes without username suffix or dependabot bumps
<del> puts ReleaseNotes.generate_release_notes(latest_major_minor_version, "origin/HEAD")
<del> .lines
<del> .reject { |l| l.include?(" (@Homebrew)") }
<del> .map { |l| l.gsub(/ \(@[\w-]+\)$/, "") }
<del> .sort
<add> # release notes without usernames, new contributors, or extra lines
<add> blog_post_notes = GitHub.generate_release_notes("Homebrew", "brew", new_version,
<add> previous_tag: latest_major_minor_version)["body"]
<add> blog_post_notes = blog_post_notes.lines.map do |line|
<add> next unless (match = line.match(/^\* (.*) by @[\w-]+ in (.*)$/))
<add>
<add> "- [#{match[1]}](#{match[2]})"
<add> end.compact.sort
<add> puts blog_post_notes
<ide> end
<ide>
<ide> ohai "Creating draft release for version #{new_version}"
<ide> def release
<ide> else
<ide> ""
<ide> end
<del> release_notes += ReleaseNotes.generate_release_notes latest_version, "origin/HEAD"
<add> release_notes += GitHub.generate_release_notes("Homebrew", "brew", new_version,
<add> previous_tag: latest_version)["body"]
<ide>
<ide> begin
<ide> release = GitHub.create_or_update_release "Homebrew", "brew", new_version, body: release_notes, draft: true
<ide><path>Library/Homebrew/release_notes.rb
<del># typed: strict
<del># frozen_string_literal: true
<del>
<del># Helper functions for generating release notes.
<del>#
<del># @api private
<del>module ReleaseNotes
<del> extend T::Sig
<del>
<del> module_function
<del>
<del> sig {
<del> params(start_ref: T.any(String, Version), end_ref: T.any(String, Version), markdown: T.nilable(T::Boolean))
<del> .returns(String)
<del> }
<del> def generate_release_notes(start_ref, end_ref, markdown: false)
<del> Utils.safe_popen_read(
<del> "git", "-C", HOMEBREW_REPOSITORY, "log", "--pretty=format:'%s >> - %b%n'", "#{start_ref}..#{end_ref}"
<del> ).lines.map do |s|
<del> matches = s.match(%r{.*Merge pull request #(?<pr>\d+) from (?<user>[^/]+)/[^>]*>> - (?<body>.*)})
<del> next if matches.blank?
<del> next if matches[:user] == "Homebrew"
<del>
<del> body = matches[:body].presence
<del> body ||= s.gsub(/.*(Merge pull request .*) >> - .*/, "\\1").chomp
<del>
<del> "- [#{body}](https://github.com/Homebrew/brew/pull/#{matches[:pr]}) (@#{matches[:user]})\n"
<del> end.compact.join
<del> end
<del>end
<ide><path>Library/Homebrew/test/release_notes_spec.rb
<del># typed: false
<del># frozen_string_literal: true
<del>
<del>require "release_notes"
<del>
<del>describe ReleaseNotes do
<del> before do
<del> HOMEBREW_REPOSITORY.cd do
<del> system "git", "init"
<del> system "git", "commit", "--allow-empty", "-m", "Initial commit"
<del> system "git", "tag", "release-notes-testing"
<del> system "git", "commit", "--allow-empty", "-m", "Merge pull request #1 from Homebrew/fix", "-m", "Do something"
<del> system "git", "commit", "--allow-empty", "-m", "make a change"
<del> system "git", "commit", "--allow-empty", "-m", "Merge pull request #2 from User/fix", "-m", "Do something else"
<del> system "git", "commit", "--allow-empty", "-m", "another change"
<del> system "git", "commit", "--allow-empty", "-m", "Merge pull request #3 from User/another_change"
<del> end
<del> end
<del>
<del> describe ".generate_release_notes" do
<del> it "generates markdown release notes" do
<del> expect(described_class.generate_release_notes("release-notes-testing", "HEAD")).to eq <<~NOTES
<del> - [Merge pull request #3 from User/another_change](https://github.com/Homebrew/brew/pull/3) (@User)
<del> - [Do something else](https://github.com/Homebrew/brew/pull/2) (@User)
<del> NOTES
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/utils/github.rb
<ide> def get_latest_release(user, repo)
<ide> API.open_rest(url, request_method: :GET)
<ide> end
<ide>
<add> def generate_release_notes(user, repo, tag, previous_tag: nil)
<add> url = "#{API_URL}/repos/#{user}/#{repo}/releases/generate-notes"
<add> data = { tag_name: tag }
<add> data[:previous_tag_name] = previous_tag if previous_tag.present?
<add> API.open_rest(url, data: data, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
<add> end
<add>
<ide> def create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false)
<ide> url = "#{API_URL}/repos/#{user}/#{repo}/releases"
<ide> method = if id | 4 |
Mixed | Javascript | add debugger alias for exec(expr) | 7d75e3f5420ecc41784ea9d3409c405dad756a37 | <ide><path>doc/api/debugger.md
<ide> debug>
<ide> * `watchers`: List all watchers and their values (automatically listed on each
<ide> breakpoint)
<ide> * `repl`: Open debugger's repl for evaluation in debugging script's context
<del>* `exec expr`: Execute an expression in debugging script's context
<add>* `exec expr`, `p expr`: Execute an expression in debugging script's context and
<add> print its value
<ide>
<ide> ### Execution control
<ide>
<ide><path>lib/internal/debugger/inspect_repl.js
<ide> const SHORTCUTS = {
<ide> setBreakpoint: 'sb',
<ide> clearBreakpoint: 'cb',
<ide> run: 'r',
<add> exec: 'p'
<ide> };
<ide>
<ide> const HELP = StringPrototypeTrim(`
<ide> watch(expr) Start watching the given expression
<ide> unwatch(expr) Stop watching an expression
<ide> watchers Print all watched expressions and their current values
<ide>
<del>exec(expr) Evaluate the expression and print the value
<add>exec(expr), p(expr), exec expr, p expr
<add> Evaluate the expression and print the value
<ide> repl Enter a debug repl that works like exec
<ide>
<ide> scripts List application scripts that are currently loaded
<ide> function createRepl(inspector) {
<ide> function prepareControlCode(input) {
<ide> if (input === '\n') return lastCommand;
<ide> // Add parentheses: exec process.title => exec("process.title");
<del> const match = RegExpPrototypeSymbolMatch(/^\s*exec\s+([^\n]*)/, input);
<add> const match = RegExpPrototypeSymbolMatch(/^\s*(?:exec|p)\s+([^\n]*)/, input);
<ide> if (match) {
<ide> lastCommand = `exec(${JSONStringify(match[1])})`;
<ide> } else {
<ide><path>test/sequential/test-debugger-exec.js
<ide> const assert = require('assert');
<ide> 'works w/o paren'
<ide> );
<ide> })
<add> .then(() => cli.command('p [typeof heartbeat, typeof process.exit]'))
<add> .then(() => {
<add> assert.match(
<add> cli.output,
<add> /\[ 'function', 'function' \]/,
<add> 'works w/o paren, short'
<add> );
<add> })
<ide> .then(() => cli.command('repl'))
<ide> .then(() => {
<ide> assert.match(
<ide> const assert = require('assert');
<ide> 'works w/ paren'
<ide> );
<ide> })
<add> .then(() => cli.command('p("[typeof heartbeat, typeof process.exit]")'))
<add> .then(() => {
<add> assert.match(
<add> cli.output,
<add> /\[ 'function', 'function' \]/,
<add> 'works w/ paren, short'
<add> );
<add> })
<ide> .then(() => cli.command('cont'))
<ide> .then(() => cli.command('exec [typeof heartbeat, typeof process.exit]'))
<ide> .then(() => { | 3 |
Text | Text | add breaking change note for | fd1528a6c8920d032af65304e7659171c29106a0 | <ide><path>CHANGELOG.md
<ide> - strip off empty hash segments when comparing
<ide> ([e93710fe](https://github.com/angular/angular.js/commit/e93710fe0e4fb05ceee59a04f290692a5bec5d20),
<ide> [#9635](https://github.com/angular/angular.js/issues/9635))
<del>- **$parse:**
<add>- **$parse:**
<ide> - fix operators associativity
<ide> ([ed1243ff](https://github.com/angular/angular.js/commit/ed1243ffc7c2cb4bd5b4dece597597db8eb08e34))
<ide> - follow JavaScript context for unbound functions
<ide> ## Breaking Changes
<ide>
<ide> - **$location:** due to [2dc34a96](https://github.com/angular/angular.js/commit/2dc34a969956eea680be4c8d9f800556d110996a),
<del>
<add>
<ide>
<ide> We no longer throw an `ihshprfx` error if the URL after the base path
<ide> contains only a hash fragment. Previously, if the base URL was `http://abc.com/base/`
<ide> and hashPrfix are set up as above, then `http://abc.com/base/other/path` does no
<ide> throw an error but just ignores the extra path: `http://abc.com/base`.
<ide>
<ide>
<add>- **filterFilter:** due to [a75537d4](https://github.com/angular/angular.js/commit/a75537d461c92e3455e372ff5005bf0cad2d2e95),
<add>
<add> Named properties in the expression object will only match against properties on the **same level**.
<add> Previously, named string properties would match against properties on the same level **or deeper**.
<add>
<add> Before:
<add>
<add> ```js
<add> arr = filterFilter([{level1: {level2: 'test'}}], {level1: 'test'}); // arr.length -> 1
<add> ```
<add>
<add> After:
<add>
<add> ```js
<add> arr = filterFilter([{level1: {level2: 'test'}}], {level1: 'test'}); // arr.length -> 0
<add> ```
<add>
<add> In order to match deeper nested properties, you have to either match the depth level of the
<add> property or use the special `$` key (which still matches properties on the same level
<add> **or deeper**). E.g.:
<add>
<add> ```js
<add> // Both examples below have `arr.length === 1`
<add> arr = filterFilter([{level1: {level2: 'test'}}], {level1: {level2: 'test'}});
<add> arr = filterFilter([{level1: {level2: 'test'}}], {$: 'test'});
<add> ```
<add>
<add>
<ide> <a name="1.3.5"></a>
<ide> # 1.3.5 cybernetic-mercantilism (2014-12-01)
<ide> | 1 |
Ruby | Ruby | remove mass_assignment_options from activerecord | 2d7ae1b08ee2a10b12cbfeef3a6cc6da55b57df6 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def invertible_for?(record)
<ide> def stale_state
<ide> end
<ide>
<del> def build_record(attributes, options)
<del> reflection.build_association(attributes, options) do |record|
<add> def build_record(attributes)
<add> reflection.build_association(attributes) do |record|
<ide> attributes = create_scope.except(*(record.changed - [reflection.foreign_key]))
<del> record.assign_attributes(attributes, :without_protection => true)
<add> record.assign_attributes(attributes)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/collection_association.rb
<ide> def last(*args)
<ide> first_or_last(:last, *args)
<ide> end
<ide>
<del> def build(attributes = {}, options = {}, &block)
<add> def build(attributes = {}, &block)
<ide> if attributes.is_a?(Array)
<del> attributes.collect { |attr| build(attr, options, &block) }
<add> attributes.collect { |attr| build(attr, &block) }
<ide> else
<del> add_to_target(build_record(attributes, options)) do |record|
<add> add_to_target(build_record(attributes)) do |record|
<ide> yield(record) if block_given?
<ide> end
<ide> end
<ide> end
<ide>
<del> def create(attributes = {}, options = {}, &block)
<del> create_record(attributes, options, &block)
<add> def create(attributes = {}, &block)
<add> create_record(attributes, &block)
<ide> end
<ide>
<del> def create!(attributes = {}, options = {}, &block)
<del> create_record(attributes, options, true, &block)
<add> def create!(attributes = {}, &block)
<add> create_record(attributes, true, &block)
<ide> end
<ide>
<ide> # Add +records+ to this association. Returns +self+ so method calls may
<ide> def merge_target_lists(persisted, memory)
<ide> persisted + memory
<ide> end
<ide>
<del> def create_record(attributes, options, raise = false, &block)
<add> def create_record(attributes, raise = false, &block)
<ide> unless owner.persisted?
<ide> raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
<ide> end
<ide>
<ide> if attributes.is_a?(Array)
<del> attributes.collect { |attr| create_record(attr, options, raise, &block) }
<add> attributes.collect { |attr| create_record(attr, raise, &block) }
<ide> else
<ide> transaction do
<del> add_to_target(build_record(attributes, options)) do |record|
<add> add_to_target(build_record(attributes)) do |record|
<ide> yield(record) if block_given?
<ide> insert_record(record, true, raise)
<ide> end
<ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> def last(*args)
<ide> #
<ide> # person.pets.size # => 5 # size of the collection
<ide> # person.pets.count # => 0 # count from database
<del> def build(attributes = {}, options = {}, &block)
<del> @association.build(attributes, options, &block)
<add> def build(attributes = {}, &block)
<add> @association.build(attributes, &block)
<ide> end
<ide>
<ide> ##
<ide> def build(attributes = {}, options = {}, &block)
<ide> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<ide> # # ]
<del> def create(attributes = {}, options = {}, &block)
<del> @association.create(attributes, options, &block)
<add> def create(attributes = {}, &block)
<add> @association.create(attributes, &block)
<ide> end
<ide>
<ide> ##
<ide> def create(attributes = {}, options = {}, &block)
<ide> #
<ide> # person.pets.create!(name: nil)
<ide> # # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
<del> def create!(attributes = {}, options = {}, &block)
<del> @association.create!(attributes, options, &block)
<add> def create!(attributes = {}, &block)
<add> @association.create!(attributes, &block)
<ide> end
<ide>
<ide> ##
<ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def save_through_record(record)
<ide> @through_records.delete(record.object_id)
<ide> end
<ide>
<del> def build_record(attributes, options = {})
<add> def build_record(attributes)
<ide> ensure_not_nested
<ide>
<del> record = super(attributes, options)
<add> record = super(attributes)
<ide>
<ide> inverse = source_reflection.inverse_of
<ide> if inverse
<ide><path>activerecord/lib/active_record/associations/singular_association.rb
<ide> def writer(record)
<ide> replace(record)
<ide> end
<ide>
<del> def create(attributes = {}, options = {}, &block)
<del> create_record(attributes, options, &block)
<add> def create(attributes = {}, &block)
<add> create_record(attributes, &block)
<ide> end
<ide>
<del> def create!(attributes = {}, options = {}, &block)
<del> create_record(attributes, options, true, &block)
<add> def create!(attributes = {}, &block)
<add> create_record(attributes, true, &block)
<ide> end
<ide>
<del> def build(attributes = {}, options = {})
<del> record = build_record(attributes, options)
<add> def build(attributes = {})
<add> record = build_record(attributes)
<ide> yield(record) if block_given?
<ide> set_new_record(record)
<ide> record
<ide> def set_new_record(record)
<ide> replace(record)
<ide> end
<ide>
<del> def create_record(attributes, options, raise_error = false)
<del> record = build_record(attributes, options)
<add> def create_record(attributes, raise_error = false)
<add> record = build_record(attributes)
<ide> yield(record) if block_given?
<ide> saved = record.save
<ide> set_new_record(record)
<ide><path>activerecord/lib/active_record/attribute_assignment.rb
<ide> def attributes=(new_attributes)
<ide>
<ide> # Allows you to set all the attributes by passing in a hash of attributes with
<ide> # keys matching the attribute names (which again matches the column names)
<del> #
<del> # To bypass forbidden attributes protection you can use the without_protection: true
<del> # option.
<del> def assign_attributes(new_attributes, options = {})
<add> def assign_attributes(new_attributes)
<ide> return if new_attributes.blank?
<ide>
<ide> attributes = new_attributes.stringify_keys
<ide> multi_parameter_attributes = []
<ide> nested_parameter_attributes = []
<del> previous_options = @mass_assignment_options
<del> @mass_assignment_options = options
<ide>
<del> unless options[:without_protection]
<del> attributes = sanitize_for_mass_assignment(attributes)
<del> end
<add> attributes = sanitize_for_mass_assignment(attributes)
<ide>
<ide> attributes.each do |k, v|
<ide> if k.include?("(")
<ide> def assign_attributes(new_attributes, options = {})
<ide>
<ide> assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
<ide> assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
<del> ensure
<del> @mass_assignment_options = previous_options
<del> end
<del>
<del> protected
<del>
<del> def mass_assignment_options
<del> @mass_assignment_options ||= {}
<ide> end
<ide>
<ide> private
<ide><path>activerecord/lib/active_record/core.rb
<ide> def relation #:nodoc:
<ide> #
<ide> # # Instantiates a single new object bypassing mass-assignment security
<ide> # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
<del> def initialize(attributes = nil, options = {})
<add> def initialize(attributes = nil)
<ide> defaults = self.class.column_defaults.dup
<ide> defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
<ide>
<ide> def initialize(attributes = nil, options = {})
<ide> ensure_proper_type
<ide> populate_with_current_scope_attributes
<ide>
<del> assign_attributes(attributes, options) if attributes
<add> assign_attributes(attributes) if attributes
<ide>
<ide> yield self if block_given?
<ide> run_callbacks :initialize unless _initialize_callbacks.empty?
<ide> def init_internals
<ide> @destroyed = false
<ide> @marked_for_destruction = false
<ide> @new_record = true
<del> @mass_assignment_options = nil
<add> @txn = nil
<ide> @_start_transaction_state = {}
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/nested_attributes.rb
<ide> def accepts_nested_attributes_for(*attr_names)
<ide> remove_method(:#{association_name}_attributes=)
<ide> end
<ide> def #{association_name}_attributes=(attributes)
<del> assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
<add> assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
<ide> end
<ide> eoruby
<ide> else
<ide> def assign_nested_attributes_for_one_to_one_association(association_name, attrib
<ide>
<ide> if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
<ide> (options[:update_only] || record.id.to_s == attributes['id'].to_s)
<del> assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
<add> assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
<ide>
<del> elsif attributes['id'].present? && !assignment_opts[:without_protection]
<add> elsif attributes['id'].present?
<ide> raise_nested_attributes_record_not_found(association_name, attributes['id'])
<ide>
<ide> elsif !reject_new_record?(association_name, attributes)
<ide> method = "build_#{association_name}"
<ide> if respond_to?(method)
<del> send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
<add> send(method, attributes.except(*UNASSIGNABLE_KEYS))
<ide> else
<ide> raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
<ide> end
<ide> def assign_nested_attributes_for_one_to_one_association(association_name, attrib
<ide> # { :name => 'John' },
<ide> # { :id => '2', :_destroy => true }
<ide> # ])
<del> def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
<add> def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
<ide> options = self.nested_attributes_options[association_name]
<ide>
<ide> unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
<ide> def assign_nested_attributes_for_collection_association(association_name, attrib
<ide>
<ide> if attributes['id'].blank?
<ide> unless reject_new_record?(association_name, attributes)
<del> association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
<add> association.build(attributes.except(*UNASSIGNABLE_KEYS))
<ide> end
<ide> elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
<ide> unless association.loaded? || call_reject_if(association_name, attributes)
<ide> def assign_nested_attributes_for_collection_association(association_name, attrib
<ide> end
<ide>
<ide> if !call_reject_if(association_name, attributes)
<del> assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts)
<add> assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
<ide> end
<del> elsif assignment_opts[:without_protection]
<del> association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
<ide> else
<ide> raise_nested_attributes_record_not_found(association_name, attributes['id'])
<ide> end
<ide> def assign_nested_attributes_for_collection_association(association_name, attrib
<ide>
<ide> # Updates a record with the +attributes+ or marks it for destruction if
<ide> # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
<del> def assign_to_or_mark_for_destruction(record, attributes, allow_destroy, assignment_opts)
<del> record.assign_attributes(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
<add> def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
<add> record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
<ide> record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
<ide> end
<ide>
<ide> def raise_nested_attributes_record_not_found(association_name, record_id)
<ide> end
<ide>
<ide> def unassignable_keys(assignment_opts)
<del> assignment_opts[:without_protection] ? UNASSIGNABLE_KEYS - %w[id] : UNASSIGNABLE_KEYS
<add> UNASSIGNABLE_KEYS
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> module ClassMethods
<ide> # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
<ide> # u.is_admin = false
<ide> # end
<del> def create(attributes = nil, options = {}, &block)
<add> def create(attributes = nil, &block)
<ide> if attributes.is_a?(Array)
<del> attributes.collect { |attr| create(attr, options, &block) }
<add> attributes.collect { |attr| create(attr, &block) }
<ide> else
<del> object = new(attributes, options, &block)
<add> object = new(attributes, &block)
<ide> object.save
<ide> object
<ide> end
<ide> def update_attribute(name, value)
<ide> # If no +:as+ option is supplied then the +:default+ role will be used.
<ide> # If you want to bypass the forbidden attributes protection then you can do so using
<ide> # the +:without_protection+ option.
<del> def update_attributes(attributes, options = {})
<add> def update_attributes(attributes)
<ide> # The following transaction covers any possible database side-effects of the
<ide> # attributes assignment. For example, setting the IDs of a child collection.
<ide> with_transaction_returning_status do
<del> assign_attributes(attributes, options)
<add> assign_attributes(attributes)
<ide> save
<ide> end
<ide> end
<ide>
<ide> # Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead
<ide> # of +save+, so an exception is raised if the record is invalid.
<del> def update_attributes!(attributes, options = {})
<add> def update_attributes!(attributes)
<ide> # The following transaction covers any possible database side-effects of the
<ide> # attributes assignment. For example, setting the IDs of a child collection.
<ide> with_transaction_returning_status do
<del> assign_attributes(attributes, options)
<add> assign_attributes(attributes)
<ide> save!
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def initialize(*args)
<ide>
<ide> # Returns a new, unsaved instance of the associated class. +options+ will
<ide> # be passed to the class's constructor.
<del> def build_association(*options, &block)
<del> klass.new(*options, &block)
<add> def build_association(attributes, &block)
<add> klass.new(attributes, &block)
<ide> end
<ide>
<ide> def table_name
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def create!(*args, &block)
<ide> # user.last_name = "O'Hara"
<ide> # end
<ide> # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
<del> def first_or_create(attributes = nil, options = {}, &block)
<del> first || create(attributes, options, &block)
<add> def first_or_create(attributes = nil, &block)
<add> first || create(attributes, &block)
<ide> end
<ide>
<ide> # Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
<ide> #
<ide> # Expects arguments in the same format as <tt>Base.create!</tt>.
<del> def first_or_create!(attributes = nil, options = {}, &block)
<del> first || create!(attributes, options, &block)
<add> def first_or_create!(attributes = nil, &block)
<add> first || create!(attributes, &block)
<ide> end
<ide>
<ide> # Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
<ide> #
<ide> # Expects arguments in the same format as <tt>Base.new</tt>.
<del> def first_or_initialize(attributes = nil, options = {}, &block)
<del> first || new(attributes, options, &block)
<add> def first_or_initialize(attributes = nil, &block)
<add> first || new(attributes, &block)
<ide> end
<ide>
<ide> # Runs EXPLAIN on the query or queries triggered by this relation and
<ide><path>activerecord/lib/active_record/validations.rb
<ide> module Validations
<ide> module ClassMethods
<ide> # Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
<ide> # so an exception is raised if the record is invalid.
<del> def create!(attributes = nil, options = {}, &block)
<add> def create!(attributes = nil, &block)
<ide> if attributes.is_a?(Array)
<del> attributes.collect { |attr| create!(attr, options, &block) }
<add> attributes.collect { |attr| create!(attr, &block) }
<ide> else
<del> object = new(attributes, options)
<add> object = new(attributes)
<ide> yield(object) if block_given?
<ide> object.save!
<ide> object
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_merging_with_custom_attribute_writer
<ide> assert_equal "RED!", car.bulbs.to_a.first.color
<ide> end
<ide>
<del> def test_new_is_called_with_attributes_and_options
<del> car = Car.create(:name => 'honda')
<del>
<del> bulb = car.bulbs.build
<del> assert_equal Bulb, bulb.class
<del>
<del> bulb = car.bulbs.build(:bulb_type => :custom)
<del> assert_equal Bulb, bulb.class
<del>
<del> bulb = car.bulbs.build({ :bulb_type => :custom }, :as => :admin)
<del> assert_equal CustomBulb, bulb.class
<del> end
<del>
<ide> def test_abstract_class_with_polymorphic_has_many
<ide> post = SubStiPost.create! :title => "fooo", :body => "baa"
<ide> tagging = Tagging.create! :taggable => post
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_association_protect_foreign_key
<ide> assert_equal pirate.id, ship.pirate_id
<ide> end
<ide>
<del> def test_new_is_called_with_attributes_and_options
<del> car = Car.create(:name => 'honda')
<del>
<del> bulb = car.build_bulb
<del> assert_equal Bulb, bulb.class
<del>
<del> bulb = car.build_bulb
<del> assert_equal Bulb, bulb.class
<del>
<del> bulb = car.build_bulb(:bulb_type => :custom)
<del> assert_equal Bulb, bulb.class
<del>
<del> bulb = car.build_bulb({ :bulb_type => :custom }, :as => :admin)
<del> assert_equal CustomBulb, bulb.class
<del> end
<del>
<ide> def test_build_with_block
<ide> car = Car.create(:name => 'honda')
<ide>
<ide><path>activerecord/test/cases/dup_test.rb
<ide> def test_dup_with_changes
<ide> dbtopic = Topic.first
<ide> topic = Topic.new
<ide>
<del> topic.attributes = dbtopic.attributes
<add> topic.attributes = dbtopic.attributes.except("id")
<ide>
<ide> #duped has no timestamp values
<ide> duped = dbtopic.dup
<ide><path>activerecord/test/cases/forbidden_attributes_protection_test.rb
<ide> def test_regular_hash_should_still_be_used_for_mass_assignment
<ide> assert_equal 'Guille', person.first_name
<ide> assert_equal 'm', person.gender
<ide> end
<del>
<del> def test_protected_attributes_cannot_be_used_for_mass_assignment
<del> params = ProtectedParams.new(id: 1, first_name: 'Guille', gender: 'm')
<del> params.permit!
<del> person = Person.new(params)
<del>
<del> assert_equal 'Guille', person.first_name
<del> assert_equal 'm', person.gender
<del> assert_not_equal 1, person.id
<del> end
<ide> end
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> def test_update_attributes
<ide> assert_equal "The First Topic", topic.title
<ide> end
<ide>
<del> def test_update_attributes_as_admin
<del> person = TightPerson.create({ "first_name" => 'Joshua' })
<del> person.update_attributes({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :as => :admin)
<del> person.reload
<del>
<del> assert_equal 'Josh', person.first_name
<del> assert_equal 'm', person.gender
<del> assert_equal 'from NZ', person.comments
<del> end
<del>
<del> def test_update_attributes_without_protection
<del> person = TightPerson.create({ "first_name" => 'Joshua' })
<del> person.update_attributes({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :without_protection => true)
<del> person.reload
<del>
<del> assert_equal 'Josh', person.first_name
<del> assert_equal 'm', person.gender
<del> assert_equal 'from NZ', person.comments
<del> end
<del>
<ide> def test_update_attributes!
<ide> Reply.validates_presence_of(:title)
<ide> reply = Reply.find(2)
<ide> def test_update_attributes!
<ide> Reply.reset_callbacks(:validate)
<ide> end
<ide>
<del> def test_update_attributes_with_bang_as_admin
<del> person = TightPerson.create({ "first_name" => 'Joshua' })
<del> person.update_attributes!({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :as => :admin)
<del> person.reload
<del>
<del> assert_equal 'Josh', person.first_name
<del> assert_equal 'm', person.gender
<del> assert_equal 'from NZ', person.comments
<del> end
<del>
<del> def test_update_attributestes_with_bang_without_protection
<del> person = TightPerson.create({ "first_name" => 'Joshua' })
<del> person.update_attributes!({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :without_protection => true)
<del> person.reload
<del>
<del> assert_equal 'Josh', person.first_name
<del> assert_equal 'm', person.gender
<del> assert_equal 'from NZ', person.comments
<del> end
<del>
<ide> def test_destroyed_returns_boolean
<ide> developer = Developer.first
<ide> assert_equal false, developer.destroyed?
<ide><path>activerecord/test/models/bulb.rb
<ide> def color=(color)
<ide> self[:color] = color.upcase + "!"
<ide> end
<ide>
<del> def self.new(attributes = {}, options = {}, &block)
<add> def self.new(attributes = {}, &block)
<ide> bulb_type = (attributes || {}).delete(:bulb_type)
<ide>
<del> if options && options[:as] == :admin && bulb_type.present?
<add> if bulb_type.present?
<ide> bulb_class = "#{bulb_type.to_s.camelize}Bulb".constantize
<del> bulb_class.new(attributes, options, &block)
<add> bulb_class.new(attributes, &block)
<ide> else
<ide> super
<ide> end | 18 |
Ruby | Ruby | fix pg warnings on geometric types | dbdbda9a4a5cb9cd22e7a5a5625caa84edae6d5d | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def reload_type_map
<ide> initialize_type_map(type_map)
<ide> end
<ide>
<add> def add_oid(row, records_by_oid, type_map)
<add> return type_map if type_map.key? row['type_elem'].to_i
<add>
<add> if OID.registered_type? row['typname']
<add> # this composite type is explicitly registered
<add> vector = OID::NAMES[row['typname']]
<add> else
<add> # use the default for composite types
<add> unless type_map.key? row['typelem'].to_i
<add> add_oid records_by_oid[row['typelem']], records_by_oid, type_map
<add> end
<add>
<add> vector = OID::Vector.new row['typdelim'], type_map[row['typelem'].to_i]
<add> end
<add>
<add> type_map[row['oid'].to_i] = vector
<add> type_map
<add> end
<add>
<ide> def initialize_type_map(type_map)
<ide> result = execute('SELECT oid, typname, typelem, typdelim, typinput FROM pg_type', 'SCHEMA')
<ide> leaves, nodes = result.partition { |row| row['typelem'] == '0' }
<ide> def initialize_type_map(type_map)
<ide> type_map[row['oid'].to_i] = OID::NAMES[row['typname']]
<ide> end
<ide>
<add> records_by_oid = result.group_by { |row| row['oid'] }
<add>
<ide> arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
<ide>
<ide> # populate composite types
<del> nodes.find_all { |row| type_map.key? row['typelem'].to_i }.each do |row|
<del> if OID.registered_type? row['typname']
<del> # this composite type is explicitly registered
<del> vector = OID::NAMES[row['typname']]
<del> else
<del> # use the default for composite types
<del> vector = OID::Vector.new row['typdelim'], type_map[row['typelem'].to_i]
<del> end
<del>
<del> type_map[row['oid'].to_i] = vector
<add> nodes.each do |row|
<add> add_oid row, records_by_oid, type_map
<ide> end
<ide>
<ide> # populate array types | 1 |
PHP | PHP | add test cases | b2833d90647b14c0a8150f3ad6610ba567881498 | <ide><path>src/Validation/Validator.php
<ide> public function count(): int
<ide> * @param string $field The name of the field from which the rule will be added
<ide> * @param array|string $name The alias for a single rule or multiple rules array
<ide> * @param array|\Cake\Validation\ValidationRule $rule the rule to add
<add> * @throws \InvalidArgumentException If numeric index cannot be resolved to a string one
<ide> * @return $this
<ide> */
<ide> public function add(string $field, $name, $rule = [])
<ide> public function add(string $field, $name, $rule = [])
<ide> }
<ide> if (!is_string($name)) {
<ide> $name = $rule['rule'];
<del> if (isset($this->_rules[$name])) {
<del> throw new InvalidArgumentException('You cannot add a rule without a unique name, already existing rule found: ' . $name);
<add> if (is_array($name)) {
<add> $name = array_shift($name);
<ide> }
<add>
<add> if ($validationSet->offsetExists($name)) {
<add> $message = 'You cannot add a rule without a unique name, already existing rule found: ' . $name;
<add> throw new InvalidArgumentException($message);
<add> }
<add>
<add> deprecationWarning(
<add> 'Using numeric indexes for adding validation rules is deprecated. Use string indexes instead.'
<add> );
<ide> }
<ide>
<ide> $validationSet->add($name, $rule);
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> use Cake\Validation\ValidationRule;
<ide> use Cake\Validation\ValidationSet;
<ide> use Cake\Validation\Validator;
<add>use InvalidArgumentException;
<ide> use Zend\Diactoros\UploadedFile;
<ide>
<ide> /**
<ide> public function testAddingRulesToField()
<ide> $validator = new Validator();
<ide> $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
<ide> $set = $validator->field('title');
<del> $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
<add> $this->assertInstanceOf(ValidationSet::class, $set);
<ide> $this->assertCount(1, $set);
<ide>
<ide> $validator->add('title', 'another', ['rule' => 'alphanumeric']);
<ide> public function testFieldDefault()
<ide> $this->assertFalse($validator->hasField('foo'));
<ide>
<ide> $field = $validator->field('foo');
<del> $this->assertInstanceOf('Cake\Validation\ValidationSet', $field);
<add> $this->assertInstanceOf(ValidationSet::class, $field);
<ide> $this->assertCount(0, $field);
<ide> $this->assertTrue($validator->hasField('foo'));
<ide> }
<ide> public function testAddMultiple()
<ide> ],
<ide> ]);
<ide> $set = $validator->field('title');
<del> $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
<add> $this->assertInstanceOf(ValidationSet::class, $set);
<ide> $this->assertCount(2, $set);
<ide> }
<ide>
<add> /**
<add> * Tests adding rules via alternative syntax and numeric keys
<add> *
<add> * @return void
<add> */
<add> public function testAddMultipleNumericKeyArrays()
<add> {
<add> $validator = new Validator();
<add>
<add> $this->deprecated(function () use ($validator) {
<add> $validator->add('title', [
<add> [
<add> 'rule' => 'notBlank',
<add> ],
<add> [
<add> 'rule' => ['minLength', 10],
<add> 'message' => 'Titles need to be at least 10 characters long',
<add> ],
<add> ]);
<add> });
<add>
<add> $set = $validator->field('title');
<add> $this->assertInstanceOf(ValidationSet::class, $set);
<add> $this->assertCount(2, $set);
<add> }
<add>
<add> /**
<add> * Tests adding rules via alternative syntax and numeric keys
<add> *
<add> * @return void
<add> */
<add> public function testAddMultipleNumericKeyArraysInvalid()
<add> {
<add> $validator = new Validator();
<add> $validator->add('title', 'notBlank', ['rule' => 'notBlank']);
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage('You cannot add a rule without a unique name, already existing rule found: notBlank');
<add>
<add> $validator->add('title', [
<add> [
<add> 'rule' => 'notBlank',
<add> ],
<add> [
<add> 'rule' => ['minLength', 10],
<add> 'message' => 'Titles need to be at least 10 characters long',
<add> ],
<add> ]);
<add> }
<add>
<ide> /**
<ide> * Integration test for compareWith validator.
<ide> * | 2 |
Ruby | Ruby | create `rails@localhost` user on travis ci | 249a982a2518facd0332f49196be7a6084330246 | <ide><path>ci/travis.rb
<ide> include FileUtils
<ide>
<ide> commands = [
<add> 'mysql -e "create user rails@localhost;"',
<add> 'mysql -e "grant all privileges on activerecord_unittest.* to rails@localhost;"',
<add> 'mysql -e "grant all privileges on activerecord_unittest2.* to rails@localhost;"',
<add> 'mysql -e "grant all privileges on inexistent_activerecord_unittest.* to rails@localhost;"',
<ide> 'mysql -e "create database activerecord_unittest;"',
<ide> 'mysql -e "create database activerecord_unittest2;"',
<ide> 'psql -c "create database activerecord_unittest;" -U postgres', | 1 |
Javascript | Javascript | pass cache instance into $http | 16363d8000a484b428a16eb07d8bd0f19c4b4337 | <ide><path>src/widgets.js
<ide> angularWidget('ng:include', function(element){
<ide> useScope = scope.$eval(scopeExp),
<ide> fromCache;
<ide>
<del> function updateContent(content) {
<del> element.html(content);
<del> if (useScope) {
<del> childScope = useScope;
<del> } else {
<del> releaseScopes.push(childScope = scope.$new());
<del> }
<del> compiler.compile(element)(childScope);
<del> $autoScroll();
<del> scope.$eval(onloadExp);
<del> }
<del>
<ide> function clearContent() {
<ide> childScope = null;
<ide> element.html('');
<ide> angularWidget('ng:include', function(element){
<ide> releaseScopes.pop().$destroy();
<ide> }
<ide> if (src) {
<del> if ((fromCache = $templateCache.get(src))) {
<del> scope.$evalAsync(function() {
<del> updateContent(fromCache);
<del> });
<del> } else {
<del> $http.get(src).on('success', function(response) {
<del> updateContent(response);
<del> $templateCache.put(src, response);
<del> }).on('error', clearContent);
<del> }
<add> $http.get(src, {cache: $templateCache}).on('success', function(response) {
<add> element.html(response);
<add> if (useScope) {
<add> childScope = useScope;
<add> } else {
<add> releaseScopes.push(childScope = scope.$new());
<add> }
<add> compiler.compile(element)(childScope);
<add> $autoScroll();
<add> scope.$eval(onloadExp);
<add> }).on('error', clearContent);
<ide> } else {
<ide> clearContent();
<ide> }
<ide> angularWidget('ng:view', function(element) {
<ide> var template = $route.current && $route.current.template,
<ide> fromCache;
<ide>
<del> function updateContent(content) {
<del> element.html(content);
<del> compiler.compile(element)($route.current.scope);
<del> }
<del>
<ide> function clearContent() {
<ide> element.html('');
<ide> }
<ide>
<ide> if (template) {
<del> if ((fromCache = $templateCache.get(template))) {
<del> scope.$evalAsync(function() {
<del> updateContent(fromCache);
<del> });
<del> } else {
<del> // xhr's callback must be async, see commit history for more info
<del> $http.get(template).on('success', function(response) {
<del> // ignore callback if another route change occured since
<del> if (newChangeCounter == changeCounter)
<del> updateContent(response);
<del> $templateCache.put(template, response);
<add> // xhr's callback must be async, see commit history for more info
<add> $http.get(template, {cache: $templateCache}).on('success', function(response) {
<add> // ignore callback if another route change occured since
<add> if (newChangeCounter == changeCounter) {
<add> element.html(response);
<add> compiler.compile(element)($route.current.scope);
<ide> $autoScroll();
<del> }).on('error', clearContent);
<del> }
<add> }
<add> }).on('error', clearContent);
<ide> } else {
<ide> clearContent();
<ide> }
<ide><path>test/widgetsSpec.js
<ide> describe("widget", function() {
<ide>
<ide>
<ide> describe('ng:include', inject(function($rootScope, $compile) {
<del> it('should include on external file', inject(function($rootScope, $compile, $cacheFactory) {
<add>
<add> function putIntoCache(url, content) {
<add> return function($templateCache) {
<add> $templateCache.put(url, [200, content, {}]);
<add> };
<add> }
<add>
<add>
<add> it('should include on external file', inject(putIntoCache('myUrl', '{{name}}'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = jqLite('<ng:include src="url" scope="childScope"></ng:include>');
<ide> var element = $compile(element)($rootScope);
<ide> $rootScope.childScope = $rootScope.$new();
<ide> $rootScope.childScope.name = 'misko';
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', '{{name}}');
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide> expect(element.text()).toEqual('misko');
<ide> }));
<ide>
<del>
<del> it('should remove previously included text if a falsy value is bound to src',
<del> inject(function($rootScope, $compile, $cacheFactory) {
<add>
<add> it('should remove previously included text if a falsy value is bound to src', inject(
<add> putIntoCache('myUrl', '{{name}}'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = jqLite('<ng:include src="url" scope="childScope"></ng:include>');
<ide> var element = $compile(element)($rootScope);
<ide> $rootScope.childScope = $rootScope.$new();
<ide> $rootScope.childScope.name = 'igor';
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', '{{name}}');
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide>
<ide> expect(element.text()).toEqual('igor');
<ide>
<ide> describe("widget", function() {
<ide> expect(element.text()).toEqual('');
<ide> }));
<ide>
<del>
<del> it('should allow this for scope', inject(function($rootScope, $compile, $cacheFactory) {
<add>
<add> it('should allow this for scope', inject(putIntoCache('myUrl', '{{"abc"}}'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = jqLite('<ng:include src="url" scope="this"></ng:include>');
<ide> var element = $compile(element)($rootScope);
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', '{{"abc"}}');
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<add>
<ide> // TODO(misko): because we are using scope==this, the eval gets registered
<ide> // during the flush phase and hence does not get called.
<ide> // I don't think passing 'this' makes sense. Does having scope on ng:include makes sense?
<ide> describe("widget", function() {
<ide> expect(element.text()).toEqual('abc');
<ide> }));
<ide>
<del>
<del> it('should evaluate onload expression when a partial is loaded',
<del> inject(function($rootScope, $compile, $cacheFactory) {
<add>
<add> it('should evaluate onload expression when a partial is loaded', inject(
<add> putIntoCache('myUrl', 'my partial'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = jqLite('<ng:include src="url" onload="loaded = true"></ng:include>');
<ide> var element = $compile(element)($rootScope);
<ide>
<ide> expect($rootScope.loaded).not.toBeDefined();
<ide>
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', 'my partial');
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<add>
<ide> expect(element.text()).toEqual('my partial');
<ide> expect($rootScope.loaded).toBe(true);
<ide> }));
<ide>
<del>
<del> it('should destroy old scope', inject(function($rootScope, $compile, $cacheFactory) {
<add>
<add> it('should destroy old scope', inject(putIntoCache('myUrl', 'my partial'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = jqLite('<ng:include src="url"></ng:include>');
<ide> var element = $compile(element)($rootScope);
<ide>
<ide> expect($rootScope.$$childHead).toBeFalsy();
<ide>
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', 'my partial');
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide> expect($rootScope.$$childHead).toBeTruthy();
<ide>
<ide> $rootScope.url = null;
<ide> $rootScope.$digest();
<ide> expect($rootScope.$$childHead).toBeFalsy();
<ide> }));
<ide>
<del> it('should do xhr request and cache it', inject(function($rootScope, $httpBackend, $compile) {
<add> it('should do xhr request and cache it',
<add> inject(function($rootScope, $httpBackend, $compile, $browser) {
<ide> var element = $compile('<ng:include src="url"></ng:include>')($rootScope);
<ide> $httpBackend.expect('GET', 'myUrl').respond('my partial');
<ide>
<ide> describe("widget", function() {
<ide>
<ide> $rootScope.url = 'myUrl';
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide> expect(element.text()).toEqual('my partial');
<ide> dealoc($rootScope);
<ide> }));
<ide> describe("widget", function() {
<ide> expect(element.text()).toBe('');
<ide> }));
<ide>
<del> it('should be async even if served from cache', inject(function($rootScope, $compile, $cacheFactory) {
<add> it('should be async even if served from cache', inject(
<add> putIntoCache('myUrl', 'my partial'),
<add> function($rootScope, $compile, $browser) {
<ide> var element = $compile('<ng:include src="url"></ng:include>')($rootScope);
<ide>
<ide> $rootScope.url = 'myUrl';
<del> $cacheFactory.get('templates').put('myUrl', 'my partial');
<ide>
<ide> var called = 0;
<ide> // we want to assert only during first watch
<ide> describe("widget", function() {
<ide> });
<ide>
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide> expect(element.text()).toBe('my partial');
<ide> }));
<ide> }));
<ide> describe("widget", function() {
<ide> }));
<ide>
<ide> it('should initialize view template after the view controller was initialized even when ' +
<del> 'templates were cached', inject(function($rootScope, $compile, $location, $httpBackend, $route) {
<add> 'templates were cached',
<add> inject(function($rootScope, $compile, $location, $httpBackend, $route, $browser) {
<ide> //this is a test for a regression that was introduced by making the ng:view cache sync
<ide>
<ide> $route.when('/foo', {controller: ParentCtrl, template: 'viewPartial.html'});
<ide> describe("widget", function() {
<ide> $rootScope.log = [];
<ide> $location.path('/foo');
<ide> $rootScope.$apply();
<add> $browser.defer.flush();
<ide>
<ide> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<ide> }));
<ide> describe("widget", function() {
<ide> }));
<ide>
<ide> it('should be async even if served from cache',
<del> inject(function($route, $rootScope, $location, $cacheFactory) {
<add> inject(function($route, $rootScope, $location, $templateCache, $browser) {
<add> $templateCache.put('myUrl1', [200, 'my partial', {}]);
<ide> $route.when('/foo', {controller: noop, template: 'myUrl1'});
<del> $cacheFactory.get('templates').put('myUrl1', 'my partial');
<ide> $location.path('/foo');
<ide>
<ide> var called = 0;
<ide> describe("widget", function() {
<ide> });
<ide>
<ide> $rootScope.$digest();
<add> $browser.defer.flush();
<ide> expect(element.text()).toBe('my partial');
<ide> }));
<ide> }); | 2 |
Javascript | Javascript | add secp224k1 check in crypto-dh-stateless | 940325042bef787e84917a27f9435d423b3f7f6d | <ide><path>test/parallel/test-crypto-dh-stateless.js
<ide> for (const [params1, params2] of [
<ide> test(crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }),
<ide> crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }));
<ide>
<add>const not256k1 = crypto.getCurves().find((c) => /^sec.*(224|384|512)/.test(c));
<ide> assert.throws(() => {
<ide> test(crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }),
<del> crypto.generateKeyPairSync('ec', { namedCurve: 'secp224k1' }));
<add> crypto.generateKeyPairSync('ec', { namedCurve: not256k1 }));
<ide> }, {
<ide> name: 'Error',
<ide> code: 'ERR_OSSL_EVP_DIFFERENT_PARAMETERS' | 1 |
Python | Python | simplify origin string cleaning | 68cb2daa410a72bcfb548587747afc9c5b946d11 | <ide><path>airflow/www/views.py
<ide> from json import JSONDecodeError
<ide> from operator import itemgetter
<ide> from typing import Any, Callable
<del>from urllib.parse import parse_qsl, unquote, urlencode, urlparse
<add>from urllib.parse import unquote, urljoin, urlsplit
<ide>
<ide> import configupdater
<ide> import flask.json
<ide> def truncate_task_duration(task_duration):
<ide>
<ide> def get_safe_url(url):
<ide> """Given a user-supplied URL, ensure it points to our web server"""
<del> valid_schemes = ['http', 'https', '']
<del> valid_netlocs = [request.host, '']
<del>
<ide> if not url:
<ide> return url_for('Airflow.index')
<ide>
<del> parsed = urlparse(url)
<del>
<ide> # If the url contains semicolon, redirect it to homepage to avoid
<ide> # potential XSS. (Similar to https://github.com/python/cpython/pull/24297/files (bpo-42967))
<ide> if ';' in unquote(url):
<ide> return url_for('Airflow.index')
<ide>
<del> query = parse_qsl(parsed.query, keep_blank_values=True)
<del>
<del> url = parsed._replace(query=urlencode(query)).geturl()
<del>
<del> if parsed.scheme in valid_schemes and parsed.netloc in valid_netlocs:
<del> return url
<add> host_url = urlsplit(request.host_url)
<add> redirect_url = urlsplit(urljoin(request.host_url, url))
<add> if not (redirect_url.scheme in ("http", "https") and host_url.netloc == redirect_url.netloc):
<add> return url_for('Airflow.index')
<ide>
<del> return url_for('Airflow.index')
<add> # This will ensure we only redirect to the right scheme/netloc
<add> return redirect_url.geturl()
<ide>
<ide>
<ide> def get_date_time_num_runs_dag_runs_form_data(www_request, session, dag):
<ide><path>tests/www/views/test_views.py
<ide> def test_task_dag_id_equals_filter(admin_client, url, content):
<ide> "test_url, expected_url",
<ide> [
<ide> ("", "/home"),
<add> ("javascript:alert(1)", "/home"),
<add> (" javascript:alert(1)", "http://localhost:8080/ javascript:alert(1)"),
<ide> ("http://google.com", "/home"),
<add> ("google.com", "http://localhost:8080/google.com"),
<add> ("\\/google.com", "http://localhost:8080/\\/google.com"),
<add> ("//google.com", "/home"),
<add> ("\\/\\/google.com", "http://localhost:8080/\\/\\/google.com"),
<ide> ("36539'%3balert(1)%2f%2f166", "/home"),
<ide> (
<ide> "http://localhost:8080/trigger?dag_id=test&origin=36539%27%3balert(1)%2f%2f166&abc=2",
<ide><path>tests/www/views/test_views_trigger_dag.py
<ide> def test_trigger_dag_form(admin_client):
<ide> ("36539'%3balert(1)%2f%2f166", "/home"),
<ide> (
<ide> '"><script>alert(99)</script><a href="',
<del> ""><script>alert(99)</script><a href="",
<add> "http://localhost/"><script>alert(99)</script><a href="",
<ide> ),
<ide> (
<ide> "%2Ftree%3Fdag_id%3Dexample_bash_operator';alert(33)//",
<ide> "/home",
<ide> ),
<del> ("%2Ftree%3Fdag_id%3Dexample_bash_operator", "/tree?dag_id=example_bash_operator"),
<del> ("%2Fgraph%3Fdag_id%3Dexample_bash_operator", "/graph?dag_id=example_bash_operator"),
<add> ("%2Ftree%3Fdag_id%3Dexample_bash_operator", "http://localhost/tree?dag_id=example_bash_operator"),
<add> ("%2Fgraph%3Fdag_id%3Dexample_bash_operator", "http://localhost/graph?dag_id=example_bash_operator"),
<ide> ],
<ide> )
<ide> def test_trigger_dag_form_origin_url(admin_client, test_origin, expected_origin): | 3 |
Python | Python | fix unitnorm to be a class, like other constraints | 24be9eb88b899b3cc8ed0470bb4f72e33060698e | <ide><path>keras/constraints.py
<ide> def __call__(self, p):
<ide> p *= T.ge(p, 0)
<ide> return p
<ide>
<del>def UnitNorm(Constraint):
<add>class UnitNorm(Constraint):
<ide> def __call__(self, p):
<ide> return e / T.sqrt(T.sum(e**2, axis=-1, keepdims=True))
<ide>
<ide> identity = Constraint
<ide> maxnorm = MaxNorm
<ide> nonneg = NonNeg
<del>unitnorm = UnitNorm
<ide>\ No newline at end of file
<add>unitnorm = UnitNorm | 1 |
Text | Text | use consistent typography in streams.md | a78c2335b137a1038610b7daa2d85406c3098f61 | <ide><path>doc/api/stream.md
<ide> pre-v0.10 style streams can be wrapped in a Readable class using the
<ide> There are some cases where it is necessary to trigger a refresh of the
<ide> underlying readable stream mechanisms, without actually consuming any
<ide> data. In such cases, it is possible to call `readable.read(0)`, which will
<del>always return null.
<add>always return `null`.
<ide>
<ide> If the internal read buffer is below the `highWaterMark`, and the
<ide> stream is not currently reading, then calling `stream.read(0)` will trigger | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.