content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
remove shape_tuple usage for keras_tensor
59568edf69803a56d419cd211dd1ae6024d0195a
<ide><path>keras/engine/keras_tensor.py <ide> def type_spec_with_shape(spec, shape): <ide> # private fields.) <ide> shape = tf.TensorShape(shape) <ide> spec._shape = shape <del> if shape.rank is None: <del> spec._shape_tuple = None <del> else: <del> spec._shape_tuple = tuple(shape.as_list()) <ide> return spec <ide> elif isinstance(spec, tf.RaggedTensorSpec): <ide> return tf.RaggedTensorSpec(shape, spec.dtype, spec.ragged_rank,
1
Text
Text
add info for `change` column and table comment
e2ffa662564fd9ee9b9c6f386c833b11f521946c
<ide><path>guides/source/active_record_migrations.md <ide> and <ide> ### Using the `change` Method <ide> <ide> The `change` method is the primary way of writing migrations. It works for the <del>majority of cases, where Active Record knows how to reverse the migration <del>automatically. Currently, the `change` method supports only these migration <del>definitions: <add>majority of cases in which Active Record knows how to reverse a migration's <add>actions automatically. Below are some of the actions that `change` supports: <ide> <ide> * [`add_column`][] <ide> * [`add_foreign_key`][] <ide> * [`add_index`][] <ide> * [`add_reference`][] <ide> * [`add_timestamps`][] <add>* [`change_column_comment`][] (must supply a `:from` and `:to` option) <ide> * [`change_column_default`][] (must supply a `:from` and `:to` option) <ide> * [`change_column_null`][] <add>* [`change_table_comment`][] (must supply a `:from` and `:to` option) <ide> * [`create_join_table`][] <ide> * [`create_table`][] <ide> * `disable_extension` <ide> or write the `up` and `down` methods instead of using the `change` method. <ide> <ide> [`add_foreign_key`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key <ide> [`add_timestamps`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_timestamps <add>[`change_column_comment`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_comment <add>[`change_table_comment`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_table_comment <ide> [`drop_join_table`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-drop_join_table <ide> [`drop_table`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-drop_table <ide> [`remove_foreign_key`]: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_foreign_key
1
Text
Text
add missing instruction text
ae7404eab72061c7710001769118e0d4e9ac2453
<ide><path>curriculum/challenges/russian/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.russian.md <ide> localeTitle: Ссылка на внешние страницы с элемент <ide> --- <ide> <ide> ## Description <add> <ide> <section id="description"> Вы можете использовать элементы <code>anchor</code> для ссылки на контент вне вашей веб-страницы. Элементам <code>anchor</code> нужен адрес веб-сайта назначения, называемый атрибутом <code>href</code>. Им также нужен якорный текст. Вот пример: <code>&lt;a href=&quot;https://freecodecamp.org&quot;&gt;this links to freecodecamp.org&lt;/a&gt;</code> Затем ваш браузер отобразит текст <strong>«это ссылки на freecodecamp.org»</strong> в качестве ссылки, которую вы можете щелкнуть. И эта ссылка приведет вас к веб-адресу <strong>https://www.freecodecamp.org</strong> . </section> <ide> <ide> ## Instructions <ide> Создайте элемент, который ссылается на <code>http://freecatphotoapp.com</code> и имеет «фотографии котят» в качестве его якорного текста. <ide> <add> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Ваш элемент должен иметь <code>a</code> в качестве <code>anchor text</code> должен иметь «фотографии котят». <add> <add> - text: Ваш элемент <code>a</code> должен иметь <code>якорный текст</code> «cat photos». <add> <ide> testString: 'assert((/cat photos/gi).test($("a").text()), "Your <code>a</code> element should have the <code>anchor text</code> of "cat photos".");' <ide> - text: 'Вам нужно создать <code>a</code> элемент, являющийся ссылкой на <code>http://freecatphotoapp .com</code>' <ide> testString: 'assert(/http:\/\/(www\.)?freecatphotoapp\.com/gi.test($("a").attr("href")), "You need an <code>a</code> element that links to <code>http&#58;//freecatphotoapp<wbr>.com</code>");'
1
Ruby
Ruby
remove time stubs after each test
f51cf2e4b558787e6027b63d1ad051d553dfc80f
<ide><path>activerecord/test/cases/mixin_test.rb <ide> class TouchTest < ActiveRecord::TestCase <ide> travel_to Time.now <ide> end <ide> <del> teardown do <del> travel_back <del> end <del> <ide> def test_update <ide> stamped = Mixin.new <ide> <ide><path>activesupport/lib/active_support/testing/time_helpers.rb <ide> def unstub_object(stub) <ide> <ide> # Contains helpers that help you test passage of time. <ide> module TimeHelpers <add> def after_teardown <add> travel_back <add> super <add> end <add> <ide> # Changes current time to the time in the future or in the past by a given time difference by <del> # stubbing +Time.now+, +Date.today+, and +DateTime.now+. <add> # stubbing +Time.now+, +Date.today+, and +DateTime.now+. The stubs are automatically removed <add> # at the end of the test. <ide> # <ide> # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 <ide> # travel 1.day <ide> def travel(duration, &block) <ide> <ide> # Changes current time to the given time by stubbing +Time.now+, <ide> # +Date.today+, and +DateTime.now+ to return the time or date passed into this method. <add> # The stubs are automatically removed at the end of the test. <ide> # <ide> # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 <ide> # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44) <ide><path>activesupport/test/time_zone_test.rb <ide> def test_today <ide> assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today <ide> travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST <ide> assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].today <del> travel_back <ide> end <ide> <ide> def test_tomorrow <ide> def test_tomorrow <ide> assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow <ide> travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST <ide> assert_equal Date.new(2000, 1, 3), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].tomorrow <del> travel_back <ide> end <ide> <ide> def test_yesterday <ide> def test_yesterday <ide> assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday <ide> travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST <ide> assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone["Eastern Time (US & Canada)"].yesterday <del> travel_back <ide> end <ide> <ide> def test_travel_to_a_date
3
Go
Go
stream the cp operation on the client
fdd8d4b7d9dbc32a76a708d0d51c201cf9c977f0
<ide><path>commands.go <ide> func (cli *DockerCli) CmdLogin(args ...string) error { <ide> authconfig.ServerAddress = serverAddress <ide> cli.configFile.Configs[serverAddress] = authconfig <ide> <del> body, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress]) <add> body, statusCode, err := readBody(cli.call("POST", "/auth", cli.configFile.Configs[serverAddress])) <ide> if statusCode == 401 { <ide> delete(cli.configFile.Configs, serverAddress) <ide> auth.SaveConfig(cli.configFile) <ide> func (cli *DockerCli) CmdVersion(args ...string) error { <ide> fmt.Fprintf(cli.out, "Git commit (client): %s\n", GITCOMMIT) <ide> } <ide> <del> body, _, err := cli.call("GET", "/version", nil) <add> body, _, err := readBody(cli.call("GET", "/version", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdInfo(args ...string) error { <ide> return nil <ide> } <ide> <del> body, _, err := cli.call("GET", "/info", nil) <add> body, _, err := readBody(cli.call("GET", "/info", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdStop(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range cmd.Args() { <del> _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil) <add> _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)) <ide> if err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to stop one or more containers") <ide> func (cli *DockerCli) CmdRestart(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range cmd.Args() { <del> _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil) <add> _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)) <ide> if err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to restart one or more containers") <ide> func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { <ide> if s == syscall.SIGCHLD { <ide> continue <ide> } <del> if _, _, err := cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%d", cid, s), nil); err != nil { <add> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%d", cid, s), nil)); err != nil { <ide> utils.Debugf("Error sending signal: %s", err) <ide> } <ide> } <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> return fmt.Errorf("Impossible to start and attach multiple containers at once.") <ide> } <ide> <del> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range cmd.Args() { <del> _, _, err := cli.call("POST", "/containers/"+name+"/start", nil) <add> _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil)) <ide> if err != nil { <ide> if !*attach || !*openStdin { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> func (cli *DockerCli) CmdInspect(args ...string) error { <ide> status := 0 <ide> <ide> for _, name := range cmd.Args() { <del> obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil) <add> obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil)) <ide> if err != nil { <del> obj, _, err = cli.call("GET", "/images/"+name+"/json", nil) <add> obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil)) <ide> if err != nil { <ide> if strings.Contains(err.Error(), "No such") { <ide> fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name) <ide> func (cli *DockerCli) CmdTop(args ...string) error { <ide> val.Set("ps_args", strings.Join(cmd.Args()[1:], " ")) <ide> } <ide> <del> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdPort(args ...string) error { <ide> port = parts[0] <ide> proto = parts[1] <ide> } <del> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdRmi(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range cmd.Args() { <del> body, _, err := cli.call("DELETE", "/images/"+name, nil) <add> body, _, err := readBody(cli.call("DELETE", "/images/"+name, nil)) <ide> if err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images") <ide> func (cli *DockerCli) CmdHistory(args ...string) error { <ide> return nil <ide> } <ide> <del> body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil) <add> body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdRm(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range cmd.Args() { <del> _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil) <add> _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)) <ide> if err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to remove one or more containers") <ide> func (cli *DockerCli) CmdKill(args ...string) error { <ide> <ide> var encounteredError error <ide> for _, name := range args { <del> if _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil); err != nil { <add> if _, _, err := readBody(cli.call("POST", "/containers/"+name+"/kill", nil)); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to kill one or more containers") <ide> } else { <ide> func (cli *DockerCli) CmdImages(args ...string) error { <ide> filter := cmd.Arg(0) <ide> <ide> if *flViz || *flTree { <del> body, _, err := cli.call("GET", "/images/json?all=1", nil) <add> body, _, err := readBody(cli.call("GET", "/images/json?all=1", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdImages(args ...string) error { <ide> v.Set("all", "1") <ide> } <ide> <del> body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil) <add> body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> v.Set("size", "1") <ide> } <ide> <del> body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil) <add> body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdCommit(args ...string) error { <ide> return err <ide> } <ide> } <del> body, _, err := cli.call("POST", "/commit?"+v.Encode(), config) <add> body, _, err := readBody(cli.call("POST", "/commit?"+v.Encode(), config)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdDiff(args ...string) error { <ide> return nil <ide> } <ide> <del> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdLogs(args ...string) error { <ide> return nil <ide> } <ide> name := cmd.Arg(0) <del> body, _, err := cli.call("GET", "/containers/"+name+"/json", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdAttach(args ...string) error { <ide> return nil <ide> } <ide> name := cmd.Arg(0) <del> body, _, err := cli.call("GET", "/containers/"+name+"/json", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdSearch(args ...string) error { <ide> <ide> v := url.Values{} <ide> v.Set("term", cmd.Arg(0)) <del> body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil) <add> body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil)) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdTag(args ...string) error { <ide> v.Set("force", "1") <ide> } <ide> <del> if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil { <add> if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil)); err != nil { <ide> return err <ide> } <ide> return nil <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> } <ide> <ide> //create the container <del> body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config) <add> body, statusCode, err := readBody(cli.call("POST", "/containers/create?"+containerValues.Encode(), config)) <ide> //if image not found try to pull it <ide> if statusCode == 404 { <ide> _, tag := utils.ParseRepositoryTag(config.Image) <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil { <ide> return err <ide> } <del> if body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config); err != nil { <add> if body, _, err = readBody(cli.call("POST", "/containers/create?"+containerValues.Encode(), config)); err != nil { <ide> return err <ide> } <ide> } else if err != nil { <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> } <ide> <ide> //start the container <del> if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil { <add> if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig)); err != nil { <ide> return err <ide> } <ide> <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> if autoRemove { <ide> // Autoremove: wait for the container to finish, retrieve <ide> // the exit code and remove the container <del> if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil { <add> if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.ID+"/wait", nil)); err != nil { <ide> return err <ide> } <ide> if _, status, err = getExitCode(cli, runResult.ID); err != nil { <ide> return err <ide> } <del> if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID+"?v=1", nil); err != nil { <add> if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.ID+"?v=1", nil)); err != nil { <ide> return err <ide> } <ide> } else { <ide> func (cli *DockerCli) CmdCp(args ...string) error { <ide> copyData.Resource = info[1] <ide> copyData.HostPath = cmd.Arg(1) <ide> <del> data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData) <add> stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData) <add> if stream != nil { <add> defer stream.Close() <add> } <ide> if err != nil { <ide> return err <ide> } <ide> <ide> if statusCode == 200 { <del> r := bytes.NewReader(data) <del> if err := archive.Untar(r, copyData.HostPath, nil); err != nil { <add> if err := archive.Untar(stream, copyData.HostPath, nil); err != nil { <ide> return err <ide> } <ide> } <ide> func (cli *DockerCli) CmdLoad(args ...string) error { <ide> return nil <ide> } <ide> <del>func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) { <add>func (cli *DockerCli) call(method, path string, data interface{}) (io.ReadCloser, int, error) { <ide> var params io.Reader <ide> if data != nil { <ide> buf, err := json.Marshal(data) <ide> func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, <ide> } <ide> clientconn := httputil.NewClientConn(dial, nil) <ide> resp, err := clientconn.Do(req) <del> defer clientconn.Close() <ide> if err != nil { <add> clientconn.Close() <ide> if strings.Contains(err.Error(), "connection refused") { <ide> return nil, -1, ErrConnectionRefused <ide> } <ide> return nil, -1, err <ide> } <del> defer resp.Body.Close() <del> <del> body, err := ioutil.ReadAll(resp.Body) <del> if err != nil { <del> return nil, -1, err <del> } <del> if resp.StatusCode < 200 || resp.StatusCode >= 400 { <del> if len(body) == 0 { <del> return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode)) <add> wrapper := utils.NewReadCloserWrapper(resp.Body, func() error { <add> if resp != nil && resp.Body != nil { <add> resp.Body.Close() <ide> } <del> return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body)) <del> } <del> return body, resp.StatusCode, nil <add> return clientconn.Close() <add> }) <add> return wrapper, resp.StatusCode, nil <ide> } <ide> <ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error { <ide> func (cli *DockerCli) resizeTty(id string) { <ide> v := url.Values{} <ide> v.Set("h", strconv.Itoa(height)) <ide> v.Set("w", strconv.Itoa(width)) <del> if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil { <add> if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil)); err != nil { <ide> utils.Errorf("Error resize: %s", err) <ide> } <ide> } <ide> func (cli *DockerCli) LoadConfigFile() (err error) { <ide> } <ide> <ide> func waitForExit(cli *DockerCli, containerId string) (int, error) { <del> body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil) <add> body, _, err := readBody(cli.call("POST", "/containers/"+containerId+"/wait", nil)) <ide> if err != nil { <ide> return -1, err <ide> } <ide> func waitForExit(cli *DockerCli, containerId string) (int, error) { <ide> // getExitCode perform an inspect on the container. It returns <ide> // the running state and the exit code. <ide> func getExitCode(cli *DockerCli, containerId string) (bool, int, error) { <del> body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil) <add> body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil)) <ide> if err != nil { <ide> // If we can't connect, then the daemon probably died. <ide> if err != ErrConnectionRefused { <ide> func getExitCode(cli *DockerCli, containerId string) (bool, int, error) { <ide> return c.State.IsRunning(), c.State.GetExitCode(), nil <ide> } <ide> <add>func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) { <add> if stream != nil { <add> defer stream.Close() <add> } <add> if err != nil { <add> return nil, statusCode, err <add> } <add> body, err := ioutil.ReadAll(stream) <add> if err != nil { <add> return nil, -1, err <add> } <add> if statusCode < 200 || statusCode >= 400 { <add> if len(body) == 0 { <add> return nil, statusCode, fmt.Errorf("Error: %s", http.StatusText(statusCode)) <add> } <add> return nil, statusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body)) <add> } <add> return body, statusCode, nil <add>} <add> <ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli { <ide> var ( <ide> isTerminal = false <ide><path>utils/utils.go <ide> func CopyFile(src, dst string) (int64, error) { <ide> defer df.Close() <ide> return io.Copy(df, sf) <ide> } <add> <add>type readCloserWrapper struct { <add> io.Reader <add> closer func() error <add>} <add> <add>func (r *readCloserWrapper) Close() error { <add> return r.closer() <add>} <add> <add>func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { <add> return &readCloserWrapper{ <add> Reader: r, <add> closer: closer, <add> } <add>}
2
Javascript
Javascript
resolve react-dom/server (#688)
929041133cc05d958ddb5ab60ea82c5d8af324ad
<ide><path>server/build/babel/preset.js <ide> module.exports = { <ide> 'babel-runtime': babelRuntimePath, <ide> react: require.resolve('react'), <ide> 'react-dom': require.resolve('react-dom'), <add> 'react-dom/server': require.resolve('react-dom/server'), <ide> 'next/link': require.resolve('../../../lib/link'), <ide> 'next/prefetch': require.resolve('../../../lib/prefetch'), <ide> 'next/css': require.resolve('../../../lib/css'),
1
Text
Text
add a function call to seed contents
aa0ae1ae6712ccec817286406cbddead4b74610b
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.md <ide> function urlSlug(title) { <ide> <ide> } <ide> // Only change code above this line <add>urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone"); <ide> ``` <ide> <ide> # --solutions--
1
Ruby
Ruby
treat future sdks as "latest"
e63eff22014d1a8ede20312f715fe062702abe2c
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def below_minimum_version? <ide> end <ide> <ide> def latest_sdk_version? <del> OS::Mac.version == OS::Mac.latest_sdk_version <add> OS::Mac.version >= OS::Mac.latest_sdk_version <ide> end <ide> <ide> def needs_clt_installed?
1
Python
Python
use less precision for almostequal
7664b74a2433df4527b0de578cbe830f0be51b1f
<ide><path>celery/tests/test_task.py <ide> def test_every_minute_execution_is_due(self): <ide> last_ran = self.now - timedelta(seconds=61) <ide> due, remaining = EveryMinutePeriodic().is_due(last_ran) <ide> self.assertTrue(due) <del> self.assertAlmostEquals(remaining, self.next_minute, 2) <add> self.assertAlmostEquals(remaining, self.next_minute, 1) <ide> <ide> def test_every_minute_execution_is_not_due(self): <ide> last_ran = self.now - timedelta(seconds=self.now.second) <ide> due, remaining = EveryMinutePeriodic().is_due(last_ran) <ide> self.assertFalse(due) <del> self.assertAlmostEquals(remaining, self.next_minute, 2) <add> self.assertAlmostEquals(remaining, self.next_minute, 1) <ide> <ide> # 29th of May 2010 is a saturday <ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 29, 10, 30)) <ide> def test_execution_is_due_on_saturday(self): <ide> last_ran = self.now - timedelta(seconds=61) <ide> due, remaining = EveryMinutePeriodic().is_due(last_ran) <ide> self.assertTrue(due) <del> self.assertAlmostEquals(remaining, self.next_minute, 2) <add> self.assertAlmostEquals(remaining, self.next_minute, 1) <ide> <ide> # 30th of May 2010 is a sunday <ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 30, 10, 30)) <ide> def test_execution_is_due_on_sunday(self): <ide> last_ran = self.now - timedelta(seconds=61) <ide> due, remaining = EveryMinutePeriodic().is_due(last_ran) <ide> self.assertTrue(due) <del> self.assertAlmostEquals(remaining, self.next_minute, 2) <add> self.assertAlmostEquals(remaining, self.next_minute, 1) <ide> <ide> # 31st of May 2010 is a monday <ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 31, 10, 30)) <ide> def test_execution_is_due_on_monday(self): <ide> last_ran = self.now - timedelta(seconds=61) <ide> due, remaining = EveryMinutePeriodic().is_due(last_ran) <ide> self.assertTrue(due) <del> self.assertAlmostEquals(remaining, self.next_minute, 2) <add> self.assertAlmostEquals(remaining, self.next_minute, 1) <ide> <ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 10, 10, 30)) <ide> def test_every_hour_execution_is_due(self):
1
Mixed
Javascript
add cwd to cluster.settings
e0864e50ecf917cbfa98d443e6f122425d6447cf
<ide><path>doc/api/cluster.md <ide> changes: <ide> * `exec` {string} File path to worker file. **Default:** `process.argv[1]` <ide> * `args` {Array} String arguments passed to worker. <ide> **Default:** `process.argv.slice(2)` <add> * `cwd` {string} Current working directory of the worker process. **Default:** <add> `undefined` (inherits from parent process) <ide> * `silent` {boolean} Whether or not to send output to parent's stdio. <ide> **Default:** `false` <ide> * `stdio` {Array} Configures the stdio of forked processes. Because the <ide><path>lib/internal/cluster/master.js <ide> function createWorkerProcess(id, env) { <ide> } <ide> <ide> return fork(cluster.settings.exec, cluster.settings.args, { <add> cwd: cluster.settings.cwd, <ide> env: workerEnv, <ide> silent: cluster.settings.silent, <ide> windowsHide: cluster.settings.windowsHide, <ide><path>test/parallel/test-cluster-cwd.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const cluster = require('cluster'); <add> <add>if (cluster.isMaster) { <add> common.refreshTmpDir(); <add> <add> assert.strictEqual(cluster.settings.cwd, undefined); <add> cluster.fork().on('message', common.mustCall((msg) => { <add> assert.strictEqual(msg, process.cwd()); <add> })); <add> <add> cluster.setupMaster({ cwd: common.tmpDir }); <add> assert.strictEqual(cluster.settings.cwd, common.tmpDir); <add> cluster.fork().on('message', common.mustCall((msg) => { <add> assert.strictEqual(msg, common.tmpDir); <add> })); <add>} else { <add> process.send(process.cwd()); <add> process.disconnect(); <add>}
3
PHP
PHP
map small/tinyint to number input types
9102690ccaf33921024b7ab50b29a6d7556cbfae
<ide><path>src/View/Helper/FormHelper.php <ide> class FormHelper extends Helper <ide> 'idPrefix' => null, <ide> 'errorClass' => 'form-error', <ide> 'typeMap' => [ <del> 'string' => 'text', 'datetime' => 'datetime', 'boolean' => 'checkbox', <del> 'timestamp' => 'datetime', 'text' => 'textarea', 'time' => 'time', <del> 'date' => 'date', 'float' => 'number', 'integer' => 'number', <del> 'decimal' => 'number', 'binary' => 'file', 'uuid' => 'string' <add> 'string' => 'text', <add> 'datetime' => 'datetime', <add> 'boolean' => 'checkbox', <add> 'timestamp' => 'datetime', <add> 'text' => 'textarea', <add> 'time' => 'time', <add> 'date' => 'date', <add> 'float' => 'number', <add> 'integer' => 'number', <add> 'tinyint' => 'number', <add> 'smallint' => 'number', <add> 'decimal' => 'number', <add> 'binary' => 'file', <add> 'uuid' => 'string' <ide> ], <ide> 'templates' => [ <ide> 'button' => '<button{{attrs}}>{{text}}</button>', <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testFormSecurityFieldsNoDebugMode() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * Tests correct generation of number fields for smallint <add> * <add> * @return void <add> */ <add> public function testTextFieldGenerationForSmallint() <add> { <add> $this->article['schema'] = [ <add> 'foo' => [ <add> 'type' => 'smallint', <add> 'null' => false, <add> 'default' => null, <add> 'length' => 10 <add> ] <add> ]; <add> <add> $this->Form->create($this->article); <add> $result = $this->Form->control('foo'); <add> $this->assertContains('class="input number"', $result); <add> $this->assertContains('type="number"', $result); <add> } <add> <add> /** <add> * Tests correct generation of number fields for tinyint <add> * <add> * @return void <add> */ <add> public function testTextFieldGenerationForTinyint() <add> { <add> $this->article['schema'] = [ <add> 'foo' => [ <add> 'type' => 'tinyint', <add> 'null' => false, <add> 'default' => null, <add> 'length' => 10 <add> ] <add> ]; <add> <add> $this->Form->create($this->article); <add> $result = $this->Form->control('foo'); <add> $this->assertContains('class="input number"', $result); <add> $this->assertContains('type="number"', $result); <add> } <add> <ide> /** <ide> * Tests correct generation of number fields for double and float fields <ide> *
2
Ruby
Ruby
use polymorphism to remove conditional
026c40fc1887b19af0f9a73a616d736f4ac4f5b4
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def define_named_route_methods(name, route) <ide> # <ide> class UrlHelper <ide> def self.create(route, options) <del> new route, options <add> if optimize_helper?(route) <add> OptimizedUrlHelper.new(route, options) <add> else <add> new route, options <add> end <add> end <add> <add> def self.optimize_helper?(route) <add> route.requirements.except(:controller, :action).empty? <add> end <add> <add> class OptimizedUrlHelper < UrlHelper <add> def initialize(route, options) <add> super <add> end <add> <add> def call(t, args) <add> if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t) <add> @options.merge!(t.url_options) if t.respond_to?(:url_options) <add> @options[:path] = eval("\"#{optimized_helper}\"") <add> ActionDispatch::Http::URL.url_for(@options) <add> else <add> super <add> end <add> end <ide> end <ide> <ide> def initialize(route, options) <ide> def initialize(route, options) <ide> @route = route <ide> end <ide> <del> def optimize_helper? <del> @route.requirements.except(:controller, :action).empty? <del> end <del> <ide> def arg_size <ide> @route.required_parts.size <ide> end <ide> def optimized_helper <ide> string_route <ide> end <ide> <del> def url_else(t, args) <add> def call(t, args) <ide> t.url_for(handle_positional_args(t, args, @options, @segment_keys)) <ide> end <ide> <del> def url_if(t, args) <del> if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t) <del> @options.merge!(t.url_options) if t.respond_to?(:url_options) <del> @options[:path] = eval("\"#{optimized_helper}\"") <del> ActionDispatch::Http::URL.url_for(@options) <del> else <del> url_else(t, args) <del> end <del> end <del> <ide> def optimize_routes_generation?(t) <ide> t.send(:optimize_routes_generation?) <ide> end <ide> def handle_positional_args(t, args, options, segment_keys) <ide> <ide> def define_url_helper(route, name, options) <ide> @module.remove_possible_method name <del> #@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 <del> # def #{name}(*args) <del> # if #{optimize_helper?(route)} && args.size == #{route.required_parts.size} && !args.last.is_a?(Hash) && optimize_routes_generation? <del> # options = #{options.inspect} <del> # UrlHelp.new.url_if(self, options, "#{optimized_helper(route)}") <del> # else <del> # UrlHelp.new.url_else(self, args, #{options.inspect}, #{route.segment_keys.inspect}) <del> # end <del> # end <del> #END_EVAL <ide> <ide> helper = UrlHelper.create(route, options.dup) <ide> <del> ohelp = helper.optimize_helper? <del> <ide> @module.module_eval do <ide> define_method(name) do |*args| <del> #helper.call t, args <del> if ohelp <del> helper.url_if(self, args) <del> else <del> helper.url_else(self, args) <del> end <add> helper.call self, args <ide> end <ide> end <ide> <ide> helpers << name <ide> end <del> <ide> end <ide> <ide> attr_accessor :formatter, :set, :named_routes, :default_scope, :router
1
Javascript
Javascript
fix the threshold for the florida keys
8a77b18d849234a641d6c0066796945f91e499d8
<ide><path>d3.geo.js <ide> d3.geo.albersUsa = function() { <ide> function albersUsa(coordinates) { <ide> var lon = coordinates[0], <ide> lat = coordinates[1]; <del> return (lat < 25 <add> return (lat < 21 <ide> ? (lon < -100 ? hawaii : puertoRico) <ide> : (lat > 50 ? alaska : lower48))(coordinates); <ide> } <ide><path>d3.geo.min.js <del>(function(){function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={},d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b=="stereographic"?1/(1+i*n+h*m*k):1,p=o*m*l,q=o*(i*m*k-h*n);return[d*p+e[0],d*q+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.mode=function(a){if(!arguments.length)return b;b=a;return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g<25?f<-100?c:d:g>50?b:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())};var a=Math.PI/180;d3.geo.mercator=function(){function c(c){var d=c[0]/360,e=-180/Math.PI*Math.log(Math.tan(Math.PI/4+c[1]*Math.PI/360))/360;return[a*d+b[0],a*Math.max(-0.5,Math.min(.5,e))+b[1]]}var a=500,b=[480,250];c.scale=function(b){if(!arguments.length)return a;a=+b;return c},c.translate=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return c};return c},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m}})() <ide>\ No newline at end of file <add>(function(){function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={},d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b=="stereographic"?1/(1+i*n+h*m*k):1,p=o*m*l,q=o*(i*m*k-h*n);return[d*p+e[0],d*q+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.mode=function(a){if(!arguments.length)return b;b=a;return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g<21?f<-100?c:d:g>50?b:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())};var a=Math.PI/180;d3.geo.mercator=function(){function c(c){var d=c[0]/360,e=-180/Math.PI*Math.log(Math.tan(Math.PI/4+c[1]*Math.PI/360))/360;return[a*d+b[0],a*Math.max(-0.5,Math.min(.5,e))+b[1]]}var a=500,b=[480,250];c.scale=function(b){if(!arguments.length)return a;a=+b;return c},c.translate=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return c};return c},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m}})() <ide>\ No newline at end of file <ide><path>src/geo/albers.js <ide> d3.geo.albersUsa = function() { <ide> function albersUsa(coordinates) { <ide> var lon = coordinates[0], <ide> lat = coordinates[1]; <del> return (lat < 25 <add> return (lat < 21 <ide> ? (lon < -100 ? hawaii : puertoRico) <ide> : (lat > 50 ? alaska : lower48))(coordinates); <ide> }
3
PHP
PHP
remove unneeded argument
0ecbd7fd259ba40affc33133ecae7f9095873730
<ide><path>src/Controller/ControllerFactory.php <ide> use Cake\Core\App; <ide> use Cake\Http\ControllerFactoryInterface; <ide> use Cake\Http\Exception\MissingControllerException; <del>use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Utility\Inflector; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> use ReflectionClass; <ide> <ide> /** <del> * Factory method for building controllers from request/response pairs. <add> * Factory method for building controllers for request. <ide> * <ide> * @implements \Cake\Http\ControllerFactoryInterface<\Cake\Controller\Controller> <ide> */ <ide> class ControllerFactory implements ControllerFactoryInterface <ide> { <ide> /** <del> * Create a controller for a given request/response <add> * Create a controller for a given request. <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request to build a controller for. <ide> * @return \Cake\Controller\Controller <ide> public function create(ServerRequestInterface $request): Controller <ide> $this->missingController($request); <ide> } <ide> <del> $response = new Response(); <del> <ide> /** @var \Cake\Controller\Controller $controller */ <del> $controller = $reflection->newInstance($request, $response); <add> $controller = $reflection->newInstance($request); <ide> <ide> return $controller; <ide> }
1
Python
Python
add tests for print of float types
f66bcae0bf4fd13e499bf77fccf43eeb98bbdc47
<ide><path>numpy/core/tests/test_print.py <ide> <ide> import locale <ide> import sys <add>from StringIO import StringIO <ide> <ide> def check_float_type(tp): <ide> for x in [0, 1,-1, 1e10, 1e20] : <ide> def test_complex_types(): <ide> for t in [np.complex64, np.cdouble, np.clongdouble] : <ide> yield check_complex_type, t <ide> <add># print tests <add>def check_float_type_print(tp): <add> for x in [0, 1,-1, 1e10, 1e20, float('inf'), float('nan'), float('-inf')] : <add> file = StringIO() <add> file_tp = StringIO() <add> stdout = sys.stdout <add> try: <add> sys.stdout = file_tp <add> print tp(x) <add> sys.stdout = file <add> print x <add> finally: <add> sys.stdout = stdout <add> <add> assert_equal(file.getvalue(), file_tp.getvalue(), <add> err_msg='print failed for type%s' % tp) <add> <add>def test_float_type_print(): <add> """Check formatting when using print """ <add> for t in [np.float32, np.double, np.longdouble] : <add> yield check_float_type_print, t <add> <add># Locale tests: scalar types formatting should be independant of the locale <ide> def has_french_locale(): <ide> curloc = locale.getlocale(locale.LC_NUMERIC) <ide> try:
1
PHP
PHP
add proper annotation
f633dc9aee95f245c485d1e9a9d55f83a3cfed1b
<ide><path>src/Filesystem/Folder.php <ide> public function tree($path = null, $exceptions = false, $type = null) <ide> continue; <ide> } <ide> } <add> /** @var \FilesystemIterator $item */ <ide> $item = $fsIterator->current(); <ide> if (!empty($exceptions) && isset($exceptions[$item->getFilename()])) { <ide> continue;
1
Ruby
Ruby
add basic json option to brew cask
2d5ae645d9cc46af57aaaabbfe6bfb2db9f9e1bd
<ide><path>Library/Homebrew/cask/lib/hbc/cask.rb <ide> def dumpcask <ide> odebug "Cask instance method '#{method}':", send(method).to_yaml <ide> end <ide> end <add> <add> def to_hash <add> hsh = { <add> "name" => name, <add> "homepage" => homepage, <add> "url" => url, <add> "appcast" => appcast, <add> "version" => version, <add> "sha256" => sha256, <add> "artifacts" => artifacts, <add> "caveats" => caveats, <add> "depends_on" => depends_on, <add> "conflicts_with" => conflicts_with, <add> "container" => container, <add> "gpg" => gpg, <add> "accessibility_access" => accessibility_access, <add> "auto_updates" => auto_updates <add> } <add> <add> hsh <add> end <ide> end <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/cli/info.rb <add>require "json" <add> <ide> module Hbc <ide> class CLI <ide> class Info < AbstractCommand <add> option "--json", :json, false <add> <ide> def initialize(*) <ide> super <ide> raise CaskUnspecifiedError if args.empty? <ide> end <ide> <ide> def run <del> casks.each do |cask| <del> odebug "Getting info for Cask #{cask}" <del> self.class.info(cask) <add> if json? <add> json = casks.map(&:to_hash) <add> puts JSON.generate(json) <add> else <add> casks.each do |cask| <add> odebug "Getting info for Cask #{cask}" <add> self.class.info(cask) <add> end <ide> end <ide> end <ide>
2
Ruby
Ruby
fix build failures on mysql
2eaa7be638854ec513be4966f526f2564aecb7dd
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def primary_keys(table_name) # :nodoc: <ide> <ide> def case_sensitive_comparison(table, attribute, column, value) # :nodoc: <ide> if column.collation && !column.case_sensitive? <del> table[attribute].eq(Arel::Nodes::Bin.new(value)) <add> table[attribute].eq(Arel::Nodes::Bin.new(Arel::Nodes::BindParam.new(value))) <ide> else <ide> super <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> class Mysql2Adapter < AbstractMysqlAdapter <ide> <ide> def initialize(connection, logger, connection_options, config) <ide> super <del> @prepared_statements = false unless config.key?(:prepared_statements) <add> @prepared_statements = true unless config[:prepared_statements] == false <ide> configure_connection <ide> end <ide>
2
Ruby
Ruby
add tests for cp_path_sub
522f7ea8c729ef6a5fddc5921ba045713236c28d
<ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_install_renamed_directory <ide> @dst.install @src <ide> assert_equal "a", File.read(@[email protected][email protected]) <ide> end <add> <add> def test_cp_path_sub_file <add> @file.write "a" <add> @file.cp_path_sub @src, @dst <add> assert_equal "a", File.read(@dst+"foo") <add> end <add> <add> def test_cp_path_sub_directory <add> @dir.mkpath <add> @dir.cp_path_sub @src, @dst <add> assert_predicate @[email protected], :directory? <add> end <ide> end <ide> <ide> class PathnameInstallTests < Homebrew::TestCase
1
Javascript
Javascript
fix regexp nits in v8_prof_polyfill.js
6b9500bfc29f9917f13f0957ab719a9c09b3ea78
<ide><path>lib/internal/v8_prof_polyfill.js <ide> function versionCheck() { <ide> function macCppfiltNm(out) { <ide> // Re-grouped copy-paste from `tickprocessor.js` <ide> const FUNC_RE = /^([0-9a-fA-F]{8,16} [iItT] )(.*)$/gm; <add> const CLEAN_RE = /^[0-9a-fA-F]{8,16} [iItT] /; <ide> let entries = out.match(FUNC_RE); <ide> if (entries === null) <ide> return out; <ide> <ide> entries = entries.map((entry) => { <del> return entry.replace(/^[0-9a-fA-F]{8,16} [iItT] /, '') <add> return entry.replace(CLEAN_RE, '') <ide> }); <ide> <ide> let filtered; <ide> function macCppfiltNm(out) { <ide> } <ide> <ide> let i = 0; <del> filtered = filtered.split(/\n/g); <add> filtered = filtered.split('\n'); <ide> return out.replace(FUNC_RE, (all, prefix, postfix) => { <ide> return prefix + (filtered[i++] || postfix); <ide> });
1
Javascript
Javascript
fix support for haste packages
a26e0427846796809afb8a5742f864d733cad440
<ide><path>packager/src/ModuleGraph/node-haste/node-haste.js <ide> function getFakeModuleMap(hasteMap: HasteMap) { <ide> return module && module.type === 'Module' ? module.path : null; <ide> }, <ide> getPackage(name: string, platform: ?string): ?string { <del> const module = hasteMap.getModule(name, platform); <del> return module && module.type === 'Package' ? module.path : null; <add> const pkg = hasteMap.getPackage(name); <add> return pkg && pkg.path; <ide> }, <ide> }; <ide> } <ide><path>packager/src/node-haste/DependencyGraph/HasteMap.js <ide> class HasteMap extends EventEmitter { <ide> <ide> build() { <ide> this._map = Object.create(null); <add> this._packages = Object.create(null); <ide> const promises = []; <ide> this._files.forEach(filePath => { <ide> if (!this._helpers.isNodeModulesDir(filePath)) { <ide> class HasteMap extends EventEmitter { <ide> return module; <ide> } <ide> <add> getPackage(name): Package { <add> return this._packages[name]; <add> } <add> <ide> _processHasteModule(file, previousName) { <ide> const module = this._moduleCache.getModule(file); <ide> return module.isHaste().then( <ide> class HasteMap extends EventEmitter { <ide> } <ide> <ide> _updateHasteMap(name, mod) { <del> if (this._map[name] == null) { <del> this._map[name] = Object.create(null); <add> let existingModule; <add> <add> if (mod.type === 'Package') { <add> existingModule = this._packages[name]; <add> this._packages[name] = mod; <add> } else { <add> if (this._map[name] == null) { <add> this._map[name] = Object.create(null); <add> } <add> const moduleMap = this._map[name]; <add> const modulePlatform = getPlatformExtension(mod.path, this._platforms) || GENERIC_PLATFORM; <add> existingModule = moduleMap[modulePlatform]; <add> moduleMap[modulePlatform] = mod; <ide> } <ide> <del> const moduleMap = this._map[name]; <del> const modulePlatform = getPlatformExtension(mod.path, this._platforms) || GENERIC_PLATFORM; <del> const existingModule = moduleMap[modulePlatform]; <del> <ide> if (existingModule && existingModule.path !== mod.path) { <ide> throw new Error( <ide> `@providesModule naming collision:\n` + <ide> class HasteMap extends EventEmitter { <ide> 'with the same name across two different files.' <ide> ); <ide> } <del> <del> moduleMap[modulePlatform] = mod; <ide> } <ide> } <ide>
2
Ruby
Ruby
use public_send for form tags
1ff67d82861c11cba7896e39536565ce93d0fc08
<ide><path>actionview/test/template/form_helper_test.rb <ide> class FooTag < ActionView::Helpers::Tags::Base <ide> def initialize; end <ide> end <ide> <add> class FooObject <add> <add> def method_missing(*args) <add> nil <add> end <add> <add> private <add> def private_property <add> raise "This method should not be called." <add> end <add> end <add> <ide> def test_tags_base_child_without_render_method <ide> assert_raise(NotImplementedError) { FooTag.new.render } <ide> end <ide> def test_form_for_with_symbol_object_name <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_form_tags_do_not_call_private_properties_on_form_object <add> obj = FooObject.new <add> form_for(obj, as: "other_name", url: '/', html: { id: "edit-other-name" }) do |f| <add> concat f.hidden_field(:private_property) <add> concat f.submit('Create Foo') <add> end <add> <add> expected = whole_form("/", "edit-other-name", "new_other_name", method: "post") do <add> "<input id='other_name_private_property' name='other_name[private_property]' type='hidden' />" + <add> "<input name='commit' value='Create Foo' type='submit' />" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_form_for_with_method_as_part_of_html_options <ide> form_for(@post, url: '/', html: { id: 'create-post', method: :delete }) do |f| <ide> concat f.text_field(:title)
1
Javascript
Javascript
fix path to require hello-world module
d2fba2bf35e3d55c55590116e7b7fd6951bb1fdb
<ide><path>test/addons/hello-world/test.js <ide> var assert = require('assert'); <del>var binding = require('./out/Release/binding'); <add>var binding = require('./build/Release/binding'); <ide> assert.equal('world', binding.hello()); <ide> console.log('binding.hello() =', binding.hello());
1
PHP
PHP
add docblocks for filesystem
0466fbefebf60c2a378ab475551c7ce9a400ccd6
<ide><path>src/Filesystem/Filesystem.php <ide> */ <ide> class Filesystem <ide> { <add> /** <add> * Direcotory type constant <add> * <add> * @var string <add> */ <ide> public const TYPE_DIR = 'dir'; <ide> <add> /** <add> * Find files (non-recursively) in given directory path. <add> * <add> * @param string $path Directory path. <add> * @param mixed $filter If string will be used as regex for filtering using <add> * `RegexIterator`, if callable will be as callback for `CallbackFilterIterator`. <add> * @param int|null $flags Flags for FilesystemIterator::__construct(); <add> * @return \Traversable <add> */ <ide> public function find(string $path, $filter = null, ?int $flags = null): Traversable <ide> { <ide> $flags = $flags ?? FilesystemIterator::KEY_AS_PATHNAME <ide> public function find(string $path, $filter = null, ?int $flags = null): Traversa <ide> return new CallbackFilterIterator($directory, $filter); <ide> } <ide> <add> /** <add> * Find files recursively in given directory path. <add> * <add> * @param string $path Directory path. <add> * @param mixed $filter If string will be used as regex for filtering using <add> * `RegexIterator`, if callable will be as callback for `CallbackFilterIterator`. <add> * Hidden directories (starting with dot e.g. .git) are always skipped. <add> * @param int|null $flags Flags for FilesystemIterator::__construct(); <add> * @return \Traversable <add> */ <ide> public function findRecursive(string $path, $filter = null, ?int $flags = null): Traversable <ide> { <ide> $flags = $flags ?? FilesystemIterator::KEY_AS_PATHNAME <ide> function (SplFileInfo $current) { <ide> return new CallbackFilterIterator($flatten, $filter); <ide> } <ide> <add> /** <add> * Dump contents to file. <add> * <add> * @param string $filename File path. <add> * @param string $content Content to dump. <add> * @return void <add> * @throws \Cake\Core\Exception When dumping fails. <add> */ <ide> public function dumpFile(string $filename, string $content): void <ide> { <ide> $dir = dirname($filename); <ide> public function dumpFile(string $filename, string $content): void <ide> $exits = file_exists($filename); <ide> <ide> if ($this->isStream($filename)) { <add> // @codingStandardsIgnoreLine <ide> $success = @file_put_contents($filename, $content); <ide> } else { <add> // @codingStandardsIgnoreLine <ide> $success = @file_put_contents($filename, $content, LOCK_EX); <ide> } <ide> <ide> public function dumpFile(string $filename, string $content): void <ide> } <ide> } <ide> <add> /** <add> * Create directory. <add> * <add> * @param string $dir Directory path. <add> * @param int $mode Octal mode passed to mkdir(). Defaults to 0755. <add> * @return void <add> * @throws \Cake\Core\Exception When directory creation fails. <add> */ <ide> public function mkdir(string $dir, int $mode = 0755): void <ide> { <ide> if (is_dir($dir)) { <ide> public function mkdir(string $dir, int $mode = 0755): void <ide> umask($old); <ide> } <ide> <add> /** <add> * Delete directory along with all it's contents. <add> * <add> * @param string $path Directory path. <add> * @return bool <add> * @throws \Cake\Core\Exception If path is not a directory. <add> */ <ide> public function deleteDir(string $path): bool <ide> { <ide> if (!file_exists($path)) { <ide> public function deleteDir(string $path): bool <ide> return $result; <ide> } <ide> <add> /** <add> * Copies directory with all it's contents. <add> * <add> * @param string $source Source path. <add> * @param string $destination Destination path. <add> * @return bool <add> */ <ide> public function copyDir(string $source, string $destination): bool <ide> { <ide> $destination = (new SplFileInfo($destination))->getPathname(); <ide> public function copyDir(string $source, string $destination): bool <ide> return $result; <ide> } <ide> <add> /** <add> * Check whether given path is a stream path. <add> * <add> * @param string $path Path. <add> * @return bool <add> */ <ide> public function isStream(string $path): bool <ide> { <ide> return strpos($path, '://') !== false;
1
Ruby
Ruby
remove use of mocha in the railties path tests
b36f159adf30657491e430b9c227de1bf2a9b042
<ide><path>railties/test/paths_test.rb <ide> require 'abstract_unit' <ide> require 'rails/paths' <del>require 'mocha/setup' # FIXME: stop using mocha <add>require 'minitest/mock' <ide> <ide> class PathsTest < ActiveSupport::TestCase <ide> def setup <del> File.stubs(:exist?).returns(true) <ide> @root = Rails::Paths::Root.new("/foo/bar") <ide> end <ide> <ide> def setup <ide> end <ide> <ide> test "it is possible to add a path that should be autoloaded only once" do <del> @root.add "app", with: "/app" <del> @root["app"].autoload_once! <del> assert @root["app"].autoload_once? <del> assert @root.autoload_once.include?(@root["app"].expanded.first) <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app" <add> @root["app"].autoload_once! <add> assert @root["app"].autoload_once? <add> assert @root.autoload_once.include?(@root["app"].expanded.first) <add> end <ide> end <ide> <ide> test "it is possible to remove a path that should be autoloaded only once" do <ide> def setup <ide> end <ide> <ide> test "it is possible to add a path without assignment and specify it should be loaded only once" do <del> @root.add "app", with: "/app", autoload_once: true <del> assert @root["app"].autoload_once? <del> assert @root.autoload_once.include?("/app") <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app", autoload_once: true <add> assert @root["app"].autoload_once? <add> assert @root.autoload_once.include?("/app") <add> end <ide> end <ide> <ide> test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do <del> @root.add "app", with: ["/app", "/app2"], autoload_once: true <del> assert @root["app"].autoload_once? <del> assert @root.autoload_once.include?("/app") <del> assert @root.autoload_once.include?("/app2") <add> File.stub(:exist?, true) do <add> @root.add "app", with: ["/app", "/app2"], autoload_once: true <add> assert @root["app"].autoload_once? <add> assert @root.autoload_once.include?("/app") <add> assert @root.autoload_once.include?("/app2") <add> end <ide> end <ide> <ide> test "making a path autoload_once more than once only includes it once in @root.load_once" do <del> @root["app"] = "/app" <del> @root["app"].autoload_once! <del> @root["app"].autoload_once! <del> assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size <add> File.stub(:exist?, true) do <add> @root["app"] = "/app" <add> @root["app"].autoload_once! <add> @root["app"].autoload_once! <add> assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size <add> end <ide> end <ide> <ide> test "paths added to a load_once path should be added to the autoload_once collection" do <del> @root["app"] = "/app" <del> @root["app"].autoload_once! <del> @root["app"] << "/app2" <del> assert_equal 2, @root.autoload_once.size <add> File.stub(:exist?, true) do <add> @root["app"] = "/app" <add> @root["app"].autoload_once! <add> @root["app"] << "/app2" <add> assert_equal 2, @root.autoload_once.size <add> end <ide> end <ide> <ide> test "it is possible to mark a path as eager loaded" do <del> @root["app"] = "/app" <del> @root["app"].eager_load! <del> assert @root["app"].eager_load? <del> assert @root.eager_load.include?(@root["app"].to_a.first) <add> File.stub(:exist?, true) do <add> @root["app"] = "/app" <add> @root["app"].eager_load! <add> assert @root["app"].eager_load? <add> assert @root.eager_load.include?(@root["app"].to_a.first) <add> end <ide> end <ide> <ide> test "it is possible to skip a path from eager loading" do <ide> def setup <ide> end <ide> <ide> test "it is possible to add a path without assignment and mark it as eager" do <del> @root.add "app", with: "/app", eager_load: true <del> assert @root["app"].eager_load? <del> assert @root.eager_load.include?("/app") <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app", eager_load: true <add> assert @root["app"].eager_load? <add> assert @root.eager_load.include?("/app") <add> end <ide> end <ide> <ide> test "it is possible to add multiple paths without assignment and mark them as eager" do <del> @root.add "app", with: ["/app", "/app2"], eager_load: true <del> assert @root["app"].eager_load? <del> assert @root.eager_load.include?("/app") <del> assert @root.eager_load.include?("/app2") <add> File.stub(:exist?, true) do <add> @root.add "app", with: ["/app", "/app2"], eager_load: true <add> assert @root["app"].eager_load? <add> assert @root.eager_load.include?("/app") <add> assert @root.eager_load.include?("/app2") <add> end <ide> end <ide> <ide> test "it is possible to create a path without assignment and mark it both as eager and load once" do <del> @root.add "app", with: "/app", eager_load: true, autoload_once: true <del> assert @root["app"].eager_load? <del> assert @root["app"].autoload_once? <del> assert @root.eager_load.include?("/app") <del> assert @root.autoload_once.include?("/app") <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app", eager_load: true, autoload_once: true <add> assert @root["app"].eager_load? <add> assert @root["app"].autoload_once? <add> assert @root.eager_load.include?("/app") <add> assert @root.autoload_once.include?("/app") <add> end <ide> end <ide> <ide> test "making a path eager more than once only includes it once in @root.eager_paths" do <del> @root["app"] = "/app" <del> @root["app"].eager_load! <del> @root["app"].eager_load! <del> assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size <add> File.stub(:exist?, true) do <add> @root["app"] = "/app" <add> @root["app"].eager_load! <add> @root["app"].eager_load! <add> assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size <add> end <ide> end <ide> <ide> test "paths added to an eager_load path should be added to the eager_load collection" do <del> @root["app"] = "/app" <del> @root["app"].eager_load! <del> @root["app"] << "/app2" <del> assert_equal 2, @root.eager_load.size <add> File.stub(:exist?, true) do <add> @root["app"] = "/app" <add> @root["app"].eager_load! <add> @root["app"] << "/app2" <add> assert_equal 2, @root.eager_load.size <add> end <ide> end <ide> <ide> test "it should be possible to add a path's default glob" do <ide> def setup <ide> end <ide> <ide> test "a path can be added to the load path" do <del> @root["app"] = "app" <del> @root["app"].load_path! <del> @root["app/models"] = "app/models" <del> assert_equal ["/foo/bar/app"], @root.load_paths <add> File.stub(:exist?, true) do <add> @root["app"] = "app" <add> @root["app"].load_path! <add> @root["app/models"] = "app/models" <add> assert_equal ["/foo/bar/app"], @root.load_paths <add> end <ide> end <ide> <ide> test "a path can be added to the load path on creation" do <del> @root.add "app", with: "/app", load_path: true <del> assert @root["app"].load_path? <del> assert_equal ["/app"], @root.load_paths <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app", load_path: true <add> assert @root["app"].load_path? <add> assert_equal ["/app"], @root.load_paths <add> end <ide> end <ide> <ide> test "a path can be marked as autoload path" do <del> @root["app"] = "app" <del> @root["app"].autoload! <del> @root["app/models"] = "app/models" <del> assert_equal ["/foo/bar/app"], @root.autoload_paths <add> File.stub(:exist?, true) do <add> @root["app"] = "app" <add> @root["app"].autoload! <add> @root["app/models"] = "app/models" <add> assert_equal ["/foo/bar/app"], @root.autoload_paths <add> end <ide> end <ide> <ide> test "a path can be marked as autoload on creation" do <del> @root.add "app", with: "/app", autoload: true <del> assert @root["app"].autoload? <del> assert_equal ["/app"], @root.autoload_paths <add> File.stub(:exist?, true) do <add> @root.add "app", with: "/app", autoload: true <add> assert @root["app"].autoload? <add> assert_equal ["/app"], @root.autoload_paths <add> end <ide> end <ide> end
1
Python
Python
fix cropping2d empty list
f31256bca86bf551d9beeb4bd899234cc2f725d4
<ide><path>keras/layers/convolutional.py <ide> def compute_output_shape(self, input_shape): <ide> def call(self, inputs): <ide> # pylint: disable=invalid-unary-operand-type <ide> if self.data_format == 'channels_first': <add> if (inputs.shape[2] is not None and inputs.shape[3] is not None and <add> (sum(self.cropping[0]) >= inputs.shape[2] or <add> sum(self.cropping[1]) >= inputs.shape[3])): <add> raise ValueError('cropping parameter of Cropping layer must be ' <add> 'greater than the input shape. Received: inputs.shape=' <add> f'{inputs.shape}, and cropping={self.cropping}') <ide> if self.cropping[0][1] == self.cropping[1][1] == 0: <ide> return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] <ide> elif self.cropping[0][1] == 0: <ide> def call(self, inputs): <ide> return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], <ide> self.cropping[1][0]:-self.cropping[1][1]] <ide> else: <add> if (inputs.shape[1] is not None and inputs.shape[2] is not None and <add> (sum(self.cropping[0]) >= inputs.shape[1] or <add> sum(self.cropping[1]) >= inputs.shape[2])): <add> raise ValueError('cropping parameter of Cropping layer must be ' <add> 'greater than the input shape. Received: inputs.shape=' <add> f'{inputs.shape}, and cropping={self.cropping}') <ide> if self.cropping[0][1] == self.cropping[1][1] == 0: <ide> return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] <ide> elif self.cropping[0][1] == 0: <ide><path>keras/layers/convolutional_test.py <ide> def test_cropping_2d(self): <ide> keras.layers.Cropping2D(cropping=(1, 1, 1)) <ide> with self.assertRaises(ValueError): <ide> keras.layers.Cropping2D(cropping=None) <add> with self.assertRaises(ValueError): <add> input_layer = keras.layers.Input( <add> shape=(num_samples, input_len_dim1, input_len_dim2, stack_size)) <add> keras.layers.Cropping2D(cropping=((5, 4),(3, 4)))(input_layer) <ide> <ide> def test_cropping_3d(self): <ide> num_samples = 2
2
Text
Text
fix typo and formatting, add colons
d57fdb6510f13343a88abe1977056935c624a7ee
<ide><path>README.md <ide> These are the available config options for making requests. Only the `url` is re <ide> }, <ide> <ide> formSerializer: { <del> visitor: (value, key, path, helpers)=> {}; // custom visitor funaction to serrialize form values <add> visitor: (value, key, path, helpers) => {}; // custom visitor funaction to serrialize form values <ide> dots: boolean; // use dots instead of brackets format <ide> metaTokens: boolean; // keep special endings like {} in parameter key <ide> indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes <ide> axios.post('https://httpbin.org/post', {x: 1}, { <ide> headers: { <ide> 'Content-Type': 'multipart/form-data' <ide> } <del>}).then(({data})=> console.log(data)); <add>}).then(({data}) => console.log(data)); <ide> ``` <ide> <ide> In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default. <ide> You can overload the FormData class by setting the `env.FormData` config variabl <ide> but you probably won't need it in most cases: <ide> <ide> ```js <del>const axios= require('axios'); <add>const axios = require('axios'); <ide> var FormData = require('form-data'); <ide> <ide> axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { <ide> headers: { <ide> 'Content-Type': 'multipart/form-data' <ide> } <del>}).then(({data})=> console.log(data)); <add>}).then(({data}) => console.log(data)); <ide> ``` <ide> <ide> Axios FormData serializer supports some special endings to perform the following operations: <ide> const obj = { <ide> The following steps will be executed by the Axios serializer internally: <ide> <ide> ```js <del>const formData= new FormData(); <add>const formData = new FormData(); <ide> formData.append('x', '1'); <ide> formData.append('arr[]', '1'); <ide> formData.append('arr[]', '2'); <ide> which are just the corresponding http methods with the `Content-Type` header pre <ide> <ide> ## Files Posting <ide> <del>You can easily sumbit a single file <add>You can easily submit a single file: <ide> <ide> ```js <ide> await axios.postForm('https://httpbin.org/post', { <ide> await axios.postForm('https://httpbin.org/post', { <ide> }); <ide> ``` <ide> <del>or multiple files as `multipart/form-data`. <add>or multiple files as `multipart/form-data`: <ide> <ide> ```js <ide> await axios.postForm('https://httpbin.org/post', {
1
Javascript
Javascript
add test for output.charset
68b601716feeffa1cebd8a9d6d9a98da2498cd96
<ide><path>test/configCases/web/charset-attribute/chunk1.js <add>export default function () {} <ide><path>test/configCases/web/charset-attribute/index.js <add>const doImport = () => import(/* webpackChunkName: "chunk1" */ "./chunk1"); <add>__webpack_public_path__ = "https://example.com/public/path/"; <add> <add>it("should not add charset attribute", () => { <add> const promise = doImport(); <add> expect(document.head._children).toHaveLength(1); <add> <add> const script = document.head._children[0]; <add> console.log(script); <add> expect(script._type).toBe("script"); <add> expect(script.src).toBe("https://example.com/public/path/chunk1.js"); <add> expect(script.getAttribute("charset")).toBeUndefined(); <add>}); <ide><path>test/configCases/web/charset-attribute/webpack.config.js <add>/** @type {import("../../../../").Configuration} */ <add>module.exports = { <add> target: "web", <add> output: { <add> chunkFilename: "[name].js", <add> charset: false <add> } <add>};
3
Go
Go
skip testdevicepermissions on lxc
e55649192ef9c947e9c90018c71bbc0a8d99a546
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunPublishPort(c *check.C) { <ide> <ide> // Issue #10184. <ide> func (s *DockerSuite) TestDevicePermissions(c *check.C) { <add> testRequires(c, NativeExecDriver) <ide> const permissions = "crw-rw-rw-" <ide> out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") <ide> if status != 0 {
1
Ruby
Ruby
simplify the code in target_scope
384984d7ca188d1dae59b204650b8319de9f9f05
<ide><path>activerecord/lib/active_record/associations/through_association.rb <ide> module ThroughAssociation #:nodoc: <ide> def target_scope <ide> scope = super <ide> chain.drop(1).each do |reflection| <del> relation = if reflection.scope <del> reflection.klass.all.instance_eval(&reflection.scope) <del> else <del> reflection.klass.all <del> end <add> relation = reflection.klass.all <add> relation.instance_eval(&reflection.scope) if reflection.scope <ide> <ide> scope.merge!( <ide> relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)
1
Javascript
Javascript
add tests for console.[info|error|warn]
fd49556c23a458455a460b6f043b079963e3576f
<ide><path>test/parallel/test-console.js <ide> assert.doesNotThrow(function() { <ide> }); <ide> <ide> // an Object with a custom .inspect() function <del>var custom_inspect = { foo: 'bar', inspect: function() { return 'inspect'; } }; <add>const custom_inspect = { foo: 'bar', inspect: () => { return 'inspect'; } }; <ide> <del>var stdout_write = global.process.stdout.write; <del>var strings = []; <add>const stdout_write = global.process.stdout.write; <add>const stderr_write = global.process.stderr.write; <add>const strings = []; <add>const errStrings = []; <ide> global.process.stdout.write = function(string) { <ide> strings.push(string); <ide> }; <del>console._stderr = process.stdout; <add>global.process.stderr.write = function(string) { <add> errStrings.push(string); <add>}; <ide> <ide> // test console.log() <ide> console.log('foo'); <ide> console.log('%s %s', 'foo', 'bar', 'hop'); <ide> console.log({slashes: '\\\\'}); <ide> console.log(custom_inspect); <ide> <add>// test console.info() <add>console.info('foo'); <add>console.info('foo', 'bar'); <add>console.info('%s %s', 'foo', 'bar', 'hop'); <add>console.info({slashes: '\\\\'}); <add>console.info(custom_inspect); <add> <add>// test console.error() <add>console.error('foo'); <add>console.error('foo', 'bar'); <add>console.error('%s %s', 'foo', 'bar', 'hop'); <add>console.error({slashes: '\\\\'}); <add>console.error(custom_inspect); <add> <add>// test console.warn() <add>console.warn('foo'); <add>console.warn('foo', 'bar'); <add>console.warn('%s %s', 'foo', 'bar', 'hop'); <add>console.warn({slashes: '\\\\'}); <add>console.warn(custom_inspect); <add> <ide> // test console.dir() <ide> console.dir(custom_inspect); <ide> console.dir(custom_inspect, { showHidden: false }); <ide> console.time('hasOwnProperty'); <ide> console.timeEnd('hasOwnProperty'); <ide> <ide> global.process.stdout.write = stdout_write; <add>global.process.stderr.write = stderr_write; <ide> <ide> // verify that console.timeEnd() doesn't leave dead links <ide> const timesMapSize = console._times.size; <ide> console.timeEnd('label2'); <ide> console.timeEnd('label3'); <ide> assert.strictEqual(console._times.size, timesMapSize); <ide> <del>assert.equal('foo\n', strings.shift()); <del>assert.equal('foo bar\n', strings.shift()); <del>assert.equal('foo bar hop\n', strings.shift()); <del>assert.equal("{ slashes: '\\\\\\\\' }\n", strings.shift()); <del>assert.equal('inspect\n', strings.shift()); <add>const expectedStrings = [ <add> 'foo', 'foo bar', 'foo bar hop', "{ slashes: '\\\\\\\\' }", 'inspect' <add>]; <add> <add>for (const expected of expectedStrings) { <add> assert.equal(expected + '\n', strings.shift()); // console.log (stdout) <add> assert.equal(expected + '\n', errStrings.shift()); // console.error (stderr) <add>} <add> <add>for (const expected of expectedStrings) { <add> assert.equal(expected + '\n', strings.shift()); // console.info (stdout) <add> assert.equal(expected + '\n', errStrings.shift()); // console.warn (stderr) <add>} <add> <ide> assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); <ide> assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); <ide> assert.notEqual(-1, strings.shift().indexOf('foo: [Object]')); <ide> assert.equal(-1, strings.shift().indexOf('baz')); <del>assert.equal('Trace: This is a {"formatted":"trace"} 10 foo', <del> strings.shift().split('\n').shift()); <ide> assert.ok(/^label: \d+\.\d{3}ms$/.test(strings.shift().trim())); <ide> assert.ok(/^__proto__: \d+\.\d{3}ms$/.test(strings.shift().trim())); <ide> assert.ok(/^constructor: \d+\.\d{3}ms$/.test(strings.shift().trim())); <ide> assert.ok(/^hasOwnProperty: \d+\.\d{3}ms$/.test(strings.shift().trim())); <add> <add>assert.equal('Trace: This is a {"formatted":"trace"} 10 foo', <add> errStrings.shift().split('\n').shift()); <add> <ide> assert.equal(strings.length, 0); <add>assert.equal(errStrings.length, 0); <ide> <ide> assert.throws(() => { <ide> console.assert(false, 'should throw');
1
Ruby
Ruby
match any values in hash match
7f2fda104a47b696b4333e424d078b28860cb5c3
<ide><path>Library/Homebrew/rubocops/extend/formula_cop.rb <ide> def find_const(node, const_name) <ide> EOS <ide> <ide> def_node_search :dependency_name_hash_match?, <<~EOS <del> (hash (pair ({str sym} %1) ({str sym array} _))) <add> (hash (pair ({str sym} %1) (...))) <ide> EOS <ide> <ide> # To compare node with appropriate Ruby variable
1
PHP
PHP
add container support to controllerfactory
74166ca0b98185791aeb7fdb3c3aa6c2b3f0cd61
<ide><path>src/Controller/ControllerFactory.php <ide> namespace Cake\Controller; <ide> <ide> use Cake\Core\App; <add>use Cake\Core\ContainerInterface; <ide> use Cake\Http\ControllerFactoryInterface; <ide> use Cake\Http\Exception\MissingControllerException; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Utility\Inflector; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> use ReflectionClass; <add>use ReflectionFunction; <ide> <ide> /** <ide> * Factory method for building controllers for request. <ide> */ <ide> class ControllerFactory implements ControllerFactoryInterface <ide> { <add> /** <add> * Constructor <add> * <add> * @param \Cake\Core\ContainerInterface $container The container to build controllers with. <add> */ <add> public function __construct(ContainerInterface $container) <add> { <add> $this->container = $container; <add> } <add> <ide> /** <ide> * Create a controller for a given request. <ide> * <ide> public function create(ServerRequestInterface $request): Controller <ide> if ($className === null) { <ide> $this->missingController($request); <ide> } <del> <ide> /** @psalm-suppress PossiblyNullArgument */ <ide> $reflection = new ReflectionClass($className); <ide> if ($reflection->isAbstract()) { <ide> $this->missingController($request); <ide> } <ide> <del> /** @var \Cake\Controller\Controller $controller */ <del> $controller = $reflection->newInstance($request); <add> // If the controller has a container definition <add> // add the request as a service. <add> if ($this->container->has($className)) { <add> $this->container->add(ServerRequest::class, $request); <add> $controller = $this->container->get($className); <add> } else { <add> /** @var \Cake\Controller\Controller $controller */ <add> $controller = $reflection->newInstance($request); <add> } <ide> <ide> return $controller; <ide> } <ide> public function invoke($controller): ResponseInterface <ide> if ($result instanceof ResponseInterface) { <ide> return $result; <ide> } <del> <ide> $action = $controller->getAction(); <del> $args = array_values($controller->getRequest()->getParam('pass')); <add> <add> $args = []; <add> $reflection = new ReflectionFunction($action); <add> $passed = array_values((array)$controller->getRequest()->getParam('pass')); <add> foreach ($reflection->getParameters() as $i => $parameter) { <add> if (isset($passed[$i])) { <add> $args[$i] = $passed[$i]; <add> continue; <add> } <add> $class = $parameter->getClass(); <add> $value = $parameter->getDefaultValue(); <add> if ($class) { <add> $value = $this->container->get($class->getName()); <add> } <add> $args[$parameter->getPosition()] = $value; <add> } <ide> $controller->invokeAction($action, $args); <ide> <ide> $result = $controller->shutdownProcess(); <ide><path>tests/TestCase/Controller/ControllerFactoryTest.php <ide> namespace Cake\Test\TestCase\Controller; <ide> <ide> use Cake\Controller\ControllerFactory; <add>use Cake\Core\Container; <ide> use Cake\Http\Exception\MissingControllerException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <add>use League\Container\Exception\NotFoundException as ContainerNotFound; <add>use stdClass; <add>use TestApp\Controller\DependenciesController; <ide> <ide> /** <ide> * Test case for ControllerFactory. <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> static::setAppNamespace(); <del> $this->factory = new ControllerFactory(); <add> $this->container = new Container(); <add> $this->factory = new ControllerFactory($this->container); <ide> } <ide> <ide> /** <ide> public function testAbsoluteReferenceFailure() <ide> $this->factory->create($request); <ide> } <ide> <add> /** <add> * Test create() injecting dependcies on defined controllers. <add> * <add> * @return void <add> */ <add> public function testCreateWithContainerDependenciesNoController() <add> { <add> $this->container->add(stdClass::class, json_decode('{"key":"value"}')); <add> <add> $request = new ServerRequest([ <add> 'url' => 'test_plugin_three/dependencies/index', <add> 'params' => [ <add> 'plugin' => null, <add> 'controller' => 'Dependencies', <add> 'action' => 'index', <add> ], <add> ]); <add> $controller = $this->factory->create($request); <add> $this->assertNull($controller->inject); <add> } <add> <add> /** <add> * Test create() injecting dependcies on defined controllers. <add> * <add> * @return void <add> */ <add> public function testCreateWithContainerDependenciesWithController() <add> { <add> $this->container->add(stdClass::class, json_decode('{"key":"value"}')); <add> $this->container->add(DependenciesController::class) <add> ->addArgument(ServerRequest::class) <add> ->addArgument(null) <add> ->addArgument(null) <add> ->addArgument(null) <add> ->addArgument(null) <add> ->addArgument(stdClass::class); <add> <add> $request = new ServerRequest([ <add> 'url' => 'test_plugin_three/dependencies/index', <add> 'params' => [ <add> 'plugin' => null, <add> 'controller' => 'Dependencies', <add> 'action' => 'index', <add> ], <add> ]); <add> $controller = $this->factory->create($request); <add> $this->assertInstanceOf(DependenciesController::class, $controller); <add> $this->assertSame($controller->inject, $this->container->get(stdClass::class)); <add> } <add> <ide> /** <ide> * Test building controller name when passing no controller name <ide> * <ide> public function testShutdownProcessResponse() <ide> <ide> $this->assertSame('shutdown stop', (string)$result->getBody()); <ide> } <add> <add> /** <add> * Ensure that a controllers startup process can emit a response <add> * <add> * @return void <add> */ <add> public function testInvokeInjectParametersDefined() <add> { <add> $this->container->add(stdClass::class, json_decode('{"key":"value"}')); <add> $request = new ServerRequest([ <add> 'url' => 'test_plugin_three/dependencies/index', <add> 'params' => [ <add> 'plugin' => null, <add> 'controller' => 'Dependencies', <add> 'action' => 'index', <add> ], <add> ]); <add> $controller = $this->factory->create($request); <add> $result = $this->factory->invoke($controller); <add> $data = json_decode((string)$result->getBody()); <add> <add> $this->assertNotNull($data); <add> $this->assertNull($data->one); <add> $this->assertNull($data->two); <add> $this->assertSame('value', $data->three->key); <add> } <add> <add> /** <add> * Ensure that a controllers startup process can emit a response <add> * <add> * @return void <add> */ <add> public function testInvokeInjectParametersNotDefined() <add> { <add> $request = new ServerRequest([ <add> 'url' => 'test_plugin_three/dependencies/index', <add> 'params' => [ <add> 'plugin' => null, <add> 'controller' => 'Dependencies', <add> 'action' => 'index', <add> ], <add> ]); <add> $controller = $this->factory->create($request); <add> <add> $this->expectException(ContainerNotFound::class); <add> $this->factory->invoke($controller); <add> } <add> <add> /** <add> * Ensure that a controllers startup process can emit a response <add> * <add> * @return void <add> */ <add> public function testInvokeInjectParametersWithPassedParameters() <add> { <add> $this->container->add(stdClass::class, json_decode('{"key":"value"}')); <add> $request = new ServerRequest([ <add> 'url' => 'test_plugin_three/dependencies/index', <add> 'params' => [ <add> 'plugin' => null, <add> 'controller' => 'Dependencies', <add> 'action' => 'index', <add> 'pass' => ['one', 'two'], <add> ], <add> ]); <add> $controller = $this->factory->create($request); <add> $result = $this->factory->invoke($controller); <add> $data = json_decode((string)$result->getBody()); <add> <add> $this->assertNotNull($data); <add> $this->assertSame($data->one, 'one'); <add> $this->assertSame($data->two, 'two'); <add> $this->assertSame('value', $data->three->key); <add> } <ide> }
2
Python
Python
move tf2_encoder_checkpoint_converter to public
da228b4224adce9534496e398a76802268230a45
<ide><path>official/nlp/bert/tf1_to_keras_checkpoint_converter.py <del># Copyright 2019 The TensorFlow Authors. All Rights Reserved. <del># <del># Licensed under the Apache License, Version 2.0 (the "License"); <del># you may not use this file except in compliance with the License. <del># You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del># limitations under the License. <del># ============================================================================== <del>r"""Convert checkpoints created by Estimator (tf1) to be Keras compatible. <del> <del>Keras manages variable names internally, which results in subtly different names <del>for variables between the Estimator and Keras version. <del>The script should be used with TF 1.x. <del> <del>Usage: <del> <del> python checkpoint_convert.py \ <del> --checkpoint_from_path="/path/to/checkpoint" \ <del> --checkpoint_to_path="/path/to/new_checkpoint" <del>""" <del>from __future__ import absolute_import <del>from __future__ import division <del>from __future__ import print_function <del> <del>from absl import app <del> <del>import tensorflow as tf # TF 1.x <del>from official.nlp.bert import tf1_checkpoint_converter_lib <del> <del> <del>flags = tf.flags <del> <del>FLAGS = flags.FLAGS <del> <del>## Required parameters <del>flags.DEFINE_string("checkpoint_from_path", None, <del> "Source BERT checkpoint path.") <del>flags.DEFINE_string("checkpoint_to_path", None, <del> "Destination BERT checkpoint path.") <del>flags.DEFINE_string( <del> "exclude_patterns", None, <del> "Comma-delimited string of a list of patterns to exclude" <del> " variables from source checkpoint.") <del>flags.DEFINE_integer( <del> "num_heads", -1, <del> "The number of attention heads, used to reshape variables. If it is -1, " <del> "we do not reshape variables." <del>) <del>flags.DEFINE_boolean( <del> "create_v2_checkpoint", False, <del> "Whether to create a checkpoint compatible with KerasBERT V2 modeling code." <del>) <del> <del> <del>def main(_): <del> exclude_patterns = None <del> if FLAGS.exclude_patterns: <del> exclude_patterns = FLAGS.exclude_patterns.split(",") <del> <del> if FLAGS.create_v2_checkpoint: <del> name_replacements = tf1_checkpoint_converter_lib.BERT_V2_NAME_REPLACEMENTS <del> permutations = tf1_checkpoint_converter_lib.BERT_V2_PERMUTATIONS <del> else: <del> name_replacements = tf1_checkpoint_converter_lib.BERT_NAME_REPLACEMENTS <del> permutations = tf1_checkpoint_converter_lib.BERT_PERMUTATIONS <del> <del> tf1_checkpoint_converter_lib.convert(FLAGS.checkpoint_from_path, <del> FLAGS.checkpoint_to_path, <del> FLAGS.num_heads, name_replacements, <del> permutations, exclude_patterns) <del> <del> <del>if __name__ == "__main__": <del> flags.mark_flag_as_required("checkpoint_from_path") <del> flags.mark_flag_as_required("checkpoint_to_path") <del> app.run(main) <ide><path>official/nlp/bert/tf2_checkpoint_converter.py <del># Copyright 2019 The TensorFlow Authors. All Rights Reserved. <del># <del># Licensed under the Apache License, Version 2.0 (the "License"); <del># you may not use this file except in compliance with the License. <del># You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del># limitations under the License. <del># ============================================================================== <del>"""A converter for BERT name-based checkpoint to object-based checkpoint. <del> <del>The conversion will yield objected-oriented checkpoint for TF2 Bert models, <del>when BergConfig.backward_compatible is true. <del>The variable/tensor shapes matches TF1 BERT model, but backward compatiblity <del>introduces unnecessary reshape compuation. <del>""" <del>from __future__ import absolute_import <del>from __future__ import division <del>from __future__ import print_function <del> <del>from absl import app <del>from absl import flags <del> <del>import tensorflow as tf # TF 1.x <del>from official.nlp import bert_modeling as modeling <del> <del>FLAGS = flags.FLAGS <del> <del>flags.DEFINE_string("bert_config_file", None, <del> "Bert configuration file to define core bert layers.") <del>flags.DEFINE_string( <del> "init_checkpoint", None, <del> "Initial checkpoint (usually from a pre-trained BERT model).") <del>flags.DEFINE_string("converted_checkpoint", None, <del> "Path to objected-based V2 checkpoint.") <del>flags.DEFINE_bool( <del> "export_bert_as_layer", False, <del> "Whether to use a layer rather than a model inside the checkpoint.") <del> <del> <del>def create_bert_model(bert_config): <del> """Creates a BERT keras core model from BERT configuration. <del> <del> Args: <del> bert_config: A BertConfig` to create the core model. <del> Returns: <del> A keras model. <del> """ <del> max_seq_length = bert_config.max_position_embeddings <del> <del> # Adds input layers just as placeholders. <del> input_word_ids = tf.keras.layers.Input( <del> shape=(max_seq_length,), dtype=tf.int32, name="input_word_ids") <del> input_mask = tf.keras.layers.Input( <del> shape=(max_seq_length,), dtype=tf.int32, name="input_mask") <del> input_type_ids = tf.keras.layers.Input( <del> shape=(max_seq_length,), dtype=tf.int32, name="input_type_ids") <del> core_model = modeling.get_bert_model( <del> input_word_ids, <del> input_mask, <del> input_type_ids, <del> config=bert_config, <del> name="bert_model", <del> float_type=tf.float32) <del> return core_model <del> <del> <del>def convert_checkpoint(): <del> """Converts a name-based matched TF V1 checkpoint to TF V2 checkpoint.""" <del> bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) <del> core_model = create_bert_model(bert_config) <del> <del> # Uses streaming-restore in eager model to read V1 name-based checkpoints. <del> core_model.load_weights(FLAGS.init_checkpoint) <del> if FLAGS.export_bert_as_layer: <del> bert_layer = core_model.get_layer("bert_model") <del> checkpoint = tf.train.Checkpoint(bert_layer=bert_layer) <del> else: <del> checkpoint = tf.train.Checkpoint(model=core_model) <del> <del> checkpoint.save(FLAGS.converted_checkpoint) <del> <del> <del>def main(_): <del> tf.enable_eager_execution() <del> convert_checkpoint() <del> <del> <del>if __name__ == "__main__": <del> app.run(main) <ide><path>official/nlp/bert/tf2_encoder_checkpoint_converter.py <add># Copyright 2019 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""A converter from a V1 BERT encoder checkpoint to a V2 encoder checkpoint. <add> <add>The conversion will yield an object-oriented checkpoint that can be used <add>to restore a TransformerEncoder object. <add>""" <add>from __future__ import absolute_import <add>from __future__ import division <add>from __future__ import print_function <add> <add>import os <add> <add>from absl import app <add>from absl import flags <add> <add>import tensorflow as tf <add>from official.modeling import activations <add>from official.nlp import bert_modeling as modeling <add>from official.nlp.bert import tf1_checkpoint_converter_lib <add>from official.nlp.modeling import networks <add> <add>FLAGS = flags.FLAGS <add> <add>flags.DEFINE_string("bert_config_file", None, <add> "Bert configuration file to define core bert layers.") <add>flags.DEFINE_string( <add> "checkpoint_to_convert", None, <add> "Initial checkpoint from a pretrained BERT model core (that is, only the " <add> "BertModel, with no task heads.)") <add>flags.DEFINE_string("converted_checkpoint_path", None, <add> "Name for the created object-based V2 checkpoint.") <add> <add> <add>def _create_bert_model(cfg): <add> """Creates a BERT keras core model from BERT configuration. <add> <add> Args: <add> cfg: A `BertConfig` to create the core model. <add> Returns: <add> A keras model. <add> """ <add> bert_encoder = networks.TransformerEncoder( <add> vocab_size=cfg.vocab_size, <add> hidden_size=cfg.hidden_size, <add> num_layers=cfg.num_hidden_layers, <add> num_attention_heads=cfg.num_attention_heads, <add> intermediate_size=cfg.intermediate_size, <add> activation=activations.gelu, <add> dropout_rate=cfg.hidden_dropout_prob, <add> attention_dropout_rate=cfg.attention_probs_dropout_prob, <add> sequence_length=cfg.max_position_embeddings, <add> type_vocab_size=cfg.type_vocab_size, <add> initializer=tf.keras.initializers.TruncatedNormal( <add> stddev=cfg.initializer_range)) <add> <add> return bert_encoder <add> <add> <add>def convert_checkpoint(bert_config, output_path, v1_checkpoint): <add> """Converts a V1 checkpoint into an OO V2 checkpoint.""" <add> output_dir, _ = os.path.split(output_path) <add> <add> # Create a temporary V1 name-converted checkpoint in the output directory. <add> temporary_checkpoint_dir = os.path.join(output_dir, "temp_v1") <add> temporary_checkpoint = os.path.join(temporary_checkpoint_dir, "ckpt") <add> tf1_checkpoint_converter_lib.convert( <add> checkpoint_from_path=v1_checkpoint, <add> checkpoint_to_path=temporary_checkpoint, <add> num_heads=bert_config.num_attention_heads, <add> name_replacements=tf1_checkpoint_converter_lib.BERT_V2_NAME_REPLACEMENTS, <add> permutations=tf1_checkpoint_converter_lib.BERT_V2_PERMUTATIONS, <add> exclude_patterns=["adam", "Adam"]) <add> <add> # Create a V2 checkpoint from the temporary checkpoint. <add> model = _create_bert_model(bert_config) <add> tf1_checkpoint_converter_lib.create_v2_checkpoint(model, temporary_checkpoint, <add> output_path) <add> <add> # Clean up the temporary checkpoint, if it exists. <add> try: <add> tf.io.gfile.rmtree(temporary_checkpoint_dir) <add> except tf.errors.OpError: <add> # If it doesn't exist, we don't need to clean it up; continue. <add> pass <add> <add> <add>def main(_): <add> assert tf.version.VERSION.startswith('2.') <add> output_path = FLAGS.converted_checkpoint_path <add> v1_checkpoint = FLAGS.checkpoint_to_convert <add> bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) <add> convert_checkpoint(bert_config, output_path, v1_checkpoint) <add> <add> <add>if __name__ == "__main__": <add> app.run(main)
3
PHP
PHP
replace deprecated functions
8f2d3ef57d4d13de850181e5a253b14923893909
<ide><path>src/Illuminate/Http/Client/Factory.php <ide> namespace Illuminate\Http\Client; <ide> <ide> use Closure; <del>use function GuzzleHttp\Promise\promise_for; <add>use GuzzleHttp\Promise\Create; <ide> use GuzzleHttp\Psr7\Response as Psr7Response; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Support\Traits\Macroable; <ide> * @method \Illuminate\Http\Client\PendingRequest withoutVerifying() <ide> * @method \Illuminate\Http\Client\PendingRequest dump() <ide> * @method \Illuminate\Http\Client\PendingRequest dd() <add> * @method \Illuminate\Http\Client\PendingRequest async() <add> * @method \Illuminate\Http\Client\Pool pool() <ide> * @method \Illuminate\Http\Client\Response delete(string $url, array $data = []) <ide> * @method \Illuminate\Http\Client\Response get(string $url, array $query = []) <ide> * @method \Illuminate\Http\Client\Response head(string $url, array $query = []) <ide> public static function response($body = null, $status = 200, $headers = []) <ide> $headers['Content-Type'] = 'application/json'; <ide> } <ide> <del> return promise_for(new Psr7Response($status, $headers, $body)); <add> return Create::promiseFor(new Psr7Response($status, $headers, $body)); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Http/Client/RequestException.php <ide> <ide> namespace Illuminate\Http\Client; <ide> <add>use GuzzleHttp\Psr7\Message; <add> <ide> class RequestException extends HttpClientException <ide> { <ide> /** <ide> protected function prepareMessage(Response $response) <ide> { <ide> $message = "HTTP request returned status code {$response->status()}"; <ide> <del> $summary = \GuzzleHttp\Psr7\get_message_body_summary($response->toPsrResponse()); <add> $summary = Message::bodySummary($response->toPsrResponse()); <ide> <ide> return is_null($summary) ? $message : $message .= ":\n{$summary}\n"; <ide> }
2
PHP
PHP
add missing header
e42bfc62a9de2d8a3c48f3ccccafe3fe16d2b132
<ide><path>tests/TestCase/TestSuite/Fixture/TransactionStrategyTest.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.3.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Test\TestCase\TestSuite; <ide> <ide> use Cake\ORM\TableRegistry;
1
PHP
PHP
remove welcome message and remove dead paths
530719bd95c240e02af1c4a02c9177a07cf74338
<ide><path>src/Shell/Task/ExtractTask.php <ide> class ExtractTask extends Shell <ide> */ <ide> protected $_extractCore = false; <ide> <add> /** <add> * No welcome message. <add> * <add> * @return void <add> */ <add> protected function _welcome() <add> { <add> } <add> <ide> /** <ide> * Method to interact with the User and get path selections. <ide> * <ide> public function main() <ide> <ide> if ($this->_extractCore) { <ide> $this->_paths[] = CAKE; <del> $this->_exclude = array_merge($this->_exclude, [ <del> CAKE . 'Test', <del> CAKE . 'Console' . DS . 'Templates' <del> ]); <ide> } <ide> <ide> if (isset($this->params['output'])) {
1
Java
Java
remove unnecessary workaround
1e8017107a2fd600de6b8743485d1da2f577dd33
<ide><path>spring-context/src/test/java/org/springframework/context/generator/ApplicationContextAotGeneratorRuntimeHintsTests.java <ide> <ide> import org.junit.jupiter.api.Test; <ide> <del>import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <del>import org.springframework.aot.hint.RuntimeHintsRegistrar; <del>import org.springframework.aot.hint.TypeReference; <ide> import org.springframework.aot.test.agent.EnabledIfRuntimeHintsAgent; <ide> import org.springframework.aot.test.agent.RuntimeHintsInvocations; <ide> import org.springframework.aot.test.agent.RuntimeHintsRecorder; <ide> void generateApplicationContextWithMultipleInitDestroyMethods() { <ide> beanDefinition.setInitMethodName("customInit"); <ide> beanDefinition.setDestroyMethodName("customDestroy"); <ide> context.registerBeanDefinition("initDestroyComponent", beanDefinition); <del> compile(context, (hints, invocations) -> assertThat(invocations) <del> .withRegistrar(new InitDestroyIssueRegistrar()).match(hints)); <del> } <del> <del> // TODO: Remove once https://github.com/spring-projects/spring-framework/issues/29077 is fixed <del> static class InitDestroyIssueRegistrar implements RuntimeHintsRegistrar { <del> @Override <del> public void registerHints(RuntimeHints hints, ClassLoader classLoader) { <del> hints.reflection() <del> .registerType(TypeReference.of(InitDestroyComponent.class.getName()), typeHint -> <del> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS)); <del> } <add> compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); <ide> } <ide> <ide> @SuppressWarnings({ "rawtypes", "unchecked" })
1
PHP
PHP
remove unused local var
1ff3f0b92776cfb8329ca6415f595d76c56291a0
<ide><path>src/View/Helper/FormHelper.php <ide> public function secure(array $fields = [], array $secureAttributes = []) <ide> if (empty($this->request['_Token'])) { <ide> return null; <ide> } <del> $locked = []; <ide> <ide> $tokenData = $this->_buildFieldToken( <ide> $this->_lastAction,
1
Go
Go
call stickruntimedircontents only in rootless mode
56bea903efd2816722f2a71928872caacd54c586
<ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> }() <ide> } <ide> <del> // Set sticky bit if XDG_RUNTIME_DIR is set && the file is actually under XDG_RUNTIME_DIR <del> if _, err := homedir.StickRuntimeDirContents(potentiallyUnderRuntimeDir); err != nil { <del> // StickRuntimeDirContents returns nil error if XDG_RUNTIME_DIR is just unset <del> logrus.WithError(err).Warn("cannot set sticky bit on files under XDG_RUNTIME_DIR") <add> if cli.Config.IsRootless() { <add> // Set sticky bit if XDG_RUNTIME_DIR is set && the file is actually under XDG_RUNTIME_DIR <add> if _, err := homedir.StickRuntimeDirContents(potentiallyUnderRuntimeDir); err != nil { <add> // StickRuntimeDirContents returns nil error if XDG_RUNTIME_DIR is just unset <add> logrus.WithError(err).Warn("cannot set sticky bit on files under XDG_RUNTIME_DIR") <add> } <ide> } <ide> <ide> serverConfig, err := newAPIServerConfig(cli)
1
Text
Text
add changelog entry for `direct` method
960e73a96df55aecfaf196e35df80f8f0121f51d
<ide><path>actionpack/CHANGELOG.md <add>* Add the `direct` method to the routing DSL <add> <add> This new method allows customization of the routing behavior in two ways: <add> <add> 1. Custom url helpers: <add> <add> ``` ruby <add> direct(:apple) { "http://www.apple.com" } <add> <add> >> apple_url <add> => "http://www.apple.com" <add> ``` <add> <add> This has the advantage of being available everywhere url helpers are available <add> unlike custom url helpers defined in helper modules, etc. <add> <add> 2. Custom polymorphic mappings: <add> <add> ``` ruby <add> resource :basket <add> direct(class: "Basket") { [:basket] } <add> ``` <add> <add> ``` erb <add> <%= form_for @basket do |form| %> <add> <!-- basket form --> <add> <% end %> <add> ``` <add> <add> This generates the correct singular URL for the form instead of the default <add> resources member url, e.g. `/basket` vs. `/basket/:id`. <add> <add> Currently both forms of `direct` do not take anything from the current routing <add> scope so it's recommended to declare them outside of any `namespace` or `scope` block. <add> <add> Fixes #1769. <add> <add> *Andrew White* <add> <ide> * Add `ActionDispatch::SystemTestCase` to Action Pack <ide> <ide> Adds Capybara integration directly into Rails through Action Pack!
1
Python
Python
prepare new pypi release
2ddd2bd557bd20e2f6856621bf22e8da8cb6acc8
<ide><path>keras/__init__.py <ide> from . import optimizers <ide> from . import regularizers <ide> <del>__version__ = '1.1.1' <add>__version__ = '1.1.2' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='1.1.1', <add> version='1.1.2', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='[email protected]', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/1.1.1', <add> download_url='https://github.com/fchollet/keras/tarball/1.1.2', <ide> license='MIT', <ide> install_requires=['theano', 'pyyaml', 'six'], <ide> extras_require={
2
Javascript
Javascript
use local scope param in watcher
2931a6df034ad0b93b24718e86814e4592ade43e
<ide><path>src/ng/directive/ngModel.js <ide> function setupModelWatcher(ctrl) { <ide> // -> scope value did not change since the last digest as <ide> // ng-change executes in apply phase <ide> // 4. view should be changed back to 'a' <del> ctrl.$$scope.$watch(function ngModelWatch() { <del> var modelValue = ctrl.$$ngModelGet(ctrl.$$scope); <add> ctrl.$$scope.$watch(function ngModelWatch(scope) { <add> var modelValue = ctrl.$$ngModelGet(scope); <ide> <ide> // if scope model value and ngModel value are out of sync <ide> // TODO(perf): why not move this to the action fn?
1
Javascript
Javascript
handle unhandled rejections on quicsession
16b32eae3e76348c954e46965739fbfb91d097bd
<ide><path>lib/internal/quic/core.js <ide> class QuicSession extends EventEmitter { <ide> socket[kAddSession](this); <ide> } <ide> <add> [kRejections](err, eventname, ...args) { <add> this.destroy(err); <add> } <add> <ide> // Used to get the configured options for peer initiated QuicStream <ide> // instances. <ide> get [kStreamOptions]() { <ide> class QuicSession extends EventEmitter { <ide> const state = this[kInternalState]; <ide> state.qlogStream = stream; <ide> process.nextTick(() => { <del> this.emit('qlog', state.qlogStream); <add> try { <add> this.emit('qlog', state.qlogStream); <add> } catch (error) { <add> this.destroy(error); <add> } <ide> }); <ide> } <ide>
1
Text
Text
give the commmand to install 1.0.0-rc
3ee3ae94de8555f853eace777fab3c8832ae7e9c
<ide><path>README.md <ide> Whether you used them or not, Redux takes a few minutes to get started with. <ide> <ide> ### Installation <ide> <add>To install the stable version: <ide> ``` <ide> npm install --save redux <ide> ``` <ide> <add>To install the release candidate (1.0.0-rc at the time of this writing): <add>``` <add>npm install --save [email protected] <add>``` <add> <ide> Most likely, you’ll also need [the React bindings](http://github.com/gaearon/react-redux) and [the developer tools](http://github.com/gaearon/redux-devtools). <ide> <ide> ```
1
Python
Python
pass bind parameters to execute
625bf75332d12205197349d469690520efd874bd
<ide><path>airflow/hooks/dbapi_hook.py <ide> def get_pandas_df(self, sql, parameters=None): <ide> ''' <ide> import pandas.io.sql as psql <ide> conn = self.get_conn() <del> df = psql.read_sql(sql, con=conn) <add> df = psql.read_sql(sql, con=conn, params=parameters) <ide> conn.close() <ide> return df <ide> <ide> def get_records(self, sql, parameters=None): <ide> ''' <ide> conn = self.get_conn() <ide> cur = self.get_cursor() <del> cur.execute(sql) <add> cur.execute(sql, parameters) <ide> rows = cur.fetchall() <ide> cur.close() <ide> conn.close() <ide> def get_first(self, sql, parameters=None): <ide> ''' <ide> conn = self.get_conn() <ide> cur = conn.cursor() <del> cur.execute(sql) <add> cur.execute(sql, parameters) <ide> rows = cur.fetchone() <ide> cur.close() <ide> conn.close() <ide> def run(self, sql, autocommit=False, parameters=None): <ide> <ide> cur = conn.cursor() <ide> for s in sql: <del> cur.execute(s) <add> cur.execute(s, parameters) <ide> conn.commit() <ide> cur.close() <ide> conn.close()
1
PHP
PHP
fix phpdoc return type
cfbc233215fb0800f4c0104bb7f748605e95d8f1
<ide><path>src/Illuminate/Mail/Mailer.php <ide> protected function createMessage() <ide> * <ide> * @param string $view <ide> * @param array $data <del> * @return \Illuminate\View\View <add> * @return string <ide> */ <ide> protected function getView($view, $data) <ide> {
1
PHP
PHP
apply fixes from styleci
cefd1c8a00d69aefb944c9c53f052039e6aa3d05
<ide><path>src/Illuminate/Support/Str.php <ide> public static function substrReplace($string, $replace, $offset = 0, $length = n <ide> public static function swap(array $map, $subject) <ide> { <ide> return strtr($subject, $map); <add> <ide> return str_replace(array_keys($map), array_values($map), $subject); <ide> } <ide>
1
Ruby
Ruby
fix meson template
b181328ac24395a291582aa38220fdbe54d98194
<ide><path>Library/Homebrew/formula_creator.rb <ide> class #{Formulary.class_s(name)} < Formula <ide> <% if mode == :cmake %> <ide> depends_on "cmake" => :build <ide> <% elsif mode == :meson %> <del> depends_on "meson-internal" => :build <add> depends_on "meson" => :build <ide> depends_on "ninja" => :build <ide> depends_on "python" => :build <ide> <% elsif mode.nil? %> <ide> def install <ide> "--disable-silent-rules", <ide> "--prefix=\#{prefix}" <ide> <% elsif mode == :meson %> <del> ENV.refurbish_args <del> <ide> mkdir "build" do <ide> system "meson", "--prefix=\#{prefix}", ".." <del> system "ninja" <del> system "ninja", "install" <add> system "ninja", "-v" <add> system "ninja", "install", "-v" <ide> end <ide> <% else %> <ide> # Remove unrecognized options if warned by configure
1
Javascript
Javascript
place holders for test animations
516dce8f38107e8585e438dc335e8fb4bdc04b09
<ide><path>src/animation/AnimationClip.js <ide> THREE.AnimationClip.prototype = { <ide> }; <ide> <ide> <add>THREE.AnimationClip.CreateMorphAnimation = function( morphTargetNames, duration ) { <add> // TODO <add> // - should create three keys per morphTarget track. <add> // - one track per morphTarget name. <add>}; <add> <add>THREE.AnimationClip.CreateRotationAnimation = function( node, period ) { <add> // TODO <add> // - create a single track representing the rotation <add> // - create a few quaternion keys representing the rotation path <add>}; <add> <add>THREE.AnimationClip.CreateShakeAnimation = function( node, duration, shakeScale ) { <add> // TODO <add> // - create a single track representing the shake <add> // - multiple random vector by shake scalar/vector <add>}; <add> <add> <add>THREE.AnimationClip.CreatePulsationAnimation = function( node, duration, pulseScale ) { <add> // TODO <add> // - create a single track representing the shake <add> // - multiple random vector by pulse scalar/vector <add>}; <ide>\ No newline at end of file <ide><path>src/animation/KeyframeTrack.js <ide> THREE.KeyframeTrack = function ( name, keys ) { <ide> <ide> THREE.KeyframeTrack.prototype = { <ide> <del> constructor: THREE.Track, <add> constructor: THREE.KeyframeTrack, <ide> <ide> getAt: function( time ) { <ide> console.log( 'KeyframeTrack[' + this.name + '].getAt( ' + time + ' )' );
2
PHP
PHP
update helpers.php
db794ceea6734cc90286e04a8a2a48e5b4cd4130
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function rescue(callable $callback, $rescue = null, $report = true) <ide> report($e); <ide> } <ide> <del> return value($rescue); <add> return $rescue instanceof Closure ? $rescue($e) : $rescue; <ide> } <ide> } <ide> }
1
Python
Python
remove tolerance + drop_rows_to_fit by default
d415882b41e61c962df5c2c8086ec83fa4b71629
<ide><path>src/transformers/models/tapas/tokenization_tapas.py <ide> class TapasTokenizer(PreTrainedTokenizer): <ide> value for :obj:`lowercase` (as in the original BERT). <ide> cell_trim_length (:obj:`int`, `optional`, defaults to -1): <ide> If > 0: Trim cells so that the length is <= this value. Also disables further cell trimming, should thus be <del> used with 'drop_rows_to_fit' below. <add> used with :obj:`truncation` set to :obj:`True`. <ide> max_column_id (:obj:`int`, `optional`): <ide> Max column id to extract. <ide> max_row_id (:obj:`int`, `optional`): <ide> class TapasTokenizer(PreTrainedTokenizer): <ide> Whether to add empty strings instead of column names. <ide> update_answer_coordinates (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Whether to recompute the answer coordinates from the answer text. <del> drop_rows_to_fit (:obj:`bool`, `optional`, defaults to :obj:`False`): <del> Whether to drop the last rows if a table doesn't fit within max sequence length. <ide> <ide> """ <ide> <ide> def __init__( <ide> max_row_id: int = None, <ide> strip_column_names: bool = False, <ide> update_answer_coordinates: bool = False, <del> drop_rows_to_fit: bool = False, <ide> model_max_length: int = 512, <ide> additional_special_tokens: Optional[List[str]] = None, <ide> **kwargs <ide> def __init__( <ide> max_row_id=max_row_id, <ide> strip_column_names=strip_column_names, <ide> update_answer_coordinates=update_answer_coordinates, <del> drop_rows_to_fit=drop_rows_to_fit, <ide> model_max_length=model_max_length, <ide> additional_special_tokens=additional_special_tokens, <ide> **kwargs, <ide> def __init__( <ide> self.max_row_id = max_row_id if max_row_id is not None else self.model_max_length <ide> self.strip_column_names = strip_column_names <ide> self.update_answer_coordinates = update_answer_coordinates <del> self.drop_rows_to_fit = drop_rows_to_fit <ide> <ide> @property <ide> def do_lower_case(self): <ide> def prepare_for_model( <ide> prev_answer_coordinates = kwargs["prev_answer_coordinates"] <ide> prev_answer_text = kwargs["prev_answer_text"] <ide> <del> num_rows = self._get_num_rows(raw_table, self.drop_rows_to_fit) <add> num_rows = self._get_num_rows(raw_table, truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE) <ide> num_columns = self._get_num_columns(raw_table) <ide> _, _, num_tokens = self._get_table_boundaries(tokenized_table) <ide> <ide><path>tests/test_modeling_tapas.py <ide> def prepare_tapas_batch_inputs_for_training(): <ide> return table, queries, answer_coordinates, answer_text, float_answer <ide> <ide> <del>TOLERANCE = 1 <del> <del> <ide> @require_torch <ide> @require_scatter <ide> class TapasModelIntegrationTest(unittest.TestCase): <ide> def test_inference_no_head(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(outputs.last_hidden_state[:, :3, :3], expected_slice, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(outputs.last_hidden_state[:, :3, :3], expected_slice, atol=0.0005)) <ide> <ide> # test the pooled output <ide> expected_slice = torch.tensor([[0.987518311, -0.970520139, -0.994303405]], device=torch_device) <ide> <del> self.assertTrue(torch.allclose(outputs.pooler_output[:, :3], expected_slice, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(outputs.pooler_output[:, :3], expected_slice, atol=0.0005)) <ide> <ide> @unittest.skip(reason="Model not available yet") <ide> def test_inference_masked_lm(self): <ide> def test_inference_question_answering_head_conversational(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.015)) <ide> <ide> @slow <ide> def test_inference_question_answering_head_conversational_absolute_embeddings(self): <ide> def test_inference_question_answering_head_conversational_absolute_embeddings(se <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.01)) <ide> <ide> @slow <ide> def test_inference_question_answering_head_weak_supervision(self): <ide> def test_inference_question_answering_head_weak_supervision(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits[:, -6:], expected_slice, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits[:, -6:], expected_slice, atol=0.4)) <ide> <ide> # test the aggregation logits <ide> logits_aggregation = outputs.logits_aggregation <ide> def test_inference_question_answering_head_weak_supervision(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=0.001)) <ide> <ide> # test the predicted answer coordinates and aggregation indices <ide> EXPECTED_PREDICTED_ANSWER_COORDINATES = [[(0, 0)], [(1, 2)]] <ide> def test_training_question_answering_head_weak_supervision(self): <ide> # test the loss <ide> loss = outputs.loss <ide> expected_loss = torch.tensor(3.3527612686157227e-08, device=torch_device) <del> self.assertTrue(torch.allclose(loss, expected_loss, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(loss, expected_loss, atol=1e-6)) <ide> <ide> # test the logits on the first example <ide> logits = outputs.logits <ide> def test_training_question_answering_head_weak_supervision(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits[0, -9:], expected_slice, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits[0, -9:], expected_slice, atol=1e-6)) <ide> <ide> # test the aggregation logits on the second example <ide> logits_aggregation = outputs.logits_aggregation <ide> expected_shape = torch.Size((2, 4)) <ide> self.assertEqual(logits_aggregation.shape, expected_shape) <ide> expected_slice = torch.tensor([-4.0538, 40.0304, -5.3554, 23.3965], device=torch_device) <ide> <del> self.assertTrue(torch.allclose(logits_aggregation[1, -4:], expected_slice, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits_aggregation[1, -4:], expected_slice, atol=1e-4)) <ide> <ide> @slow <ide> def test_inference_question_answering_head_strong_supervision(self): <ide> def test_inference_question_answering_head_strong_supervision(self): <ide> device=torch_device, <ide> ) <ide> <del> self.assertTrue(torch.allclose(logits, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.02)) <ide> <ide> # test the aggregation logits <ide> logits_aggregation = outputs.logits_aggregation <ide> def test_inference_question_answering_head_strong_supervision(self): <ide> [[16.5659733, -3.06624889, -2.34152961, -0.970244825]], device=torch_device <ide> ) # PyTorch model outputs [[16.5679, -3.0668, -2.3442, -0.9674]] <ide> <del> self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=0.003)) <ide> <ide> @slow <ide> def test_inference_classification_head(self): <ide> def test_inference_classification_head(self): <ide> [[0.795137286, 9.5572]], device=torch_device <ide> ) # Note that the PyTorch model outputs [[0.8057, 9.5281]] <ide> <del> self.assertTrue(torch.allclose(outputs.logits, expected_tensor, atol=TOLERANCE)) <add> self.assertTrue(torch.allclose(outputs.logits, expected_tensor, atol=0.05)) <ide> <ide> <ide> # Below: tests for Tapas utilities which are defined in modeling_tapas.py. <ide><path>tests/test_tokenization_tapas.py <ide> def test_clean_text(self): <ide> <ide> @slow <ide> def test_sequence_builders(self): <del> tokenizer = self.tokenizer_class.from_pretrained("nielsr/tapas-base-finetuned-wtq") <add> tokenizer = self.tokenizer_class.from_pretrained("google/tapas-base-finetuned-wtq") <ide> <ide> empty_table = self.get_table(tokenizer, length=0) <ide> table = self.get_table(tokenizer, length=10)
3
PHP
PHP
fix stickler errors
25cba6f1aa4e04ae67bec570089c4393a29ae1f0
<ide><path>src/I18n/TranslatorFactory.php <ide> class TranslatorFactory extends BaseTranslatorFactory <ide> * Returns a new Translator. <ide> * @param string $locale The locale code for the translator. <ide> * @param array $messages The localized messages for the translator. <del> * @param FormatterInterface $formatter The formatter to use for <add> * @param FormatterInterface $formatter The formatter to use for <ide> * interpolating token values. <ide> * @param TranslatorInterface $fallback A fallback translator to use, if <ide> * any. <ide> public function newInstance( <ide> get_class($fallback) <ide> )); <ide> } <add> <ide> return new $class($locale, $messages, $formatter, $fallback); <ide> } <ide> }
1
PHP
PHP
add typehint for urloptions argument
1ce7a97f382f159d4b3a182cc94837625a92ecba
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function sort($key, $title = null, array $options = []) <ide> * @return string By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript) <ide> * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls <ide> */ <del> public function generateUrl(array $options = [], $model = null, $urlOptions = []) <add> public function generateUrl(array $options = [], $model = null, array $urlOptions = []) <ide> { <ide> $urlOptions += [ <ide> 'escape' => true,
1
Ruby
Ruby
fix route creation when format is a blank string
ec14aad419381b502f510a9b3360f0e211e41066
<ide><path>actionpack/lib/action_dispatch/journey/formatter.rb <ide> def generate(name, options, path_parameters, parameterize = nil) <ide> defaults = route.defaults <ide> required_parts = route.required_parts <ide> parameterized_parts.keep_if do |key, value| <del> defaults[key].nil? || value.to_s != defaults[key].to_s || required_parts.include?(key) <add> (defaults[key].nil? && value.present?) || value.to_s != defaults[key].to_s || required_parts.include?(key) <ide> end <ide> <ide> return [route.format(parameterized_parts), params] <ide><path>actionpack/test/controller/url_for_integration_test.rb <ide> def setup <ide> <ide> ['/posts/ping',[ { :controller => 'posts', :action => 'ping' }]], <ide> ['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1' }]], <add> ['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1', :format => '' }]], <ide> ['/posts',[ { :controller => 'posts' }]], <ide> ['/posts',[ { :controller => 'posts', :action => 'index' }]], <ide> ['/posts/create',[ { :action => 'create' }, {:day=>nil, :month=>nil, :controller=>"posts", :action=>"show_date"}, '/blog']],
2
Javascript
Javascript
refactor the repeat logic in readblock function
d54e425a96e2e5d3f68eababc3140eeedbcda900
<ide><path>pdf.js <ide> var FlateStream = (function() { <ide> }; <ide> <ide> constructor.prototype.readBlock = function() { <del> function repeat(stream, array, len, offset, what) { <del> var repeatLength = stream.getBits(len) + offset; <del> while (repeatLength-- > 0) <del> array[i++] = what; <del> } <del> <ide> // read block header <ide> var hdr = this.getBits(3); <ide> if (hdr & 1) <ide> var FlateStream = (function() { <ide> while (i < codes) { <ide> var code = this.getCode(codeLenCodeTab); <ide> if (code == 16) { <del> repeat(this, codeLengths, 2, 3, len); <add> var bitsLength = 2, bitsOffset = 3, what = len; <ide> } else if (code == 17) { <del> repeat(this, codeLengths, 3, 3, len = 0); <add> var bitsLength = 3, bitsOffset = 3, what = (len = 0); <ide> } else if (code == 18) { <del> repeat(this, codeLengths, 7, 11, len = 0); <add> var bitsLength = 7, bitsOffset = 11, what = (len = 0); <ide> } else { <ide> codeLengths[i++] = len = code; <add> continue; <ide> } <add> <add> var repeatLength = this.getBits(bitsLength) + bitsOffset; <add> while (repeatLength-- > 0) <add> codeLengths[i++] = what; <ide> } <ide> <ide> litCodeTable =
1
Text
Text
add note to upgrade.md about new controller alias
e8f6597e2d01bdd824670dcd405f64421bbb8ec3
<ide><path>upgrade.md <ide> - `composer update`. <ide> - Replace `public/index.php`, `artisan.php`. <ide> - Add new `expire_on_close` option to `session` configuration file. <del>- Remove call to `redirectIfTrailingSlash` in `bootstrap/start.php` file. <ide>\ No newline at end of file <add>- Remove call to `redirectIfTrailingSlash` in `bootstrap/start.php` file. <add>- Edit `app/config/app.php`; in `aliases` change `'Controller' => 'Illuminate\Routing\Controllers\Controller',` <add> to use `Illuminate\Routing\Controller`
1
PHP
PHP
fix failing test
2d9b6ccd8bce405dd57127d9df3c8931d653da9f
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testInputDatetime() { <ide> 'interval' => 15, <ide> 'options' => null, <ide> 'empty' => false, <del> 'id' => 'prueba' <add> 'id' => 'prueba', <add> 'required' => false, <ide> ]) <ide> ->will($this->returnValue('This is it!')); <ide> $result = $this->Form->input('prueba', array(
1
Javascript
Javascript
add spec for exceptionsmanager
8ea749ad3e2cb8b73079fd7a3e409d723326c0aa
<ide><path>Libraries/Core/Devtools/parseErrorStack.js <ide> <ide> 'use strict'; <ide> <del>export type StackFrame = { <del> column: ?number, <del> file: string, <del> lineNumber: number, <del> methodName: string, <del>}; <add>import type {StackFrame} from '../NativeExceptionsManager'; <ide> <ide> export type ExtendedError = Error & { <ide> framesToPop?: number, <ide><path>Libraries/Core/Devtools/symbolicateStackTrace.js <ide> import NativeSourceCode from '../../NativeModules/specs/NativeSourceCode'; <ide> // Avoid requiring fetch on load of this module; see symbolicateStackTrace <ide> let fetch; <ide> <del>import type {StackFrame} from './parseErrorStack'; <add>import type {StackFrame} from '../NativeExceptionsManager'; <ide> <ide> function isSourcedFromDisk(sourcePath: string): boolean { <ide> return !/^http/.test(sourcePath) && /[\\/]/.test(sourcePath); <ide><path>Libraries/Core/ExceptionsManager.js <ide> * LICENSE file in the root directory of this source tree. <ide> * <ide> * @format <del> * @flow <add> * @flow strict-local <ide> */ <ide> <ide> 'use strict'; <ide> const INTERNAL_CALLSITES_REGEX = new RegExp( <ide> */ <ide> let exceptionID = 0; <ide> function reportException(e: ExtendedError, isFatal: boolean) { <del> const {ExceptionsManager} = require('../BatchedBridge/NativeModules'); <del> if (ExceptionsManager) { <add> const NativeExceptionsManager = require('./NativeExceptionsManager').default; <add> if (NativeExceptionsManager) { <ide> const parseErrorStack = require('./Devtools/parseErrorStack'); <ide> const stack = parseErrorStack(e); <ide> const currentExceptionID = ++exceptionID; <ide> const message = <ide> e.jsEngine == null ? e.message : `${e.message}, js engine: ${e.jsEngine}`; <ide> if (isFatal) { <del> ExceptionsManager.reportFatalException( <add> NativeExceptionsManager.reportFatalException( <ide> message, <ide> stack, <ide> currentExceptionID, <ide> ); <ide> } else { <del> ExceptionsManager.reportSoftException(message, stack, currentExceptionID); <add> NativeExceptionsManager.reportSoftException( <add> message, <add> stack, <add> currentExceptionID, <add> ); <ide> } <ide> if (__DEV__) { <ide> const symbolicateStackTrace = require('./Devtools/symbolicateStackTrace'); <ide> function reportException(e: ExtendedError, isFatal: boolean) { <ide> frame.file && <ide> frame.file.match(INTERNAL_CALLSITES_REGEX) === null, <ide> ); <del> ExceptionsManager.updateExceptionMessage( <add> NativeExceptionsManager.updateExceptionMessage( <ide> message, <ide> stackWithoutInternalCallsites, <ide> currentExceptionID, <ide> function reportException(e: ExtendedError, isFatal: boolean) { <ide> } <ide> <ide> declare var console: typeof console & { <del> _errorOriginal: Function, <add> _errorOriginal: typeof console.error, <ide> reportErrorsAsExceptions: boolean, <ide> }; <ide> <ide> function handleException(e: Error, isFatal: boolean) { <ide> // case, so if you ended up here trying to trace an error, look for <ide> // `throw '<error message>'` somewhere in your codebase. <ide> if (!e.message) { <add> // $FlowFixMe - cannot reassign constant, explanation above <ide> e = new Error(e); <ide> } <ide> if (console._errorOriginal) { <ide><path>Libraries/Core/NativeExceptionsManager.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow strict-local <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export type StackFrame = {| <add> column: ?number, <add> file: string, <add> lineNumber: number, <add> methodName: string, <add>|}; <add> <add>export interface Spec extends TurboModule { <add> +reportFatalException: ( <add> message: string, <add> stack: Array<StackFrame>, <add> exceptionId: number, <add> ) => void; <add> +reportSoftException: ( <add> message: string, <add> stack: Array<StackFrame>, <add> exceptionId: number, <add> ) => void; <add> +updateExceptionMessage: ( <add> message: string, <add> stack: Array<StackFrame>, <add> exceptionId: number, <add> ) => void; <add> // Android only <add> +dismissRedbox: () => void; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('ExceptionsManager'); <ide><path>Libraries/Utilities/HMRClient.js <ide> Error: ${e.message}`; <ide> ) { <ide> NativeRedBox.dismiss(); <ide> } else { <del> const RCTExceptionsManager = require('../BatchedBridge/NativeModules') <del> .ExceptionsManager; <del> RCTExceptionsManager && <del> RCTExceptionsManager.dismissRedbox && <del> RCTExceptionsManager.dismissRedbox(); <add> const NativeExceptionsManager = require('../Core/NativeExceptionsManager') <add> .default; <add> NativeExceptionsManager && <add> NativeExceptionsManager.dismissRedbox && <add> NativeExceptionsManager.dismissRedbox(); <ide> } <ide> }); <ide> <ide><path>Libraries/YellowBox/Data/YellowBoxSymbolication.js <ide> <ide> const symbolicateStackTrace = require('../../Core/Devtools/symbolicateStackTrace'); <ide> <del>import type {StackFrame} from '../../Core/Devtools/parseErrorStack'; <add>import type {StackFrame} from '../../Core/NativeExceptionsManager'; <ide> <ide> type CacheKey = string; <ide> <ide><path>Libraries/YellowBox/Data/__tests__/YellowBoxSymbolication-test.js <ide> <ide> 'use strict'; <ide> <del>import type {StackFrame} from '../../../Core/Devtools/parseErrorStack'; <add>import type {StackFrame} from '../../../Core/NativeExceptionsManager'; <ide> <ide> jest.mock('../../../Core/Devtools/symbolicateStackTrace'); <ide> <ide><path>Libraries/YellowBox/Data/__tests__/YellowBoxWarning-test.js <ide> <ide> 'use strict'; <ide> <del>import type {StackFrame} from '../../../Core/Devtools/parseErrorStack'; <add>import type {StackFrame} from '../../../Core/NativeExceptionsManager'; <ide> <ide> jest.mock('../YellowBoxSymbolication'); <ide> <ide><path>Libraries/YellowBox/UI/YellowBoxInspectorStackFrame.js <ide> const YellowBoxPressable = require('./YellowBoxPressable'); <ide> const YellowBoxStyle = require('./YellowBoxStyle'); <ide> <ide> import type {PressEvent} from '../../Types/CoreEventTypes'; <del>import type {StackFrame} from '../../Core/Devtools/parseErrorStack'; <add>import type {StackFrame} from '../../Core/NativeExceptionsManager'; <ide> <ide> type Props = $ReadOnly<{| <ide> frame: StackFrame,
9
Mixed
Javascript
add reset method to chart prototype
16f23b2c44ebeccda1e144b3dd75e9c63f81307b
<ide><path>docs/09-Advanced.md <ide> myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's v <ide> myLineChart.update(); // Calling update now animates the position of March from 90 to 50. <ide> ``` <ide> <add>#### .reset() <add> <add>Reset the chart to it's state before the initial animation. A new animation can then be triggered using `update`. <add> <add>```javascript <add>myLineChart.reset(); <add>``` <add> <ide> #### .render(duration, lazy) <ide> <ide> Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use `.update()` in that case. <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> return newControllers; <ide> }, <ide> <add> /** <add> * Reset the elements of all datasets <add> * @method resetElements <add> * @private <add> */ <ide> resetElements: function() { <ide> var me = this; <ide> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <ide> me.getDatasetMeta(datasetIndex).controller.reset(); <ide> }, me); <ide> }, <ide> <add> /** <add> * Resets the chart back to it's state before the initial animation <add> * @method reset <add> */ <add> reset: function() { <add> this.resetElements(); <add> this.tooltip.initialize(); <add> }, <add> <ide> update: function(animationDuration, lazy) { <ide> var me = this; <ide> Chart.plugins.notify('beforeUpdate', [me]); <ide><path>test/core.controller.tests.js <ide> describe('Chart.Controller', function() { <ide> expect(wrapper.firstChild.tagName).toBe('CANVAS'); <ide> }); <ide> }); <add> <add> describe('controller.reset', function() { <add> it('should reset the chart elements', function() { <add> var chart = acquireChart({ <add> type: 'line', <add> data: { <add> labels: ['A', 'B', 'C', 'D'], <add> datasets: [{ <add> data: [10, 20, 30, 0] <add> }] <add> }, <add> options: { <add> responsive: true <add> } <add> }); <add> <add> var meta = chart.getDatasetMeta(0); <add> <add> // Verify that points are at their initial correct location, <add> // then we will reset and see that they moved <add> expect(meta.data[0]._model.y).toBe(333); <add> expect(meta.data[1]._model.y).toBe(183); <add> expect(meta.data[2]._model.y).toBe(32); <add> expect(meta.data[3]._model.y).toBe(484); <add> <add> chart.reset(); <add> <add> // For a line chart, the animation state is the bottom <add> expect(meta.data[0]._model.y).toBe(484); <add> expect(meta.data[1]._model.y).toBe(484); <add> expect(meta.data[2]._model.y).toBe(484); <add> expect(meta.data[3]._model.y).toBe(484); <add> }); <add> }); <ide> });
3
Text
Text
add null length to crypto.subtle.derivebits
22fbf8333355ec9b34db32e48a92a3c22e671ca8
<ide><path>doc/api/webcrypto.md <ide> changes: <ide> <ide> * `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params} <ide> * `baseKey`: {CryptoKey} <del>* `length`: {number} <add>* `length`: {number|null} <ide> * Returns: {Promise} containing {ArrayBuffer} <ide> <ide> <!--lint enable maximum-line-length remark-lint--> <ide> <ide> Using the method and parameters specified in `algorithm` and the keying <ide> material provided by `baseKey`, `subtle.deriveBits()` attempts to generate <del>`length` bits. The Node.js implementation requires that `length` is a <del>multiple of `8`. If successful, the returned promise will be resolved with <del>an {ArrayBuffer} containing the generated data. <add>`length` bits. <add> <add>The Node.js implementation requires that when `length` is a <add>number it must be multiple of `8`. <add> <add>When `length` is `null` the maximum number of bits for a given algorithm is <add>generated. This is allowed for the `'ECDH'`, `'X25519'`[^1], and `'X448'`[^1] <add>algorithms. <add> <add>If successful, the returned promise will be resolved with an {ArrayBuffer} <add>containing the generated data. <ide> <ide> The algorithms currently supported include: <ide>
1
Javascript
Javascript
modernize js and tighten equality checking
3ffa6a884c48fe8dad6114cff022267fd836da82
<ide><path>test/parallel/test-child-process-cwd.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <add>const assert = require('assert'); <ide> <del>var returns = 0; <add>let returns = 0; <ide> <ide> /* <ide> Spawns 'pwd' with given options, then test <ide> - whether the exit code equals forCode, <ide> - optionally whether the stdout result matches forData <del> (after removing traling whitespace) <add> (after removing trailing whitespace) <ide> */ <ide> function testCwd(options, forCode, forData) { <del> var data = ''; <add> let data = ''; <ide> <del> var child = common.spawnPwd(options); <add> const child = common.spawnPwd(options); <ide> <ide> child.stdout.setEncoding('utf8'); <ide> <ide> if (common.isWindows) { <ide> // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT <ide> { <ide> testCwd({cwd: 'does-not-exist'}, -1).on('error', common.mustCall(function(e) { <del> assert.equal(e.code, 'ENOENT'); <add> assert.strictEqual(e.code, 'ENOENT'); <ide> })); <ide> } <ide> <ide> testCwd({cwd: undefined}, 0); <ide> testCwd({cwd: null}, 0); <ide> <ide> // Check whether all tests actually returned <del>assert.notEqual(0, returns); <add>assert.notStrictEqual(returns, 0); <ide> process.on('exit', function() { <del> assert.equal(0, returns); <add> assert.strictEqual(returns, 0); <ide> });
1
PHP
PHP
add apply(), map() and reduce()
ae66682c35d1f9055a82e9dc99cd29c9730f74e4
<ide><path>lib/Cake/Test/Case/Utility/Set2Test.php <ide> public function testFormatNullValues() { <ide> $expected = array('Boston, 42', 'Boondock, ', 'Venice Beach, '); <ide> $this->assertEquals($expected, $result); <ide> } <add> <add>/** <add> * Test map() <add> * <add> * @return void <add> */ <add> public function testMap() { <add> $data = self::articleData(); <add> <add> $result = Set2::map($data, '{n}.Article.id', array($this, '_mapCallback')); <add> $expected = array(2, 4, 6, 8, 10); <add> $this->assertEquals($expected, $result); <add> } <add> <add> public function testApply() { <add> $data = self::articleData(); <add> <add> $result = Set2::apply($data, '{n}.Article.id', 'array_sum'); <add> $this->assertEquals(15, $result); <add> } <add> <add>/** <add> * Test reduce() <add> * <add> * @return void <add> */ <add> public function testReduce() { <add> $data = self::articleData(); <add> <add> $result = Set2::reduce($data, '{n}.Article.id', array($this, '_reduceCallback')); <add> $this->assertEquals(15, $result); <add> } <add> <add>/** <add> * testing method for map callbacks. <add> * <add> * @param mixed $value <add> * @return mixed. <add> */ <add> public function _mapCallback($value) { <add> return $value * 2; <add> } <add> <add>/** <add> * testing method for reduce callbacks. <add> * <add> * @param mixed $one <add> * @param mixed $two <add> * @return mixed. <add> */ <add> public function _reduceCallback($one, $two) { <add> return $one + $two; <add> } <ide> } <ide><path>lib/Cake/Utility/Set2.php <ide> public static function maxDimensions(array $data) { <ide> * Map a callback across all elements in a set. <ide> * Can be provided a path to only modify slices of the set. <ide> * <add> * @param array $data The data to map over, and extract data out of. <add> * @param string $path The path to extract for mapping over. <add> * @param callable $function The function to call on each extracted value. <add> * @return array An array of the modified values. <ide> */ <del> public static function map(array $data, $path, $function = null) { <add> public static function map(array $data, $path, $function) { <add> $values = (array)self::extract($data, $path); <add> return array_map($function, $values); <add> } <ide> <add>/** <add> * Reduce a set of extracted values using `$function`. <add> * <add> * @param array $data The data to reduce. <add> * @param string $path The path to extract from $data. <add> * @return mixed The reduced value. <add> */ <add> public static function reduce(array $data, $path, $function) { <add> $values = (array)self::extract($data, $path); <add> return array_reduce($values, $function); <add> } <add> <add>/** <add> * Apply a callback to a set of extracted values using `$function`. <add> * The function will get the extracted values as the first argument. <add> * <add> * @param array $data The data to reduce. <add> * @param string $path The path to extract from $data. <add> * @return mixed The results of the applied method. <add> */ <add> public static function apply(array $data, $path, $function) { <add> $values = (array)self::extract($data, $path); <add> return call_user_func($function, $values); <ide> } <ide> <ide> /**
2
Java
Java
use @payload on method declaration
e0103095301c580643d602ab6cd25d37b51d22ca
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.messaging.converter.MessageConverter; <ide> <ide> /** <del> * Annotation that binds a method parameter to the payload of a message. The payload may <del> * be passed through a {@link MessageConverter} to convert it from serialized form with a <add> * Annotation that binds a method parameter to the payload of a message. Can also <add> * be used to associate a payload to a method invocation. The payload may be passed <add> * through a {@link MessageConverter} to convert it from serialized form with a <ide> * specific MIME type to an Object matching the target method parameter. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>@Target(ElementType.PARAMETER) <add>@Target({ElementType.PARAMETER, ElementType.METHOD}) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Documented <ide> public @interface Payload {
1
Javascript
Javascript
fix some stragglers
16249f0acd36d44d15a2d676ce932b10a7be06f2
<ide><path>test/unit/attributes.js <ide> test("attr(jquery_method)", function(){ <ide> equal( elem.style.paddingRight, "1px", "attr({...})"); <ide> }); <ide> <del>if ( !isLocal ) { <del> test("attr(String, Object) - Loaded via XML document", function() { <del> expect(2); <del> stop(); <del> jQuery.get("data/dashboard.xml", function( xml ) { <del> var titles = []; <del> jQuery( "tab", xml ).each(function() { <del> titles.push( jQuery(this).attr("title") ); <del> }); <del> equal( titles[0], "Location", "attr() in XML context: Check first title" ); <del> equal( titles[1], "Users", "attr() in XML context: Check second title" ); <del> start(); <del> }); <add>test("attr(String, Object) - Loaded via XML document", function() { <add> expect(2); <add> var xml = createDashboardXML(); <add> var titles = []; <add> jQuery( "tab", xml ).each(function() { <add> titles.push( jQuery(this).attr("title") ); <ide> }); <del>} <add> equal( titles[0], "Location", "attr() in XML context: Check first title" ); <add> equal( titles[1], "Users", "attr() in XML context: Check second title" ); <add>}); <ide> <ide> test("attr('tabindex')", function() { <ide> expect(8); <ide><path>test/unit/core.js <ide> test("XSS via location.hash", function() { <ide> <ide> test("isXMLDoc - XML", function() { <ide> expect(3); <del> var xml = createXMLDocument(); <del> xml.documentElement.appendChild( xml.createElement( "tab" ) ); <add> var xml = createDashboardXML(); <ide> ok( jQuery.isXMLDoc( xml ), "XML document" ); <ide> ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" ); <ide> ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
2
Ruby
Ruby
add underscore in front of internal method
8a91423b92e6583bf1799a000616982147ca2467
<ide><path>activerecord/lib/active_record/persistence.rb <ide> def reload(options = nil) <ide> self.class.connection.clear_query_cache <ide> <ide> fresh_object = if self.class.default_scopes?(all_queries: true) && !(options && options[:unscoped]) <del> find_record(options) <add> _find_record(options) <ide> else <del> self.class.unscoped { find_record(options) } <add> self.class.unscoped { _find_record(options) } <ide> end <ide> <ide> @attributes = fresh_object.instance_variable_get(:@attributes) <ide> def touch(*names, time: nil) <ide> end <ide> <ide> private <del> def find_record(options) <add> def _find_record(options) <ide> if options && options[:lock] <ide> self.class.lock(options[:lock]).find(id) <ide> else
1
PHP
PHP
add connectoptions to doc block
3763b5f3db8e2d74c7a90e5b3f408f05d02d50b7
<ide><path>src/Routing/RouteBuilder.php <ide> public function namePrefix($value = null) <ide> * make sure that your mapped methods are also in the 'only' list. <ide> * - 'prefix' - Define a routing prefix for the resource controller. If the current scope <ide> * defines a prefix, this prefix will be appended to it. <add> * - 'connectOptions' – Custom options for connecting the routes. <ide> * <ide> * @param string $name A controller name to connect resource routes for. <ide> * @param array|callable $options Options to use when generating REST routes, or a callback.
1
Ruby
Ruby
rescue only downloaderror
fd4f985cb6a915baf2dabb1d6b9b07b1d7d138a1
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch_fetchable f <ide> f.clear_cache if ARGV.force? <ide> <ide> already_fetched = f.cached_download.exist? <del> download = nil <ide> <ide> begin <ide> download = f.fetch <del> rescue => e <add> rescue DownloadError <ide> retry if retry_fetch? f <del> raise e <add> raise <ide> end <ide> <ide> return unless download.file?
1
Javascript
Javascript
fix lint errors in src/
fbdcc71ad082065717027edec7460b8ea03e034c
<ide><path>src/createStore.js <del>import isPlainObject from './utils/isPlainObject'; <add>import isPlainObject from './utils/isPlainObject' <ide> <ide> /** <ide> * These are private action types reserved by Redux. <ide> import isPlainObject from './utils/isPlainObject'; <ide> */ <ide> export var ActionTypes = { <ide> INIT: '@@redux/INIT' <del>}; <add>} <ide> <ide> /** <ide> * Creates a Redux store that holds the state tree. <ide> export var ActionTypes = { <ide> */ <ide> export default function createStore(reducer, initialState) { <ide> if (typeof reducer !== 'function') { <del> throw new Error('Expected the reducer to be a function.'); <add> throw new Error('Expected the reducer to be a function.') <ide> } <ide> <del> var currentReducer = reducer; <del> var currentState = initialState; <del> var listeners = []; <del> var isDispatching = false; <add> var currentReducer = reducer <add> var currentState = initialState <add> var listeners = [] <add> var isDispatching = false <ide> <ide> /** <ide> * Reads the state tree managed by the store. <ide> * <ide> * @returns {any} The current state tree of your application. <ide> */ <ide> function getState() { <del> return currentState; <add> return currentState <ide> } <ide> <ide> /** <ide> export default function createStore(reducer, initialState) { <ide> * @returns {Function} A function to remove this change listener. <ide> */ <ide> function subscribe(listener) { <del> listeners.push(listener); <del> var isSubscribed = true; <add> listeners.push(listener) <add> var isSubscribed = true <ide> <ide> return function unsubscribe() { <ide> if (!isSubscribed) { <del> return; <add> return <ide> } <ide> <del> isSubscribed = false; <del> var index = listeners.indexOf(listener); <del> listeners.splice(index, 1); <del> }; <add> isSubscribed = false <add> var index = listeners.indexOf(listener) <add> listeners.splice(index, 1) <add> } <ide> } <ide> <ide> /** <ide> export default function createStore(reducer, initialState) { <ide> throw new Error( <ide> 'Actions must be plain objects. ' + <ide> 'Use custom middleware for async actions.' <del> ); <add> ) <ide> } <ide> <ide> if (typeof action.type === 'undefined') { <ide> throw new Error( <ide> 'Actions may not have an undefined "type" property. ' + <ide> 'Have you misspelled a constant?' <del> ); <add> ) <ide> } <ide> <ide> if (isDispatching) { <del> throw new Error('Reducers may not dispatch actions.'); <add> throw new Error('Reducers may not dispatch actions.') <ide> } <ide> <ide> try { <del> isDispatching = true; <del> currentState = currentReducer(currentState, action); <add> isDispatching = true <add> currentState = currentReducer(currentState, action) <ide> } finally { <del> isDispatching = false; <add> isDispatching = false <ide> } <ide> <del> listeners.slice().forEach(listener => listener()); <del> return action; <add> listeners.slice().forEach(listener => listener()) <add> return action <ide> } <ide> <ide> /** <ide> export default function createStore(reducer, initialState) { <ide> * @returns {void} <ide> */ <ide> function replaceReducer(nextReducer) { <del> currentReducer = nextReducer; <del> dispatch({ type: ActionTypes.INIT }); <add> currentReducer = nextReducer <add> dispatch({ type: ActionTypes.INIT }) <ide> } <ide> <ide> // When a store is created, an "INIT" action is dispatched so that every <ide> // reducer returns their initial state. This effectively populates <ide> // the initial state tree. <del> dispatch({ type: ActionTypes.INIT }); <add> dispatch({ type: ActionTypes.INIT }) <ide> <ide> return { <ide> dispatch, <ide> subscribe, <ide> getState, <ide> replaceReducer <del> }; <add> } <ide> } <ide><path>src/index.js <del>import createStore from './createStore'; <del>import combineReducers from './utils/combineReducers'; <del>import bindActionCreators from './utils/bindActionCreators'; <del>import applyMiddleware from './utils/applyMiddleware'; <del>import compose from './utils/compose'; <add>import createStore from './createStore' <add>import combineReducers from './utils/combineReducers' <add>import bindActionCreators from './utils/bindActionCreators' <add>import applyMiddleware from './utils/applyMiddleware' <add>import compose from './utils/compose' <ide> <ide> export { <ide> createStore, <ide> combineReducers, <ide> bindActionCreators, <ide> applyMiddleware, <ide> compose <del>}; <add>} <ide><path>src/utils/applyMiddleware.js <del>import compose from './compose'; <add>import compose from './compose' <ide> <ide> /** <ide> * Creates a store enhancer that applies middleware to the dispatch method <ide> import compose from './compose'; <ide> */ <ide> export default function applyMiddleware(...middlewares) { <ide> return (next) => (reducer, initialState) => { <del> var store = next(reducer, initialState); <del> var dispatch = store.dispatch; <del> var chain = []; <add> var store = next(reducer, initialState) <add> var dispatch = store.dispatch <add> var chain = [] <ide> <ide> var middlewareAPI = { <ide> getState: store.getState, <ide> dispatch: (action) => dispatch(action) <del> }; <del> chain = middlewares.map(middleware => middleware(middlewareAPI)); <del> dispatch = compose(...chain)(store.dispatch); <add> } <add> chain = middlewares.map(middleware => middleware(middlewareAPI)) <add> dispatch = compose(...chain)(store.dispatch) <ide> <ide> return { <ide> ...store, <ide> dispatch <del> }; <del> }; <add> } <add> } <ide> } <ide><path>src/utils/bindActionCreators.js <del>import mapValues from '../utils/mapValues'; <add>import mapValues from '../utils/mapValues' <ide> <ide> function bindActionCreator(actionCreator, dispatch) { <del> return (...args) => dispatch(actionCreator(...args)); <add> return (...args) => dispatch(actionCreator(...args)) <ide> } <ide> <ide> /** <ide> function bindActionCreator(actionCreator, dispatch) { <ide> */ <ide> export default function bindActionCreators(actionCreators, dispatch) { <ide> if (typeof actionCreators === 'function') { <del> return bindActionCreator(actionCreators, dispatch); <add> return bindActionCreator(actionCreators, dispatch) <ide> } <ide> <ide> if (typeof actionCreators !== 'object' || actionCreators === null || actionCreators === undefined) { // eslint-disable-line no-eq-null <ide> throw new Error( <ide> `bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` + <ide> `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?` <del> ); <add> ) <ide> } <ide> <ide> return mapValues(actionCreators, actionCreator => <ide> bindActionCreator(actionCreator, dispatch) <del> ); <add> ) <ide> } <ide><path>src/utils/combineReducers.js <del>import { ActionTypes } from '../createStore'; <del>import isPlainObject from '../utils/isPlainObject'; <del>import mapValues from '../utils/mapValues'; <del>import pick from '../utils/pick'; <add>import { ActionTypes } from '../createStore' <add>import isPlainObject from '../utils/isPlainObject' <add>import mapValues from '../utils/mapValues' <add>import pick from '../utils/pick' <ide> <ide> /* eslint-disable no-console */ <ide> <ide> function getUndefinedStateErrorMessage(key, action) { <del> var actionType = action && action.type; <del> var actionName = actionType && `"${actionType.toString()}"` || 'an action'; <add> var actionType = action && action.type <add> var actionName = actionType && `"${actionType.toString()}"` || 'an action' <ide> <ide> return ( <ide> `Reducer "${key}" returned undefined handling ${actionName}. ` + <ide> `To ignore an action, you must explicitly return the previous state.` <del> ); <add> ) <ide> } <ide> <ide> function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) { <del> var reducerKeys = Object.keys(outputState); <add> var reducerKeys = Object.keys(outputState) <ide> var argumentName = action && action.type === ActionTypes.INIT ? <ide> 'initialState argument passed to createStore' : <del> 'previous state received by the reducer'; <add> 'previous state received by the reducer' <ide> <ide> if (reducerKeys.length === 0) { <ide> return ( <ide> 'Store does not have a valid reducer. Make sure the argument passed ' + <ide> 'to combineReducers is an object whose values are reducers.' <del> ); <add> ) <ide> } <ide> <ide> if (!isPlainObject(inputState)) { <ide> function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) { <ide> ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + <ide> `". Expected argument to be an object with the following ` + <ide> `keys: "${reducerKeys.join('", "')}"` <del> ); <add> ) <ide> } <ide> <ide> var unexpectedKeys = Object.keys(inputState).filter( <ide> key => reducerKeys.indexOf(key) < 0 <del> ); <add> ) <ide> <ide> if (unexpectedKeys.length > 0) { <ide> return ( <ide> `Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` + <ide> `"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` + <ide> `Expected to find one of the known reducer keys instead: ` + <ide> `"${reducerKeys.join('", "')}". Unexpected keys will be ignored.` <del> ); <add> ) <ide> } <ide> } <ide> <ide> function assertReducerSanity(reducers) { <ide> Object.keys(reducers).forEach(key => { <del> var reducer = reducers[key]; <del> var initialState = reducer(undefined, { type: ActionTypes.INIT }); <add> var reducer = reducers[key] <add> var initialState = reducer(undefined, { type: ActionTypes.INIT }) <ide> <ide> if (typeof initialState === 'undefined') { <ide> throw new Error( <ide> `Reducer "${key}" returned undefined during initialization. ` + <ide> `If the state passed to the reducer is undefined, you must ` + <ide> `explicitly return the initial state. The initial state may ` + <ide> `not be undefined.` <del> ); <add> ) <ide> } <ide> <del> var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); <add> var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.') <ide> if (typeof reducer(undefined, { type }) === 'undefined') { <ide> throw new Error( <ide> `Reducer "${key}" returned undefined when probed with a random type. ` + <ide> function assertReducerSanity(reducers) { <ide> `current state for any unknown actions, unless it is undefined, ` + <ide> `in which case you must return the initial state, regardless of the ` + <ide> `action type. The initial state may not be undefined.` <del> ); <add> ) <ide> } <del> }); <add> }) <ide> } <ide> <ide> /** <ide> function assertReducerSanity(reducers) { <ide> */ <ide> <ide> export default function combineReducers(reducers) { <del> var finalReducers = pick(reducers, (val) => typeof val === 'function'); <del> var sanityError; <add> var finalReducers = pick(reducers, (val) => typeof val === 'function') <add> var sanityError <ide> <ide> try { <del> assertReducerSanity(finalReducers); <add> assertReducerSanity(finalReducers) <ide> } catch (e) { <del> sanityError = e; <add> sanityError = e <ide> } <ide> <del> var defaultState = mapValues(finalReducers, () => undefined); <add> var defaultState = mapValues(finalReducers, () => undefined) <ide> <ide> return function combination(state = defaultState, action) { <ide> if (sanityError) { <del> throw sanityError; <add> throw sanityError <ide> } <ide> <del> var hasChanged = false; <add> var hasChanged = false <ide> var finalState = mapValues(finalReducers, (reducer, key) => { <del> var previousStateForKey = state[key]; <del> var nextStateForKey = reducer(previousStateForKey, action); <add> var previousStateForKey = state[key] <add> var nextStateForKey = reducer(previousStateForKey, action) <ide> if (typeof nextStateForKey === 'undefined') { <del> var errorMessage = getUndefinedStateErrorMessage(key, action); <del> throw new Error(errorMessage); <add> var errorMessage = getUndefinedStateErrorMessage(key, action) <add> throw new Error(errorMessage) <ide> } <del> hasChanged = hasChanged || nextStateForKey !== previousStateForKey; <del> return nextStateForKey; <del> }); <add> hasChanged = hasChanged || nextStateForKey !== previousStateForKey <add> return nextStateForKey <add> }) <ide> <ide> if (process.env.NODE_ENV !== 'production') { <del> var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action); <add> var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action) <ide> if (warningMessage) { <del> console.error(warningMessage); <add> console.error(warningMessage) <ide> } <ide> } <ide> <del> return hasChanged ? finalState : state; <del> }; <add> return hasChanged ? finalState : state <add> } <ide> } <ide><path>src/utils/compose.js <ide> * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))). <ide> */ <ide> export default function compose(...funcs) { <del> return arg => funcs.reduceRight((composed, f) => f(composed), arg); <add> return arg => funcs.reduceRight((composed, f) => f(composed), arg) <ide> } <ide><path>src/utils/isPlainObject.js <del>var fnToString = (fn) => Function.prototype.toString.call(fn); <del>var objStringValue = fnToString(Object); <add>var fnToString = (fn) => Function.prototype.toString.call(fn) <add>var objStringValue = fnToString(Object) <ide> <ide> /** <ide> * @param {any} obj The object to inspect. <ide> * @returns {boolean} True if the argument appears to be a plain object. <ide> */ <ide> export default function isPlainObject(obj) { <ide> if (!obj || typeof obj !== 'object') { <del> return false; <add> return false <ide> } <ide> <del> var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype; <add> var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype <ide> <ide> if (proto === null) { <del> return true; <add> return true <ide> } <ide> <del> var constructor = proto.constructor; <add> var constructor = proto.constructor <ide> <ide> return typeof constructor === 'function' <ide> && constructor instanceof constructor <del> && fnToString(constructor) === objStringValue; <add> && fnToString(constructor) === objStringValue <ide> } <ide><path>src/utils/mapValues.js <ide> */ <ide> export default function mapValues(obj, fn) { <ide> return Object.keys(obj).reduce((result, key) => { <del> result[key] = fn(obj[key], key); <del> return result; <del> }, {}); <add> result[key] = fn(obj[key], key) <add> return result <add> }, {}) <ide> } <ide><path>src/utils/pick.js <ide> export default function pick(obj, fn) { <ide> return Object.keys(obj).reduce((result, key) => { <ide> if (fn(obj[key])) { <del> result[key] = obj[key]; <add> result[key] = obj[key] <ide> } <del> return result; <del> }, {}); <add> return result <add> }, {}) <ide> }
9
Mixed
Text
use an empty query instead of select 1
8325d079763e058b4e685d1300889e99fc12478a
<ide><path>activerecord/CHANGELOG.md <add>* Use an empty query to check if the PostgreSQL connection is still active <add> <add> An empty query is faster than `SELECT 1`. <add> <add> *Heinrich Lee Yu* <add> <ide> * Add `ActiveRecord::Base#previously_persisted?` <ide> <ide> Returns `true` if the object has been previously persisted but now it has been deleted. <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def self.database_exists?(config) <ide> # Is this connection alive and ready for queries? <ide> def active? <ide> @lock.synchronize do <del> @connection.query "SELECT 1" <add> @connection.query ";" <ide> end <ide> true <ide> rescue PG::Error
2
Go
Go
remove checkpoint methods from builder backend
5fb3b4205a8b0635ff193791ef581939806eb8da
<ide><path>builder/builder.go <ide> type Backend interface { <ide> // ContainerUpdateCmdOnBuild updates container.Path and container.Args <ide> ContainerUpdateCmdOnBuild(containerID string, cmd []string) error <ide> <del> // CheckpointCreate checkpoints a running container <del> CheckpointCreate(container string, config types.CheckpointCreateOptions) error <del> // CheckpointDelete deletes a container's checkpoint <del> CheckpointDelete(container string, checkpoint string) error <del> // CheckpointList lists the available checkpoints for a container <del> CheckpointList(container string) ([]types.Checkpoint, error) <del> <ide> // ContainerCopy copies/extracts a source FileInfo to a destination path inside a container <ide> // specified by a container object. <ide> // TODO: make an Extract method instead of passing `decompress`
1
Ruby
Ruby
add workflow scope to github.rb
f1ef1afd2130993cce87f27a634929810331ba1a
<ide><path>Library/Homebrew/utils/github.rb <ide> module GitHub <ide> <ide> CREATE_GIST_SCOPES = ["gist"].freeze <ide> CREATE_ISSUE_FORK_OR_PR_SCOPES = ["public_repo"].freeze <del> ALL_SCOPES = (CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES).freeze <add> CREATE_WORKFLOW_SCOPES = ["workflow"].freeze <add> ALL_SCOPES = (CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES + CREATE_WORKFLOW_SCOPES).freeze <ide> ALL_SCOPES_URL = Formatter.url( <ide> "https://github.com/settings/tokens/new?scopes=#{ALL_SCOPES.join(",")}&description=Homebrew", <ide> ).freeze
1
Javascript
Javascript
move aggrow table header into its own component
0c157bea367db82fc9955ee684ca920790e08292
<ide><path>local-cli/server/middleware/heapCapture/out/table.js <ide> dropFilter:React.PropTypes.func.isRequired, <ide> dropAction:React.PropTypes.func.isRequired};var <ide> <ide> <del>Table=function(_React$Component3){_inherits(Table,_React$Component3);// eslint-disable-line no-unused-vars <del>function Table(props){_classCallCheck(this,Table);var _this3=_possibleConstructorReturn(this,Object.getPrototypeOf(Table).call(this, <add>TableHeader=function(_React$Component3){_inherits(TableHeader,_React$Component3); <add>function TableHeader(props){_classCallCheck(this,TableHeader);return _possibleConstructorReturn(this,Object.getPrototypeOf(TableHeader).call(this, <ide> props)); <del>_this3.state={ <add>}_createClass(TableHeader,[{key:'render',value:function render() <add>{ <add>var aggrow=this.props.aggrow; <add>var aggregators=aggrow.getActiveAggregators(); <add>var expanders=aggrow.getActiveExpanders(); <add>var headers=[]; <add>for(var i=0;i<aggregators.length;i++){ <add>var name=aggrow.getAggregatorName(aggregators[i]); <add>headers.push( <add>React.createElement(DropTarget,{ <add>id:'aggregate:insert:'+i.toString(), <add>dropFilter:function dropFilter(s){return s.startsWith('aggregate');}, <add>dropAction:this.props.dropAction}, <add> <add>React.createElement('div',{style:{ <add>width:'16px', <add>height:'inherit', <add>backgroundColor:'darkGray', <add>flexShrink:'0'}}))); <add> <add> <add>headers.push(React.createElement(Draggable,{id:'aggregate:active:'+i.toString()}, <add>React.createElement('div',{style:{width:'128px',textAlign:'center',flexShrink:'0'}},name))); <add> <add>} <add>headers.push( <add>React.createElement(DropTarget,{ <add>id:'divider:insert', <add>dropFilter:function dropFilter(s){return s.startsWith('aggregate')||s.startsWith('expander');}, <add>dropAction:this.props.dropAction}, <add> <add>React.createElement('div',{style:{ <add>width:'16px', <add>height:'inherit', <add>backgroundColor:'gold', <add>flexShrink:'0'}}))); <add> <add> <add>for(var _i=0;_i<expanders.length;_i++){ <add>var _name=aggrow.getExpanderName(expanders[_i]); <add>var bg=_i%2===0?'white':'lightGray'; <add>headers.push(React.createElement(Draggable,{id:'expander:active:'+_i.toString()}, <add>React.createElement('div',{style:{ <add>width:'128px', <add>textAlign:'center', <add>backgroundColor:bg, <add>flexShrink:'0'}}, <add> <add>_name))); <add> <add> <add>var sep=_i+1<expanders.length?'->':'...'; <add>headers.push( <add>React.createElement(DropTarget,{ <add>id:'expander:insert:'+(_i+1).toString(), <add>dropFilter:function dropFilter(){return true;}, <add>dropAction:this.props.dropAction}, <add> <add>React.createElement('div',{style:{ <add>height:'inherit', <add>backgroundColor:'darkGray', <add>flexShrink:'0'}}, <add> <add>sep))); <add> <add> <add> <add>} <add>return( <add>React.createElement('div',{style:{ <add>width:'100%', <add>height:'26px', <add>display:'flex', <add>flexDirection:'row', <add>alignItems:'center', <add>borderBottom:'2px solid black'}}, <add> <add>headers)); <add> <add> <add>}}]);return TableHeader;}(React.Component); <add> <add> <add>TableHeader.propTypes={ <add>aggrow:React.PropTypes.object.isRequired, <add>dropAction:React.PropTypes.func.isRequired};var <add> <add> <add>Table=function(_React$Component4){_inherits(Table,_React$Component4);// eslint-disable-line no-unused-vars <add>function Table(props){_classCallCheck(this,Table);var _this4=_possibleConstructorReturn(this,Object.getPrototypeOf(Table).call(this, <add>props)); <add>_this4.state={ <ide> aggrow:props.aggrow, <ide> viewport:{top:0,height:100}, <del>cursor:0};return _this3; <add>cursor:0};return _this4; <ide> <ide> }_createClass(Table,[{key:'scroll',value:function scroll( <ide> <ide> this._keepCursorInViewport(); <ide> e.preventDefault(); <ide> break;} <ide> <del>}},{key:'dropAggregator',value:function dropAggregator( <add>}},{key:'dropAction',value:function dropAction( <ide> <ide> s,d){ <ide> var aggrow=this.state.aggrow; <ide> this.setState({cursor:0}); <ide> } <ide> }},{key:'render',value:function render() <ide> <del>{var _this4=this; <del>var headers=[]; <del>var aggrow=this.state.aggrow; <del>var aggregators=aggrow.getActiveAggregators(); <del>var expanders=aggrow.getActiveExpanders(); <del>// aggregators <del>for(var i=0;i<aggregators.length;i++){ <del>var name=aggrow.getAggregatorName(aggregators[i]); <del>headers.push( <del>React.createElement(DropTarget,{ <del>id:'aggregate:insert:'+i.toString(), <del>dropFilter:function dropFilter(){return true;}, <del>dropAction:function dropAction(s,d){_this4.dropAggregator(s,d);}}, <del> <del>React.createElement('div',{style:{ <del>width:'16px', <del>height:'inherit', <del>backgroundColor:'darkGray', <del>flexShrink:'0'}}))); <del> <del> <del>headers.push(React.createElement(Draggable,{id:'aggregate:active:'+i.toString()}, <del>React.createElement('div',{style:{width:'128px',textAlign:'center',flexShrink:'0'}},name))); <del> <del>} <del>headers.push( <del>React.createElement(DropTarget,{ <del>id:'divider:insert', <del>dropFilter:function dropFilter(){return true;}, <del>dropAction:function dropAction(s,d){_this4.dropAggregator(s,d);}}, <del> <del>React.createElement('div',{style:{ <del>width:'16px', <del>height:'inherit', <del>backgroundColor:'gold', <del>flexShrink:'0'}}))); <del> <del> <del>for(var _i=0;_i<expanders.length;_i++){ <del>var _name=aggrow.getExpanderName(expanders[_i]); <del>var bg=_i%2===0?'white':'lightGray'; <del>headers.push(React.createElement(Draggable,{id:'expander:active:'+_i.toString()}, <del>React.createElement('div',{style:{ <del>width:'128px', <del>textAlign:'center', <del>backgroundColor:bg, <del>flexShrink:'0'}}, <del> <del>_name))); <del> <del> <del>var sep=_i+1<expanders.length?'->':'...'; <del>headers.push( <del>React.createElement(DropTarget,{ <del>id:'expander:insert:'+(_i+1).toString(), <del>dropFilter:function dropFilter(){return true;}, <del>dropAction:function dropAction(s,d){_this4.dropAggregator(s,d);}}, <del> <del>React.createElement('div',{style:{ <del>height:'inherit', <del>backgroundColor:'darkGray', <del>flexShrink:'0'}}, <del> <del>sep))); <del> <del> <del> <del>} <del> <add>{var _this5=this; <ide> return( <ide> React.createElement('div',{style:{width:'100%',height:'100%',display:'flex',flexDirection:'column'}}, <del>React.createElement('div',{style:{ <del>width:'100%', <del>height:'26px', <del>display:'flex', <del>flexDirection:'row', <del>alignItems:'center', <del>borderBottom:'2px solid black'}}, <del> <del>headers), <del> <add>React.createElement(TableHeader,{aggrow:this.state.aggrow,dropAction:function dropAction(s,d){return _this5.dropAction(s,d);}}), <ide> React.createElement('div',{ <ide> style:{ <ide> width:'100%', <ide> flexGrow:'1', <ide> overflow:'scroll'}, <ide> <del>onScroll:function onScroll(e){return _this4.scroll(e);}, <del>ref:function ref(div){_this4._scrollDiv=div;}}, <add>onScroll:function onScroll(e){return _this5.scroll(e);}, <add>ref:function ref(div){_this5._scrollDiv=div;}}, <ide> React.createElement('div',{style:{position:'relative'}}, <ide> this.renderVirtualizedRows())))); <ide> <ide> this.renderVirtualizedRows())))); <ide> <ide> }},{key:'renderVirtualizedRows',value:function renderVirtualizedRows() <ide> <del>{var _this5=this; <add>{var _this6=this; <ide> var aggrow=this.state.aggrow; <ide> var viewport=this.state.viewport; <ide> var rows=aggrow.getRows(viewport.top,viewport.height); <ide> position:'absolute', <ide> width:'100%', <ide> height:(rowHeight*(aggrow.getHeight()+20)).toString()+'px'}}, <ide> <del>rows.map(function(child){return _this5.renderRow(child);}))); <add>rows.map(function(child){return _this6.renderRow(child);}))); <ide> <ide> <ide> }},{key:'renderRow',value:function renderRow( <ide> <del>row){var _this6=this; <add>row){var _this7=this; <ide> if(row===null){ <ide> return null; <ide> } <ide> width:'12px', <ide> textAlign:'center', <ide> border:'1px solid gray'}, <ide> <del>onClick:function onClick(){return _this6._expandRow(row);}},'+')); <add>onClick:function onClick(){return _this7._expandRow(row);}},'+')); <ide> <ide> <ide> }else if(aggrow.canContract(row)){ <ide> width:'12px', <ide> textAlign:'center', <ide> border:'1px solid gray'}, <ide> <del>onClick:function onClick(){return _this6._contractRow(row);}},'-')); <add>onClick:function onClick(){return _this7._contractRow(row);}},'-')); <ide> <ide> <ide> }else{ <ide> backgroundColor:bg, <ide> borderBottom:'1px solid gray'}, <ide> <ide> onClick:function onClick(){ <del>_this6.setState({cursor:row.top}); <add>_this7.setState({cursor:row.top}); <ide> }}, <ide> columns)); <ide> <ide><path>local-cli/server/middleware/heapCapture/src/table.js <ide> DropTarget.propTypes = { <ide> dropAction: React.PropTypes.func.isRequired, <ide> }; <ide> <add>class TableHeader extends React.Component { <add> constructor(props) { <add> super(props); <add> } <add> render() { <add> const aggrow = this.props.aggrow; <add> const aggregators = aggrow.getActiveAggregators(); <add> const expanders = aggrow.getActiveExpanders(); <add> const headers = []; <add> for (let i = 0; i < aggregators.length; i++) { <add> const name = aggrow.getAggregatorName(aggregators[i]); <add> headers.push(( <add> <DropTarget <add> id={'aggregate:insert:' + i.toString()} <add> dropFilter={(s) => s.startsWith('aggregate')} <add> dropAction={this.props.dropAction} <add> > <add> <div style={{ <add> width: '16px', <add> height: 'inherit', <add> backgroundColor: 'darkGray', <add> flexShrink: '0' }} <add> ></div> <add> </DropTarget>)); <add> headers.push((<Draggable id={'aggregate:active:' + i.toString()}> <add> <div style={{ width: '128px', textAlign: 'center', flexShrink: '0' }}>{name}</div> <add> </Draggable>)); <add> } <add> headers.push(( <add> <DropTarget <add> id="divider:insert" <add> dropFilter={(s) => s.startsWith('aggregate') || s.startsWith('expander')} <add> dropAction={this.props.dropAction} <add> > <add> <div style={{ <add> width: '16px', <add> height: 'inherit', <add> backgroundColor: 'gold', <add> flexShrink: '0' <add> }}></div> <add> </DropTarget>)); <add> for (let i = 0; i < expanders.length; i++) { <add> const name = aggrow.getExpanderName(expanders[i]); <add> const bg = (i % 2 === 0) ? 'white' : 'lightGray'; <add> headers.push((<Draggable id={'expander:active:' + i.toString()}> <add> <div style={{ <add> width: '128px', <add> textAlign: 'center', <add> backgroundColor: bg, <add> flexShrink: '0' <add> }}> <add> {name} <add> </div> <add> </Draggable>)); <add> const sep = i + 1 < expanders.length ? '->' : '...'; <add> headers.push(( <add> <DropTarget <add> id={'expander:insert:' + (i + 1).toString()} <add> dropFilter={()=>{return true; }} <add> dropAction={this.props.dropAction} <add> > <add> <div style={{ <add> height: 'inherit', <add> backgroundColor: 'darkGray', <add> flexShrink: '0' <add> }}> <add> {sep} <add> </div> <add> </DropTarget>) <add> ); <add> } <add> return ( <add> <div style={{ <add> width: '100%', <add> height: '26px', <add> display: 'flex', <add> flexDirection: 'row', <add> alignItems: 'center', <add> borderBottom: '2px solid black', <add> }}> <add> {headers} <add> </div> <add> ); <add> } <add>} <add> <add>TableHeader.propTypes = { <add> aggrow: React.PropTypes.object.isRequired, <add> dropAction: React.PropTypes.func.isRequired, <add>}; <add> <ide> class Table extends React.Component { // eslint-disable-line no-unused-vars <ide> constructor(props) { <ide> super(props); <ide> class Table extends React.Component { // eslint-disable-line no-unused-vars <ide> } <ide> } <ide> <del> dropAggregator(s, d) { <add> dropAction(s, d) { <ide> const aggrow = this.state.aggrow; <ide> console.log('dropped ' + s + ' to ' + d); <ide> if (s.startsWith('aggregate:active:')) { <ide> class Table extends React.Component { // eslint-disable-line no-unused-vars <ide> } <ide> <ide> render() { <del> const headers = []; <del> const aggrow = this.state.aggrow; <del> const aggregators = aggrow.getActiveAggregators(); <del> const expanders = aggrow.getActiveExpanders(); <del> // aggregators <del> for (let i = 0; i < aggregators.length; i++) { <del> const name = aggrow.getAggregatorName(aggregators[i]); <del> headers.push(( <del> <DropTarget <del> id={'aggregate:insert:' + i.toString()} <del> dropFilter={()=>{return true; }} <del> dropAction={(s, d)=>{ this.dropAggregator(s, d); }} <del> > <del> <div style={{ <del> width: '16px', <del> height: 'inherit', <del> backgroundColor: 'darkGray', <del> flexShrink: '0' }} <del> ></div> <del> </DropTarget>)); <del> headers.push((<Draggable id={'aggregate:active:' + i.toString()}> <del> <div style={{ width: '128px', textAlign: 'center', flexShrink: '0' }}>{name}</div> <del> </Draggable>)); <del> } <del> headers.push(( <del> <DropTarget <del> id="divider:insert" <del> dropFilter={()=>{return true; }} <del> dropAction={(s, d)=>{ this.dropAggregator(s, d); }} <del> > <del> <div style={{ <del> width: '16px', <del> height: 'inherit', <del> backgroundColor: 'gold', <del> flexShrink: '0' <del> }}></div> <del> </DropTarget>)); <del> for (let i = 0; i < expanders.length; i++) { <del> const name = aggrow.getExpanderName(expanders[i]); <del> const bg = (i % 2 === 0) ? 'white' : 'lightGray'; <del> headers.push((<Draggable id={'expander:active:' + i.toString()}> <del> <div style={{ <del> width: '128px', <del> textAlign: 'center', <del> backgroundColor: bg, <del> flexShrink: '0' <del> }}> <del> {name} <del> </div> <del> </Draggable>)); <del> const sep = i + 1 < expanders.length ? '->' : '...'; <del> headers.push(( <del> <DropTarget <del> id={'expander:insert:' + (i + 1).toString()} <del> dropFilter={()=>{return true; }} <del> dropAction={(s, d)=>{ this.dropAggregator(s, d);}} <del> > <del> <div style={{ <del> height: 'inherit', <del> backgroundColor: 'darkGray', <del> flexShrink: '0' <del> }}> <del> {sep} <del> </div> <del> </DropTarget>) <del> ); <del> } <del> <ide> return ( <ide> <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}> <del> <div style={{ <del> width: '100%', <del> height: '26px', <del> display: 'flex', <del> flexDirection: 'row', <del> alignItems: 'center', <del> borderBottom: '2px solid black', <del> }}> <del> {headers} <del> </div> <add> <TableHeader aggrow={this.state.aggrow} dropAction={(s, d) => this.dropAction(s, d)} /> <ide> <div <ide> style={{ <ide> width: '100%',
2
Javascript
Javascript
use strings as the type for dom elements
3aaccd2dc96cf229c0170d538fe81f7d22059a4e
<ide><path>src/browser/ReactDOM.js <ide> var ReactDescriptor = require('ReactDescriptor'); <ide> var ReactDescriptorValidator = require('ReactDescriptorValidator'); <ide> var ReactLegacyDescriptor = require('ReactLegacyDescriptor'); <del>var ReactDOMComponent = require('ReactDOMComponent'); <ide> <del>var mergeInto = require('mergeInto'); <ide> var mapObject = require('mapObject'); <ide> <ide> /** <del> * Creates a new React class that is idempotent and capable of containing other <del> * React components. It accepts event listeners and DOM properties that are <del> * valid according to `DOMProperty`. <add> * Create a factory that creates HTML tag descriptors. <ide> * <del> * - Event listeners: `onClick`, `onMouseDown`, etc. <del> * - DOM properties: `className`, `name`, `title`, etc. <del> * <del> * The `style` property functions differently from the DOM API. It accepts an <del> * object mapping of style properties to values. <del> * <del> * @param {boolean} omitClose True if the close tag should be omitted. <ide> * @param {string} tag Tag name (e.g. `div`). <ide> * @private <ide> */ <del>function createDOMComponentClass(omitClose, tag) { <del> var Constructor = function(props) { <del> // This constructor and it's argument is currently used by mocks. <del> }; <del> Constructor.prototype = new ReactDOMComponent(tag, omitClose); <del> Constructor.prototype.constructor = Constructor; <del> Constructor.displayName = tag; <del> <add>function createDOMFactory(tag) { <ide> if (__DEV__) { <ide> return ReactLegacyDescriptor.wrapFactory( <del> ReactDescriptorValidator.createFactory(Constructor) <add> ReactDescriptorValidator.createFactory(tag) <ide> ); <ide> } <ide> return ReactLegacyDescriptor.wrapFactory( <del> ReactDescriptor.createFactory(Constructor) <add> ReactDescriptor.createFactory(tag) <ide> ); <ide> } <ide> <ide> function createDOMComponentClass(omitClose, tag) { <ide> * @public <ide> */ <ide> var ReactDOM = mapObject({ <del> a: false, <del> abbr: false, <del> address: false, <del> area: true, <del> article: false, <del> aside: false, <del> audio: false, <del> b: false, <del> base: true, <del> bdi: false, <del> bdo: false, <del> big: false, <del> blockquote: false, <del> body: false, <del> br: true, <del> button: false, <del> canvas: false, <del> caption: false, <del> cite: false, <del> code: false, <del> col: true, <del> colgroup: false, <del> data: false, <del> datalist: false, <del> dd: false, <del> del: false, <del> details: false, <del> dfn: false, <del> dialog: false, <del> div: false, <del> dl: false, <del> dt: false, <del> em: false, <del> embed: true, <del> fieldset: false, <del> figcaption: false, <del> figure: false, <del> footer: false, <del> form: false, // NOTE: Injected, see `ReactDOMForm`. <del> h1: false, <del> h2: false, <del> h3: false, <del> h4: false, <del> h5: false, <del> h6: false, <del> head: false, <del> header: false, <del> hr: true, <del> html: false, <del> i: false, <del> iframe: false, <del> img: true, <del> input: true, <del> ins: false, <del> kbd: false, <del> keygen: true, <del> label: false, <del> legend: false, <del> li: false, <del> link: true, <del> main: false, <del> map: false, <del> mark: false, <del> menu: false, <del> menuitem: false, // NOTE: Close tag should be omitted, but causes problems. <del> meta: true, <del> meter: false, <del> nav: false, <del> noscript: false, <del> object: false, <del> ol: false, <del> optgroup: false, <del> option: false, <del> output: false, <del> p: false, <del> param: true, <del> picture: false, <del> pre: false, <del> progress: false, <del> q: false, <del> rp: false, <del> rt: false, <del> ruby: false, <del> s: false, <del> samp: false, <del> script: false, <del> section: false, <del> select: false, <del> small: false, <del> source: true, <del> span: false, <del> strong: false, <del> style: false, <del> sub: false, <del> summary: false, <del> sup: false, <del> table: false, <del> tbody: false, <del> td: false, <del> textarea: false, // NOTE: Injected, see `ReactDOMTextarea`. <del> tfoot: false, <del> th: false, <del> thead: false, <del> time: false, <del> title: false, <del> tr: false, <del> track: true, <del> u: false, <del> ul: false, <del> 'var': false, <del> video: false, <del> wbr: true, <add> a: 'a', <add> abbr: 'abbr', <add> address: 'address', <add> area: 'area', <add> article: 'article', <add> aside: 'aside', <add> audio: 'audio', <add> b: 'b', <add> base: 'base', <add> bdi: 'bdi', <add> bdo: 'bdo', <add> big: 'big', <add> blockquote: 'blockquote', <add> body: 'body', <add> br: 'br', <add> button: 'button', <add> canvas: 'canvas', <add> caption: 'caption', <add> cite: 'cite', <add> code: 'code', <add> col: 'col', <add> colgroup: 'colgroup', <add> data: 'data', <add> datalist: 'datalist', <add> dd: 'dd', <add> del: 'del', <add> details: 'details', <add> dfn: 'dfn', <add> dialog: 'dialog', <add> div: 'div', <add> dl: 'dl', <add> dt: 'dt', <add> em: 'em', <add> embed: 'embed', <add> fieldset: 'fieldset', <add> figcaption: 'figcaption', <add> figure: 'figure', <add> footer: 'footer', <add> form: 'form', <add> h1: 'h1', <add> h2: 'h2', <add> h3: 'h3', <add> h4: 'h4', <add> h5: 'h5', <add> h6: 'h6', <add> head: 'head', <add> header: 'header', <add> hr: 'hr', <add> html: 'html', <add> i: 'i', <add> iframe: 'iframe', <add> img: 'img', <add> input: 'input', <add> ins: 'ins', <add> kbd: 'kbd', <add> keygen: 'keygen', <add> label: 'label', <add> legend: 'legend', <add> li: 'li', <add> link: 'link', <add> main: 'main', <add> map: 'map', <add> mark: 'mark', <add> menu: 'menu', <add> menuitem: 'menuitem', <add> meta: 'meta', <add> meter: 'meter', <add> nav: 'nav', <add> noscript: 'noscript', <add> object: 'object', <add> ol: 'ol', <add> optgroup: 'optgroup', <add> option: 'option', <add> output: 'output', <add> p: 'p', <add> param: 'param', <add> picture: 'picture', <add> pre: 'pre', <add> progress: 'progress', <add> q: 'q', <add> rp: 'rp', <add> rt: 'rt', <add> ruby: 'ruby', <add> s: 's', <add> samp: 'samp', <add> script: 'script', <add> section: 'section', <add> select: 'select', <add> small: 'small', <add> source: 'source', <add> span: 'span', <add> strong: 'strong', <add> style: 'style', <add> sub: 'sub', <add> summary: 'summary', <add> sup: 'sup', <add> table: 'table', <add> tbody: 'tbody', <add> td: 'td', <add> textarea: 'textarea', <add> tfoot: 'tfoot', <add> th: 'th', <add> thead: 'thead', <add> time: 'time', <add> title: 'title', <add> tr: 'tr', <add> track: 'track', <add> u: 'u', <add> ul: 'ul', <add> 'var': 'var', <add> video: 'video', <add> wbr: 'wbr', <ide> <ide> // SVG <del> circle: false, <del> defs: false, <del> ellipse: false, <del> g: false, <del> line: false, <del> linearGradient: false, <del> mask: false, <del> path: false, <del> pattern: false, <del> polygon: false, <del> polyline: false, <del> radialGradient: false, <del> rect: false, <del> stop: false, <del> svg: false, <del> text: false, <del> tspan: false <del>}, createDOMComponentClass); <del> <del>var injection = { <del> injectComponentClasses: function(componentClasses) { <del> mergeInto(ReactDOM, componentClasses); <del> } <del>}; <add> circle: 'circle', <add> defs: 'defs', <add> ellipse: 'ellipse', <add> g: 'g', <add> line: 'line', <add> linearGradient: 'linearGradient', <add> mask: 'mask', <add> path: 'path', <add> pattern: 'pattern', <add> polygon: 'polygon', <add> polyline: 'polyline', <add> radialGradient: 'radialGradient', <add> rect: 'rect', <add> stop: 'stop', <add> svg: 'svg', <add> text: 'text', <add> tspan: 'tspan' <ide> <del>ReactDOM.injection = injection; <add>}, createDOMFactory); <ide> <ide> module.exports = ReactDOM; <ide><path>src/browser/server/ReactServerRendering.js <ide> function renderComponentToString(component) { <ide> transaction = ReactServerRenderingTransaction.getPooled(false); <ide> <ide> return transaction.perform(function() { <del> var componentInstance = instantiateReactComponent(component); <add> var componentInstance = instantiateReactComponent(component, null); <ide> var markup = componentInstance.mountComponent(id, transaction, 0); <ide> return ReactMarkupChecksum.addChecksumToMarkup(markup); <ide> }, null); <ide> function renderComponentToStaticMarkup(component) { <ide> transaction = ReactServerRenderingTransaction.getPooled(true); <ide> <ide> return transaction.perform(function() { <del> var componentInstance = instantiateReactComponent(component); <add> var componentInstance = instantiateReactComponent(component, null); <ide> return componentInstance.mountComponent(id, transaction, 0); <ide> }, null); <ide> } finally { <ide><path>src/browser/ui/ReactDOMComponent.js <ide> function putListener(id, registrationName, listener, transaction) { <ide> ); <ide> } <ide> <add>// For HTML, certain tags should omit their close tag. We keep a whitelist for <add>// those special cased tags. <add> <add>var omittedCloseTags = { <add> 'area': true, <add> 'base': true, <add> 'br': true, <add> 'col': true, <add> 'embed': true, <add> 'hr': true, <add> 'img': true, <add> 'input': true, <add> 'keygen': true, <add> 'link': true, <add> 'meta': true, <add> 'param': true, <add> 'source': true, <add> 'track': true, <add> 'wbr': true <add> // NOTE: menuitem's close tag should be omitted, but that causes problems. <add>}; <ide> <ide> /** <add> * Creates a new React class that is idempotent and capable of containing other <add> * React components. It accepts event listeners and DOM properties that are <add> * valid according to `DOMProperty`. <add> * <add> * - Event listeners: `onClick`, `onMouseDown`, etc. <add> * - DOM properties: `className`, `name`, `title`, etc. <add> * <add> * The `style` property functions differently from the DOM API. It accepts an <add> * object mapping of style properties to values. <add> * <ide> * @constructor ReactDOMComponent <ide> * @extends ReactComponent <ide> * @extends ReactMultiChild <ide> */ <del>function ReactDOMComponent(tag, omitClose) { <del> this._tagOpen = '<' + tag; <del> this._tagClose = omitClose ? '' : '</' + tag + '>'; <add>function ReactDOMComponent(tag) { <add> // TODO: DANGEROUS this tag should be sanitized. <add> this._tag = tag; <ide> this.tagName = tag.toUpperCase(); <ide> } <ide> <add>ReactDOMComponent.displayName = 'ReactDOMComponent'; <add> <ide> ReactDOMComponent.Mixin = { <ide> <ide> /** <ide> ReactDOMComponent.Mixin = { <ide> mountDepth <ide> ); <ide> assertValidProps(this.props); <add> var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>'; <ide> return ( <ide> this._createOpenTagMarkupAndPutListeners(transaction) + <ide> this._createContentMarkup(transaction) + <del> this._tagClose <add> closeTag <ide> ); <ide> } <ide> ), <ide> ReactDOMComponent.Mixin = { <ide> */ <ide> _createOpenTagMarkupAndPutListeners: function(transaction) { <ide> var props = this.props; <del> var ret = this._tagOpen; <add> var ret = '<' + this._tag; <ide> <ide> for (var propKey in props) { <ide> if (!props.hasOwnProperty(propKey)) { <ide><path>src/browser/ui/ReactDefaultInjection.js <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactComponentBrowserEnvironment = <ide> require('ReactComponentBrowserEnvironment'); <ide> var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy'); <del>var ReactDOM = require('ReactDOM'); <add>var ReactDOMComponent = require('ReactDOMComponent'); <ide> var ReactDOMButton = require('ReactDOMButton'); <ide> var ReactDOMForm = require('ReactDOMForm'); <ide> var ReactDOMImg = require('ReactDOMImg'); <ide> function inject() { <ide> BeforeInputEventPlugin: BeforeInputEventPlugin <ide> }); <ide> <del> ReactInjection.DOM.injectComponentClasses({ <del> button: ReactDOMButton, <del> form: ReactDOMForm, <del> img: ReactDOMImg, <del> input: ReactDOMInput, <del> option: ReactDOMOption, <del> select: ReactDOMSelect, <del> textarea: ReactDOMTextarea, <del> <del> html: createFullPageComponent(ReactDOM.html), <del> head: createFullPageComponent(ReactDOM.head), <del> body: createFullPageComponent(ReactDOM.body) <add> ReactInjection.NativeComponent.injectGenericComponentClass( <add> ReactDOMComponent <add> ); <add> <add> ReactInjection.NativeComponent.injectComponentClasses({ <add> 'button': ReactDOMButton, <add> 'form': ReactDOMForm, <add> 'img': ReactDOMImg, <add> 'input': ReactDOMInput, <add> 'option': ReactDOMOption, <add> 'select': ReactDOMSelect, <add> 'textarea': ReactDOMTextarea, <add> <add> 'html': createFullPageComponent('html'), <add> 'head': createFullPageComponent('head'), <add> 'body': createFullPageComponent('body') <ide> }); <ide> <ide> // This needs to happen after createFullPageComponent() otherwise the mixin <ide> function inject() { <ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); <ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); <ide> <del> ReactInjection.EmptyComponent.injectEmptyComponent(ReactDOM.noscript); <add> ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); <ide> <ide> ReactInjection.Updates.injectReconcileTransaction( <ide> ReactComponentBrowserEnvironment.ReactReconcileTransaction <ide><path>src/browser/ui/ReactInjection.js <ide> var DOMProperty = require('DOMProperty'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactCompositeComponent = require('ReactCompositeComponent'); <del>var ReactDOM = require('ReactDOM'); <ide> var ReactEmptyComponent = require('ReactEmptyComponent'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <add>var ReactNativeComponent = require('ReactNativeComponent'); <ide> var ReactPerf = require('ReactPerf'); <ide> var ReactRootIndex = require('ReactRootIndex'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> var ReactInjection = { <ide> DOMProperty: DOMProperty.injection, <ide> EmptyComponent: ReactEmptyComponent.injection, <ide> EventPluginHub: EventPluginHub.injection, <del> DOM: ReactDOM.injection, <ide> EventEmitter: ReactBrowserEventEmitter.injection, <add> NativeComponent: ReactNativeComponent.injection, <ide> Perf: ReactPerf.injection, <ide> RootIndex: ReactRootIndex.injection, <ide> Updates: ReactUpdates.injection <ide><path>src/browser/ui/ReactMount.js <ide> var ReactMount = { <ide> 'componentDidUpdate.' <ide> ); <ide> <del> var componentInstance = instantiateReactComponent(nextComponent); <add> var componentInstance = instantiateReactComponent(nextComponent, null); <ide> var reactRootID = ReactMount._registerComponent( <ide> componentInstance, <ide> container <ide><path>src/browser/ui/dom/components/createFullPageComponent.js <ide> var invariant = require('invariant'); <ide> * take advantage of React's reconciliation for styling and <title> <ide> * management. So we just document it and throw in dangerous cases. <ide> * <del> * @param {function} componentClass convenience constructor to wrap <add> * @param {string} tag The tag to wrap <ide> * @return {function} convenience constructor of new component <ide> */ <del>function createFullPageComponent(componentClass) { <del> var elementFactory = ReactDescriptor.createFactory(componentClass.type); <add>function createFullPageComponent(tag) { <add> var elementFactory = ReactDescriptor.createFactory(tag); <ide> <ide> var FullPageComponent = ReactCompositeComponent.createClass({ <del> displayName: 'ReactFullPageComponent' + ( <del> componentClass.type.displayName || '' <del> ), <add> displayName: 'ReactFullPageComponent' + tag, <ide> <ide> componentWillUnmount: function() { <ide> invariant( <ide><path>src/core/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> } <ide> <ide> this._renderedComponent = instantiateReactComponent( <del> this._renderValidatedComponent() <add> this._renderValidatedComponent(), <add> this._descriptor.type // The wrapping type <ide> ); <ide> <ide> // Done with mounting, `setState` will now trigger UI changes. <ide> var ReactCompositeComponentMixin = { <ide> var thisID = this._rootNodeID; <ide> var prevComponentID = prevComponentInstance._rootNodeID; <ide> prevComponentInstance.unmountComponent(); <del> this._renderedComponent = instantiateReactComponent(nextDescriptor); <add> this._renderedComponent = instantiateReactComponent( <add> nextDescriptor, <add> this._descriptor.type <add> ); <ide> var nextMarkup = this._renderedComponent.mountComponent( <ide> thisID, <ide> transaction, <ide><path>src/core/ReactDescriptor.js <ide> ReactDescriptor.cloneAndReplaceProps = function(oldDescriptor, newProps) { <ide> * @public <ide> */ <ide> ReactDescriptor.isValidFactory = function(factory) { <del> return typeof factory === 'function' && <del> typeof factory.type === 'function' && <del> typeof factory.type.prototype.mountComponent === 'function' && <del> typeof factory.type.prototype.receiveComponent === 'function'; <add> return typeof factory === 'function' && ( <add> typeof factory.type === 'string' || ( <add> typeof factory.type === 'function' && <add> typeof factory.type.prototype.mountComponent === 'function' && <add> typeof factory.type.prototype.receiveComponent === 'function' <add> ) <add> ); <ide> }; <ide> <ide> /** <ide><path>src/core/ReactEmptyComponent.js <ide> var nullComponentIdsRegistry = {}; <ide> <ide> var ReactEmptyComponentInjection = { <ide> injectEmptyComponent: function(emptyComponent) { <del> component = ReactDescriptor.createFactory(emptyComponent.type); <add> component = ReactDescriptor.createFactory(emptyComponent); <ide> } <ide> }; <ide> <ide><path>src/core/ReactMultiChild.js <ide> var ReactMultiChild = { <ide> if (children.hasOwnProperty(name)) { <ide> // The rendered children must be turned into instances as they're <ide> // mounted. <del> var childInstance = instantiateReactComponent(child); <add> var childInstance = instantiateReactComponent(child, null); <ide> children[name] = childInstance; <ide> // Inlined for performance, see `ReactInstanceHandles.createReactID`. <ide> var rootID = this._rootNodeID + name; <ide> var ReactMultiChild = { <ide> this._unmountChildByName(prevChild, name); <ide> } <ide> // The child must be instantiated before it's mounted. <del> var nextChildInstance = instantiateReactComponent(nextDescriptor); <add> var nextChildInstance = instantiateReactComponent( <add> nextDescriptor, <add> null <add> ); <ide> this._mountChildByNameAtIndex( <ide> nextChildInstance, name, nextIndex, transaction <ide> ); <ide><path>src/core/ReactNativeComponent.js <add>/** <add> * Copyright 2014 Facebook, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> * @providesModule ReactNativeComponent <add> */ <add> <add>"use strict"; <add> <add>var invariant = require('invariant'); <add>var mergeInto = require('mergeInto'); <add> <add>var genericComponentClass = null; <add>// This registry keeps track of wrapper classes around native tags <add>var tagToComponentClass = {}; <add> <add>var ReactNativeComponentInjection = { <add> // This accepts a class that receives the tag string. This is a catch all <add> // that can render any kind of tag. <add> injectGenericComponentClass: function(componentClass) { <add> genericComponentClass = componentClass; <add> }, <add> // This accepts a keyed object with classes as values. Each key represents a <add> // tag. That particular tag will use this class instead of the generic one. <add> injectComponentClasses: function(componentClasses) { <add> mergeInto(tagToComponentClass, componentClasses); <add> } <add>}; <add> <add>/** <add> * Create an internal class for a specific tag. <add> * <add> * @param {string} tag The tag for which to create an internal instance. <add> * @param {any} props The props passed to the instance constructor. <add> * @return {ReactComponent} component The injected empty component. <add> */ <add>function createInstanceForTag(tag, props, parentType) { <add> var componentClass = tagToComponentClass[tag]; <add> if (componentClass == null) { <add> invariant( <add> genericComponentClass, <add> 'There is no registered component for the tag %s', <add> tag <add> ); <add> return new genericComponentClass(tag, props); <add> } <add> if (parentType === tag) { <add> // Avoid recursion <add> invariant( <add> genericComponentClass, <add> 'There is no registered component for the tag %s', <add> tag <add> ); <add> return new genericComponentClass(tag, props); <add> } <add> // Unwrap legacy factories <add> return new componentClass.type(props); <add>} <add> <add>var ReactNativeComponent = { <add> createInstanceForTag: createInstanceForTag, <add> injection: ReactNativeComponentInjection, <add>}; <add> <add>module.exports = ReactNativeComponent; <ide><path>src/core/ReactPropTransferer.js <ide> var ReactPropTransferer = { <ide> 'don\'t own, %s. This usually means you are calling ' + <ide> 'transferPropsTo() on a component passed in as props or children.', <ide> this.constructor.displayName, <add> typeof descriptor.type === 'string' ? <add> descriptor.type : <ide> descriptor.type.displayName <ide> ); <ide> <ide><path>src/core/__tests__/ReactDescriptor-test.js <ide> describe('ReactDescriptor', function() { <ide> expect(typeof Component.specialType.isRequired).toBe("function"); <ide> }); <ide> <add> it('allows a DOM descriptor to be used with a string', function() { <add> var descriptor = React.createDescriptor('div', { className: 'foo' }); <add> var instance = ReactTestUtils.renderIntoDocument(descriptor); <add> expect(instance.getDOMNode().tagName).toBe('DIV'); <add> }); <add> <ide> }); <ide><path>src/core/instantiateReactComponent.js <ide> var warning = require('warning'); <ide> <ide> var ReactDescriptor = require('ReactDescriptor'); <ide> var ReactLegacyDescriptor = require('ReactLegacyDescriptor'); <add>var ReactNativeComponent = require('ReactNativeComponent'); <ide> var ReactEmptyComponent = require('ReactEmptyComponent'); <ide> <ide> /** <ide> * Given a `componentDescriptor` create an instance that will actually be <ide> * mounted. <ide> * <ide> * @param {object} descriptor <del> * @return {object} A new instance of componentDescriptor's constructor. <add> * @param {*} parentCompositeType The composite type that resolved this. <add> * @return {object} A new instance of the descriptor's constructor. <ide> * @protected <ide> */ <del>function instantiateReactComponent(descriptor) { <add>function instantiateReactComponent(descriptor, parentCompositeType) { <ide> var instance; <ide> <ide> if (__DEV__) { <ide> warning( <ide> descriptor && (typeof descriptor.type === 'function' || <ide> typeof descriptor.type === 'string'), <ide> 'Only functions or strings can be mounted as React components.' <del> // Not really strings yet, but as soon as I solve the cyclic dep, they <del> // will be allowed here. <ide> ); <ide> <ide> // Resolve mock instances <ide> function instantiateReactComponent(descriptor) { <ide> // there is no render function on the instance. We replace the whole <ide> // component with an empty component instance instead. <ide> descriptor = ReactEmptyComponent.getEmptyComponent(); <del> instance = new descriptor.type(descriptor.props); <add> } else { <add> if (render._isMockFunction && !render._getMockImplementation()) { <add> // Auto-mocked components may have a prototype with a mocked render <add> // function. For those, we'll need to mock the result of the render <add> // since we consider undefined to be invalid results from render. <add> render.mockImplementation( <add> ReactEmptyComponent.getEmptyComponent <add> ); <add> } <ide> instance.construct(descriptor); <ide> return instance; <del> } else if (render._isMockFunction && !render._getMockImplementation()) { <del> // Auto-mocked components may have a prototype with a mocked render <del> // function. For those, we'll need to mock the result of the render <del> // since we consider undefined to be invalid results from render. <del> render.mockImplementation( <del> ReactEmptyComponent.getEmptyComponent <del> ); <ide> } <del> instance.construct(descriptor); <del> return instance; <ide> } <ide> } <ide> <del> // Normal case for non-mocks <del> instance = new descriptor.type(descriptor.props); <add> // Special case string values <add> if (typeof descriptor.type === 'string') { <add> instance = ReactNativeComponent.createInstanceForTag( <add> descriptor.type, <add> descriptor.props, <add> parentCompositeType <add> ); <add> } else { <add> // Normal case for non-mocks and non-strings <add> instance = new descriptor.type(descriptor.props); <add> } <ide> <ide> if (__DEV__) { <ide> warning( <ide><path>src/test/reactComponentExpect.js <ide> mergeInto(reactComponentExpect.prototype, { <ide> <ide> toBeComponentOfType: function(convenienceConstructor) { <ide> expect( <del> this.instance().constructor === convenienceConstructor.type <add> this.instance()._descriptor.type === convenienceConstructor.type <ide> ).toBe(true); <ide> return this; <ide> }, <ide> mergeInto(reactComponentExpect.prototype, { <ide> toBeCompositeComponentWithType: function(convenienceConstructor) { <ide> this.toBeCompositeComponent(); <ide> expect( <del> this.instance().constructor === convenienceConstructor.type <add> this.instance()._descriptor.type === convenienceConstructor.type <ide> ).toBe(true); <ide> return this; <ide> },
16
Python
Python
add test to hit rankwarning in polyutils._fit
dc4cdc8c1d388c921dd732596e9130f5db79f40f
<ide><path>numpy/polynomial/tests/test_classes.py <ide> from numpy.polynomial import ( <ide> Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) <ide> from numpy.testing import ( <del> assert_almost_equal, assert_raises, assert_equal, assert_, <add> assert_almost_equal, assert_raises, assert_equal, assert_, assert_warns, <ide> ) <ide> from numpy.compat import long <del> <add>from numpy.polynomial.polyutils import RankWarning <ide> <ide> # <ide> # fixtures <ide> def test_fromroots(Poly): <ide> assert_almost_equal(p2.coef[-1], 1) <ide> <ide> <add>def test_bad_conditioned_fit(Poly): <add> <add> x = [0., 0., 1.] <add> y = [1., 2., 3.] <add> <add> # check RankWarning is raised <add> with assert_warns(RankWarning): <add> Poly.fit(x, y, 2) <add> <add> <ide> def test_fit(Poly): <ide> <ide> def f(x):
1
Mixed
Ruby
add documentation for class_attribute options
5fa6563f09cd1ee84860364195249a9f7faa26a7
<ide><path>activesupport/lib/active_support/core_ext/class/attribute.rb <ide> class Class <ide> # Declare a class-level attribute whose value is inheritable by subclasses. <ide> # Subclasses can change their own value and it will not impact parent class. <ide> # <add> # ==== Options <add> # <add> # * <tt>:instance_reader</tt> - Sets the instance reader method (defaults to true). <add> # * <tt>:instance_writer</tt> - Sets the instance writer method (defaults to true). <add> # * <tt>:instance_accessor</tt> - Sets both instance methods (defaults to true). <add> # * <tt>:instance_predicate</tt> - Sets a predicate method (defaults to true). <add> # * <tt>:default</tt> - Sets a default value for the attribute (defaults to nil). <add> # <add> # ==== Examples <add> # <ide> # class Base <ide> # class_attribute :setting <ide> # end <ide><path>guides/source/active_support_core_extensions.md <ide> The generation of the writer instance method can be prevented by setting the opt <ide> ```ruby <ide> module ActiveRecord <ide> class Base <del> class_attribute :table_name_prefix, instance_writer: false <del> self.table_name_prefix = "" <add> class_attribute :table_name_prefix, instance_writer: false, default: "my" <ide> end <ide> end <ide> ```
2
Ruby
Ruby
move renderers in to their own files
a85494dc0cba9f29e40ee910005b343ba8225434
<ide><path>actionview/lib/action_view.rb <ide> module ActionView <ide> autoload :Renderer <ide> autoload :AbstractRenderer <ide> autoload :PartialRenderer <del> autoload :CollectionRenderer, "action_view/renderer/partial_renderer" <del> autoload :ObjectRenderer, "action_view/renderer/partial_renderer" <add> autoload :CollectionRenderer <add> autoload :ObjectRenderer <ide> autoload :TemplateRenderer <ide> autoload :StreamingTemplateRenderer <ide> end <ide><path>actionview/lib/action_view/renderer/collection_renderer.rb <add># frozen_string_literal: true <add> <add>require "action_view/renderer/partial_renderer" <add> <add>module ActionView <add> class PartialIteration <add> # The number of iterations that will be done by the partial. <add> attr_reader :size <add> <add> # The current iteration of the partial. <add> attr_reader :index <add> <add> def initialize(size) <add> @size = size <add> @index = 0 <add> end <add> <add> # Check if this is the first iteration of the partial. <add> def first? <add> index == 0 <add> end <add> <add> # Check if this is the last iteration of the partial. <add> def last? <add> index == size - 1 <add> end <add> <add> def iterate! # :nodoc: <add> @index += 1 <add> end <add> end <add> <add> class CollectionRenderer < PartialRenderer # :nodoc: <add> include ObjectRendering <add> <add> class CollectionIterator # :nodoc: <add> include Enumerable <add> <add> attr_reader :collection <add> <add> def initialize(collection) <add> @collection = collection <add> end <add> <add> def each(&blk) <add> @collection.each(&blk) <add> end <add> <add> def size <add> @collection.size <add> end <add> end <add> <add> class SameCollectionIterator < CollectionIterator # :nodoc: <add> def initialize(collection, path, variables) <add> super(collection) <add> @path = path <add> @variables = variables <add> end <add> <add> def from_collection(collection) <add> return collection if collection == self <add> self.class.new(collection, @path, @variables) <add> end <add> <add> def each_with_info <add> return enum_for(:each_with_info) unless block_given? <add> variables = [@path] + @variables <add> @collection.each { |o| yield(o, variables) } <add> end <add> end <add> <add> class MixedCollectionIterator < CollectionIterator # :nodoc: <add> def initialize(collection, paths) <add> super(collection) <add> @paths = paths <add> end <add> <add> def each_with_info <add> return enum_for(:each_with_info) unless block_given? <add> collection.each_with_index { |o, i| yield(o, @paths[i]) } <add> end <add> end <add> <add> def render_collection_with_partial(collection, partial, context, block) <add> @collection = build_collection_iterator(collection, partial, context) <add> <add> if @options[:cached] && !partial <add> raise NotImplementedError, "render caching requires a template. Please specify a partial when rendering" <add> end <add> <add> template = find_template(partial, template_keys(partial)) if partial <add> <add> if !block && (layout = @options[:layout]) <add> layout = find_template(layout.to_s, template_keys(partial)) <add> end <add> <add> render_collection(context, template, partial, layout) <add> end <add> <add> def render_collection_derive_partial(collection, context, block) <add> paths = collection.map { |o| partial_path(o, context) } <add> <add> if paths.uniq.length == 1 <add> # Homogeneous <add> render_collection_with_partial(collection, paths.first, context, block) <add> else <add> render_collection_with_partial(collection, nil, context, block) <add> end <add> end <add> <add> private <add> def retrieve_variable(path) <add> vars = super <add> variable = vars.first <add> vars << :"#{variable}_counter" <add> vars << :"#{variable}_iteration" <add> vars <add> end <add> <add> def build_collection_iterator(collection, path, context) <add> if path <add> SameCollectionIterator.new(collection, path, retrieve_variable(path)) <add> else <add> paths = collection.map { |o| partial_path(o, context) } <add> paths.map! { |path| retrieve_variable(path).unshift(path) } <add> MixedCollectionIterator.new(collection, paths) <add> end <add> end <add> <add> def render_collection(view, template, path, layout) <add> identifier = (template && template.identifier) || path <add> instrument(:collection, identifier: identifier, count: @collection.size) do |payload| <add> spacer = if @options.key?(:spacer_template) <add> spacer_template = find_template(@options[:spacer_template], @locals.keys) <add> build_rendered_template(spacer_template.render(view, @locals), spacer_template) <add> else <add> RenderedTemplate::EMPTY_SPACER <add> end <add> <add> collection_body = if template <add> cache_collection_render(payload, view, template, @collection) do |collection| <add> collection_with_template(view, template, layout, collection) <add> end <add> else <add> collection_with_template(view, nil, layout, @collection) <add> end <add> <add> return RenderedCollection.empty(@lookup_context.formats.first) if collection_body.empty? <add> <add> build_rendered_collection(collection_body, spacer) <add> end <add> end <add> <add> def collection_with_template(view, template, layout, collection) <add> locals = @locals <add> cache = template || {} <add> <add> partial_iteration = PartialIteration.new(collection.size) <add> <add> collection.each_with_info.map do |object, (path, as, counter, iteration)| <add> index = partial_iteration.index <add> <add> locals[as] = object <add> locals[counter] = index <add> locals[iteration] = partial_iteration <add> <add> _template = template || (cache[path] ||= find_template(path, @locals.keys + [as, counter, iteration])) <add> content = _template.render(view, locals) <add> content = layout.render(view, locals) { content } if layout <add> partial_iteration.iterate! <add> build_rendered_template(content, _template) <add> end <add> end <add> end <add>end <ide><path>actionview/lib/action_view/renderer/object_renderer.rb <add># frozen_string_literal: true <add> <add>module ActionView <add> class ObjectRenderer < PartialRenderer # :nodoc: <add> include ObjectRendering <add> <add> def render_object_with_partial(object, partial, context, block) <add> @object = object <add> render(partial, context, block) <add> end <add> <add> def render_object_derive_partial(object, context, block) <add> path = partial_path(object, context) <add> render_object_with_partial(object, path, context, block) <add> end <add> <add> private <add> <add> def render_partial_template(view, locals, template, layout, block) <add> as = template.variable <add> locals[as] = @object <add> super(view, locals, template, layout, block) <add> end <add> end <add>end <ide><path>actionview/lib/action_view/renderer/partial_renderer.rb <ide> require "action_view/renderer/partial_renderer/collection_caching" <ide> <ide> module ActionView <del> class PartialIteration <del> # The number of iterations that will be done by the partial. <del> attr_reader :size <del> <del> # The current iteration of the partial. <del> attr_reader :index <del> <del> def initialize(size) <del> @size = size <del> @index = 0 <del> end <del> <del> # Check if this is the first iteration of the partial. <del> def first? <del> index == 0 <del> end <del> <del> # Check if this is the last iteration of the partial. <del> def last? <del> index == size - 1 <del> end <del> <del> def iterate! # :nodoc: <del> @index += 1 <del> end <del> end <del> <ide> # = Action View Partials <ide> # <ide> # There's also a convenience method for rendering sub templates within the current controller that depends on a <ide> def find_template(path, locals) <ide> @lookup_context.find_template(path, prefixes, true, locals, @details) <ide> end <ide> end <del> <del> class CollectionRenderer < PartialRenderer <del> include ObjectRendering <del> <del> class CollectionIterator # :nodoc: <del> include Enumerable <del> <del> attr_reader :collection <del> <del> def initialize(collection) <del> @collection = collection <del> end <del> <del> def each(&blk) <del> @collection.each(&blk) <del> end <del> <del> def size <del> @collection.size <del> end <del> end <del> <del> class SameCollectionIterator < CollectionIterator # :nodoc: <del> def initialize(collection, path, variables) <del> super(collection) <del> @path = path <del> @variables = variables <del> end <del> <del> def from_collection(collection) <del> return collection if collection == self <del> self.class.new(collection, @path, @variables) <del> end <del> <del> def each_with_info <del> return enum_for(:each_with_info) unless block_given? <del> variables = [@path] + @variables <del> @collection.each { |o| yield(o, variables) } <del> end <del> end <del> <del> class MixedCollectionIterator < CollectionIterator # :nodoc: <del> def initialize(collection, paths) <del> super(collection) <del> @paths = paths <del> end <del> <del> def each_with_info <del> return enum_for(:each_with_info) unless block_given? <del> collection.each_with_index { |o, i| yield(o, @paths[i]) } <del> end <del> end <del> <del> def render_collection_with_partial(collection, partial, context, block) <del> @collection = build_collection_iterator(collection, partial, context) <del> <del> if @options[:cached] && !partial <del> raise NotImplementedError, "render caching requires a template. Please specify a partial when rendering" <del> end <del> <del> template = find_template(partial, template_keys(partial)) if partial <del> <del> if !block && (layout = @options[:layout]) <del> layout = find_template(layout.to_s, template_keys(partial)) <del> end <del> <del> render_collection(context, template, partial, layout) <del> end <del> <del> def render_collection_derive_partial(collection, context, block) <del> paths = collection.map { |o| partial_path(o, context) } <del> <del> if paths.uniq.length == 1 <del> # Homogeneous <del> render_collection_with_partial(collection, paths.first, context, block) <del> else <del> render_collection_with_partial(collection, nil, context, block) <del> end <del> end <del> <del> private <del> def retrieve_variable(path) <del> vars = super <del> variable = vars.first <del> vars << :"#{variable}_counter" <del> vars << :"#{variable}_iteration" <del> vars <del> end <del> <del> def build_collection_iterator(collection, path, context) <del> if path <del> SameCollectionIterator.new(collection, path, retrieve_variable(path)) <del> else <del> paths = collection.map { |o| partial_path(o, context) } <del> paths.map! { |path| retrieve_variable(path).unshift(path) } <del> MixedCollectionIterator.new(collection, paths) <del> end <del> end <del> <del> def render_collection(view, template, path, layout) <del> identifier = (template && template.identifier) || path <del> instrument(:collection, identifier: identifier, count: @collection.size) do |payload| <del> spacer = if @options.key?(:spacer_template) <del> spacer_template = find_template(@options[:spacer_template], @locals.keys) <del> build_rendered_template(spacer_template.render(view, @locals), spacer_template) <del> else <del> RenderedTemplate::EMPTY_SPACER <del> end <del> <del> collection_body = if template <del> cache_collection_render(payload, view, template, @collection) do |collection| <del> collection_with_template(view, template, layout, collection) <del> end <del> else <del> collection_with_template(view, nil, layout, @collection) <del> end <del> <del> return RenderedCollection.empty(@lookup_context.formats.first) if collection_body.empty? <del> <del> build_rendered_collection(collection_body, spacer) <del> end <del> end <del> <del> def collection_with_template(view, template, layout, collection) <del> locals = @locals <del> cache = template || {} <del> <del> partial_iteration = PartialIteration.new(collection.size) <del> <del> collection.each_with_info.map do |object, (path, as, counter, iteration)| <del> index = partial_iteration.index <del> <del> locals[as] = object <del> locals[counter] = index <del> locals[iteration] = partial_iteration <del> <del> _template = template || (cache[path] ||= find_template(path, @locals.keys + [as, counter, iteration])) <del> content = _template.render(view, locals) <del> content = layout.render(view, locals) { content } if layout <del> partial_iteration.iterate! <del> build_rendered_template(content, _template) <del> end <del> end <del> end <del> <del> class ObjectRenderer < PartialRenderer <del> include ObjectRendering <del> <del> def render_object_with_partial(object, partial, context, block) <del> @object = object <del> render(partial, context, block) <del> end <del> <del> def render_object_derive_partial(object, context, block) <del> path = partial_path(object, context) <del> render_object_with_partial(object, path, context, block) <del> end <del> <del> private <del> <del> def render_partial_template(view, locals, template, layout, block) <del> as = template.variable <del> locals[as] = @object <del> super(view, locals, template, layout, block) <del> end <del> end <ide> end
4
Ruby
Ruby
handle empty database
1621eb0b9d296a80fb5190e28c1d2e8721fed030
<ide><path>Library/Homebrew/description_cache_store.rb <ide> def delete!(formula_name) <ide> # @return [nil] <ide> def populate_if_empty! <ide> return unless database.empty? <add> <ide> Formula.each { |f| update!(f.full_name, f.desc) } <ide> end <ide> <ide> def populate_if_empty! <ide> # @param [Report] report: an update report generated by cmd/update.rb <ide> # @return [nil] <ide> def update_from_report!(report) <add> return populate_if_empty! if database.empty? <ide> return if report.empty? <ide> <ide> renamings = report.select_formula(:R) <ide> def update_from_report!(report) <ide> # @param [Array] formula_names: the formulae to update. <ide> # @return [nil] <ide> def update_from_formula_names!(formula_names) <add> return populate_if_empty! if database.empty? <add> <ide> formula_names.each do |name| <ide> begin <ide> update!(name, Formula[name].desc) <del> rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS => e <del> p e <add> rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS <ide> delete!(name) <ide> end <ide> end <ide> def update_from_formula_names!(formula_names) <ide> # @param [Array] formula_names: the formulae to delete. <ide> # @return [nil] <ide> def delete_from_formula_names!(formula_names) <add> return if database.empty? <add> <ide> formula_names.each(&method(:delete!)) <ide> end <ide> <ide><path>Library/Homebrew/test/description_cache_store_spec.rb <ide> let(:report) { double(select_formula: [], empty?: false) } <ide> <ide> it "reads from the report" do <add> expect(database).to receive(:empty?).at_least(:once).and_return(false) <ide> cache_store.update_from_report!(report) <ide> end <ide> end <ide> desc "desc" <ide> end <ide> expect(Formulary).to receive(:factory).with(f.name).and_return(f) <add> expect(database).to receive(:empty?).and_return(false) <ide> expect(database).to receive(:set).with(f.name, f.desc) <ide> cache_store.update_from_formula_names!([f.name]) <ide> end <ide> end <ide> <ide> describe "#delete_from_formula_names!" do <ide> it "deletes the formulae descriptions" do <add> expect(database).to receive(:empty?).and_return(false) <ide> expect(database).to receive(:delete).with(formula_name) <ide> cache_store.delete_from_formula_names!([formula_name]) <ide> end
2
PHP
PHP
replace camel_case with studly_case where needed
60f329b2ec008100971a7648c72b55ab0c978a88
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function getAttributeFromArray($key) <ide> */ <ide> public function hasGetMutator($key) <ide> { <del> return method_exists($this, 'get'.camel_case($key).'Attribute'); <add> return method_exists($this, 'get'.studly_case($key).'Attribute'); <ide> } <ide> <ide> /** <ide> public function hasGetMutator($key) <ide> */ <ide> protected function mutateAttribute($key, $value) <ide> { <del> return $this->{'get'.camel_case($key).'Attribute'}($value); <add> return $this->{'get'.studly_case($key).'Attribute'}($value); <ide> } <ide> <ide> /** <ide> public function setAttribute($key, $value) <ide> // the model, such as "json_encoding" an listing of data for storage. <ide> if ($this->hasSetMutator($key)) <ide> { <del> $method = 'set'.camel_case($key).'Attribute'; <add> $method = 'set'.studly_case($key).'Attribute'; <ide> <ide> return $this->{$method}($value); <ide> } <ide> public function setAttribute($key, $value) <ide> */ <ide> public function hasSetMutator($key) <ide> { <del> return method_exists($this, 'set'.camel_case($key).'Attribute'); <add> return method_exists($this, 'set'.studly_case($key).'Attribute'); <ide> } <ide> <ide> /** <ide> public function getMutatedAttributes() <ide> <ide> if (isset(static::$mutatorCache[$class])) <ide> { <del> return static::$mutatorCache[get_class($this)]; <add> return static::$mutatorCache[get_class($this)]; <ide> } <del> <add> <ide> return array(); <ide> } <ide> <ide><path>src/Illuminate/Database/Migrations/MigrationCreator.php <ide> protected function getStub($table, $create) <ide> */ <ide> protected function populateStub($name, $stub, $table) <ide> { <del> $stub = str_replace('{{class}}', camel_case($name), $stub); <add> $stub = str_replace('{{class}}', studly_case($name), $stub); <ide> <ide> // Here we will replace the table place-holders with the table specified by <ide> // the developer, which is useful for quickly creating a tables creation <ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> public function resolve($file) <ide> { <ide> $file = implode('_', array_slice(explode('_', $file), 4)); <ide> <del> $class = camel_case($file); <add> $class = studly_case($file); <ide> <ide> return new $class; <ide> } <ide><path>src/Illuminate/Validation/Validator.php <ide> protected function parseRule($rule) <ide> $rule = substr($rule, 0, $colon); <ide> } <ide> <del> return array(camel_case($rule), $parameters); <add> return array(studly_case($rule), $parameters); <ide> } <ide> <ide> /** <ide> public function addImplicitExtensions(array $extensions) <ide> <ide> foreach ($extensions as $rule => $extension) <ide> { <del> $this->implicitRules[] = camel_case($rule); <add> $this->implicitRules[] = studly_case($rule); <ide> } <ide> } <ide> <ide> public function addImplicitExtension($rule, Closure $extension) <ide> { <ide> $this->addExtension($rule, $extension); <ide> <del> $this->implicitRules[] = camel_case($rule); <add> $this->implicitRules[] = studly_case($rule); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Workbench/Console/WorkbenchMakeCommand.php <ide> protected function callComposerUpdate($path) <ide> */ <ide> protected function buildPackage() <ide> { <del> $vendor = camel_case($this->ask('What is vendor name of the package?')); <add> $vendor = studly_case($this->ask('What is vendor name of the package?')); <ide> <del> $name = camel_case($this->ask('What is the package name?')); <add> $name = studly_case($this->ask('What is the package name?')); <ide> <ide> $author = $this->ask('What is your name?'); <ide>
5
Python
Python
add unit test for issctype
b1fb17ab7c4e6479bd4632a2407930019ca4877e
<ide><path>numpy/core/tests/test_numerictypes.py <ide> def test_abstract_type(self): <ide> def test_non_type(self): <ide> assert_raises(ValueError, np.sctype2char, 1) <ide> <add>@pytest.mark.parametrize("rep, expected", [ <add> (np.int32, True), <add> (list, False), <add> (1.1, False), <add> (str, True), <add> ]) <add>def test_issctype(rep, expected): <add> # ensure proper identification of scalar <add> # data-types by issctype() <add> actual = np.issctype(rep) <add> assert_equal(actual, expected) <add> <ide> <ide> @pytest.mark.skipif(sys.flags.optimize > 1, <ide> reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1")
1
Javascript
Javascript
defer invocation checks
65ec9f35e97c02e23c05232ac10d9192e98206be
<ide><path>test/async-hooks/test-tcpwrap.js <ide> function onconnection(c) { <ide> } <ide> <ide> function onserverClosed() { <del> checkInvocations(tcpserver, { init: 1, before: 1, after: 1, destroy: 1 }, <del> 'tcpserver when server is closed'); <ide> setImmediate(() => { <add> checkInvocations(tcpserver, { init: 1, before: 1, after: 1, destroy: 1 }, <add> 'tcpserver when server is closed'); <ide> checkInvocations(tcp1, { init: 1, before: 2, after: 2, destroy: 1 }, <ide> 'tcp1 after server is closed'); <ide> });
1
Ruby
Ruby
handle missing methods
cab0090048cc0caae1d73a74778f82dcd8ee4b2e
<ide><path>Library/Homebrew/formulary.rb <ide> def self.load_formula(name, path, contents, namespace) <ide> const_set(namespace, mod) <ide> begin <ide> mod.module_eval(contents, path) <del> rescue ArgumentError, ScriptError => e <add> rescue NoMethodError, ArgumentError, ScriptError => e <ide> raise FormulaUnreadableError.new(name, e) <ide> end <ide> class_name = class_s(name)
1
Python
Python
fix history in graph model
a6aa7940bf76aa12ed13df07c753f9b4abeaaa27
<ide><path>keras/models.py <ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> val_ins = [validation_data[name] for name in self.input_order] + [standardize_y(validation_data[name]) for name in self.output_order] + sample_weight <ide> <ide> f = self._train <del> out_labels = self.output_order <del> metrics = self.output_order + ['val_' + m for m in self.output_order] <add> out_labels = ['loss'] <add> metrics = ['loss', 'val_loss'] <ide> history = self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, <ide> verbose=verbose, callbacks=callbacks, <ide> validation_split=validation_split, val_f=val_f, val_ins=val_ins,
1
Text
Text
add readme.md (nyu-mll)
1c5cd8e5f59154905c5ae0f47a8c8905618a12ff
<ide><path>model_cards/nyu-mll/roberta-base-100M-1/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-100M-2/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-100M-3/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-10M-1/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-10M-2/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-10M-3/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-1B-1/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-1B-2/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-base-1B-3/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-med-small-1M-1/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-med-small-1M-2/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta-med-small-1M-3/README.md <add>../roberta_1M_to_1B/README.md <ide>\ No newline at end of file <ide><path>model_cards/nyu-mll/roberta_1M_to_1B/README.md <add># RoBERTa Pretrained on Smaller Datasets <add> <add>We pretrain RoBERTa on smaller datasets (1M, 10M, 100M, 1B tokens). We release 3 models with lowest perplexities for each pretraining data size out of 25 runs (or 10 in the case of 1B tokens). The pretraining data reproduces that of BERT: We combine English Wikipedia and a reproduction of BookCorpus using texts from smashwords in a ratio of approximately 3:1. <add> <add>### Hyperparameters and Validation Perplexity <add> <add>The hyperparameters and validation perplexities corresponding to each model are as follows: <add> <add>| Model Name | Training Size | Model Size | Max Steps | Batch Size | Validation Perplexity | <add>|--------------------------|---------------|------------|-----------|------------|-----------------------| <add>| [roberta-base-1B-1][link-roberta-base-1B-1] | 1B | BASE | 100K | 512 | 3.93 | <add>| [roberta-base-1B-2][link-roberta-base-1B-2] | 1B | BASE | 31K | 1024 | 4.25 | <add>| [roberta-base-1B-3][link-roberta-base-1B-3] | 1B | BASE | 31K | 4096 | 3.84 | <add>| [roberta-base-100M-1][link-roberta-base-100M-1] | 100M | BASE | 100K | 512 | 4.99 | <add>| [roberta-base-100M-2][link-roberta-base-100M-2] | 100M | BASE | 31K | 1024 | 4.61 | <add>| [roberta-base-100M-3][link-roberta-base-100M-3] | 100M | BASE | 31K | 512 | 5.02 | <add>| [roberta-base-10M-1][link-roberta-base-10M-1] | 10M | BASE | 10K | 1024 | 11.31 | <add>| [roberta-base-10M-2][link-roberta-base-10M-2] | 10M | BASE | 10K | 512 | 10.78 | <add>| [roberta-base-10M-3][link-roberta-base-10M-3] | 10M | BASE | 31K | 512 | 11.58 | <add>| [roberta-med-small-1M-1][link-roberta-med-small-1M-1] | 1M | MED-SMALL | 100K | 512 | 153.38 | <add>| [roberta-med-small-1M-2][link-roberta-med-small-1M-2] | 1M | MED-SMALL | 10K | 512 | 134.18 | <add>| [roberta-med-small-1M-3][link-roberta-med-small-1M-3] | 1M | MED-SMALL | 31K | 512 | 139.39 | <add> <add>The hyperparameters corresponding to model sizes mentioned above are as follows: <add> <add>| Model Size | L | AH | HS | FFN | P | <add>|------------|----|----|-----|------|------| <add>| BASE | 12 | 12 | 768 | 3072 | 125M | <add>| MED-SMALL | 6 | 8 | 512 | 2048 | 45M | <add> <add>(AH = number of attention heads; HS = hidden size; FFN = feedforward network dimension; P = number of parameters.) <add> <add>For other hyperparameters, we select: <add>- Peak Learning rate: 5e-4 <add>- Warmup Steps: 6% of max steps <add>- Dropout: 0.1 <add> <add>[link-roberta-med-small-1M-1]: https://huggingface.co/nyu-mll/roberta-med-small-1M-1 <add>[link-roberta-med-small-1M-2]: https://huggingface.co/nyu-mll/roberta-med-small-1M-2 <add>[link-roberta-med-small-1M-3]: https://huggingface.co/nyu-mll/roberta-med-small-1M-3 <add>[link-roberta-base-10M-1]: https://huggingface.co/nyu-mll/roberta-base-10M-1 <add>[link-roberta-base-10M-2]: https://huggingface.co/nyu-mll/roberta-base-10M-2 <add>[link-roberta-base-10M-3]: https://huggingface.co/nyu-mll/roberta-base-10M-3 <add>[link-roberta-base-100M-1]: https://huggingface.co/nyu-mll/roberta-base-100M-1 <add>[link-roberta-base-100M-2]: https://huggingface.co/nyu-mll/roberta-base-100M-2 <add>[link-roberta-base-100M-3]: https://huggingface.co/nyu-mll/roberta-base-100M-3 <add>[link-roberta-base-1B-1]: https://huggingface.co/nyu-mll/roberta-base-1B-1 <add>[link-roberta-base-1B-2]: https://huggingface.co/nyu-mll/roberta-base-1B-2 <add>[link-roberta-base-1B-3]: https://huggingface.co/nyu-mll/roberta-base-1B-3
13
Python
Python
check clip for byteorder
0b26cf1b2b4d82fc88708733b453aa4699e4145f
<ide><path>numpy/core/tests/test_multiarray.py <ide> def _check_range(self,x,cmin,cmax): <ide> assert N.all(x >= cmin) <ide> assert N.all(x <= cmax) <ide> <del> def _clip_type(self,type_group,amax,cmin,cmax,inplace=False): <add> def _clip_type(self,type_group,array_max, <add> clip_min,clip_max,inplace=False, <add> expected_min=None,expected_max=None): <add> if expected_min is None: <add> expected_min = clip_min <add> if expected_max is None: <add> expected_max = clip_max <add> <ide> for T in N.sctypes[type_group]: <del> x = (N.random.random(1000) * amax).astype(T) <del> if inplace: <del> x.clip(cmin,cmax,x) <add> if sys.byteorder == 'little': <add> byte_orders = ['=','>'] <ide> else: <del> x = x.clip(cmin,cmax) <add> byte_orders = ['<','='] <add> <add> for byteorder in byte_orders: <add> dtype = N.dtype(T).newbyteorder(byteorder) <add> if dtype.byteorder == '|': byteorder = '|' <add> <add> x = (N.random.random(1000) * array_max).astype(dtype) <add> if inplace: <add> x.clip(clip_min,clip_max,x) <add> else: <add> x = x.clip(clip_min,clip_max) <ide> <del> self._check_range(x,cmin,cmax) <del> return x <add> assert_equal(byteorder,x.dtype.byteorder) <add> self._check_range(x,expected_min,expected_max) <add> return x <ide> <ide> def check_basic(self): <ide> for inplace in [False]: # XXX fixme -> ,True]: <ide> def check_basic(self): <ide> self._clip_type('int',1024,0,0) <ide> <ide> # XXX fixme <del> #x = self._check_type('uint',1024,-120,100) <del> #assert N.all(x >= 0) <add> #x = self._check_type('uint',1024,-120,100,expected_min=0) <ide> x = self._clip_type('uint',1024,0,0) <ide> <ide> # Import tests from unicode
1
Ruby
Ruby
use strip instead of chomp.chomp
f231a8b07962d5307c16316106a294dbfa98dba7
<ide><path>Library/Homebrew/utils.rb <ide> def xctoolchain_path <ide> def sdk_path(v=MacOS.version) <ide> # The path of the MacOSX SDK. <ide> if !MacOS.xctools_fucked? and File.directory? `xcode-select -print-path`.chomp <del> path = `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp.chomp <add> path = `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.strip <ide> elsif File.directory? '/Developer/SDKs/MacOS#{v}.sdk' <ide> # the old default (or wild wild west style) <ide> path = "/Developer/SDKs/MacOS#{v}.sdk"
1
Javascript
Javascript
use common.port instead of hardcoded port number
debdc1dbb6851a0c341d58efe50d34a79807278a
<ide><path>test/sequential/test-debugger-invalid-args.js <ide> const { createServer } = require('net'); <ide> <ide> // Launch w/ invalid host:port. <ide> { <del> const cli = startCLI(['localhost:914']); <add> const cli = startCLI([`localhost:${common.PORT}`]); <ide> cli.quit() <ide> .then((code) => { <ide> assert.match(
1
Javascript
Javascript
change misleading variable name
7abbbf2ff32b14da47ee4a8e345adb6e424b8689
<ide><path>test/pummel/test-crypto-dh-hash.js <ide> const hashes = { <ide> <ide> for (const name in hashes) { <ide> const group = crypto.getDiffieHellman(name); <del> const private_key = group.getPrime('hex'); <add> const prime = group.getPrime('hex'); <ide> const hash1 = hashes[name]; <ide> const hash2 = crypto.createHash('sha1') <del> .update(private_key.toUpperCase()).digest('hex'); <add> .update(prime.toUpperCase()).digest('hex'); <ide> assert.strictEqual(hash1, hash2); <ide> assert.strictEqual(group.getGenerator('hex'), '02'); <ide> }
1
Ruby
Ruby
extract transliteration code to a seperate method
a4629e707d80a5769f7a71ca6ed9471015e14dc9
<ide><path>activesupport/lib/active_support/inflector.rb <ide> require 'singleton' <add>require 'iconv' <ide> <ide> module ActiveSupport <ide> # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, <ide> def demodulize(class_name_in_module) <ide> # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> <ide> def parameterize(string, sep = '-') <ide> re_sep = Regexp.escape(sep) <del> string.mb_chars.normalize(:kd). # Decompose accented characters <del> gsub(/[^\x00-\x7F]+/, ''). # Remove anything non-ASCII entirely (e.g. diacritics). <add> transliterate(string). <ide> gsub(/[^a-z0-9\-_\+]+/i, sep). # Turn unwanted chars into the separator. <ide> squeeze(sep). # No more than one of the separator in a row. <ide> gsub(/^#{re_sep}|#{re_sep}$/i, ''). # Remove leading/trailing separator. <ide> downcase <ide> end <ide> <add> <add> # Replaces accented characters with their ascii equivalents. <add> def transliterate(string) <add> Iconv.iconv('ascii//translit//IGNORE', 'utf-8', string).to_s <add> end <add> <add> # The iconv transliteration code doesn't function correctly <add> # on some platforms, but it's very fast where it does function. <add> if "foo" != Inflector.transliterate("föö") <add> def transliterate(string) <add> string.mb_chars.normalize(:kd). # Decompose accented characters <add> gsub(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics). <add> end <add> end <add> <ide> # Create the name of a table like Rails does for models to table names. This method <ide> # uses the +pluralize+ method on the last word in the string. <ide> #
1
Text
Text
add v3.24.2 to changelog.md
aa2594b09b8ce8e2df794aa46a1f86d03442ca43
<ide><path>CHANGELOG.md <ide> - [#19338](https://github.com/emberjs/ember.js/pull/19338) [BUGFIX] Add missing `deprecate` options (`for` + `since`) <ide> - [#19342](https://github.com/emberjs/ember.js/pull/19342) [BUGFIX] Fix misleading LinkTo error message <ide> <add>### v3.24.2 (February 10, 2021) <add> <add>- [#19326](https://github.com/emberjs/ember.js/pull/19326) / [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] Fix usage of `<LinkTo />` prior to routing (e.g. component rendering tests) <add> <ide> ### v3.24.1 (January 14, 2021) <ide> <ide> - [#19337](https://github.com/emberjs/ember.js/pull/19337) [BUGFIX] Ensure query param only `<LinkTo />` are properly scoped in engines
1
Mixed
Go
add filter for `network ls` to hide predefined net
26dd026bd70c9c18a16b0e339821c309e56d8ff0
<ide><path>api/client/client.go <ide> type apiClient interface { <ide> NetworkCreate(options types.NetworkCreate) (types.NetworkCreateResponse, error) <ide> NetworkDisconnect(networkID, containerID string) error <ide> NetworkInspect(networkID string) (types.NetworkResource, error) <del> NetworkList() ([]types.NetworkResource, error) <add> NetworkList(options types.NetworkListOptions) ([]types.NetworkResource, error) <ide> NetworkRemove(networkID string) error <ide> RegistryLogin(auth types.AuthConfig) (types.AuthResponse, error) <ide> ServerVersion() (types.Version, error) <ide><path>api/client/lib/network.go <ide> package lib <ide> import ( <ide> "encoding/json" <ide> "net/http" <add> "net/url" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <ide> ) <ide> <ide> // NetworkCreate creates a new network in the docker host. <ide> func (cli *Client) NetworkDisconnect(networkID, containerID string) error { <ide> } <ide> <ide> // NetworkList returns the list of networks configured in the docker host. <del>func (cli *Client) NetworkList() ([]types.NetworkResource, error) { <add>func (cli *Client) NetworkList(options types.NetworkListOptions) ([]types.NetworkResource, error) { <add> query := url.Values{} <add> if options.Filters.Len() > 0 { <add> filterJSON, err := filters.ToParam(options.Filters) <add> if err != nil { <add> return nil, err <add> } <add> <add> query.Set("filters", filterJSON) <add> } <ide> var networkResources []types.NetworkResource <del> resp, err := cli.get("/networks", nil, nil) <add> resp, err := cli.get("/networks", query, nil) <ide> if err != nil { <ide> return networkResources, err <ide> } <ide><path>api/client/network.go <ide> import ( <ide> "text/tabwriter" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/api/types/network" <ide> Cli "github.com/docker/docker/cli" <ide> "github.com/docker/docker/opts" <ide> func (cli *DockerCli) CmdNetworkLs(args ...string) error { <ide> quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs") <ide> noTrunc := cmd.Bool([]string{"-no-trunc"}, false, "Do not truncate the output") <ide> <add> flFilter := opts.NewListOpts(nil) <add> cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") <add> <ide> cmd.Require(flag.Exact, 0) <del> if err := cmd.ParseFlags(args, true); err != nil { <add> err := cmd.ParseFlags(args, true) <add> if err != nil { <ide> return err <ide> } <ide> <del> networkResources, err := cli.client.NetworkList() <add> // Consolidate all filter flags, and sanity check them early. <add> // They'll get process after get response from server. <add> netFilterArgs := filters.NewArgs() <add> for _, f := range flFilter.GetAll() { <add> if netFilterArgs, err = filters.ParseFlag(f, netFilterArgs); err != nil { <add> return err <add> } <add> } <add> <add> options := types.NetworkListOptions{ <add> Filters: netFilterArgs, <add> } <add> <add> networkResources, err := cli.client.NetworkList(options) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/server/router/network/backend.go <ide> type Backend interface { <ide> FindNetwork(idName string) (libnetwork.Network, error) <ide> GetNetwork(idName string, by int) (libnetwork.Network, error) <ide> GetNetworksByID(partialID string) []libnetwork.Network <add> GetAllNetworks() []libnetwork.Network <ide> CreateNetwork(name, driver string, ipam network.IPAM, <ide> options map[string]string) (libnetwork.Network, error) <ide> ConnectContainerToNetwork(containerName, networkName string) error <ide><path>api/server/router/network/filter.go <add>package network <add> <add>import ( <add> "fmt" <add> "regexp" <add> "strings" <add> <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/runconfig" <add> "github.com/docker/libnetwork" <add>) <add> <add>type filterHandler func([]libnetwork.Network, string) ([]libnetwork.Network, error) <add> <add>var ( <add> // supportedFilters predefined some supported filter handler function <add> supportedFilters = map[string]filterHandler{ <add> "type": filterNetworkByType, <add> "name": filterNetworkByName, <add> "id": filterNetworkByID, <add> } <add> <add> // acceptFilters is an acceptable filter flag list <add> // generated for validation. e.g. <add> // acceptedFilters = map[string]bool{ <add> // "type": true, <add> // "name": true, <add> // "id": true, <add> // } <add> acceptedFilters = func() map[string]bool { <add> ret := make(map[string]bool) <add> for k := range supportedFilters { <add> ret[k] = true <add> } <add> return ret <add> }() <add>) <add> <add>func filterNetworkByType(nws []libnetwork.Network, netType string) (retNws []libnetwork.Network, err error) { <add> switch netType { <add> case "builtin": <add> for _, nw := range nws { <add> if runconfig.IsPreDefinedNetwork(nw.Name()) { <add> retNws = append(retNws, nw) <add> } <add> } <add> case "custom": <add> for _, nw := range nws { <add> if !runconfig.IsPreDefinedNetwork(nw.Name()) { <add> retNws = append(retNws, nw) <add> } <add> } <add> default: <add> return nil, fmt.Errorf("Invalid filter: 'type'='%s'", netType) <add> } <add> return retNws, nil <add>} <add> <add>func filterNetworkByName(nws []libnetwork.Network, name string) (retNws []libnetwork.Network, err error) { <add> for _, nw := range nws { <add> // exact match (fast path) <add> if nw.Name() == name { <add> retNws = append(retNws, nw) <add> continue <add> } <add> <add> // regexp match (slow path) <add> match, err := regexp.MatchString(name, nw.Name()) <add> if err != nil || !match { <add> continue <add> } else { <add> retNws = append(retNws, nw) <add> } <add> } <add> return retNws, nil <add>} <add> <add>func filterNetworkByID(nws []libnetwork.Network, id string) (retNws []libnetwork.Network, err error) { <add> for _, nw := range nws { <add> if strings.HasPrefix(nw.ID(), id) { <add> retNws = append(retNws, nw) <add> } <add> } <add> return retNws, nil <add>} <add> <add>// filterAllNetworks filter network list according to user specified filter <add>// and return user chosen networks <add>func filterNetworks(nws []libnetwork.Network, filter filters.Args) ([]libnetwork.Network, error) { <add> // if filter is empty, return original network list <add> if filter.Len() == 0 { <add> return nws, nil <add> } <add> <add> var displayNet []libnetwork.Network <add> for fkey, fhandler := range supportedFilters { <add> errFilter := filter.WalkValues(fkey, func(fval string) error { <add> passList, err := fhandler(nws, fval) <add> if err != nil { <add> return err <add> } <add> displayNet = append(displayNet, passList...) <add> return nil <add> }) <add> if errFilter != nil { <add> return nil, errFilter <add> } <add> } <add> return displayNet, nil <add>} <ide><path>api/server/router/network/network_routes.go <ide> import ( <ide> <ide> "golang.org/x/net/context" <ide> <del> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> func (n *networkRouter) getNetworksList(ctx context.Context, w http.ResponseWrit <ide> return err <ide> } <ide> <del> list := []*types.NetworkResource{} <del> netFilters.WalkValues("name", func(name string) error { <del> if nw, err := n.backend.GetNetwork(name, daemon.NetworkByName); err == nil { <del> list = append(list, buildNetworkResource(nw)) <del> } else { <del> logrus.Errorf("failed to get network for filter=%s : %v", name, err) <add> if netFilters.Len() != 0 { <add> if err := netFilters.Validate(acceptedFilters); err != nil { <add> return err <ide> } <del> return nil <del> }) <add> } <ide> <del> netFilters.WalkValues("id", func(id string) error { <del> for _, nw := range n.backend.GetNetworksByID(id) { <del> list = append(list, buildNetworkResource(nw)) <del> } <del> return nil <del> }) <add> list := []*types.NetworkResource{} <ide> <del> if !netFilters.Include("name") && !netFilters.Include("id") { <del> nwList := n.backend.GetNetworksByID("") <del> for _, nw := range nwList { <del> list = append(list, buildNetworkResource(nw)) <del> } <add> nwList := n.backend.GetAllNetworks() <add> displayable, err := filterNetworks(nwList, netFilters) <add> if err != nil { <add> return err <ide> } <add> <add> for _, nw := range displayable { <add> list = append(list, buildNetworkResource(nw)) <add> } <add> <ide> return httputils.WriteJSON(w, http.StatusOK, list) <ide> } <ide> <ide><path>api/types/client.go <ide> type EventsOptions struct { <ide> Filters filters.Args <ide> } <ide> <add>// NetworkListOptions holds parameters to filter the list of networks with. <add>type NetworkListOptions struct { <add> Filters filters.Args <add>} <add> <ide> // HijackedResponse holds connection information for a hijacked request. <ide> type HijackedResponse struct { <ide> Conn net.Conn <ide><path>daemon/network.go <ide> func (daemon *Daemon) GetNetworksByID(partialID string) []libnetwork.Network { <ide> return list <ide> } <ide> <add>// GetAllNetworks returns a list containing all networks <add>func (daemon *Daemon) GetAllNetworks() []libnetwork.Network { <add> c := daemon.netController <add> list := []libnetwork.Network{} <add> l := func(nw libnetwork.Network) bool { <add> list = append(list, nw) <add> return false <add> } <add> c.WalkNetworks(l) <add> <add> return list <add>} <add> <ide> // CreateNetwork creates a network with the given name, driver and other optional parameters <ide> func (daemon *Daemon) CreateNetwork(name, driver string, ipam network.IPAM, options map[string]string) (libnetwork.Network, error) { <ide> c := daemon.netController <ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> the push or pull completes. <ide> * `POST /containers/create` now allows you to set a read/write rate limit for a <ide> device (in bytes per second or IO per second). <add>* `GET /networks` now supports filtering by `name`, `id` and `type`. <ide> <ide> ### v1.21 API changes <ide> <ide><path>docs/reference/api/docker_remote_api_v1.22.md <ide> Status Codes <ide> <ide> **Example request**: <ide> <del> GET /networks HTTP/1.1 <add> GET /networks?filters={"type":{"custom":true}} HTTP/1.1 <ide> <ide> **Example response**: <ide> <ide> Content-Type: application/json <ide> ] <ide> ``` <ide> <del> <del> <ide> Query Parameters: <ide> <del>- **filters** - JSON encoded value of the filters (a `map[string][]string`) to process on the networks list. Available filters: `name=[network-names]` , `id=[network-ids]` <add>- **filters** - JSON encoded network list filter. The filter value is one of: <add> - `name=<network-name>` Matches all or part of a network name. <add> - `id=<network-id>` Matches all or part of a network id. <add> - `type=["custom"|"builtin"]` Filters networks by type. The `custom` keyword returns all user-defined networks. <ide> <ide> Status Codes: <ide> <ide><path>docs/reference/commandline/network_ls.md <ide> parent = "smn_cli" <ide> Usage: docker network ls [OPTIONS] <ide> <ide> Lists all the networks created by the user <add> -f, --filter=[] Filter output based on conditions provided <ide> --help=false Print usage <ide> --no-trunc=false Do not truncate the output <ide> -q, --quiet=false Only display numeric IDs <ide> NETWORK ID NAME <ide> c288470c46f6c8949c5f7e5099b5b7947b07eabe8d9a27d79a9cbf111adcbf47 host host <ide> 7b369448dccbf865d397c8d2be0cda7cf7edc6b0945f77d2529912ae917a0185 bridge bridge <ide> 95e74588f40db048e86320c6526440c504650a1ff3e9f7d60a497c4d2163e5bd foo bridge <add>63d1ff1f77b07ca51070a8c227e962238358bd310bde1529cf62e6c307ade161 dev bridge <ide> ``` <ide> <add>## Filtering <add> <add>The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there <add>is more than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`). <add>Multiple filter flags are combined as an `OR` filter. For example, <add>`-f type=custom -f type=builtin` returns both `custom` and `builtin` networks. <add> <add>The currently supported filters are: <add> <add>* id (network's id) <add>* name (network's name) <add>* type (custom|builtin) <add> <add>#### Type <add> <add>The `type` filter supports two values; `builtin` displays predefined networks <add>(`bridge`, `none`, `host`), whereas `custom` displays user defined networks. <add> <add>The following filter matches all user defined networks: <add> <add>```bash <add>$ docker network ls --filter type=custom <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add>63d1ff1f77b0 dev bridge <add>``` <add> <add>By having this flag it allows for batch cleanup. For example, use this filter <add>to delete all user defined networks: <add> <add>```bash <add>$ docker network rm `docker network ls --filter type=custom -q` <add>``` <add> <add>A warning will be issued when trying to remove a network that has containers <add>attached. <add> <add>#### Name <add> <add>The `name` filter matches on all or part of a network's name. <add> <add>The following filter matches all networks with a name containing the `foobar` string. <add> <add>```bash <add>$ docker network ls --filter name=foobar <add>NETWORK ID NAME DRIVER <add>06e7eef0a170 foobar bridge <add>``` <add> <add>You can also filter for a substring in a name as this shows: <add> <add>```bash <add>$ docker ps --filter name=foo <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add>06e7eef0a170 foobar bridge <add>``` <add> <add>#### ID <add> <add>The `id` filter matches on all or part of a network's ID. <add> <add>The following filter matches all networks with a name containing the <add>`06e7eef01700` string. <add> <add>```bash <add>$ docker network ls --filter id=63d1ff1f77b07ca51070a8c227e962238358bd310bde1529cf62e6c307ade161 <add>NETWORK ID NAME DRIVER <add>63d1ff1f77b0 dev bridge <add>``` <add> <add>You can also filter for a substring in a ID as this shows: <add> <add>```bash <add>$ docker ps --filter id=95e74588f40d <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add> <add>$ docker ps --filter id=95e <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add>``` <ide> <ide> ## Related information <ide> <ide><path>integration-cli/docker_cli_network_unix_test.go <ide> import ( <ide> "net/http" <ide> "net/http/httptest" <ide> "os" <add> "sort" <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <ide> func isNwPresent(c *check.C, name string) bool { <ide> return false <ide> } <ide> <add>// assertNwList checks network list retrived with ls command <add>// equals to expected network list <add>// note: out should be `network ls [option]` result <add>func assertNwList(c *check.C, out string, expectNws []string) { <add> lines := strings.Split(out, "\n") <add> var nwList []string <add> for _, line := range lines[1 : len(lines)-1] { <add> netFields := strings.Fields(line) <add> // wrap all network name in nwList <add> nwList = append(nwList, netFields[1]) <add> } <add> // first need to sort out and expected <add> sort.StringSlice(nwList).Sort() <add> sort.StringSlice(expectNws).Sort() <add> <add> // network ls should contains all expected networks <add> c.Assert(nwList, checker.DeepEquals, expectNws) <add>} <add> <ide> func getNwResource(c *check.C, name string) *types.NetworkResource { <ide> out, _ := dockerCmd(c, "network", "inspect", name) <ide> nr := []types.NetworkResource{} <ide> func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) { <add> out, _ := dockerCmd(c, "network", "create", "dev") <add> defer func() { <add> dockerCmd(c, "network", "rm", "dev") <add> }() <add> containerID := strings.TrimSpace(out) <add> <add> // filter with partial ID and partial name <add> // only show 'bridge' and 'dev' network <add> out, _ = dockerCmd(c, "network", "ls", "-f", "id="+containerID[0:5], "-f", "name=dge") <add> assertNwList(c, out, []string{"dev", "bridge"}) <add> <add> // only show built-in network (bridge, none, host) <add> out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin") <add> assertNwList(c, out, []string{"bridge", "none", "host"}) <add> <add> // only show custom networks (dev) <add> out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom") <add> assertNwList(c, out, []string{"dev"}) <add> <add> // show all networks with filter <add> // it should be equivalent of ls without option <add> out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin") <add> assertNwList(c, out, []string{"dev", "bridge", "host", "none"}) <add>} <add> <ide> func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) { <ide> dockerCmd(c, "network", "create", "test") <ide> assertNwIsAvailable(c, "test") <ide><path>man/docker-network-ls.1.md <ide> docker-network-ls - list networks <ide> <ide> # SYNOPSIS <ide> **docker network ls** <add>[**-f**|**--filter**[=*[]*]] <ide> [**--no-trunc**[=*true*|*false*]] <ide> [**-q**|**--quiet**[=*true*|*false*]] <ide> [**--help**] <ide> Lists all the networks the Engine `daemon` knows about. This includes the <ide> networks that span across multiple hosts in a cluster, for example: <ide> <ide> ```bash <del> $ sudo docker network ls <add> $ docker network ls <ide> NETWORK ID NAME DRIVER <ide> 7fca4eb8c647 bridge bridge <ide> 9f904ee27bf5 none null <ide> networks that span across multiple hosts in a cluster, for example: <ide> Use the `--no-trunc` option to display the full network id: <ide> <ide> ```bash <del>docker network ls --no-trunc <add>$ docker network ls --no-trunc <ide> NETWORK ID NAME DRIVER <ide> 18a2866682b85619a026c81b98a5e375bd33e1b0936a26cc497c283d27bae9b3 none null <ide> c288470c46f6c8949c5f7e5099b5b7947b07eabe8d9a27d79a9cbf111adcbf47 host host <ide> 7b369448dccbf865d397c8d2be0cda7cf7edc6b0945f77d2529912ae917a0185 bridge bridge <ide> 95e74588f40db048e86320c6526440c504650a1ff3e9f7d60a497c4d2163e5bd foo bridge <add>63d1ff1f77b07ca51070a8c227e962238358bd310bde1529cf62e6c307ade161 dev bridge <add>``` <add> <add>## Filtering <add> <add>The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there <add>is more than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`). <add>Multiple filter flags are combined as an `OR` filter. For example, <add>`-f type=custom -f type=builtin` returns both `custom` and `builtin` networks. <add> <add>The currently supported filters are: <add> <add>* id (network's id) <add>* name (network's name) <add>* type (custom|builtin) <add> <add>#### Type <add> <add>The `type` filter supports two values; `builtin` displays predefined networks <add>(`bridge`, `none`, `host`), whereas `custom` displays user defined networks. <add> <add>The following filter matches all user defined networks: <add> <add>```bash <add>$ docker network ls --filter type=custom <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add>63d1ff1f77b0 dev bridge <add>``` <add> <add>By having this flag it allows for batch cleanup. For example, use this filter <add>to delete all user defined networks: <add> <add>```bash <add>$ docker network rm `docker network ls --filter type=custom -q` <add>``` <add> <add>A warning will be issued when trying to remove a network that has containers <add>attached. <add> <add>#### Name <add> <add>The `name` filter matches on all or part of a network's name. <add> <add>The following filter matches all networks with a name containing the `foobar` string. <add> <add>```bash <add>$ docker network ls --filter name=foobar <add>NETWORK ID NAME DRIVER <add>06e7eef0a170 foobar bridge <add>``` <add> <add>You can also filter for a substring in a name as this shows: <add> <add>```bash <add>$ docker ps --filter name=foo <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add>06e7eef0a170 foobar bridge <add>``` <add> <add>#### ID <add> <add>The `id` filter matches on all or part of a network's ID. <add> <add>The following filter matches all networks with a name containing the <add>`06e7eef01700` string. <add> <add>```bash <add>$ docker network ls --filter id=63d1ff1f77b07ca51070a8c227e962238358bd310bde1529cf62e6c307ade161 <add>NETWORK ID NAME DRIVER <add>63d1ff1f77b0 dev bridge <add>``` <add> <add>You can also filter for a substring in a ID as this shows: <add> <add>```bash <add>$ docker ps --filter id=95e74588f40d <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <add> <add>$ docker ps --filter id=95e <add>NETWORK ID NAME DRIVER <add>95e74588f40d foo bridge <ide> ``` <ide> <ide> # OPTIONS <ide> <add>**-f**, **--filter**=*[]* <add> filter output based on conditions provided. <add> <ide> **--no-trunc**=*true*|*false* <ide> Do not truncate the output <ide>
13
Javascript
Javascript
improve error message for unregistered callbacks
fd2cf119b13af65dbaeed9c5a6a34cfd27ef06af
<ide><path>Libraries/Utilities/MessageQueue.js <ide> class MessageQueue { <ide> let debug = this._debugInfo[cbID >> 1]; <ide> let module = debug && this._remoteModuleTable[debug[0]]; <ide> let method = debug && this._remoteMethodTable[debug[0]][debug[1]]; <del> invariant( <del> callback, <del> `Callback with id ${cbID}: ${module}.${method}() not found` <del> ); <add> if (!callback) { <add> let errorMessage = `Callback with id ${cbID}: ${module}.${method}() not found`; <add> if (method) { <add> errorMessage = `The callback ${method}() exists in module ${module}, ` <add> + `but only one callback may be registered to a function in a native module.`; <add> } <add> invariant( <add> callback, <add> errorMessage <add> ); <add> } <ide> let profileName = debug ? '<callback for ' + module + '.' + method + '>' : cbID; <ide> if (callback && SPY_MODE && __DEV__) { <ide> console.log('N->JS : ' + profileName + '(' + JSON.stringify(args) + ')');
1
Javascript
Javascript
filter more characters on font name
4275a68e2982840c201e3a5a43839603ca034d13
<ide><path>pdf.js <ide> var PartialEvaluator = (function() { <ide> <ide> var fontName = descriptor.get('FontName'); <ide> assertWellFormed(IsName(fontName), 'invalid font name'); <del> fontName = fontName.name.replace('+', '_'); <add> fontName = fontName.name.replace(/[\+,\-]/g, '_'); <ide> <ide> var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3'); <ide> if (!fontFile)
1
Javascript
Javascript
add a version class to the player
ae423df4f56ae15bb105a8016822244d2bb7f9e1
<ide><path>src/js/player.js <ide> class Player extends Component { <ide> // Make player easily findable by ID <ide> Player.players[this.id_] = this; <ide> <add> // Add a major version class to aid css in plugins <add> const majorVersion = require('../../package.json').version.split('.')[0]; <add> <add> this.addClass(`vjs-v${majorVersion}`); <add> <ide> // When the player is first initialized, trigger activity so components <ide> // like the control bar show themselves if needed <ide> this.userActive(true); <ide><path>test/unit/player.test.js <ide> QUnit.test('options: plugins', function(assert) { <ide> player.dispose(); <ide> Plugin.deregisterPlugin('foo'); <ide> }); <add> <add>QUnit.test('should add a class with major version', function(assert) { <add> const majorVersion = require('../../package.json').version.split('.')[0]; <add> const player = TestHelpers.makePlayer(); <add> <add> assert.ok(player.hasClass('vjs-v' + majorVersion), 'the version class should be added to the player'); <add> <add> player.dispose(); <add>});
2
Ruby
Ruby
remove datetime#to_time override
c685d12c19f953768ee445ab29faeb4a1be54535
<ide><path>activesupport/lib/active_support/core_ext/date_time/conversions.rb <ide> require 'active_support/values/time_zone' <ide> <ide> class DateTime <del> # Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows <del> # DateTimes outside the range of what can be created with Time. <del> remove_method :to_time <del> <ide> # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats. <ide> # <ide> # This method is aliased to <tt>to_s</tt>. <ide> def readable_inspect <ide> alias_method :default_inspect, :inspect <ide> alias_method :inspect, :readable_inspect <ide> <del> # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class. <del> # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time. <del> def to_time <del> if offset == 0 <del> ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * 1000000) <del> else <del> self <del> end <del> end <del> <ide> # Returns DateTime with local offset for given year if format is local else offset is zero <ide> # <ide> # DateTime.civil_from_format :local, 2012
1
Javascript
Javascript
remove csrf from api calls
cda2fe768bc1d7ae5cd24588557693adc0c83213
<ide><path>server/middlewares/csurf.js <ide> import csurf from 'csurf'; <ide> <ide> export default function() { <del> return csurf({ cookie: true }); <add> const protection = csurf({ cookie: true }); <add> return function csrf(req, res, next) { <add> const path = req.path.split('/')[1]; <add> if (/api/.test(path)) { <add> return next(); <add> } <add> return protection(req, res, next); <add> }; <ide> } <ide><path>server/middlewares/global-locals.js <ide> export default function globalLocals() { <ide> return function(req, res, next) { <ide> // Make user object available in templates. <ide> res.locals.user = req.user; <del> res.locals._csrf = req.csrfToken(); <add> res.locals._csrf = req.csrfToken ? req.csrfToken() : null; <ide> next(); <ide> }; <ide> }
2
Python
Python
use kombu disable_insecure_serializers
b51d3ed21953114e78bb1e64d15bffd81daa8009
<ide><path>celery/security/__init__.py <ide> """ <ide> from __future__ import absolute_import <ide> <del>from kombu.serialization import registry <add>from kombu.serialization import ( <add> registry, disable_insecure_serializers as _disable_insecure_serializers, <add>) <ide> <ide> from celery.exceptions import ImproperlyConfigured <ide> <ide> Please see the configuration reference for more information. <ide> """ <ide> <del> <del>def disable_untrusted_serializers(whitelist=None): <del> for name in set(registry._decoders) - set(whitelist or []): <del> registry.disable(name) <del> for name in whitelist or []: <del> registry.enable(name) <add>__all__ = ['setup_security'] <ide> <ide> <ide> def setup_security(allowed_serializers=None, key=None, cert=None, store=None, <ide> def setup_security(allowed_serializers=None, key=None, cert=None, store=None, <ide> from celery import current_app <ide> app = current_app._get_current_object() <ide> <del> disable_untrusted_serializers(allowed_serializers) <add> _disable_insecure_serializers(allowed_serializers) <ide> <ide> conf = app.conf <ide> if conf.CELERY_TASK_SERIALIZER != 'auth': <ide> def setup_security(allowed_serializers=None, key=None, cert=None, store=None, <ide> with open(cert) as cf: <ide> register_auth(kf.read(), cf.read(), store, digest, serializer) <ide> registry._set_default_serializer('auth') <add> <add> <add>def disable_untrusted_serializers(whitelist=None): <add> _disable_insecure_serializers(allowed=whitelist) <ide><path>celery/security/certificate.py <ide> <ide> from .utils import crypto, reraise_errors <ide> <add>__all__ = ['Certificate', 'CertStore', 'FSCertStore'] <add> <ide> <ide> class Certificate(object): <ide> """X.509 certificate.""" <ide><path>celery/security/key.py <ide> <ide> from .utils import crypto, reraise_errors <ide> <add>__all__ = ['PrivateKey'] <add> <ide> <ide> class PrivateKey(object): <ide> <ide><path>celery/security/serialization.py <ide> from .key import PrivateKey <ide> from .utils import reraise_errors <ide> <add>__all__ = ['SecureSerializer', 'register_auth'] <add> <ide> <ide> def b64encode(s): <ide> return bytes_to_str(base64.b64encode(str_to_bytes(s))) <ide><path>celery/security/utils.py <ide> except ImportError: # pragma: no cover <ide> crypto = None # noqa <ide> <add>__all__ = ['reraise_errors'] <add> <ide> <ide> @contextmanager <ide> def reraise_errors(msg='{0!r}', errors=None): <ide><path>celery/tests/security/test_security.py <ide> <ide> from mock import Mock, patch <ide> <add>from kombu.serialization import disable_insecure_serializers <add> <ide> from celery.exceptions import ImproperlyConfigured, SecurityError <ide> from celery.five import builtins <del>from celery.security import disable_untrusted_serializers <ide> from celery.security.utils import reraise_errors <ide> from kombu.serialization import registry <ide> <ide> class test_security(SecurityCase): <ide> def tearDown(self): <ide> registry._disabled_content_types.clear() <ide> <del> def test_disable_untrusted_serializers(self): <del> disabled = registry._disabled_content_types <del> self.assertTrue(disabled) <del> <del> disable_untrusted_serializers( <del> ['application/json', 'application/x-python-serialize']) <del> self.assertIn('application/x-yaml', disabled) <del> self.assertNotIn('application/json', disabled) <del> self.assertNotIn('application/x-python-serialize', disabled) <del> disabled.clear() <add> def test_disable_insecure_serializers(self): <add> try: <add> disabled = registry._disabled_content_types <add> self.assertTrue(disabled) <add> <add> disable_insecure_serializers( <add> ['application/json', 'application/x-python-serialize'], <add> ) <add> self.assertIn('application/x-yaml', disabled) <add> self.assertNotIn('application/json', disabled) <add> self.assertNotIn('application/x-python-serialize', disabled) <add> disabled.clear() <ide> <del> disable_untrusted_serializers() <del> self.assertIn('application/x-yaml', disabled) <del> self.assertIn('application/json', disabled) <del> self.assertIn('application/x-python-serialize', disabled) <add> disable_insecure_serializers(allowed=None) <add> self.assertIn('application/x-yaml', disabled) <add> self.assertIn('application/json', disabled) <add> self.assertIn('application/x-python-serialize', disabled) <add> finally: <add> disable_insecure_serializers(allowed=['json']) <ide> <ide> def test_setup_security(self): <ide> disabled = registry._disabled_content_types <ide> def test_setup_security(self): <ide> self.app.conf.CELERY_TASK_SERIALIZER = prev <ide> <ide> @patch('celery.security.register_auth') <del> @patch('celery.security.disable_untrusted_serializers') <add> @patch('celery.security._disable_insecure_serializers') <ide> def test_setup_registry_complete(self, dis, reg, key='KEY', cert='CERT'): <ide> calls = [0] <ide>
6
Text
Text
add 2.8.1 changelog
b7ac16200d112c0e3221712a68d93d77edcdbb63
<ide><path>CHANGELOG.md <ide> Changelog <ide> ========= <ide> <add>### 2.8.1 <add> <add>* bugfix [#1813](https://github.com/moment/moment/issues/1813): fix moment().lang([key]) incompatibility <add> <ide> ### 2.8.0 [See changelog](https://gist.github.com/ichernev/ac3899324a5fa6c8c9b4) <ide> <ide> * incompatible changes
1
Python
Python
add docstrings for tok2vec component
39a3d64c013505a02a7b6b2116f83711dee01c42
<ide><path>spacy/pipeline/tok2vec.py <ide> def make_tok2vec(nlp: Language, name: str, model: Model) -> "Tok2Vec": <ide> <ide> <ide> class Tok2Vec(Pipe): <add> """Apply a "token-to-vector" model and set its outputs in the doc.tensor <add> attribute. This is mostly useful to share a single subnetwork between multiple <add> components, e.g. to have one embedding and CNN network shared between a <add> parser, tagger and NER. <add> <add> In order to use the `Tok2Vec` predictions, subsequent components should use <add> the `Tok2VecListener` layer as the tok2vec subnetwork of their model. This <add> layer will read data from the `doc.tensor` attribute during prediction. <add> During training, the `Tok2Vec` component will save its prediction and backprop <add> callback for each batch, so that the subsequent components can backpropagate <add> to the shared weights. This implementation is used because it allows us to <add> avoid relying on object identity within the models to achieve the parameter <add> sharing. <add> """ <ide> def __init__(self, vocab: Vocab, model: Model, name: str = "tok2vec") -> None: <ide> """Initialize a tok2vec component. <ide> <ide> vocab (Vocab): The shared vocabulary. <del> model (thinc.api.Model): The Thinc Model powering the pipeline component. <add> model (thinc.api.Model[List[Doc], List[Floats2d]]): <add> The Thinc Model powering the pipeline component. It should take <add> a list of Doc objects as input, and output a list of 2d float arrays. <ide> name (str): The component instance name. <ide> <ide> DOCS: https://spacy.io/api/tok2vec#init <ide> def __init__(self, vocab: Vocab, model: Model, name: str = "tok2vec") -> None: <ide> self.cfg = {} <ide> <ide> def add_listener(self, listener: "Tok2VecListener") -> None: <add> """Add a listener for a downstream component. Usually internals.""" <ide> self.listeners.append(listener) <ide> <ide> def find_listeners(self, model: Model) -> None: <add> """Walk over a model, looking for layers that are Tok2vecListener <add> subclasses that have an upstream_name that matches this component. <add> Listeners can also set their upstream_name attribute to the wildcard <add> string '*' to match any `Tok2Vec`. <add> <add> You're unlikely to ever need multiple `Tok2Vec` components, so it's <add> fine to leave your listeners upstream_name on '*'. <add> """ <ide> for node in model.walk(): <ide> if isinstance(node, Tok2VecListener) and node.upstream_name in ( <ide> "*", <ide> def find_listeners(self, model: Model) -> None: <ide> self.add_listener(node) <ide> <ide> def __call__(self, doc: Doc) -> Doc: <del> """Add context-sensitive embeddings to the Doc.tensor attribute. <add> """Add context-sensitive embeddings to the Doc.tensor attribute, allowing <add> them to be used as features by downstream components. <ide> <ide> docs (Doc): The Doc to preocess. <ide> RETURNS (Doc): The processed Doc. <ide> def add_label(self, label): <ide> class Tok2VecListener(Model): <ide> """A layer that gets fed its answers from an upstream connection, <ide> for instance from a component earlier in the pipeline. <del> """ <ide> <add> The Tok2VecListener layer is used as a sublayer within a component such <add> as a parser, NER or text categorizer. Usually you'll have multiple listeners <add> connecting to a single upstream Tok2Vec component, that's earlier in the <add> pipeline. The Tok2VecListener layers act as proxies, passing the predictions <add> from the Tok2Vec component into downstream components, and communicating <add> gradients back upstream. <add> """ <ide> name = "tok2vec-listener" <ide> <ide> def __init__(self, upstream_name: str, width: int) -> None: <add> """ <add> upstream_name (str): A string to identify the 'upstream' Tok2Vec component <add> to communicate with. The upstream name should either be the wildcard <add> string '*', or the name of the `Tok2Vec` component. You'll almost <add> never have multiple upstream Tok2Vec components, so the wildcard <add> string will almost always be fine. <add> width (int): <add> The width of the vectors produced by the upstream tok2vec component. <add> """ <ide> Model.__init__(self, name=self.name, forward=forward, dims={"nO": width}) <ide> self.upstream_name = upstream_name <ide> self._batch_id = None <ide> self._outputs = None <ide> self._backprop = None <ide> <ide> @classmethod <del> def get_batch_id(cls, inputs) -> int: <add> def get_batch_id(cls, inputs: List[Doc]) -> int: <add> """Calculate a content-sensitive hash of the batch of documents, to check <add> whether the next batch of documents is unexpected. <add> """ <ide> return sum(sum(token.orth for token in doc) for doc in inputs) <ide> <ide> def receive(self, batch_id: int, outputs, backprop) -> None: <add> """Store a batch of training predictions and a backprop callback. The <add> predictions and callback are produced by the upstream Tok2Vec component, <add> and later will be used when the listener's component's model is called. <add> """ <ide> self._batch_id = batch_id <ide> self._outputs = outputs <ide> self._backprop = backprop <ide> <ide> def verify_inputs(self, inputs) -> bool: <add> """Check that the batch of Doc objects matches the ones we have a <add> prediction for. <add> """ <ide> if self._batch_id is None and self._outputs is None: <ide> raise ValueError(Errors.E954) <ide> else: <ide> def verify_inputs(self, inputs) -> bool: <ide> <ide> <ide> def forward(model: Tok2VecListener, inputs, is_train: bool): <add> """Supply the outputs from the upstream Tok2Vec component.""" <ide> if is_train: <ide> model.verify_inputs(inputs) <ide> return model._outputs, model._backprop
1
Mixed
Javascript
add controllist to dom property whitelist
d7157651f7b72d9888c0123e191f9b88cd8f41e9
<ide><path>docs/docs/reference-dom-elements.md <ide> React supports all `data-*` and `aria-*` attributes as well as these attributes: <ide> accept acceptCharset accessKey action allowFullScreen allowTransparency alt <ide> async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge <ide> charSet checked cite classID className colSpan cols content contentEditable <del>contextMenu controls coords crossOrigin data dateTime default defer dir <del>disabled download draggable encType form formAction formEncType formMethod <add>contextMenu controls controlsList coords crossOrigin data dateTime default defer <add>dir disabled download draggable encType form formAction formEncType formMethod <ide> formNoValidate formTarget frameBorder headers height hidden high href hrefLang <ide> htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label <ide> lang list loop low manifest marginHeight marginWidth max maxLength media <ide><path>src/renderers/dom/shared/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> contentEditable: 0, <ide> contextMenu: 0, <ide> controls: HAS_BOOLEAN_VALUE, <add> controlsList: 0, <ide> coords: 0, <ide> crossOrigin: 0, <ide> data: 0, // For `<object />` acts as `src`.
2