content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Go
Go
add test for volume ownership and perms
c024c9bd1ec13aade038f87266a03a1d1bc13441
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildADDLocalAndRemoteFilesWithCache(t *testing.T) { <ide> logDone("build - add local and remote file with cache") <ide> } <ide> <add>// TODO: TestCaching <ide> func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) { <ide> name := "testbuildaddlocalandremotefilewithoutcache" <ide> defer deleteImages(name) <ide> func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) { <ide> } <ide> logDone("build - add local and remote file without cache") <ide> } <add> <add>func TestBuildWithVolumeOwnership(t *testing.T) { <add> name := "testbuildimg" <add> defer deleteImages(name) <add> <add> _, err := buildImage(name, <add> `FROM busybox:latest <add> RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test <add> VOLUME /test`, <add> true) <add> <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test") <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := "drw-------"; !strings.Contains(out, expected) { <add> t.Fatalf("expected %s received %s", expected, out) <add> } <add> <add> if expected := "daemon daemon"; !strings.Contains(out, expected) { <add> t.Fatalf("expected %s received %s", expected, out) <add> } <add> <add> logDone("build - volume ownership") <add>}
1
Text
Text
remove links for all docs
24f46ea3f3e5006ca38735306753a846a0823174
<ide><path>README.md <ide> Choose the right framework for every part of a model's lifetime <ide> | [Quick tour: Share your models ](#Quick-tour-of-model-sharing) | Upload and share your fine-tuned models with the community | <ide> | [Migrating from pytorch-transformers to transformers](#Migrating-from-pytorch-transformers-to-transformers) | Migrating your code from pytorch-transformers to transformers | <ide> | [Migrating from pytorch-pretrained-bert to pytorch-transformers](#Migrating-from-pytorch-pretrained-bert-to-transformers) | Migrating your code from pytorch-pretrained-bert to transformers | <del>| Documentation [(master)](https://huggingface.co/transformers/master) [(stable)](https://huggingface.co/transformers/) [(v2.10.0)](https://huggingface.co/transformers/v2.10.0) [(v2.9.0/v2.9.1)](https://huggingface.co/transformers/v2.9.1) [(v2.8.0)](https://huggingface.co/transformers/v2.8.0) [(v2.7.0)](https://huggingface.co/transformers/v2.7.0) [(v2.6.0)](https://huggingface.co/transformers/v2.6.0) [(v2.5.0/v2.5.1)](https://huggingface.co/transformers/v2.5.1) [(v2.4.0/v2.4.1)](https://huggingface.co/transformers/v2.4.0)[(v2.3.0)](https://huggingface.co/transformers/v2.3.0)[(v2.2.0/v2.2.1/v2.2.2)](https://huggingface.co/transformers/v2.2.0) [(v2.1.1)](https://huggingface.co/transformers/v2.1.1) [(v2.0.0)](https://huggingface.co/transformers/v2.0.0) [(v1.2.0)](https://huggingface.co/transformers/v1.2.0) [(v1.1.0)](https://huggingface.co/transformers/v1.1.0) [(v1.0.0)](https://huggingface.co/transformers/v1.0.0) | Full API documentation and more | <add>| [Documentation](https://huggingface.co/transformers/) | Full API documentation and more | <ide> <ide> ## Installation <ide>
1
Text
Text
translate tutorial to korean
ac466b71d8afff796490d427abb500eda8fa9e1e
<ide><path>docs/docs/tutorial.ko-KR.md <add>--- <add>id: tutorial-ko-KR <add>title: 튜토리얼 <add>prev: getting-started.ko-KR.html <add>next: thinking-in-react.ko-KR.html <add>--- <add> <add>블로그에 붙일만한 간단하지만 실용적인 댓글상자를 만들어 볼 것입니다. Disqus, LiveFyre, Facebook에서 제공하는 것 같은 실시간 댓글의 간단한 버전이죠. <add> <add>이런 기능을 넣겠습니다: <add> <add>* 댓글목록 <add>* 댓글작성폼 <add>* 커스텀 백엔드를 위한 Hooks <add> <add>멋진 기능도 조금 넣어보겠습니다: <add> <add>* **낙관적 댓글 달기:** 댓글은 서버에 저장되기도 전에 목록에 나타납니다. 그래서 빠르게 느껴집니다. <add>* **실시간 업데이트:** 다른 사용자가 남기는 댓글이 실시간으로 나타납니다. <add>* **Markdown 지원:** 사용자는 글을 꾸미기 위해 Markdown 형식을 사용할 수 있습니다. <add> <add>### 그냥 다 생략하고 소스만 보고 싶나요? <add> <add>[GitHub에 전부 있습니다.](https://github.com/reactjs/react-tutorial) <add> <add>### 서버 구동하기 <add> <add>이 튜토리얼을 시작할 때 필요한 건 아니지만, 나중에 실행 중인 서버에 `POST` 요청을 하는 기능을 추가하게 될 것입니다. 서버를 구성하는 것이 익숙하다면, 본인이 편한 방식대로 서버를 구성해 주세요. 서버사이드에 대한 고민없이 React의 학습 그 자체에 집중하고 싶은 분들을 위해서, 몇 가지 언어로 간단한 서버코드를 작성해 놓았습니다 - JavaScript (Node.js), Python, Ruby 버전이 있고, GitHub에서 찾아보실 있습니다. [소스를 확인](https://github.com/reactjs/react-tutorial/)하거나 [zip 파일을 다운로드](https://github.com/reactjs/react-tutorial/archive/master.zip)하고 시작하세요. <add> <add>튜토리얼을 다운로드 받아 시작한다면, `public/index.html`을 열고 바로 시작하세요. <add> <add>### 시작하기 <add> <add>이 튜토리얼에서는 CDN에 있는 미리 빌드된 JavaScript 파일들을 사용합니다. 좋아하는 에디터를 열고, 새로운 HTML 문서를 만드세요: <add> <add>```html <add><!-- index.html --> <add><html> <add> <head> <add> <title>Hello React</title> <add> <script src="http://fb.me/react-{{site.react_version}}.js"></script> <add> <script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <add> <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <add> </head> <add> <body> <add> <div id="content"></div> <add> <script type="text/jsx"> <add> // 여기에 코드를 작성합니다 <add> </script> <add> </body> <add></html> <add>``` <add> <add>다음 진행을 위해, 위의 스크립트 태그안에 JavaScript 코드를 작성합니다. <add> <add>> 주의: <add>> <add>> 여기서는 ajax 요청 코드를 단순화 하기 위해 jQuery를 넣었지만, 이는 React의 동작에 필수적인 것은 **아닙니다**. <add> <add>### 첫 번째 컴포넌트 <add> <add>모듈화 된, 조합가능한 컴포넌트가 React의 전부입니다. 댓글상자 예제에서 우리는 다음과 같은 컴포넌트 구조를 가질 것입니다: <add> <add>``` <add>- CommentBox <add> - CommentList <add> - Comment <add> - CommentForm <add>``` <add> <add>자, 이제 `CommentBox` 컴포넌트를 만들어 봅시다. `<div>` 하나로 구성되어 있습니다. <add> <add>```javascript <add>// tutorial1.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> Hello, world! I am a CommentBox. <add> </div> <add> ); <add> } <add>}); <add>React.render( <add> <CommentBox />, <add> document.getElementById('content') <add>); <add>``` <add> <add>#### JSX 문법 <add> <add>JavsScript 안의 유사 XML 구문이 먼저 눈에 띌 것입니다. 우리에겐 이를 일반 JavaScript로 변환해주는 간단한 프리컴파일러(precompiler)가 있습니다. <add> <add>```javascript <add>// tutorial1-raw.js <add>var CommentBox = React.createClass({displayName: 'CommentBox', <add> render: function() { <add> return ( <add> React.createElement('div', {className: "commentBox"}, <add> "Hello, world! I am a CommentBox." <add> ) <add> ); <add> } <add>}); <add>React.render( <add> React.createElement(CommentBox, null), <add> document.getElementById('content') <add>); <add>``` <add> <add>JSX의 사용은 선택적이지만 JSX 문법이 일반 JavsScript보다 사용하기 쉽습니다. [JSX 문법 문서](/react/docs/jsx-in-depth.html)에서 더 알아보세요. <add> <add>#### 무슨 일이 일어나고 있는가 <add> <add>우리는 새로운 React 컴포넌트를 만들기 위해 `React.createClass()`로 JavaScript 객체에 몇 개의 메소드를 담아 넘겼습니다. 이 중 가장 중요한것은 `render` 메소드인데, 이는 React 컴포넌트 트리를 반환해서 최종적으로 실제 HTML을 그려주게 됩니다. <add> <add>`<div>` 태그들은 실제 DOM 노드가 아니라 React `div` 컴포넌트의 인스턴스입니다. 이것은 React가 다룰 수 있는 데이터의 표지자(markers)나 조각이라 생각하셔도 됩니다. React는 **안전합니다**. 생(raw) HTML 문자열을 생성하는것이 아니기 때문에 XSS을 기본적으로 방지합니다. <add> <add>일반적인 HTML만 리턴할 수 있는 것은 아닙니다. 여러분이 직접 만든 (또는 다른 사람들이 만들어 놓은) 컴포넌트의 트리를 리턴할 수도 있습니다. 이것이 React를 **조합가능(composable)하게 만듭니다**: 유지보수 가능한 프론트엔드를 위한 핵심교리(key tenet)지요. <add> <add>`React.render()`는 최상위 컴포넌트의 인스턴스를 만들고, 두 번째 인수로 전달받은 DOM 엘리먼트에 마크업을 삽입해 프레임워크를 시작합니다. <add> <add>## 컴포넌트 조합하기 <add> <add>이제 `CommentList`와 `CommentForm`을 위한 뼈대를 구축해 봅시다. 이전과 마찬가지로 단순히 `<div>` 태그 하나 입니다. <add> <add>```javascript <add>// tutorial2.js <add>var CommentList = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentList"> <add> 안녕! 난 댓글목록이야. <add> </div> <add> ); <add> } <add>}); <add> <add>var CommentForm = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentForm"> <add> 안녕! 난 댓글폼이야. <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>다음은 `CommentBox` 컴포넌트가 새로 만든 컴포넌트들을 사용하도록 수정합니다. <add> <add>```javascript{6-8} <add>// tutorial3.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>방금 만든 컴포넌트들을 어떤방식으로 HTML 태그들과 섞어 사용하는지 살펴보세요. HTML 컴포넌트들도 한가지 차이만 제외한다면 우리가 정의한 것과 같은 표준적인 React 컴포넌트입니다. JSX 컴파일러가 자동으로 HTML 태그들을 `React.createElement(tagName)` 표현식으로 재작성하고 나머지는 그대로 둘 것입니다. 이는 전역 네임스페이스가 오염되는 것을 막아줍니다. <add> <add>### 컴포넌트 프로퍼티 (Component Properties) <add> <add>이제 세 번째 컴포넌트인 `Comment`를 만들어 봅시다. 개별 댓글마다 글쓴이와 내용을 포함하게 될 것입니다. 먼저 댓글 몇 개를 `CommentList`에 추가해 봅시다: <add> <add>```javascript{6-7} <add>// tutorial4.js <add>var CommentList = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentList"> <add> <Comment author="Pete Hunt">댓글입니다</Comment> <add> <Comment author="Jordan Walke">*또 다른* 댓글입니다</Comment> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>부모 컴포넌트인 `CommentList`에서 자식 컴포넌트인 `Comment`에 데이터들을 전달하고 있는것을 확인할 수 있습니다. 예를 들어, 우리는 어트리뷰트로 *Pete Hunt*를, XML 형식의 자식 노드로 *댓글입니다*를 첫 번째 `Comment`로 넘겼습니다. 부모에서 자식 컴포넌트로 전달되는 데이터는 **props**라 합니다. properties의 축약어지요. <add> <add>### props 사용하기 <add> <add>Comment 컴포넌트를 만들어 봅시다. **props**를 사용해 `CommentList`에서 전달받은 데이터를 읽어들이고, 마크업을 렌더할 수 있을 것입니다. <add> <add>```javascript <add>// tutorial5.js <add>var Comment = React.createClass({ <add> render: function() { <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> {this.props.children} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>JSX 내부의 중괄호로 둘러싸인 JavaScript 표현식(어트리뷰트나 엘리먼트의 자식으로 사용된)을 통해 텍스트나 React 컴포넌트를 트리에 더할 수 있습니다. `this.props`를 통해 컴포넌트에 전달된 특정한 어트리뷰트들에, `this.props.children`을 통해 중첩된 엘리먼트들에 접근할 수 있습니다. <add> <add>### Markdown 추가하기 <add> <add>Markdown은 텍스트를 포맷팅하는 간단한 방식입니다. 예를 들어, 별표(`*`)로 텍스트를 둘러싸는 것은 강조의 의미입니다. <add> <add>먼저 서드파티 라이브러리인 **Showdown**을 애플리케이션에 추가합니다. 이 JavaScript 라이브러리는 Markdown 텍스트를 HTML 문법으로 변환해줍니다. head 태그안에 스크립트 태그를 추가해 주세요. (React playground에는 이미 포함되어 있습니다): <add> <add>```html{7} <add><!-- index.html --> <add><head> <add> <title>Hello React</title> <add> <script src="http://fb.me/react-{{site.react_version}}.js"></script> <add> <script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <add> <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <add> <script src="http://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script> <add></head> <add>``` <add> <add>다음은, 댓글 텍스트를 Markdown으로 전환하고 출력해 봅시다. <add> <add>```javascript{2,10} <add>// tutorial6.js <add>var converter = new Showdown.converter(); <add>var Comment = React.createClass({ <add> render: function() { <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> {converter.makeHtml(this.props.children.toString())} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>우리가 한 일이라고는 Showdown 라이브러리를 호출한 것 뿐입니다. Showdown이 `this.props.children`에서 텍스트를 읽어들여 처리할 수 있도록 React 형식의 텍스트(React's wrapped text)를 단순 텍스트(raw string)으로 전환하기 위해 명시적으로 `toString()`을 호출했습니다. <add> <add>하지만 여기엔 문제가 있습니다! 우리는 HTML 태그들이 정상적으로 렌더되길 원하지만 브라우저에 출력된 결과물은 "`<p>``<em>`또 다른`</em>` 댓글입니다`</p>`"처럼 태그가 그대로 보일것입니다. <add> <add>React는 이런 식으로 XSS 공격을 예방합니다. 우회할 방법이 있긴 하지만 프레임워크는 사용하지 않도록 경고하고 있습니다: <add> <add>```javascript{5,11} <add>// tutorial7.js <add>var converter = new Showdown.converter(); <add>var Comment = React.createClass({ <add> render: function() { <add> var rawMarkup = converter.makeHtml(this.props.children.toString()); <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> <span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>이는 의도적으로 생(raw) HTML을 넣기 힘들게 하려고 만든 특별한 API지만 Showdown을 사용하기 위해 이 백도어를 활용합시다. <add> <add>**잊지 마세요:** 이 기능은 Showdown이 안전한 것으로 믿고 사용하는 것입니다. <add> <add>### 데이터 모델 연결하기 <add> <add>지금까지는 소스코드에 직접 댓글을 넣었습니다. 이제부터는 JSON 데이터 덩어리를 댓글 목록에 렌더해보겠습니다. 최종적으로는 서버에서 데이터가 내려오겠지만, 지금은 소스에 직접 데이터를 넣어봅시다: <add> <add>```javascript <add>// tutorial8.js <add>var data = [ <add> {author: "Pete Hunt", text: "댓글입니다"}, <add> {author: "Jordan Walke", text: "*또 다른* 댓글입니다"} <add>]; <add>``` <add> <add>이 데이터를 모듈화된 방식으로 `CommentList`에 넣어야 합니다. props을 이용해 데이터를 넘기도록 `CommentBox`와 `React.render()` 호출을 수정합시다. <add> <add>```javascript{7,15} <add>// tutorial9.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.props.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add> <add>React.render( <add> <CommentBox data={data} />, <add> document.getElementById('content') <add>); <add>``` <add> <add>이제 `CommentList`에서 데이터를 다룰 수 있습니다. 댓글을 동적으로 렌더해봅시다: <add> <add>```javascript{4-10,13} <add>// tutorial10.js <add>var CommentList = React.createClass({ <add> render: function() { <add> var commentNodes = this.props.data.map(function (comment) { <add> return ( <add> <Comment author={comment.author}> <add> {comment.text} <add> </Comment> <add> ); <add> }); <add> return ( <add> <div className="commentList"> <add> {commentNodes} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>이게 답니다! <add> <add>### 서버에서 가져오기(Fetching) <add> <add>이제 데이터를 소스에 직접 넣는 방식에서 서버에서 동적으로 받아서 처리하는 방식으로 바꿔봅시다. 데이터 prop을 삭제하고 처리할 URL로 변경해 줍시다. <add> <add>```javascript{3} <add>// tutorial11.js <add>React.render( <add> <CommentBox url="comments.json" />, <add> document.getElementById('content') <add>); <add>``` <add> <add>이 컴포넌트는 이전 것과 다르게, 스스로 다시 렌더링해야 합니다. 컴포넌트는 서버에서 요청이 들어올때까지는 아무 데이터도 가지고 있지 않다가, 특정한 시점에서 새로운 댓글을 렌더할 필요가 있을 것입니다. <add> <add>### 반응적 state <add> <add>지금까지, 각각의 구성요소는 props를 기반으로 한번 렌더되었습니다. `props`는 불변성을 갖습니다: 그것들은 부모에서 전달되어 부모에게 "소유" 되어 있습니다. 컴포넌트에 상호작용을 구현하기 위해서, 가변성을 갖는 **state**를 소개합니다. `this.state`는 컴포넌트에 한정(private)되며 `this.setState()`를 통해 변경할 수 있습니다. state가 업데이트 되면, 컴포넌트는 자신을 스스로 다시 렌더링합니다. <add> <add>`render()` 메소드는 `this.props`와 `this.state`를 위한 함수로 선언적으로 작성됩니다. 프레임워크에서 입력값에 따른 UI가 항상 일관성 있음을 보장해줍니다. <add> <add>서버가 데이터를 가져오면 댓글 데이터가 변경될 것입니다. 댓글 데이터의 배열을 `CommentBox`의 state로 추가해봅시다: <add> <add>```javascript{3-5,10} <add>// tutorial12.js <add>var CommentBox = React.createClass({ <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>`getInitialState()` 는 컴포넌트의 생명주기동안 한 번만 실행되며 컴포넌트의 초기 state를 설정합니다. <add> <add>### state 업데이트하기 <add> <add>컴포넌트의 최초 생성 시에, 서버에서 GET 방식으로 JSON을 넘겨받아 최신의 데이터가 state에 반영되길 원했습니다. 실제 애플리케이션에선 이것이 동적인 엔드포인트이지만, 이 예제에서는 정적 JSON 파일을 사용해서 간단하게 만들어보겠습니다. <add> <add>```javascript <add>// tutorial13.json <add>[ <add> {"author": "Pete Hunt", "text": "댓글입니다"}, <add> {"author": "Jordan Walke", "text": "*또 다른* 댓글입니다"} <add>] <add>``` <add> <add>서버에 비동기 요청을 위해 jQuery를 사용합니다. <add> <add>주의: 우리의 앱이 AJAX 애플리케이션으로 변화하고 있기 때문에, 이제 파일 시스템의 파일을 참조하는 대신 웹서버를 사용하도록 앱을 개발해야 합니다. [위에서 언급한 바와 같이](#running-a-server), 우리는 튜토리얼의 나머지 부분에 필요한 기능을 제공하는 서버를 몇 가지 준비해 놓았습니다. [GitHub에 올려놓았으니](https://github.com/reactjs/react-tutorial) 확인해 보세요. <add> <add>```javascript{6-17} <add>// tutorial13.js <add>var CommentBox = React.createClass({ <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>여기서 `componentDidMount`는 컴포넌트가 렌더링 된 다음 React에 의해 자동으로 호출되는 메소드입니다. 동적 업데이트의 핵심은 `this.setState()`의 호출입니다. 우리가 이전의 댓글 목록을 서버에서 넘어온 새로운 목록으로 변경하면 자동으로 UI가 업데이트 될 것입니다. 이 반응성 덕분에 실시간 업데이트에 아주 작은 수정만 가해집니다. 우리는 여기선 간단한 폴링을 사용할 것이지만 웹소켓등의 다른 기술도 쉽게 사용할 수 있습니다. <add> <add>```javascript{3,14,19-20,34} <add>// tutorial14.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add> <add>React.render( <add> <CommentBox url="comments.json" pollInterval={2000} />, <add> document.getElementById('content') <add>); <add> <add>``` <add> <add>우리가 여기서 한것은 AJAX 호출을 별도의 메소드로 분리하고 컴포넌트가 처음 로드된 시점부터 2초 간격으로 계속 호출되도록 한 것입니다. 브라우저에서 직접 돌려보고 `comments.json`파일을 수정해보세요; 2초 간격으로 변화되는 모습이 보일 것입니다! <add> <add>### 새로운 댓글 추가하기 <add> <add>이제 폼을 만들어볼 시간입니다. 우리의 `CommentForm` 컴포넌트는 사용자에게 이름과 내용을 입력받고 댓글을 저장하기 위해 서버에 요청을 전송해야 합니다. <add> <add>```javascript{5-9} <add>// tutorial15.js <add>var CommentForm = React.createClass({ <add> render: function() { <add> return ( <add> <form className="commentForm"> <add> <input type="text" placeholder="이름" /> <add> <input type="text" placeholder="내용을 입력하세요..." /> <add> <input type="submit" value="올리기" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>이제 폼의 상호작용을 만들어 보겠습니다. 사용자가 폼을 섭밋하는 시점에 우리는 폼을 초기화하고 서버에 요청을 전송하고 댓글목록을 갱신해야 합니다. 폼의 섭밋 이벤트를 감시하고 초기화 해주는 부분부터 시작해 보죠. <add> <add>```javascript{3-14,17-20} <add>// tutorial16.js <add>var CommentForm = React.createClass({ <add> handleSubmit: function(e) { <add> e.preventDefault(); <add> var author = this.refs.author.getDOMNode().value.trim(); <add> var text = this.refs.text.getDOMNode().value.trim(); <add> if (!text || !author) { <add> return; <add> } <add> // TODO: 서버에 요청을 전송합니다 <add> this.refs.author.getDOMNode().value = ''; <add> this.refs.text.getDOMNode().value = ''; <add> return; <add> }, <add> render: function() { <add> return ( <add> <form className="commentForm" onSubmit={this.handleSubmit}> <add> <input type="text" placeholder="이름" ref="author" /> <add> <input type="text" placeholder="내용을 입력하세요..." ref="text" /> <add> <input type="submit" value="올리기" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>##### 이벤트 <add> <add>React는 카멜케이스 네이밍 컨벤션으로 컴포넌트에 이벤트 핸들러를 등록합니다. 폼이 유효한 값으로 섭밋되었을 때 폼필드들을 초기화하도록 `onSubmit` 핸들러를 등록합니다. <add> <add>폼 섭밋에 대한 브라우저의 기본동작을 막기 위해 이벤트시점에 `preventDefault()`를 호출합니다. <add> <add>##### Refs <add> <add>우리는 자식 컴포넌트의 이름을 지정하기 위해 `ref` 어트리뷰트를, 컴포넌트를 참조하기 위해 `this.refs`를 사용합니다. 고유한(native) 브라우저 DOM 엘리먼트를 얻기 위해 `getDOMNode()`를 호출할 수 있습니다. <add> <add>##### props으로 콜백 처리하기 <add> <add>사용자가 댓글을 등록할 때, 새로운 댓글을 추가하기 위해 댓글목록을 갱신해주어야 합니다. `CommentBox`가 댓글목록의 state를 소유하고 있기 때문에 이 로직 또한 `CommentBox`에 있는것이 타당합니다. <add> <add>자식 컴포넌트가 그의 부모에게 데이터를 넘겨줄 필요가 있습니다. 부모의 `render` 메소드에서 새로운 콜백(`handleCommentSubmit`)을 자식에게 넘겨주고, 자식의 `onCommentSubmit` 이벤트에 그것을 바인딩해주는 식으로 구현합니다. 이벤트가 작동될때(triggerd)마다, 콜백이 호출됩니다: <add> <add>```javascript{15-17,30} <add>// tutorial17.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> // TODO: 서버에 요청을 수행하고 목록을 갱신한다 <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>사용자가 폼을 섭밋할 때, `CommentForm`에서 콜백을 호출해 봅시다: <add> <add>```javascript{10} <add>// tutorial18.js <add>var CommentForm = React.createClass({ <add> handleSubmit: function(e) { <add> e.preventDefault(); <add> var author = this.refs.author.getDOMNode().value.trim(); <add> var text = this.refs.text.getDOMNode().value.trim(); <add> if (!text || !author) { <add> return; <add> } <add> this.props.onCommentSubmit({author: author, text: text}); <add> this.refs.author.getDOMNode().value = ''; <add> this.refs.text.getDOMNode().value = ''; <add> return; <add> }, <add> render: function() { <add> return ( <add> <form className="commentForm" onSubmit={this.handleSubmit}> <add> <input type="text" placeholder="이름" ref="author" /> <add> <input type="text" placeholder="이름을 입력하세요..." ref="text" /> <add> <input type="submit" value="올리기" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>이제 콜백이 제자리를 찾았습니다. 우리가 할일은 서버에 요청을 날리고 목록을 갱신하는 것 뿐입니다: <add> <add>```javascript{16-27} <add>// tutorial19.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> type: 'POST', <add> data: comment, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>### 최적화: 낙관적 업데이트 <add> <add>우리의 애플리케이션은 이제 모든 기능을 갖추었습니다. 하지만 댓글이 목록에 갱신되기 전에 완료요청을 기다리는 게 조금 느린듯한 느낌이 드네요. 우리는 낙관적 업데이트를 통해 댓글이 목록에 추가되도록 함으로써 앱이 좀 더 빨라진 것처럼 느껴지도록 할 수 있습니다. <add> <add>```javascript{16-18} <add>// tutorial20.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> var comments = this.state.data; <add> var newComments = comments.concat([comment]); <add> this.setState({data: newComments}); <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> type: 'POST', <add> data: comment, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>댓글</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>### 축하합니다! <add> <add>몇 단계를 거쳐 간단하게 댓글상자를 만들어 보았습니다. [왜 React인가](/react/docs/why-react.html)에서 더 알아보거나, 혹은 [API 레퍼런스](/react/docs/top-level-api.html)에 뛰어들어 해킹을 시작하세요! 행운을 빕니다!
1
Python
Python
stream gold during spacy train
b59765ca9f6111a6b268ec3d1e36418366599b50
<ide><path>spacy/cli/train.py <ide> def train(lang, output_dir, train_data, dev_data, n_iter=30, n_sents=0, <ide> <ide> print("Itn.\tP.Loss\tN.Loss\tUAS\tNER P.\tNER R.\tNER F.\tTag %\tToken %") <ide> try: <del> train_docs = corpus.train_docs(nlp, projectivize=True, noise_level=0.0, <del> gold_preproc=gold_preproc, max_length=0) <del> train_docs = list(train_docs) <ide> for i in range(n_iter): <add> train_docs = corpus.train_docs(nlp, projectivize=True, noise_level=0.0, <add> gold_preproc=gold_preproc, max_length=0) <ide> with tqdm.tqdm(total=n_train_words, leave=False) as pbar: <ide> losses = {} <ide> for batch in minibatch(train_docs, size=batch_sizes):
1
Ruby
Ruby
preserve timestamp for cp
8b61d7899b6798f70509a8d3b2052ddcae0d903f
<ide><path>Library/Homebrew/download_strategy.rb <ide> def stage <ide> when :p7zip <ide> safe_system "7zr", "x", cached_location <ide> else <del> cp cached_location, basename_without_params <add> cp cached_location, basename_without_params, :preserve => true <ide> end <ide> end <ide> <ide> def _fetch <ide> # Useful for installing jars. <ide> class NoUnzipCurlDownloadStrategy < CurlDownloadStrategy <ide> def stage <del> cp cached_location, basename_without_params <add> cp cached_location, basename_without_params, :preserve => true <ide> end <ide> end <ide> <ide> def initialize(name, resource) <ide> <ide> def stage <ide> super <del> cp_r File.join(cached_location, "."), Dir.pwd <add> cp_r File.join(cached_location, "."), Dir.pwd, :preserve => true <ide> end <ide> <ide> def source_modified_time <ide> def initialize(name, resource) <ide> end <ide> <ide> def source_modified_time <del> # Look for the file timestamps under {#cached_location} because <del> # newly-unpacked directory can have timestamps of the moment of copying. <ide> # Filter CVS's files because the timestamp for each of them is the moment <ide> # of clone. <ide> max_mtime = Time.at(0) <ide> def source_modified_time <ide> end <ide> <ide> def stage <del> cp_r File.join(cached_location, "."), Dir.pwd <add> cp_r File.join(cached_location, "."), Dir.pwd, :preserve => true <ide> end <ide> <ide> private <ide> def initialize(name, resource) <ide> def stage <ide> # The export command doesn't work on checkouts <ide> # See https://bugs.launchpad.net/bzr/+bug/897511 <del> cp_r File.join(cached_location, "."), Dir.pwd <add> cp_r File.join(cached_location, "."), Dir.pwd, :preserve => true <ide> rm_r ".bzr" <ide> end <ide>
1
Go
Go
optimize .dockerignore when there are exclusions
842b8d8784b132279003580eedd0e9c12b885815
<ide><path>pkg/archive/archive.go <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> } <ide> <ide> if skip { <del> if !exceptions && f.IsDir() { <add> // If we want to skip this file and its a directory <add> // then we should first check to see if there's an <add> // excludes pattern (eg !dir/file) that starts with this <add> // dir. If so then we can't skip this dir. <add> <add> // Its not a dir then so we can just return/skip. <add> if !f.IsDir() { <add> return nil <add> } <add> <add> // No exceptions (!...) in patterns so just skip dir <add> if !exceptions { <ide> return filepath.SkipDir <ide> } <del> return nil <add> <add> dirSlash := relFilePath + string(filepath.Separator) <add> <add> for _, pat := range patterns { <add> if pat[0] != '!' { <add> continue <add> } <add> pat = pat[1:] + string(filepath.Separator) <add> if strings.HasPrefix(pat, dirSlash) { <add> // found a match - so can't skip this dir <add> return nil <add> } <add> } <add> <add> // No matching exclusion dir so just skip dir <add> return filepath.SkipDir <ide> } <ide> <ide> if seen[relFilePath] {
1
Javascript
Javascript
reduce internal usage of public require of util
de3b164f4fd069ecfcf496609466fdc85838c08f
<ide><path>lib/assert.js <ide> const { codes: { <ide> } } = require('internal/errors'); <ide> const AssertionError = require('internal/assert/assertion_error'); <ide> const { openSync, closeSync, readSync } = require('fs'); <del>const { inspect, types: { isPromise, isRegExp } } = require('util'); <add>const { inspect } = require('internal/util/inspect'); <add>const { isPromise, isRegExp } = require('internal/util/types'); <ide> const { EOL } = require('internal/constants'); <ide> const { NativeModule } = require('internal/bootstrap/loaders'); <ide>
1
Ruby
Ruby
remove unecessary method call
0edc6c8f64eb8f59c211a775a0453ddd8a1d994b
<ide><path>actionview/lib/action_view/helpers/translation_helper.rb <ide> module TranslationHelper <ide> # when you call translate in a template and translators know which keys <ide> # they can provide HTML values for. <ide> # <del> # Finally, to access the translated text along with the fully resolved <add> # To access the translated text along with the fully resolved <ide> # translation key, <tt>translate</tt> accepts a block: <ide> # <ide> # <%= translate(".relative_key") do |translation, resolved_key| %> <ide> def translate(key, **options) <ide> end <ide> <ide> fully_resolved_key = scope_key_by_partial(key) <del> translated_text = options.fetch(:default, "") <ide> <ide> if html_safe_translation_key?(key) <ide> html_safe_options = options.dup <add> <ide> options.except(*I18n::RESERVED_KEYS).each do |name, value| <ide> unless name == :count && value.is_a?(Numeric) <ide> html_safe_options[name] = ERB::Util.html_escape(value.to_s) <ide> end <ide> end <add> <ide> translation = I18n.translate(fully_resolved_key, **html_safe_options.merge(raise: i18n_raise)) <add> <ide> if translation.respond_to?(:map) <ide> translated_text = translation.map { |element| element.respond_to?(:html_safe) ? element.html_safe : element } <ide> else <ide> def translate(key, **options) <ide> title = +"translation missing: #{keys.join('.')}" <ide> <ide> interpolations = options.except(:default, :scope) <add> <ide> if interpolations.any? <ide> title << ", " << interpolations.map { |k, v| "#{k}: #{ERB::Util.html_escape(v)}" }.join(", ") <ide> end
1
Ruby
Ruby
remove unneeded python27dependency
0fd32118c7107cfc7c895b9a1aa9a95ef2986423
<ide><path>Library/Homebrew/requirements.rb <ide> class GitDependency < Requirement <ide> default_formula 'git' <ide> satisfy { which('git') } <ide> end <del> <del>class Python27Dependency < Requirement <del> fatal true <del> default_formula 'python' <del> satisfy do <del> # Note that python -V outputs to stderr <del> `python -V 2>&1` =~ /^Python 2.7/ <del> end <del>end
1
PHP
PHP
apply fixes from styleci
41305c1dd152824c3b48f7efae5f65a5a768ef2a
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> protected function addTimestampsToUpsertValues(array $values) <ide> <ide> $columns = array_filter([ <ide> $this->model->getCreatedAtColumn(), <del> $this->model->getUpdatedAtColumn() <add> $this->model->getUpdatedAtColumn(), <ide> ]); <ide> <ide> foreach ($columns as $column) {
1
Ruby
Ruby
move check env.runtime_cpu_detection to utils/ast
f2fe1b59a19c4a80e6c0ff14d4f81720e6d1c1b9
<ide><path>Library/Homebrew/formula_cellar_checks.rb <ide> def check_cpuid_instruction(formula) <ide> <ide> dot_brew_formula = formula.prefix/".brew/#{formula.name}.rb" <ide> return unless dot_brew_formula.exist? <del> # TODO: add methods to `utils/ast` to allow checking for method use <del> return unless dot_brew_formula.read.include? "ENV.runtime_cpu_detection" <add> <add> require "utils/ast" <add> return unless Utils::AST::FormulaAST.new(dot_brew_formula.read).include_runtime_cpu_detection? <ide> <ide> # macOS `objdump` is a bit slow, so we prioritise llvm's `llvm-objdump` (~5.7x faster) <ide> # or binutils' `objdump` (~1.8x faster) if they are installed. <ide><path>Library/Homebrew/utils/ast.rb <ide> def add_stanza(name, value, type: nil) <ide> tree_rewriter.insert_after(preceding_expr, "\n#{stanza_text(name, value, indent: 2)}") <ide> end <ide> <add> sig { returns(T::Boolean) } <add> def include_runtime_cpu_detection? <add> install_node = children.find do |child| <add> (child.is_a? RuboCop::AST::DefNode) && child.method_name == :install <add> end <add> <add> return false if install_node.blank? <add> <add> install_node.each_node.any? do |node| <add> node&.receiver&.const_name == "ENV" && node&.method_name == :runtime_cpu_detection <add> end <add> end <add> <ide> private <ide> <ide> sig { returns(String) }
2
Python
Python
remove unused test file
33ac2fd959d8dc470ea70cdf1b4d3c12ace80f0a
<ide><path>rest_framework/tests/mixins.py <del># """Tests for the mixin module""" <del># from django.test import TestCase <del># from rest_framework import status <del># from django.test.client import RequestFactory <del># from django.contrib.auth.models import Group, User <del># from rest_framework.mixins import CreateModelMixin, PaginatorMixin, ReadModelMixin <del># from rest_framework.resources import ModelResource <del># from rest_framework.response import Response, ImmediateResponse <del># from rest_framework.tests.models import CustomUser <del># from rest_framework.tests.testcases import TestModelsTestCase <del># from rest_framework.views import View <del> <del> <del># class TestModelRead(TestModelsTestCase): <del># """Tests on ReadModelMixin""" <del> <del># def setUp(self): <del># super(TestModelRead, self).setUp() <del># self.req = RequestFactory() <del> <del># def test_read(self): <del># Group.objects.create(name='other group') <del># group = Group.objects.create(name='my group') <del> <del># class GroupResource(ModelResource): <del># model = Group <del> <del># request = self.req.get('/groups') <del># mixin = ReadModelMixin() <del># mixin.resource = GroupResource <del> <del># response = mixin.get(request, id=group.id) <del># self.assertEquals(group.name, response.raw_content.name) <del> <del># def test_read_404(self): <del># class GroupResource(ModelResource): <del># model = Group <del> <del># request = self.req.get('/groups') <del># mixin = ReadModelMixin() <del># mixin.resource = GroupResource <del> <del># self.assertRaises(ImmediateResponse, mixin.get, request, id=12345) <del> <del> <del># class TestModelCreation(TestModelsTestCase): <del># """Tests on CreateModelMixin""" <del> <del># def setUp(self): <del># super(TestModelsTestCase, self).setUp() <del># self.req = RequestFactory() <del> <del># def test_creation(self): <del># self.assertEquals(0, Group.objects.count()) <del> <del># class GroupResource(ModelResource): <del># model = Group <del> <del># form_data = {'name': 'foo'} <del># request = self.req.post('/groups', data=form_data) <del># mixin = CreateModelMixin() <del># mixin.resource = GroupResource <del># mixin.CONTENT = form_data <del> <del># response = mixin.post(request) <del># self.assertEquals(1, Group.objects.count()) <del># self.assertEquals('foo', response.raw_content.name) <del> <del># def test_creation_with_m2m_relation(self): <del># class UserResource(ModelResource): <del># model = User <del> <del># def url(self, instance): <del># return "/users/%i" % instance.id <del> <del># group = Group(name='foo') <del># group.save() <del> <del># form_data = { <del># 'username': 'bar', <del># 'password': 'baz', <del># 'groups': [group.id] <del># } <del># request = self.req.post('/groups', data=form_data) <del># cleaned_data = dict(form_data) <del># cleaned_data['groups'] = [group] <del># mixin = CreateModelMixin() <del># mixin.resource = UserResource <del># mixin.CONTENT = cleaned_data <del> <del># response = mixin.post(request) <del># self.assertEquals(1, User.objects.count()) <del># self.assertEquals(1, response.raw_content.groups.count()) <del># self.assertEquals('foo', response.raw_content.groups.all()[0].name) <del> <del># def test_creation_with_m2m_relation_through(self): <del># """ <del># Tests creation where the m2m relation uses a through table <del># """ <del># class UserResource(ModelResource): <del># model = CustomUser <del> <del># def url(self, instance): <del># return "/customusers/%i" % instance.id <del> <del># form_data = {'username': 'bar0', 'groups': []} <del># request = self.req.post('/groups', data=form_data) <del># cleaned_data = dict(form_data) <del># cleaned_data['groups'] = [] <del># mixin = CreateModelMixin() <del># mixin.resource = UserResource <del># mixin.CONTENT = cleaned_data <del> <del># response = mixin.post(request) <del># self.assertEquals(1, CustomUser.objects.count()) <del># self.assertEquals(0, response.raw_content.groups.count()) <del> <del># group = Group(name='foo1') <del># group.save() <del> <del># form_data = {'username': 'bar1', 'groups': [group.id]} <del># request = self.req.post('/groups', data=form_data) <del># cleaned_data = dict(form_data) <del># cleaned_data['groups'] = [group] <del># mixin = CreateModelMixin() <del># mixin.resource = UserResource <del># mixin.CONTENT = cleaned_data <del> <del># response = mixin.post(request) <del># self.assertEquals(2, CustomUser.objects.count()) <del># self.assertEquals(1, response.raw_content.groups.count()) <del># self.assertEquals('foo1', response.raw_content.groups.all()[0].name) <del> <del># group2 = Group(name='foo2') <del># group2.save() <del> <del># form_data = {'username': 'bar2', 'groups': [group.id, group2.id]} <del># request = self.req.post('/groups', data=form_data) <del># cleaned_data = dict(form_data) <del># cleaned_data['groups'] = [group, group2] <del># mixin = CreateModelMixin() <del># mixin.resource = UserResource <del># mixin.CONTENT = cleaned_data <del> <del># response = mixin.post(request) <del># self.assertEquals(3, CustomUser.objects.count()) <del># self.assertEquals(2, response.raw_content.groups.count()) <del># self.assertEquals('foo1', response.raw_content.groups.all()[0].name) <del># self.assertEquals('foo2', response.raw_content.groups.all()[1].name) <del> <del> <del># class MockPaginatorView(PaginatorMixin, View): <del># total = 60 <del> <del># def get(self, request): <del># return Response(range(0, self.total)) <del> <del># def post(self, request): <del># return Response({'status': 'OK'}, status=status.HTTP_201_CREATED) <del> <del> <del># class TestPagination(TestCase): <del># def setUp(self): <del># self.req = RequestFactory() <del> <del># def test_default_limit(self): <del># """ Tests if pagination works without overwriting the limit """ <del># request = self.req.get('/paginator') <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del> <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(MockPaginatorView.total, content['total']) <del># self.assertEqual(MockPaginatorView.limit, content['per_page']) <del> <del># self.assertEqual(range(0, MockPaginatorView.limit), content['results']) <del> <del># def test_overwriting_limit(self): <del># """ Tests if the limit can be overwritten """ <del># limit = 10 <del> <del># request = self.req.get('/paginator') <del># response = MockPaginatorView.as_view(limit=limit)(request) <del># content = response.raw_content <del> <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(content['per_page'], limit) <del> <del># self.assertEqual(range(0, limit), content['results']) <del> <del># def test_limit_param(self): <del># """ Tests if the client can set the limit """ <del># from math import ceil <del> <del># limit = 5 <del># num_pages = int(ceil(MockPaginatorView.total / float(limit))) <del> <del># request = self.req.get('/paginator/?limit=%d' % limit) <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del> <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(MockPaginatorView.total, content['total']) <del># self.assertEqual(limit, content['per_page']) <del># self.assertEqual(num_pages, content['pages']) <del> <del># def test_exceeding_limit(self): <del># """ Makes sure the client cannot exceed the default limit """ <del># from math import ceil <del> <del># limit = MockPaginatorView.limit + 10 <del># num_pages = int(ceil(MockPaginatorView.total / float(limit))) <del> <del># request = self.req.get('/paginator/?limit=%d' % limit) <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del> <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(MockPaginatorView.total, content['total']) <del># self.assertNotEqual(limit, content['per_page']) <del># self.assertNotEqual(num_pages, content['pages']) <del># self.assertEqual(MockPaginatorView.limit, content['per_page']) <del> <del># def test_only_works_for_get(self): <del># """ Pagination should only work for GET requests """ <del># request = self.req.post('/paginator', data={'content': 'spam'}) <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del> <del># self.assertEqual(response.status_code, status.HTTP_201_CREATED) <del># self.assertEqual(None, content.get('per_page')) <del># self.assertEqual('OK', content['status']) <del> <del># def test_non_int_page(self): <del># """ Tests that it can handle invalid values """ <del># request = self.req.get('/paginator/?page=spam') <del># response = MockPaginatorView.as_view()(request) <del> <del># self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) <del> <del># def test_page_range(self): <del># """ Tests that the page range is handle correctly """ <del># request = self.req.get('/paginator/?page=0') <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) <del> <del># request = self.req.get('/paginator/') <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(range(0, MockPaginatorView.limit), content['results']) <del> <del># num_pages = content['pages'] <del> <del># request = self.req.get('/paginator/?page=%d' % num_pages) <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(range(MockPaginatorView.limit*(num_pages-1), MockPaginatorView.total), content['results']) <del> <del># request = self.req.get('/paginator/?page=%d' % (num_pages + 1,)) <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) <del> <del># def test_existing_query_parameters_are_preserved(self): <del># """ Tests that existing query parameters are preserved when <del># generating next/previous page links """ <del># request = self.req.get('/paginator/?foo=bar&another=something') <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertTrue('foo=bar' in content['next']) <del># self.assertTrue('another=something' in content['next']) <del># self.assertTrue('page=2' in content['next']) <del> <del># def test_duplicate_parameters_are_not_created(self): <del># """ Regression: ensure duplicate "page" parameters are not added to <del># paginated URLs. So page 1 should contain ?page=2, not ?page=1&page=2 """ <del># request = self.req.get('/paginator/?page=1') <del># response = MockPaginatorView.as_view()(request) <del># content = response.raw_content <del># self.assertTrue('page=2' in content['next']) <del># self.assertFalse('page=1' in content['next'])
1
PHP
PHP
support special float values on postgresql
ffa5803a9dd72ca431cf4711cf636f3ba20f57db
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php <ide> protected function castAttribute($key, $value) <ide> case 'real': <ide> case 'float': <ide> case 'double': <del> return (float) $value; <add> return $this->fromFloat($value); <ide> case 'string': <ide> return (string) $value; <ide> case 'bool': <ide> public function fromJson($value, $asObject = false) <ide> return json_decode($value, ! $asObject); <ide> } <ide> <add> /** <add> * Cast the given float value. <add> * <add> * @param mixed $value <add> * @return mixed <add> */ <add> public function fromFloat($value) <add> { <add> switch ($value) { <add> case 'Infinity': <add> return INF; <add> case '-Infinity': <add> return -INF; <add> case 'NaN': <add> return NAN; <add> default: <add> return (float) $value; <add> } <add> } <add> <ide> /** <ide> * Return a timestamp as DateTime object with time set to 00:00:00. <ide> * <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testModelAttributeCastingFailsOnUnencodableData() <ide> $model->getAttributes(); <ide> } <ide> <add> public function testModelAttributeCastingWithSpecialFloatValues() <add> { <add> $model = new EloquentModelCastingStub; <add> <add> $model->floatAttribute = 'Infinity'; <add> $this->assertEquals(INF, $model->floatAttribute); <add> <add> $model->floatAttribute = INF; <add> $this->assertEquals(INF, $model->floatAttribute); <add> <add> $model->floatAttribute = '-Infinity'; <add> $this->assertEquals(-INF, $model->floatAttribute); <add> <add> $model->floatAttribute = -INF; <add> $this->assertEquals(-INF, $model->floatAttribute); <add> <add> $model->floatAttribute = 'NaN'; <add> $this->assertNan($model->floatAttribute); <add> <add> $model->floatAttribute = NAN; <add> $this->assertNan($model->floatAttribute); <add> } <add> <ide> public function testUpdatingNonExistentModelFails() <ide> { <ide> $model = new EloquentModelStub;
2
Text
Text
update the roadmap
de86d33b4a39d095e29b4857bc768363a70b3adc
<ide><path>ROADMAP.md <del>Docker Engine Roadmap <del>===================== <add>Moby Project Roadmap <add>==================== <ide> <ide> ### How should I use this document? <ide> <ide> This document provides description of items that the project decided to prioritize. This should <del>serve as a reference point for Docker contributors to understand where the project is going, and <del>help determine if a contribution could be conflicting with some longer terms plans. <add>serve as a reference point for Moby contributors to understand where the project is going, and <add>help determine if a contribution could be conflicting with some longer term plans. <ide> <ide> The fact that a feature isn't listed here doesn't mean that a patch for it will automatically be <del>refused (except for those mentioned as "frozen features" below)! We are always happy to receive <del>patches for new cool features we haven't thought about, or didn't judge priority. Please however <del>understand that such patches might take longer for us to review. <add>refused! We are always happy to receive patches for new cool features we haven't thought about, <add>or didn't judge to be a priority. Please however understand that such patches might take longer <add>for us to review. <ide> <ide> ### How can I help? <ide> <del>Short term objectives are listed in the [wiki](https://github.com/docker/docker/wiki) and described <del>in [Issues](https://github.com/docker/docker/issues?q=is%3Aopen+is%3Aissue+label%3Aroadmap). Our <add>Short term objectives are listed in <add>[Issues](https://github.com/moby/moby/issues?q=is%3Aopen+is%3Aissue+label%3Aroadmap). Our <ide> goal is to split down the workload in such way that anybody can jump in and help. Please comment on <del>issues if you want to take it to avoid duplicating effort! Similarly, if a maintainer is already <del>assigned on an issue you'd like to participate in, pinging him on IRC or GitHub to offer your help is <add>issues if you want to work on it to avoid duplicating effort! Similarly, if a maintainer is already <add>assigned on an issue you'd like to participate in, pinging him on GitHub to offer your help is <ide> the best way to go. <ide> <ide> ### How can I add something to the roadmap? <ide> <del>The roadmap process is new to the Docker Engine: we are only beginning to structure and document the <add>The roadmap process is new to the Moby Project: we are only beginning to structure and document the <ide> project objectives. Our immediate goal is to be more transparent, and work with our community to <ide> focus our efforts on fewer prioritized topics. <ide> <ide> We hope to offer in the near future a process allowing anyone to propose a topic to the roadmap, but <del>we are not quite there yet. For the time being, the BDFL remains the keeper of the roadmap, and we <del>won't be accepting pull requests adding or removing items from this file. <add>we are not quite there yet. For the time being, it is best to discuss with the maintainers on an <add>issue, in the Slack channel, or in person at the Moby Summits that happen every few months. <ide> <ide> # 1. Features and refactoring <ide> <ide> ## 1.1 Runtime improvements <ide> <del>We recently introduced [`runC`](https://runc.io) as a standalone low-level tool for container <del>execution. The initial goal was to integrate runC as a replacement in the Engine for the traditional <del>default libcontainer `execdriver`, but the Engine internals were not ready for this. <add>We introduced [`runC`](https://runc.io) as a standalone low-level tool for container <add>execution in 2015, the first stage in spinning out parts of the Engine into standalone tools. <ide> <ide> As runC continued evolving, and the OCI specification along with it, we created <del>[`containerd`](https://containerd.tools/), a daemon to control and monitor multiple `runC`. This is <del>the new target for Engine integration, as it can entirely replace the whole `execdriver` <del>architecture, and container monitoring along with it. <add>[`containerd`](https://github.com/containerd/containerd), a daemon to control and monitor `runC`. <add>In late 2016 this was relaunched as the `containerd` 1.0 track, aiming to provide a common runtime <add>for the whole spectrum of container systems, including Kubernetes, with wide community support. <add>This change meant that there was an increased scope for `containerd`, including image management <add>and storage drivers. <ide> <del>Docker Engine will rely on a long-running `containerd` companion daemon for all container execution <add>Moby will rely on a long-running `containerd` companion daemon for all container execution <ide> related operations. This could open the door in the future for Engine restarts without interrupting <del>running containers. <add>running containers. The switch over to containerd 1.0 is an important goal for the project, and <add>will result in a significant simplification of the functions implemented in this repository. <ide> <del>## 1.2 Plugins improvements <add>## 1.2 Internal decoupling <ide> <del>Docker Engine 1.7.0 introduced plugin support, initially for the use cases of volumes and networks <del>extensions. The plugin infrastructure was kept minimal as we were collecting use cases and real <del>world feedback before optimizing for any particular workflow. <add>A lot of work has been done in trying to decouple Moby internals. This process of creating <add>standalone projects with a well defined function that attract a dedicated community should continue. <add>As well as integrating `containerd` we would like to integrate [BuildKit](https://github.com/moby/buildkit) <add>as the next standalone component. <ide> <del>In the future, we'd like plugins to become first class citizens, and encourage an ecosystem of <del>plugins. This implies in particular making it trivially easy to distribute plugins as containers <del>through any Registry instance, as well as solving the commonly heard pain points of plugins needing <del>to be treated as somewhat special (being active at all time, started before any other user <del>containers, and not as easily dismissed). <add>We see gRPC as the natural communication layer between decoupled components. <ide> <del>## 1.3 Internal decoupling <add>## 1.3 Custom assembly tooling <ide> <del>A lot of work has been done in trying to decouple the Docker Engine's internals. In particular, the <del>API implementation has been refactored, and the Builder side of the daemon is now <del>[fully independent](https://github.com/docker/docker/tree/master/builder) while still residing in <del>the same repository. <del> <del>We are exploring ways to go further with that decoupling, capitalizing on the work introduced by the <del>runtime renovation and plugins improvement efforts. Indeed, the combination of `containerd` support <del>with the concept of "special" containers opens the door for bootstrapping more Engine internals <del>using the same facilities. <del> <del>## 1.4 Cluster capable Engine <del> <del>The community has been pushing for a more cluster capable Docker Engine, and a huge effort was spent <del>adding features such as multihost networking, and node discovery down at the Engine level. Yet, the <del>Engine is currently incapable of taking scheduling decisions alone, and continues relying on Swarm <del>for that. <del> <del>We plan to complete this effort and make Engine fully cluster capable. Multiple instances of the <del>Docker Engine being already capable of discovering each other and establish overlay networking for <del>their container to communicate, the next step is for a given Engine to gain ability to dispatch work <del>to another node in the cluster. This will be introduced in a backward compatible way, such that a <del>`docker run` invocation on a particular node remains fully deterministic. <del> <del># 2. Frozen features <del> <del>## 2.1 Docker exec <del> <del>We won't accept patches expanding the surface of `docker exec`, which we intend to keep as a <del>*debugging* feature, as well as being strongly dependent on the Runtime ingredient effort. <del> <del>## 2.2 Remote Registry Operations <del> <del>A large amount of work is ongoing in the area of image distribution and provenance. This includes <del>moving to the V2 Registry API and heavily refactoring the code that powers these features. The <del>desired result is more secure, reliable and easier to use image distribution. <del> <del>Part of the problem with this part of the code base is the lack of a stable and flexible interface. <del>If new features are added that access the registry without solidifying these interfaces, achieving <del>feature parity will continue to be elusive. While we get a handle on this situation, we are imposing <del>a moratorium on new code that accesses the Registry API in commands that don't already make remote <del>calls. <del> <del>Currently, only the following commands cause interaction with a remote registry: <del> <del> - push <del> - pull <del> - run <del> - build <del> - search <del> - login <del> <del>In the interest of stabilizing the registry access model during this ongoing work, we are not <del>accepting additions to other commands that will cause remote interaction with the Registry API. This <del>moratorium will lift when the goals of the distribution project have been met. <add>We have been prototyping the Moby [assembly tool](https://github.com/moby/tool) which was originally <add>developed for LinuxKit and intend to turn it into a more generic packaging and assembly mechanism <add>that can build not only the default version of Moby, as distribution packages or other useful forms, <add>but can also build very different container systems, themselves built of cooperating daemons built in <add>and running in containers. We intend to merge this functionality into this repo.
1
Java
Java
combine catches block with same body
7bce04c06ccfcbcec1c4f7a3dbc75cea6621505a
<ide><path>spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java <ide> else if (value instanceof Map) { <ide> throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, <ide> "Index of out of bounds in property path '" + propertyName + "'", ex); <ide> } <del> catch (NumberFormatException ex) { <del> throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, <del> "Invalid index in property path '" + propertyName + "'", ex); <del> } <del> catch (TypeMismatchException ex) { <add> catch (NumberFormatException | TypeMismatchException ex) { <ide> throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, <ide> "Invalid index in property path '" + propertyName + "'", ex); <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java <ide> protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable O <ide> } <ide> return beanInstance; <ide> } <del> catch (BeanCreationException ex) { <add> catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { <ide> // A previously detected exception with proper bean creation context already... <del> throw ex; <del> } <del> catch (ImplicitlyAppearedSingletonException ex) { <ide> // An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry... <ide> throw ex; <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java <ide> public void setAsText(String text) throws IllegalArgumentException { <ide> return; <ide> } <ide> } <del> catch (URISyntaxException ex) { <add> catch (URISyntaxException | FileSystemNotFoundException ex) { <ide> // Not a valid URI: Let's try as Spring resource location. <del> } <del> catch (FileSystemNotFoundException ex) { <ide> // URI scheme not registered for NIO: <ide> // Let's try URL protocol handlers via Spring's resource mechanism. <ide> } <ide><path>spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java <ide> public Object invoke(MethodInvocation invocation) throws Throwable { <ide> try { <ide> return doInvoke(invocation); <ide> } <del> catch (MBeanConnectFailureException ex) { <del> return handleConnectFailure(invocation, ex); <del> } <del> catch (IOException ex) { <add> catch (MBeanConnectFailureException | IOException ex) { <ide> return handleConnectFailure(invocation, ex); <ide> } <ide> } <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/AbstractMessageListenerContainer.java <ide> protected void doExecuteListener(Session session, Message message) throws JMSExc <ide> try { <ide> invokeListener(session, message); <ide> } <del> catch (JMSException ex) { <add> catch (JMSException | RuntimeException | Error ex) { <ide> rollbackOnExceptionIfNecessary(session, ex); <ide> throw ex; <ide> } <del> catch (RuntimeException ex) { <del> rollbackOnExceptionIfNecessary(session, ex); <del> throw ex; <del> } <del> catch (Error err) { <del> rollbackOnExceptionIfNecessary(session, err); <del> throw err; <del> } <ide> commitIfNecessary(session, message); <ide> } <ide> <ide><path>spring-jms/src/main/java/org/springframework/jms/support/JmsUtils.java <ide> public static void commitIfNecessary(Session session) throws JMSException { <ide> try { <ide> session.commit(); <ide> } <del> catch (javax.jms.TransactionInProgressException ex) { <del> // Ignore -> can only happen in case of a JTA transaction. <del> } <del> catch (javax.jms.IllegalStateException ex) { <add> catch (javax.jms.TransactionInProgressException | javax.jms.IllegalStateException ex) { <ide> // Ignore -> can only happen in case of a JTA transaction. <ide> } <ide> } <ide> public static void rollbackIfNecessary(Session session) throws JMSException { <ide> try { <ide> session.rollback(); <ide> } <del> catch (javax.jms.TransactionInProgressException ex) { <del> // Ignore -> can only happen in case of a JTA transaction. <del> } <del> catch (javax.jms.IllegalStateException ex) { <add> catch (javax.jms.TransactionInProgressException | javax.jms.IllegalStateException ex) { <ide> // Ignore -> can only happen in case of a JTA transaction. <ide> } <ide> } <ide><path>spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java <ide> protected void doBegin(Object transaction, TransactionDefinition definition) { <ide> try { <ide> doJtaBegin(txObject, definition); <ide> } <del> catch (NotSupportedException ex) { <del> // assume nested transaction not supported <del> throw new NestedTransactionNotSupportedException( <del> "JTA implementation does not support nested transactions", ex); <del> } <del> catch (UnsupportedOperationException ex) { <add> catch (NotSupportedException | UnsupportedOperationException ex) { <ide> // assume nested transaction not supported <ide> throw new NestedTransactionNotSupportedException( <ide> "JTA implementation does not support nested transactions", ex); <ide><path>spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartFile.java <ide> public void transferTo(File dest) throws IOException, IllegalStateException { <ide> catch (FileUploadException ex) { <ide> throw new IllegalStateException(ex.getMessage(), ex); <ide> } <del> catch (IllegalStateException ex) { <add> catch (IllegalStateException | IOException ex) { <ide> // Pass through when coming from FileItem directly <del> throw ex; <del> } <del> catch (IOException ex) { <ide> // From I/O operations within FileItem.write <ide> throw ex; <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/AbstractMediaTypeExpression.java <ide> public final boolean match(ServerWebExchange exchange) { <ide> boolean match = matchMediaType(exchange); <ide> return (!this.isNegated == match); <ide> } <del> catch (NotAcceptableStatusException ex) { <del> return false; <del> } <del> catch (UnsupportedMediaTypeStatusException ex) { <add> catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) { <ide> return false; <ide> } <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java <ide> protected final void initServletBean() throws ServletException { <ide> this.webApplicationContext = initWebApplicationContext(); <ide> initFrameworkServlet(); <ide> } <del> catch (ServletException ex) { <del> this.logger.error("Context initialization failed", ex); <del> throw ex; <del> } <del> catch (RuntimeException ex) { <add> catch (ServletException | RuntimeException ex) { <ide> this.logger.error("Context initialization failed", ex); <ide> throw ex; <ide> }
10
Javascript
Javascript
remove paddingtop in animatedgratuitousapp
62f53ffaa7f5ccdebe133ce0d212ee80fc85c37c
<ide><path>Examples/UIExplorer/AnimatedGratuitousApp/AnExApp.js <ide> function moveToClosest({activeKey, keys, restLayouts}, position) { <ide> var styles = StyleSheet.create({ <ide> container: { <ide> flex: 1, <del> paddingTop: 64, // push content below nav bar <ide> }, <ide> grid: { <ide> flex: 1,
1
PHP
PHP
allow easy extension of user providers
4d09a3c46aac7e765710d51dfea3e800ea978a13
<ide><path>src/Illuminate/Auth/AuthManager.php <ide> public function viaRequest($name, callable $callback) <ide> /** <ide> * Register a custom driver creator Closure. <ide> * <del> * @param string $driver <add> * @param string $driver <ide> * @param \Closure $callback <ide> * @return $this <ide> */ <ide> public function extend($driver, Closure $callback) <ide> return $this; <ide> } <ide> <add> /** <add> * Register a custom provider creator Closure. <add> * <add> * @param string $name <add> * @param \Closure $callback <add> * @return $this <add> */ <add> public function provider($name, Closure $callback) <add> { <add> $this->customProviderCreators[$name] = $callback; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Dynamically call the default driver instance. <ide> * <ide> * @param string $method <del> * @param array $parameters <add> * @param array $parameters <ide> * @return mixed <ide> */ <ide> public function __call($method, $parameters) <ide><path>src/Illuminate/Auth/CreatesUserProviders.php <ide> <ide> trait CreatesUserProviders <ide> { <add> /** <add> * The registered custom provider creators. <add> * <add> * @var array <add> */ <add> protected $customProviderCreators = []; <add> <ide> /** <ide> * Create the user provider implementation for the driver. <ide> * <ide> protected function createUserProvider($provider) <ide> { <ide> $config = $this->app['config']['auth.sources.'.$provider]; <ide> <add> if (isset($this->customProviderCreators[$provider])) { <add> return call_user_func( <add> $this->customProviderCreators[$provider], $this->app, $config <add> ); <add> } <add> <ide> switch ($config['driver']) { <ide> case 'database': <ide> return $this->createDatabaseProvider($config);
2
Python
Python
make double backticks for parameters in docstring
4e70f09a4f2679a973f36a666ef4249f465af2d4
<ide><path>numpy/testing/_private/utils.py <ide> def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True, <ide> <ide> Notes <ide> ----- <del> When one of `actual` and `desired` is a scalar and the other is array_like, <add> When one of ``actual`` and ``desired`` is a scalar and the other is array_like, <ide> the function checks that each element of the array_like object is equal to <ide> the scalar. <ide>
1
Javascript
Javascript
replace checkuint() with validateint32()
d669251f67b0d6e70853b18f7d9358fc98cb5ceb
<ide><path>lib/internal/crypto/pbkdf2.js <ide> <ide> const { AsyncWrap, Providers } = process.binding('async_wrap'); <ide> const { Buffer } = require('buffer'); <del>const { pbkdf2: _pbkdf2 } = process.binding('crypto'); <add>const { INT_MAX, pbkdf2: _pbkdf2 } = process.binding('crypto'); <add>const { validateInt32 } = require('internal/validators'); <ide> const { <ide> ERR_CRYPTO_INVALID_DIGEST, <ide> ERR_CRYPTO_PBKDF2_ERROR, <ide> const { <ide> } = require('internal/errors').codes; <ide> const { <ide> checkIsArrayBufferView, <del> checkIsUint, <ide> getDefaultEncoding, <ide> } = require('internal/crypto/util'); <ide> <ide> function check(password, salt, iterations, keylen, digest, callback) { <ide> <ide> password = checkIsArrayBufferView('password', password); <ide> salt = checkIsArrayBufferView('salt', salt); <del> // FIXME(bnoordhuis) The error message is in fact wrong since |iterations| <del> // cannot be > INT_MAX. Adjust in the next major release. <del> iterations = checkIsUint('iterations', iterations, 'a non-negative number'); <del> keylen = checkIsUint('keylen', keylen); <add> iterations = validateInt32(iterations, 'iterations', 0, INT_MAX); <add> keylen = validateInt32(keylen, 'keylen', 0, INT_MAX); <ide> <ide> return { password, salt, iterations, keylen, digest }; <ide> } <ide><path>lib/internal/crypto/scrypt.js <ide> <ide> const { AsyncWrap, Providers } = process.binding('async_wrap'); <ide> const { Buffer } = require('buffer'); <del>const { scrypt: _scrypt } = process.binding('crypto'); <add>const { INT_MAX, scrypt: _scrypt } = process.binding('crypto'); <add>const { validateInt32 } = require('internal/validators'); <ide> const { <ide> ERR_CRYPTO_SCRYPT_INVALID_PARAMETER, <ide> ERR_CRYPTO_SCRYPT_NOT_SUPPORTED, <ide> ERR_INVALID_CALLBACK, <ide> } = require('internal/errors').codes; <ide> const { <ide> checkIsArrayBufferView, <del> checkIsUint, <ide> getDefaultEncoding, <ide> } = require('internal/crypto/util'); <ide> <ide> function check(password, salt, keylen, options, callback) { <ide> throw new ERR_CRYPTO_SCRYPT_NOT_SUPPORTED(); <ide> <ide> password = checkIsArrayBufferView('password', password); <del> salt = checkIsArrayBufferView('salt', salt); <del> keylen = checkIsUint('keylen', keylen); <add> salt = checkIsArrayBufferView(salt, 'salt'); <add> keylen = validateInt32(keylen, 'keylen', 0, INT_MAX); <ide> <ide> let { N, r, p, maxmem } = defaults; <ide> if (options && options !== defaults) { <del> if (options.hasOwnProperty('N')) N = checkIsUint('N', options.N); <del> if (options.hasOwnProperty('r')) r = checkIsUint('r', options.r); <del> if (options.hasOwnProperty('p')) p = checkIsUint('p', options.p); <add> if (options.hasOwnProperty('N')) <add> N = validateInt32(options.N, 'N', 0, INT_MAX); <add> if (options.hasOwnProperty('r')) <add> r = validateInt32(options.r, 'r', 0, INT_MAX); <add> if (options.hasOwnProperty('p')) <add> p = validateInt32(options.p, 'p', 0, INT_MAX); <ide> if (options.hasOwnProperty('maxmem')) <del> maxmem = checkIsUint('maxmem', options.maxmem); <add> maxmem = validateInt32(options.maxmem, 'maxmem', 0, INT_MAX); <ide> if (N === 0) N = defaults.N; <ide> if (r === 0) r = defaults.r; <ide> if (p === 0) p = defaults.p; <ide><path>lib/internal/crypto/util.js <ide> const { <ide> ERR_CRYPTO_ENGINE_UNKNOWN, <ide> ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, <ide> ERR_INVALID_ARG_TYPE, <del> ERR_OUT_OF_RANGE, <ide> } = require('internal/errors').codes; <ide> const { Buffer } = require('buffer'); <ide> const { <ide> const { <ide> const { <ide> isArrayBufferView <ide> } = require('internal/util/types'); <del>const { <del> INT_MAX <del>} = process.binding('constants').crypto; <ide> <ide> var defaultEncoding = 'buffer'; <ide> <ide> function checkIsArrayBufferView(name, buffer) { <ide> return buffer; <ide> } <ide> <del>function checkIsUint(name, value, errmsg = `>= 0 && <= ${INT_MAX}`) { <del> if (typeof value !== 'number') <del> throw new ERR_INVALID_ARG_TYPE(name, 'number', value); <del> <del> if (value < 0 || !Number.isInteger(value) || value > INT_MAX) <del> throw new ERR_OUT_OF_RANGE(name, errmsg, value); <del> <del> return value; <del>} <del> <ide> module.exports = { <ide> checkIsArrayBufferView, <del> checkIsUint, <ide> getCiphers, <ide> getCurves, <ide> getDefaultEncoding, <ide><path>lib/internal/validators.js <ide> function validateInteger(value, name) { <ide> Error.captureStackTrace(err, validateInteger); <ide> throw err; <ide> } <add> <add> return value; <ide> } <ide> <ide> function validateInt32(value, name, min = -2147483648, max = 2147483647) { <ide> function validateInt32(value, name, min = -2147483648, max = 2147483647) { <ide> Error.captureStackTrace(err, validateInt32); <ide> throw err; <ide> } <add> <add> return value; <ide> } <ide> <ide> function validateUint32(value, name, positive) { <ide> function validateUint32(value, name, positive) { <ide> Error.captureStackTrace(err, validateUint32); <ide> throw err; <ide> } <add> <add> return value; <ide> } <ide> <ide> module.exports = { <ide><path>test/parallel/test-crypto-pbkdf2.js <ide> assert.throws( <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError [ERR_OUT_OF_RANGE]', <ide> message: 'The value of "iterations" is out of range. ' + <del> 'It must be a non-negative number. Received -1' <add> 'It must be >= 0 && <= 2147483647. Received -1' <ide> } <ide> ); <ide> <ide> assert.throws( <ide> }); <ide> }); <ide> <del>[Infinity, -Infinity, NaN, -1, 4073741824, INT_MAX + 1].forEach((input) => { <add>[Infinity, -Infinity, NaN].forEach((input) => { <add> assert.throws( <add> () => { <add> crypto.pbkdf2('password', 'salt', 1, input, 'sha256', <add> common.mustNotCall()); <add> }, { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "keylen" is out of range. It ' + <add> `must be an integer. Received ${input}` <add> }); <add>}); <add> <add>[-1, 4073741824, INT_MAX + 1].forEach((input) => { <ide> assert.throws( <ide> () => { <ide> crypto.pbkdf2('password', 'salt', 1, input, 'sha256',
5
Text
Text
update instructions for running on device
c49fc1ee6c51ac690733ea3f7e673f55e3579184
<ide><path>docs/RunningOnDeviceIOS.md <ide> You can iterate quickly on device using development server. To do that, your lap <ide> <ide> ## Using offline bundle <ide> <del>You can also pack all the JavaScript code within the app itself. This way you can test it without development server running and submit the app to the AppStore. <add>When you run your app on device, we pack all the JavaScript code and the images used into the app's resources. This way you can test it without development server running and submit the app to the AppStore. <ide> <ide> 1. Open `AwesomeApp/ios/AwesomeApp/AppDelegate.m` <del>2. Follow the instructions for "OPTION 2": <del> * Uncomment `jsCodeLocation = [[NSBundle mainBundle] ...` <del> * Run the `react-native bundle --platform ios --dev false --entry-file index.ios.js --bundle-output iOS/main.jsbundle` command in terminal from the root directory of your app <del> <del>The bundle script supports a couple of flags: <del> <del>* `--dev` - a boolean with a default value of `true`. With the `--dev true` flag, the bundled JavaScript code turns on useful development warnings and limits performance optimizations. For production it is recommended to pass `--dev false`. Also for production, be sure to have your native build configuration set to `Release` (e.g., Xcode's Release configuration for iOS and gradle's `assembleRelease` task for Android) in order to disable things like the shake-to-show developer menu. <del>* `--minify` - pipe the JS code through UglifyJS. <del> <del>Note that on 0.14 we'll change the API of `react-native bundle`. The major changes are: <del> <del>* API is now `entry-file <path>` based instead of url based. <del>* Need to specify which platform you're bundling for `--platform <ios|android>`. <del>* Option `--out` has been renamed for `--bundle-output`. <del>* Source maps are no longer automatically generated. Need to specify `--sourcemap-output <path>` <add>2. Uncomment `jsCodeLocation = [[NSBundle mainBundle] ...` <add>3. The JS bundle will be built for dev or prod depending on your app's scheme (Debug = development build with warnings, Release = minified prod build with perf optimizations). <ide> <ide> ## Disabling in-app developer menu <ide> <ide> When building your app for production, your app's scheme should be set to `Relea <ide> <ide> If `curl` command fails make sure the packager is running. Also try adding `--ipv4` flag to the end of it. <ide> <del>If you started your project a while ago, `main.jsbundle` might not be included into Xcode project. To add it, right click on your project directory and click "Add Files to ..." - choose the `main.jsbundle` file that you generated. <add>Note that since [v0.14](https://github.com/facebook/react-native/releases/tag/0.14.0) JS and images are automatically packaged into the iOS app using `Bundle React Native code and images` Xcode build phase.
1
Javascript
Javascript
reflow the radar before updating to update scale
ea9d144c71819cbb3499d0640102689e10e25a02
<ide><path>src/Chart.Radar.js <ide> this.eachPoints(function(point){ <ide> point.save(); <ide> }); <add> this.reflow(); <ide> this.render(); <ide> }, <ide> reflow: function(){
1
Ruby
Ruby
improve error message when passed unsupported type
ac5dfadb485ff1e06a73d69936de14464586af2c
<ide><path>lib/arel/visitors/to_sql.rb <ide> def quoted o, a <ide> end <ide> <ide> def unsupported o, collector <del> raise "unsupported: #{o.class.name}" <add> raise "unsupported argument type: #{o.class.name}. Construct an Arel node instead." <ide> end <ide> <ide> alias :visit_ActiveSupport_Multibyte_Chars :unsupported
1
Javascript
Javascript
remove @providesmodule in www bundles
da4e85567b411a180c2cfa1ef6573cf3cc9257f1
<ide><path>scripts/rollup/wrappers.js <ide> ${source}`; <ide> ${license} <ide> * <ide> * @noflow <del> * @providesModule ${globalName}-dev <ide> * @preventMunge <ide> */ <ide> <ide> ${source} <ide> ${license} <ide> * <ide> * @noflow <del> * @providesModule ${globalName}-prod <ide> * @preventMunge <ide> */ <ide>
1
Ruby
Ruby
fix whitespace handling
6a3dc198f5501d4c98d661fd17fd2231715e8d16
<ide><path>Library/Contributions/cmd/brew-pull.rb <ide> def tap arg <ide> patch_args << '--signoff' unless ARGV.include? '--clean' <ide> # Normally we don't want whitespace errors, but squashing them can break <ide> # patches so an option is provided to skip this step. <del> patch_args << '--whitespace=fix' unless ARGV.include? '--ignore-whitespace' or ARGV.include? '--clean' <add> if ARGV.include? '--ignore-whitespace' or ARGV.include? '--clean' <add> patch_args << '--whitespace=nowarn' <add> else <add> patch_args << '--whitespace=fix' <add> end <ide> patch_args << patchpath <ide> <ide> safe_system 'git', *patch_args
1
Javascript
Javascript
expose setsurfaceprops api in js
b5e2e1d52d6fc7550bb19a5e348923b40941be46
<ide><path>Libraries/ReactNative/AppRegistry.js <ide> const AppRegistry = { <ide> runnables[appKey].run(appParameters); <ide> }, <ide> <add> /** <add> * Update initial props for a surface that's already rendered <add> */ <add> setSurfaceProps(appKey: string, appParameters: any): void { <add> if (appKey !== 'LogBox') { <add> const msg = <add> 'Updating props for Surface "' + <add> appKey + <add> '" with ' + <add> JSON.stringify(appParameters); <add> infoLog(msg); <add> BugReporting.addSource( <add> 'AppRegistry.setSurfaceProps' + runCount++, <add> () => msg, <add> ); <add> } <add> invariant( <add> runnables[appKey] && runnables[appKey].run, <add> `"${appKey}" has not been registered. This can happen if:\n` + <add> '* Metro (the local dev server) is run from the wrong folder. ' + <add> 'Check if Metro is running, stop it and restart it in the current project.\n' + <add> "* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.", <add> ); <add> <add> runnables[appKey].run(appParameters); <add> }, <add> <ide> /** <ide> * Stops an application when a view should be destroyed. <ide> *
1
Go
Go
remove layerstore indexing by os (used for lcow)
dc7cbb9b337c84bdd76e849ae361dffb191dd936
<ide><path>daemon/container.go <ide> func (daemon *Daemon) newContainer(name string, operatingSystem string, config * <ide> base.ImageID = imgID <ide> base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName} <ide> base.Name = name <del> base.Driver = daemon.imageService.GraphDriverForOS(operatingSystem) <add> base.Driver = daemon.imageService.GraphDriverName() <ide> base.OS = operatingSystem <ide> return base, err <ide> } <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) restore() error { <ide> } <ide> // Ignore the container if it does not support the current driver being used by the graph <ide> if (c.Driver == "" && daemon.graphDriver == "aufs") || c.Driver == daemon.graphDriver { <del> rwlayer, err := daemon.imageService.GetLayerByID(c.ID, c.OS) <add> rwlayer, err := daemon.imageService.GetLayerByID(c.ID) <ide> if err != nil { <ide> log.WithError(err).Error("failed to load container mount") <ide> return <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> return nil, err <ide> } <ide> <del> // TODO remove multiple imagestores map now that LCOW is no more <del> imageStore, err := image.NewImageStore(ifs, map[string]image.LayerGetReleaser{ <del> runtime.GOOS: layerStore, <del> }) <add> imageStore, err := image.NewImageStore(ifs, layerStore) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> DistributionMetadataStore: distributionMetadataStore, <ide> EventsService: d.EventsService, <ide> ImageStore: imageStore, <del> LayerStores: map[string]layer.Store{runtime.GOOS: layerStore}, // TODO remove multiple LayerStores map now that LCOW is no more <add> LayerStore: layerStore, <ide> MaxConcurrentDownloads: *config.MaxConcurrentDownloads, <ide> MaxConcurrentUploads: *config.MaxConcurrentUploads, <ide> MaxDownloadAttempts: *config.MaxDownloadAttempts, <ide> func (daemon *Daemon) Shutdown() error { <ide> log.WithError(err).Error("failed to shut down container") <ide> return <ide> } <del> if mountid, err := daemon.imageService.GetLayerMountID(c.ID, c.OS); err == nil { <add> if mountid, err := daemon.imageService.GetLayerMountID(c.ID); err == nil { <ide> daemon.cleanupMountsByID(mountid) <ide> } <ide> log.Debugf("shut down container") <ide> func (daemon *Daemon) Mount(container *container.Container) error { <ide> if runtime.GOOS != "windows" { <ide> daemon.Unmount(container) <ide> return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')", <del> daemon.imageService.GraphDriverForOS(container.OS), container.ID, container.BaseFS, dir) <add> daemon.imageService.GraphDriverName(), container.ID, container.BaseFS, dir) <ide> } <ide> } <ide> container.BaseFS = dir // TODO: combine these fields <ide><path>daemon/export.go <ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R <ide> if !system.IsOSSupported(container.OS) { <ide> return nil, fmt.Errorf("cannot export %s: %s ", container.ID, system.ErrNotSupportedOperatingSystem) <ide> } <del> rwlayer, err := daemon.imageService.GetLayerByID(container.ID, container.OS) <add> rwlayer, err := daemon.imageService.GetLayerByID(container.ID) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/images/image_builder.go <ide> func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID s <ide> if !system.IsOSSupported(os) { <ide> return nil, nil, system.ErrNotSupportedOperatingSystem <ide> } <del> layer, err := newROLayerForImage(nil, i.layerStores[os]) <add> layer, err := newROLayerForImage(nil, i.layerStore) <ide> return nil, layer, err <ide> } <ide> <ide> func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID s <ide> if !system.IsOSSupported(image.OperatingSystem()) { <ide> return nil, nil, system.ErrNotSupportedOperatingSystem <ide> } <del> layer, err := newROLayerForImage(image, i.layerStores[image.OperatingSystem()]) <add> layer, err := newROLayerForImage(image, i.layerStore) <ide> return image, layer, err <ide> } <ide> } <ide> func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID s <ide> if !system.IsOSSupported(image.OperatingSystem()) { <ide> return nil, nil, system.ErrNotSupportedOperatingSystem <ide> } <del> layer, err := newROLayerForImage(image, i.layerStores[image.OperatingSystem()]) <add> layer, err := newROLayerForImage(image, i.layerStore) <ide> return image, layer, err <ide> } <ide> <ide><path>daemon/images/image_commit.go <ide> import ( <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/ioutils" <del> "github.com/docker/docker/pkg/system" <ide> "github.com/pkg/errors" <ide> ) <ide> <ide> // CommitImage creates a new image from a commit config <ide> func (i *ImageService) CommitImage(c backend.CommitConfig) (image.ID, error) { <del> layerStore, ok := i.layerStores[c.ContainerOS] <del> if !ok { <del> return "", system.ErrNotSupportedOperatingSystem <del> } <del> rwTar, err := exportContainerRw(layerStore, c.ContainerID, c.ContainerMountLabel) <add> rwTar, err := exportContainerRw(i.layerStore, c.ContainerID, c.ContainerMountLabel) <ide> if err != nil { <ide> return "", err <ide> } <ide> func (i *ImageService) CommitImage(c backend.CommitConfig) (image.ID, error) { <ide> } <ide> } <ide> <del> l, err := layerStore.Register(rwTar, parent.RootFS.ChainID()) <add> l, err := i.layerStore.Register(rwTar, parent.RootFS.ChainID()) <ide> if err != nil { <ide> return "", err <ide> } <del> defer layer.ReleaseAndLog(layerStore, l) <add> defer layer.ReleaseAndLog(i.layerStore, l) <ide> <ide> cc := image.ChildConfig{ <ide> ContainerID: c.ContainerID, <ide><path>daemon/images/image_exporter.go <ide> import ( <ide> // the same tag are exported. names is the set of tags to export, and <ide> // outStream is the writer which the images are written to. <ide> func (i *ImageService) ExportImage(names []string, outStream io.Writer) error { <del> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStores, i.referenceStore, i) <add> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStore, i.referenceStore, i) <ide> return imageExporter.Save(names, outStream) <ide> } <ide> <ide> // LoadImage uploads a set of images into the repository. This is the <ide> // complement of ExportImage. The input stream is an uncompressed tar <ide> // ball containing images and metadata. <ide> func (i *ImageService) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error { <del> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStores, i.referenceStore, i) <add> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStore, i.referenceStore, i) <ide> return imageExporter.Load(inTar, outStream, quiet) <ide> } <ide><path>daemon/images/image_history.go <ide> func (i *ImageService) ImageHistory(name string) ([]*image.HistoryResponseItem, <ide> return nil, system.ErrNotSupportedOperatingSystem <ide> } <ide> rootFS.Append(img.RootFS.DiffIDs[layerCounter]) <del> l, err := i.layerStores[img.OperatingSystem()].Get(rootFS.ChainID()) <add> l, err := i.layerStore.Get(rootFS.ChainID()) <ide> if err != nil { <ide> return nil, err <ide> } <ide> layerSize, err = l.DiffSize() <del> layer.ReleaseAndLog(i.layerStores[img.OperatingSystem()], l) <add> layer.ReleaseAndLog(i.layerStore, l) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/images/image_import.go <ide> func (i *ImageService) ImportImage(src string, repository, os string, tag string <ide> if err != nil { <ide> return err <ide> } <del> l, err := i.layerStores[os].Register(inflatedLayerData, "") <add> l, err := i.layerStore.Register(inflatedLayerData, "") <ide> if err != nil { <ide> return err <ide> } <del> defer layer.ReleaseAndLog(i.layerStores[os], l) <add> defer layer.ReleaseAndLog(i.layerStore, l) <ide> <ide> created := time.Now().UTC() <ide> imgConfig, err := json.Marshal(&image.Image{ <ide><path>daemon/images/image_inspect.go <ide> func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) { <ide> var layerMetadata map[string]string <ide> layerID := img.RootFS.ChainID() <ide> if layerID != "" { <del> l, err := i.layerStores[img.OperatingSystem()].Get(layerID) <add> l, err := i.layerStore.Get(layerID) <ide> if err != nil { <ide> return nil, err <ide> } <del> defer layer.ReleaseAndLog(i.layerStores[img.OperatingSystem()], l) <add> defer layer.ReleaseAndLog(i.layerStore, l) <ide> size, err = l.Size() <ide> if err != nil { <ide> return nil, err <ide> func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) { <ide> }, <ide> } <ide> <del> imageInspect.GraphDriver.Name = i.layerStores[img.OperatingSystem()].DriverName() <add> imageInspect.GraphDriver.Name = i.layerStore.DriverName() <ide> imageInspect.GraphDriver.Data = layerMetadata <ide> <ide> return imageInspect, nil <ide><path>daemon/images/image_prune.go <ide> func (i *ImageService) ImagesPrune(ctx context.Context, pruneFilters filters.Arg <ide> } <ide> <ide> // Filter intermediary images and get their unique size <del> allLayers := make(map[layer.ChainID]layer.Layer) <del> for _, ls := range i.layerStores { <del> for k, v := range ls.Map() { <del> allLayers[k] = v <del> } <del> } <add> allLayers := i.layerStore.Map() <ide> topImages := map[image.ID]*image.Image{} <ide> for id, img := range allImages { <ide> select { <ide><path>daemon/images/image_push.go <ide> func (i *ImageService) PushImage(ctx context.Context, image, tag string, metaHea <ide> ReferenceStore: i.referenceStore, <ide> }, <ide> ConfigMediaType: schema2.MediaTypeImageConfig, <del> LayerStores: distribution.NewLayerProvidersFromStores(i.layerStores), <add> LayerStores: distribution.NewLayerProvidersFromStore(i.layerStore), <ide> TrustKey: i.trustKey, <ide> UploadManager: i.uploadManager, <ide> } <ide><path>daemon/images/image_unix.go <ide> package images // import "github.com/docker/docker/daemon/images" <ide> <ide> import ( <del> "runtime" <del> <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> func (i *ImageService) GetContainerLayerSize(containerID string) (int64, int64) <ide> <ide> // Safe to index by runtime.GOOS as Unix hosts don't support multiple <ide> // container operating systems. <del> rwlayer, err := i.layerStores[runtime.GOOS].GetRWLayer(containerID) <add> rwlayer, err := i.layerStore.GetRWLayer(containerID) <ide> if err != nil { <ide> logrus.Errorf("Failed to compute size of container rootfs %v: %v", containerID, err) <ide> return sizeRw, sizeRootfs <ide> } <del> defer i.layerStores[runtime.GOOS].ReleaseRWLayer(rwlayer) <add> defer i.layerStore.ReleaseRWLayer(rwlayer) <ide> <ide> sizeRw, err = rwlayer.Size() <ide> if err != nil { <ide> logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", <del> i.layerStores[runtime.GOOS].DriverName(), containerID, err) <add> i.layerStore.DriverName(), containerID, err) <ide> // FIXME: GetSize should return an error. Not changing it now in case <ide> // there is a side-effect. <ide> sizeRw = -1 <ide><path>daemon/images/image_windows.go <ide> func (i *ImageService) GetLayerFolders(img *image.Image, rwLayer layer.RWLayer) <ide> if !system.IsOSSupported(img.OperatingSystem()) { <ide> return nil, errors.Wrapf(system.ErrNotSupportedOperatingSystem, "cannot get layerpath for ImageID %s", img.RootFS.ChainID()) <ide> } <del> layerPath, err := layer.GetLayerPath(i.layerStores[img.OperatingSystem()], img.RootFS.ChainID()) <add> layerPath, err := layer.GetLayerPath(i.layerStore, img.RootFS.ChainID()) <ide> if err != nil { <del> return nil, errors.Wrapf(err, "failed to get layer path from graphdriver %s for ImageID %s", i.layerStores[img.OperatingSystem()], img.RootFS.ChainID()) <add> return nil, errors.Wrapf(err, "failed to get layer path from graphdriver %s for ImageID %s", i.layerStore, img.RootFS.ChainID()) <ide> } <ide> // Reverse order, expecting parent first <ide> folders = append([]string{layerPath}, folders...) <ide><path>daemon/images/images.go <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> layerID := img.RootFS.ChainID() <ide> var size int64 <ide> if layerID != "" { <del> l, err := i.layerStores[img.OperatingSystem()].Get(layerID) <add> l, err := i.layerStore.Get(layerID) <ide> if err != nil { <ide> // The layer may have been deleted between the call to `Map()` or <ide> // `Heads()` and the call to `Get()`, so we just ignore this error <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> } <ide> <ide> size, err = l.Size() <del> layer.ReleaseAndLog(i.layerStores[img.OperatingSystem()], l) <add> layer.ReleaseAndLog(i.layerStore, l) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> // lazily init variables <ide> if imagesMap == nil { <ide> allContainers = i.containers.List() <del> <del> // allLayers is built from all layerstores combined <del> allLayers = make(map[layer.ChainID]layer.Layer) <del> for _, ls := range i.layerStores { <del> layers := ls.Map() <del> for k, v := range layers { <del> allLayers[k] = v <del> } <del> } <add> allLayers = i.layerStore.Map() <ide> imagesMap = make(map[*image.Image]*types.ImageSummary) <ide> layerRefs = make(map[layer.ChainID]int) <ide> } <ide> func (i *ImageService) SquashImage(id, parent string) (string, error) { <ide> if !system.IsOSSupported(img.OperatingSystem()) { <ide> return "", errors.Wrap(err, system.ErrNotSupportedOperatingSystem.Error()) <ide> } <del> l, err := i.layerStores[img.OperatingSystem()].Get(img.RootFS.ChainID()) <add> l, err := i.layerStore.Get(img.RootFS.ChainID()) <ide> if err != nil { <ide> return "", errors.Wrap(err, "error getting image layer") <ide> } <del> defer i.layerStores[img.OperatingSystem()].Release(l) <add> defer i.layerStore.Release(l) <ide> <ide> ts, err := l.TarStreamFrom(parentChainID) <ide> if err != nil { <ide> return "", errors.Wrapf(err, "error getting tar stream to parent") <ide> } <ide> defer ts.Close() <ide> <del> newL, err := i.layerStores[img.OperatingSystem()].Register(ts, parentChainID) <add> newL, err := i.layerStore.Register(ts, parentChainID) <ide> if err != nil { <ide> return "", errors.Wrap(err, "error registering layer") <ide> } <del> defer i.layerStores[img.OperatingSystem()].Release(newL) <add> defer i.layerStore.Release(newL) <ide> <ide> newImage := *img <ide> newImage.RootFS = nil <ide><path>daemon/images/service.go <ide> package images // import "github.com/docker/docker/daemon/images" <ide> import ( <ide> "context" <ide> "os" <del> "runtime" <ide> <ide> "github.com/containerd/containerd/content" <ide> "github.com/containerd/containerd/leases" <ide> type ImageServiceConfig struct { <ide> DistributionMetadataStore metadata.Store <ide> EventsService *daemonevents.Events <ide> ImageStore image.Store <del> LayerStores map[string]layer.Store <add> LayerStore layer.Store <ide> MaxConcurrentDownloads int <ide> MaxConcurrentUploads int <ide> MaxDownloadAttempts int <ide> func NewImageService(config ImageServiceConfig) *ImageService { <ide> return &ImageService{ <ide> containers: config.ContainerStore, <ide> distributionMetadataStore: config.DistributionMetadataStore, <del> downloadManager: xfer.NewLayerDownloadManager(config.LayerStores, config.MaxConcurrentDownloads, xfer.WithMaxDownloadAttempts(config.MaxDownloadAttempts)), <add> downloadManager: xfer.NewLayerDownloadManager(config.LayerStore, config.MaxConcurrentDownloads, xfer.WithMaxDownloadAttempts(config.MaxDownloadAttempts)), <ide> eventsService: config.EventsService, <ide> imageStore: &imageStoreWithLease{Store: config.ImageStore, leases: config.Leases, ns: config.ContentNamespace}, <del> layerStores: config.LayerStores, <add> layerStore: config.LayerStore, <ide> referenceStore: config.ReferenceStore, <ide> registryService: config.RegistryService, <ide> trustKey: config.TrustKey, <ide> type ImageService struct { <ide> downloadManager *xfer.LayerDownloadManager <ide> eventsService *daemonevents.Events <ide> imageStore image.Store <del> layerStores map[string]layer.Store // By operating system <add> layerStore layer.Store <ide> pruneRunning int32 <ide> referenceStore dockerreference.Store <ide> registryService registry.Service <ide> type ImageService struct { <ide> type DistributionServices struct { <ide> DownloadManager distribution.RootFSDownloadManager <ide> V2MetadataService metadata.V2MetadataService <del> LayerStore layer.Store // TODO: lcow <add> LayerStore layer.Store <ide> ImageStore image.Store <ide> ReferenceStore dockerreference.Store <ide> } <ide> func (i *ImageService) DistributionServices() DistributionServices { <ide> return DistributionServices{ <ide> DownloadManager: i.downloadManager, <ide> V2MetadataService: metadata.NewV2MetadataService(i.distributionMetadataStore), <del> LayerStore: i.layerStores[runtime.GOOS], <add> LayerStore: i.layerStore, <ide> ImageStore: i.imageStore, <ide> ReferenceStore: i.referenceStore, <ide> } <ide> func (i *ImageService) CreateLayer(container *container.Container, initFunc laye <ide> <ide> // Indexing by OS is safe here as validation of OS has already been performed in create() (the only <ide> // caller), and guaranteed non-nil <del> return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts) <add> return i.layerStore.CreateRWLayer(container.ID, layerID, rwLayerOpts) <ide> } <ide> <del>// GetLayerByID returns a layer by ID and operating system <add>// GetLayerByID returns a layer by ID <ide> // called from daemon.go Daemon.restore(), and Daemon.containerExport() <del>func (i *ImageService) GetLayerByID(cid string, os string) (layer.RWLayer, error) { <del> return i.layerStores[os].GetRWLayer(cid) <add>func (i *ImageService) GetLayerByID(cid string) (layer.RWLayer, error) { <add> return i.layerStore.GetRWLayer(cid) <ide> } <ide> <ide> // LayerStoreStatus returns the status for each layer store <ide> // called from info.go <del>func (i *ImageService) LayerStoreStatus() map[string][][2]string { <del> result := make(map[string][][2]string) <del> for os, store := range i.layerStores { <del> result[os] = store.DriverStatus() <del> } <del> return result <add>func (i *ImageService) LayerStoreStatus() [][2]string { <add> return i.layerStore.DriverStatus() <ide> } <ide> <ide> // GetLayerMountID returns the mount ID for a layer <ide> // called from daemon.go Daemon.Shutdown(), and Daemon.Cleanup() (cleanup is actually continerCleanup) <del>// TODO: needs to be refactored to Unmount (see callers), or removed and replaced <del>// with GetLayerByID <del>func (i *ImageService) GetLayerMountID(cid string, os string) (string, error) { <del> return i.layerStores[os].GetMountID(cid) <add>// TODO: needs to be refactored to Unmount (see callers), or removed and replaced with GetLayerByID <add>func (i *ImageService) GetLayerMountID(cid string) (string, error) { <add> return i.layerStore.GetMountID(cid) <ide> } <ide> <ide> // Cleanup resources before the process is shutdown. <ide> // called from daemon.go Daemon.Shutdown() <ide> func (i *ImageService) Cleanup() { <del> for os, ls := range i.layerStores { <del> if ls != nil { <del> if err := ls.Cleanup(); err != nil { <del> logrus.Errorf("Error during layer Store.Cleanup(): %v %s", err, os) <del> } <del> } <add> if err := i.layerStore.Cleanup(); err != nil { <add> logrus.Errorf("Error during layer Store.Cleanup(): %v", err) <ide> } <ide> } <ide> <del>// GraphDriverForOS returns the name of the graph drvier <add>// GraphDriverName returns the name of the graph drvier <ide> // moved from Daemon.GraphDriverName, used by: <ide> // - newContainer <ide> // - to report an error in Daemon.Mount(container) <del>func (i *ImageService) GraphDriverForOS(os string) string { <del> return i.layerStores[os].DriverName() <add>func (i *ImageService) GraphDriverName() string { <add> return i.layerStore.DriverName() <ide> } <ide> <ide> // ReleaseLayer releases a layer allowing it to be removed <ide> // called from delete.go Daemon.cleanupContainer(), and Daemon.containerExport() <ide> func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer, containerOS string) error { <del> metadata, err := i.layerStores[containerOS].ReleaseRWLayer(rwlayer) <add> metadata, err := i.layerStore.ReleaseRWLayer(rwlayer) <ide> layer.LogReleaseMetadata(metadata) <ide> if err != nil && !errors.Is(err, layer.ErrMountDoesNotExist) && !errors.Is(err, os.ErrNotExist) { <ide> return errors.Wrapf(err, "driver %q failed to remove root filesystem", <del> i.layerStores[containerOS].DriverName()) <add> i.layerStore.DriverName()) <ide> } <ide> return nil <ide> } <ide> func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer, containerOS string) e <ide> func (i *ImageService) LayerDiskUsage(ctx context.Context) (int64, error) { <ide> var allLayersSize int64 <ide> layerRefs := i.getLayerRefs() <del> for _, ls := range i.layerStores { <del> allLayers := ls.Map() <del> for _, l := range allLayers { <del> select { <del> case <-ctx.Done(): <del> return allLayersSize, ctx.Err() <del> default: <del> size, err := l.DiffSize() <del> if err == nil { <del> if _, ok := layerRefs[l.ChainID()]; ok { <del> allLayersSize += size <del> } <del> } else { <del> logrus.Warnf("failed to get diff size for layer %v", l.ChainID()) <add> allLayers := i.layerStore.Map() <add> for _, l := range allLayers { <add> select { <add> case <-ctx.Done(): <add> return allLayersSize, ctx.Err() <add> default: <add> size, err := l.DiffSize() <add> if err == nil { <add> if _, ok := layerRefs[l.ChainID()]; ok { <add> allLayersSize += size <ide> } <add> } else { <add> logrus.Warnf("failed to get diff size for layer %v", l.ChainID()) <ide> } <ide> } <ide> } <ide><path>daemon/info.go <ide> func (daemon *Daemon) fillDriverInfo(v *types.Info) { <ide> v.Warnings = append(v.Warnings, fmt.Sprintf("WARNING: the %s storage-driver is deprecated, and will be removed in a future release.", daemon.graphDriver)) <ide> } <ide> <del> statuses := daemon.imageService.LayerStoreStatus() <ide> v.Driver = daemon.graphDriver <del> v.DriverStatus = statuses[runtime.GOOS] <add> v.DriverStatus = daemon.imageService.LayerStoreStatus() <ide> <ide> fillDriverWarnings(v) <ide> } <ide><path>daemon/start.go <ide> func (daemon *Daemon) Cleanup(container *container.Container) { <ide> if err := daemon.conditionalUnmountOnCleanup(container); err != nil { <ide> // FIXME: remove once reference counting for graphdrivers has been refactored <ide> // Ensure that all the mounts are gone <del> if mountid, err := daemon.imageService.GetLayerMountID(container.ID, container.OS); err == nil { <add> if mountid, err := daemon.imageService.GetLayerMountID(container.ID); err == nil { <ide> daemon.cleanupMountsByID(mountid) <ide> } <ide> } <ide><path>distribution/config.go <ide> type ImagePushConfig struct { <ide> // ConfigMediaType is the configuration media type for <ide> // schema2 manifests. <ide> ConfigMediaType string <del> // LayerStores (indexed by operating system) manages layers. <del> LayerStores map[string]PushLayerProvider <add> // LayerStores manages layers. <add> LayerStores PushLayerProvider <ide> // TrustKey is the private key for legacy signatures. This is typically <ide> // an ephemeral key, since these signatures are no longer verified. <ide> TrustKey libtrust.PrivateKey <ide> type storeLayerProvider struct { <ide> ls layer.Store <ide> } <ide> <del>// NewLayerProvidersFromStores returns layer providers backed by <add>// NewLayerProvidersFromStore returns layer providers backed by <ide> // an instance of LayerStore. Only getting layers as gzipped <ide> // tars is supported. <del>func NewLayerProvidersFromStores(lss map[string]layer.Store) map[string]PushLayerProvider { <del> plps := make(map[string]PushLayerProvider) <del> for os, ls := range lss { <del> plps[os] = &storeLayerProvider{ls: ls} <del> } <del> return plps <add>func NewLayerProvidersFromStore(ls layer.Store) PushLayerProvider { <add> return &storeLayerProvider{ls: ls} <ide> } <ide> <ide> func (p *storeLayerProvider) Get(lid layer.ChainID) (PushLayer, error) { <ide><path>distribution/push_v2.go <ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id <ide> return fmt.Errorf("unable to get rootfs for image %s: %s", reference.FamiliarString(ref), err) <ide> } <ide> <del> platform, err := p.config.ImageStore.PlatformFromConfig(imgConfig) <del> if err != nil { <del> return fmt.Errorf("unable to get platform for image %s: %s", reference.FamiliarString(ref), err) <del> } <del> <del> l, err := p.config.LayerStores[platform.OS].Get(rootfs.ChainID()) <add> l, err := p.config.LayerStores.Get(rootfs.ChainID()) <ide> if err != nil { <ide> return fmt.Errorf("failed to get top layer from image: %v", err) <ide> } <ide><path>distribution/xfer/download.go <ide> const maxDownloadAttempts = 5 <ide> // registers and downloads those, taking into account dependencies between <ide> // layers. <ide> type LayerDownloadManager struct { <del> layerStores map[string]layer.Store <add> layerStore layer.Store <ide> tm TransferManager <ide> waitDuration time.Duration <ide> maxDownloadAttempts int <ide> func (ldm *LayerDownloadManager) SetConcurrency(concurrency int) { <ide> } <ide> <ide> // NewLayerDownloadManager returns a new LayerDownloadManager. <del>func NewLayerDownloadManager(layerStores map[string]layer.Store, concurrencyLimit int, options ...func(*LayerDownloadManager)) *LayerDownloadManager { <add>func NewLayerDownloadManager(layerStore layer.Store, concurrencyLimit int, options ...func(*LayerDownloadManager)) *LayerDownloadManager { <ide> manager := LayerDownloadManager{ <del> layerStores: layerStores, <add> layerStore: layerStore, <ide> tm: NewTransferManager(concurrencyLimit), <ide> waitDuration: time.Second, <ide> maxDownloadAttempts: maxDownloadAttempts, <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> <ide> // Assume that the operating system is the host OS if blank, and validate it <ide> // to ensure we don't cause a panic by an invalid index into the layerstores. <add> // TODO remove now that LCOW is no longer a thing <ide> if os == "" { <ide> os = runtime.GOOS <ide> } <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> if err == nil { <ide> getRootFS := rootFS <ide> getRootFS.Append(diffID) <del> l, err := ldm.layerStores[os].Get(getRootFS.ChainID()) <add> l, err := ldm.layerStore.Get(getRootFS.ChainID()) <ide> if err == nil { <ide> // Layer already exists. <ide> logrus.Debugf("Layer already exists: %s", descriptor.ID()) <ide> progress.Update(progressOutput, descriptor.ID(), "Already exists") <ide> if topLayer != nil { <del> layer.ReleaseAndLog(ldm.layerStores[os], topLayer) <add> layer.ReleaseAndLog(ldm.layerStore, topLayer) <ide> } <ide> topLayer = l <ide> missingLayer = false <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> // the stack? If so, avoid downloading it more than once. <ide> var topDownloadUncasted Transfer <ide> if existingDownload, ok := downloadsByKey[key]; ok { <del> xferFunc := ldm.makeDownloadFuncFromDownload(descriptor, existingDownload, topDownload, os) <add> xferFunc := ldm.makeDownloadFuncFromDownload(descriptor, existingDownload, topDownload) <ide> defer topDownload.Transfer.Release(watcher) <ide> topDownloadUncasted, watcher = ldm.tm.Transfer(transferKey, xferFunc, progressOutput) <ide> topDownload = topDownloadUncasted.(*downloadTransfer) <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> <ide> var xferFunc DoFunc <ide> if topDownload != nil { <del> xferFunc = ldm.makeDownloadFunc(descriptor, "", topDownload, os) <add> xferFunc = ldm.makeDownloadFunc(descriptor, "", topDownload) <ide> defer topDownload.Transfer.Release(watcher) <ide> } else { <del> xferFunc = ldm.makeDownloadFunc(descriptor, rootFS.ChainID(), nil, os) <add> xferFunc = ldm.makeDownloadFunc(descriptor, rootFS.ChainID(), nil) <ide> } <ide> topDownloadUncasted, watcher = ldm.tm.Transfer(transferKey, xferFunc, progressOutput) <ide> topDownload = topDownloadUncasted.(*downloadTransfer) <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> if topDownload == nil { <ide> return rootFS, func() { <ide> if topLayer != nil { <del> layer.ReleaseAndLog(ldm.layerStores[os], topLayer) <add> layer.ReleaseAndLog(ldm.layerStore, topLayer) <ide> } <ide> }, nil <ide> } <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> <ide> defer func() { <ide> if topLayer != nil { <del> layer.ReleaseAndLog(ldm.layerStores[os], topLayer) <add> layer.ReleaseAndLog(ldm.layerStore, topLayer) <ide> } <ide> }() <ide> <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima <ide> // complete before the registration step, and registers the downloaded data <ide> // on top of parentDownload's resulting layer. Otherwise, it registers the <ide> // layer on top of the ChainID given by parentLayer. <del>func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor, parentLayer layer.ChainID, parentDownload *downloadTransfer, os string) DoFunc { <add>func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor, parentLayer layer.ChainID, parentDownload *downloadTransfer) DoFunc { <ide> return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { <ide> d := &downloadTransfer{ <ide> Transfer: NewTransfer(), <del> layerStore: ldm.layerStores[os], <add> layerStore: ldm.layerStore, <ide> } <ide> <ide> go func() { <ide> func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor, <ide> // parentDownload. This function does not log progress output because it would <ide> // interfere with the progress reporting for sourceDownload, which has the same <ide> // Key. <del>func (ldm *LayerDownloadManager) makeDownloadFuncFromDownload(descriptor DownloadDescriptor, sourceDownload *downloadTransfer, parentDownload *downloadTransfer, os string) DoFunc { <add>func (ldm *LayerDownloadManager) makeDownloadFuncFromDownload(descriptor DownloadDescriptor, sourceDownload *downloadTransfer, parentDownload *downloadTransfer) DoFunc { <ide> return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { <ide> d := &downloadTransfer{ <ide> Transfer: NewTransfer(), <del> layerStore: ldm.layerStores[os], <add> layerStore: ldm.layerStore, <ide> } <ide> <ide> go func() { <ide><path>distribution/xfer/download_test.go <ide> func TestSuccessfulDownload(t *testing.T) { <ide> } <ide> <ide> layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)} <del> lsMap := make(map[string]layer.Store) <del> lsMap[runtime.GOOS] = layerStore <del> ldm := NewLayerDownloadManager(lsMap, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond }) <add> ldm := NewLayerDownloadManager(layerStore, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond }) <ide> <ide> progressChan := make(chan progress.Progress) <ide> progressDone := make(chan struct{}) <ide> func TestSuccessfulDownload(t *testing.T) { <ide> <ide> func TestCancelledDownload(t *testing.T) { <ide> layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)} <del> lsMap := make(map[string]layer.Store) <del> lsMap[runtime.GOOS] = layerStore <del> ldm := NewLayerDownloadManager(lsMap, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond }) <add> ldm := NewLayerDownloadManager(layerStore, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond }) <ide> progressChan := make(chan progress.Progress) <ide> progressDone := make(chan struct{}) <ide> <ide> func TestMaxDownloadAttempts(t *testing.T) { <ide> t.Run(tc.name, func(t *testing.T) { <ide> t.Parallel() <ide> layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)} <del> lsMap := make(map[string]layer.Store) <del> lsMap[runtime.GOOS] = layerStore <ide> ldm := NewLayerDownloadManager( <del> lsMap, <add> layerStore, <ide> maxDownloadConcurrency, <ide> func(m *LayerDownloadManager) { <ide> m.waitDuration = time.Millisecond <ide><path>image/store.go <ide> type imageMeta struct { <ide> <ide> type store struct { <ide> sync.RWMutex <del> lss map[string]LayerGetReleaser <add> lss LayerGetReleaser <ide> images map[ID]*imageMeta <ide> fs StoreBackend <ide> digestSet *digestset.Set <ide> } <ide> <ide> // NewImageStore returns new store object for given set of layer stores <del>func NewImageStore(fs StoreBackend, lss map[string]LayerGetReleaser) (Store, error) { <add>func NewImageStore(fs StoreBackend, lss LayerGetReleaser) (Store, error) { <ide> is := &store{ <ide> lss: lss, <ide> images: make(map[ID]*imageMeta), <ide> func (is *store) restore() error { <ide> logrus.Errorf("not restoring image with unsupported operating system %v, %v, %s", dgst, chainID, img.OperatingSystem()) <ide> return nil <ide> } <del> l, err = is.lss[img.OperatingSystem()].Get(chainID) <add> l, err = is.lss.Get(chainID) <ide> if err != nil { <ide> if err == layer.ErrLayerDoesNotExist { <ide> logrus.Errorf("layer does not exist, not restoring image %v, %v, %s", dgst, chainID, img.OperatingSystem()) <ide> func (is *store) Create(config []byte) (ID, error) { <ide> if !system.IsOSSupported(img.OperatingSystem()) { <ide> return "", system.ErrNotSupportedOperatingSystem <ide> } <del> l, err = is.lss[img.OperatingSystem()].Get(layerID) <add> l, err = is.lss.Get(layerID) <ide> if err != nil { <ide> return "", errors.Wrapf(err, "failed to get layer %s", layerID) <ide> } <ide> func (is *store) Delete(id ID) ([]layer.Metadata, error) { <ide> is.fs.Delete(id.Digest()) <ide> <ide> if imageMeta.layer != nil { <del> return is.lss[img.OperatingSystem()].Release(imageMeta.layer) <add> return is.lss.Release(imageMeta.layer) <ide> } <ide> return nil, nil <ide> } <ide><path>image/store_test.go <ide> package image // import "github.com/docker/docker/image" <ide> <ide> import ( <ide> "fmt" <del> "runtime" <ide> "testing" <ide> <ide> "github.com/docker/docker/layer" <ide> func TestRestore(t *testing.T) { <ide> err = fs.SetMetadata(id2, "parent", []byte(id1)) <ide> assert.NilError(t, err) <ide> <del> mlgrMap := make(map[string]LayerGetReleaser) <del> mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{} <del> is, err := NewImageStore(fs, mlgrMap) <add> is, err := NewImageStore(fs, &mockLayerGetReleaser{}) <ide> assert.NilError(t, err) <ide> <ide> assert.Check(t, cmp.Len(is.Map(), 2)) <ide> func TestParentReset(t *testing.T) { <ide> func defaultImageStore(t *testing.T) (Store, func()) { <ide> fsBackend, cleanup := defaultFSStoreBackend(t) <ide> <del> mlgrMap := make(map[string]LayerGetReleaser) <del> mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{} <del> store, err := NewImageStore(fsBackend, mlgrMap) <add> store, err := NewImageStore(fsBackend, &mockLayerGetReleaser{}) <ide> assert.NilError(t, err) <ide> <ide> return store, cleanup <ide><path>image/tarexport/load.go <ide> import ( <ide> "path/filepath" <ide> "runtime" <ide> <del> "github.com/containerd/containerd/platforms" <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/docker/image" <ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) <ide> if err != nil { <ide> return err <ide> } <del> if err := checkCompatibleOS(img.OS); err != nil { <del> return err <add> if !system.IsOSSupported(img.OperatingSystem()) { <add> return fmt.Errorf("cannot load %s image on %s", img.OperatingSystem(), runtime.GOOS) <ide> } <ide> rootFS := *img.RootFS <ide> rootFS.DiffIDs = nil <ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) <ide> return fmt.Errorf("invalid manifest, layers length mismatch: expected %d, got %d", expected, actual) <ide> } <ide> <del> // On Windows, validate the platform, defaulting to windows if not present. <del> os := img.OS <del> if os == "" { <del> os = runtime.GOOS <del> } <del> if runtime.GOOS == "windows" { <del> if (os != "windows") && (os != "linux") { <del> return fmt.Errorf("configuration for this image has an unsupported operating system: %s", os) <del> } <del> } <del> <ide> for i, diffID := range img.RootFS.DiffIDs { <ide> layerPath, err := safePath(tmpDir, m.Layers[i]) <ide> if err != nil { <ide> return err <ide> } <ide> r := rootFS <ide> r.Append(diffID) <del> newLayer, err := l.lss[os].Get(r.ChainID()) <add> newLayer, err := l.lss.Get(r.ChainID()) <ide> if err != nil { <del> newLayer, err = l.loadLayer(layerPath, rootFS, diffID.String(), os, m.LayerSources[diffID], progressOutput) <add> newLayer, err = l.loadLayer(layerPath, rootFS, diffID.String(), m.LayerSources[diffID], progressOutput) <ide> if err != nil { <ide> return err <ide> } <ide> } <del> defer layer.ReleaseAndLog(l.lss[os], newLayer) <add> defer layer.ReleaseAndLog(l.lss, newLayer) <ide> if expected, actual := diffID, newLayer.DiffID(); expected != actual { <ide> return fmt.Errorf("invalid diffID for layer %d: expected %q, got %q", i, expected, actual) <ide> } <ide> func (l *tarexporter) setParentID(id, parentID image.ID) error { <ide> return l.is.SetParent(id, parentID) <ide> } <ide> <del>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, os string, foreignSrc distribution.Descriptor, progressOutput progress.Output) (layer.Layer, error) { <add>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, foreignSrc distribution.Descriptor, progressOutput progress.Output) (layer.Layer, error) { <ide> // We use system.OpenSequential to use sequential file access on Windows, avoiding <ide> // depleting the standby list. On Linux, this equates to a regular os.Open. <ide> rawTar, err := system.OpenSequential(filename) <ide> func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, <ide> } <ide> defer inflatedLayerData.Close() <ide> <del> if ds, ok := l.lss[os].(layer.DescribableStore); ok { <add> if ds, ok := l.lss.(layer.DescribableStore); ok { <ide> return ds.RegisterWithDescriptor(inflatedLayerData, rootFS.ChainID(), foreignSrc) <ide> } <del> return l.lss[os].Register(inflatedLayerData, rootFS.ChainID()) <add> return l.lss.Register(inflatedLayerData, rootFS.ChainID()) <ide> } <ide> <ide> func (l *tarexporter) setLoadedTag(ref reference.Named, imgID digest.Digest, outStream io.Writer) error { <ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str <ide> return err <ide> } <ide> <del> if err := checkCompatibleOS(img.OS); err != nil { <del> return err <del> } <ide> if img.OS == "" { <ide> img.OS = runtime.GOOS <ide> } <add> if !system.IsOSSupported(img.OS) { <add> return fmt.Errorf("cannot load %s image on %s", img.OS, runtime.GOOS) <add> } <ide> <ide> var parentID image.ID <ide> if img.Parent != "" { <ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str <ide> if err != nil { <ide> return err <ide> } <del> newLayer, err := l.loadLayer(layerPath, *rootFS, oldID, img.OS, distribution.Descriptor{}, progressOutput) <add> newLayer, err := l.loadLayer(layerPath, *rootFS, oldID, distribution.Descriptor{}, progressOutput) <ide> if err != nil { <ide> return err <ide> } <ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str <ide> return err <ide> } <ide> <del> metadata, err := l.lss[img.OS].Release(newLayer) <add> metadata, err := l.lss.Release(newLayer) <ide> layer.LogReleaseMetadata(metadata) <ide> if err != nil { <ide> return err <ide> func checkValidParent(img, parent *image.Image) bool { <ide> return true <ide> } <ide> <del>func checkCompatibleOS(imageOS string) error { <del> // always compatible if the images OS matches the host OS; also match an empty image OS <del> if imageOS == runtime.GOOS || imageOS == "" { <del> return nil <del> } <del> // On non-Windows hosts, for compatibility, fail if the image is Windows. <del> if runtime.GOOS != "windows" && imageOS == "windows" { <del> return fmt.Errorf("cannot load %s image on %s", imageOS, runtime.GOOS) <del> } <del> <del> _, err := platforms.Parse(imageOS) <del> return err <del>} <del> <ide> func validateManifest(manifest []manifestItem) error { <ide> // a nil manifest usually indicates a bug, so don't just silently fail. <ide> // if someone really needs to pass an empty manifest, they can pass []. <ide><path>image/tarexport/save.go <ide> func (l *tarexporter) takeLayerReference(id image.ID, imgDescr *imageDescriptor) <ide> if !system.IsOSSupported(os) { <ide> return fmt.Errorf("os %q is not supported", os) <ide> } <del> layer, err := l.lss[os].Get(topLayerID) <add> layer, err := l.lss.Get(topLayerID) <ide> if err != nil { <ide> return err <ide> } <ide> func (l *tarexporter) takeLayerReference(id image.ID, imgDescr *imageDescriptor) <ide> func (l *tarexporter) releaseLayerReferences(imgDescr map[image.ID]*imageDescriptor) error { <ide> for _, descr := range imgDescr { <ide> if descr.layerRef != nil { <del> os := descr.image.OS <del> if os == "" { <del> os = runtime.GOOS <del> } <del> l.lss[os].Release(descr.layerRef) <add> l.lss.Release(descr.layerRef) <ide> } <ide> } <ide> return nil <ide> func (s *saveSession) saveLayer(id layer.ChainID, legacyImg image.V1Image, creat <ide> <ide> // serialize filesystem <ide> layerPath := filepath.Join(outDir, legacyLayerFileName) <del> operatingSystem := legacyImg.OS <del> if operatingSystem == "" { <del> operatingSystem = runtime.GOOS <del> } <del> l, err := s.lss[operatingSystem].Get(id) <add> l, err := s.lss.Get(id) <ide> if err != nil { <ide> return distribution.Descriptor{}, err <ide> } <del> defer layer.ReleaseAndLog(s.lss[operatingSystem], l) <add> defer layer.ReleaseAndLog(s.lss, l) <ide> <ide> if oldPath, exists := s.diffIDPaths[l.DiffID()]; exists { <ide> relPath, err := filepath.Rel(outDir, oldPath) <ide><path>image/tarexport/tarexport.go <ide> type manifestItem struct { <ide> <ide> type tarexporter struct { <ide> is image.Store <del> lss map[string]layer.Store <add> lss layer.Store <ide> rs refstore.Store <ide> loggerImgEvent LogImageEvent <ide> } <ide> type LogImageEvent interface { <ide> } <ide> <ide> // NewTarExporter returns new Exporter for tar packages <del>func NewTarExporter(is image.Store, lss map[string]layer.Store, rs refstore.Store, loggerImgEvent LogImageEvent) image.Exporter { <add>func NewTarExporter(is image.Store, lss layer.Store, rs refstore.Store, loggerImgEvent LogImageEvent) image.Exporter { <ide> return &tarexporter{ <ide> is: is, <ide> lss: lss, <ide><path>integration/image/remove_unix_test.go <ide> func TestRemoveImageGarbageCollector(t *testing.T) { <ide> ctx := context.Background() <ide> client := d.NewClientT(t) <ide> <del> layerStores := make(map[string]layer.Store) <del> layerStores[runtime.GOOS], _ = layer.NewStoreFromOptions(layer.StoreOptions{ <add> layerStore, _ := layer.NewStoreFromOptions(layer.StoreOptions{ <ide> Root: d.Root, <ide> MetadataStorePathTemplate: filepath.Join(d.RootDir(), "image", "%s", "layerdb"), <ide> GraphDriver: d.StorageDriver(), <ide> func TestRemoveImageGarbageCollector(t *testing.T) { <ide> OS: runtime.GOOS, <ide> }) <ide> i := images.NewImageService(images.ImageServiceConfig{ <del> LayerStores: layerStores, <add> LayerStore: layerStore, <ide> }) <ide> <ide> img := "test-garbage-collector"
27
Javascript
Javascript
fix all errors and warnings on homepage
e379f8ec03c9b350937ef78331c0e1a0f5364838
<ide><path>docs/_js/examples/timer.js <ide> var Timer = React.createClass({\n\ <ide> this.setState({secondsElapsed: this.state.secondsElapsed + 1});\n\ <ide> },\n\ <ide> componentDidMount: function() {\n\ <del> setInterval(this.tick, 1000);\n\ <add> this.interval = setInterval(this.tick, 1000);\n\ <add> },\n\ <add> componentWillUnmount: function() {\n\ <add> clearInterval(this.interval);\n\ <ide> },\n\ <ide> render: function() {\n\ <ide> return React.DOM.div({},\n\ <ide><path>docs/_js/examples/todo.js <ide> var TodoApp = React.createClass({\n\ <ide> getInitialState: function() {\n\ <ide> return {items: [], text: ''};\n\ <ide> },\n\ <del> onKey: function(e) {\n\ <add> onChange: function(e) {\n\ <ide> this.setState({text: e.target.value});\n\ <ide> },\n\ <ide> handleSubmit: function(e) {\n\ <ide> var TodoApp = React.createClass({\n\ <ide> <h3>TODO</h3>\n\ <ide> <TodoList items={this.state.items} />\n\ <ide> <form onSubmit={this.handleSubmit}>\n\ <del> <input onKeyUp={this.onKey} defaultValue={this.state.text} />\n\ <add> <input onChange={this.onChange} value={this.state.text} />\n\ <ide> <button>{'Add #' + (this.state.items.length + 1)}</button>\n\ <ide> </form>\n\ <ide> </div>\n\ <ide><path>docs/_js/live_editor.js <ide> var CodeMirrorEditor = React.createClass({ <ide> matchBrackets: true, <ide> theme: 'solarized-light' <ide> }); <del> this.editor.on('change', this.onChange.bind(this)); <add> this.editor.on('change', this.onChange); <ide> this.onChange(); <ide> }, <ide> onChange: function() { <ide> var CodeMirrorEditor = React.createClass({ <ide> if (IS_MOBILE) { <ide> editor = <pre style={{overflow: 'scroll'}}>{this.props.codeText}</pre>; <ide> } else { <del> editor = <textarea ref="editor">{this.props.codeText}</textarea>; <add> editor = <textarea ref="editor" defaultValue={this.props.codeText} />; <ide> } <ide> <ide> return (
3
Mixed
Javascript
provide pathtofileurl and fileurltopath
eef072fa083f05f84fa6ca1908472eb228095a38
<ide><path>doc/api/url.md <ide> console.log(url.domainToUnicode('xn--iñvalid.com')); <ide> // Prints an empty string <ide> ``` <ide> <add>### url.fileURLToPath(url) <add> <add>* `url` {URL | string} The file URL string or URL object to convert to a path. <add>* Returns: {string} The fully-resolved platform-specific Node.js file path. <add> <add>This function ensures the correct decodings of percent-encoded characters as <add>well as ensuring a cross-platform valid absolute path string. <add> <add>```js <add>new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ <add>fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) <add> <add>new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt <add>fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) <add> <add>new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt <add>fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) <add> <add>new URL('file:///hello world').pathname; // Incorrect: /hello%20world <add>fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) <add>``` <add> <ide> ### url.format(URL[, options]) <ide> <!-- YAML <ide> added: v7.6.0 <ide> console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); <ide> // Prints 'https://你好你好/?abc' <ide> ``` <ide> <add>### url.pathToFileURL(path) <add> <add>* `path` {string} The path to convert to a File URL. <add>* Returns: {URL} The file URL object. <add> <add>This function ensures that `path` is resolved absolutely, and that the URL <add>control characters are correctly encoded when converting into a File URL. <add> <add>```js <add>new URL(__filename); // Incorrect: throws (POSIX) <add>new URL(__filename); // Incorrect: C:\... (Windows) <add>pathToFileURL(__filename); // Correct: file:///... (POSIX) <add>pathToFileURL(__filename); // Correct: file:///C:/... (Windows) <add> <add>new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 <add>pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) <add> <add>new URL('/some/path%.js', 'file:'); // Incorrect: file:///some/path% <add>pathToFileURL('/some/path%.js'); // Correct: file:///some/path%25 (POSIX) <add>``` <add> <ide> ## Legacy URL API <ide> <ide> ### Legacy `urlObject` <ide><path>lib/fs.js <ide> const { <ide> <ide> const { FSReqCallback, statValues } = binding; <ide> const internalFS = require('internal/fs/utils'); <del>const { getPathFromURL } = require('internal/url'); <add>const { toPathIfFileURL } = require('internal/url'); <ide> const internalUtil = require('internal/util'); <ide> const { <ide> copyObject, <ide> function access(path, mode, callback) { <ide> mode = F_OK; <ide> } <ide> <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> <ide> mode = mode | 0; <ide> function access(path, mode, callback) { <ide> } <ide> <ide> function accessSync(path, mode) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> <ide> if (mode === undefined) <ide> function readFile(path, options, callback) { <ide> return; <ide> } <ide> <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> binding.open(pathModule.toNamespacedPath(path), <ide> stringToFlags(options.flag || 'r'), <ide> function closeSync(fd) { <ide> } <ide> <ide> function open(path, flags, mode, callback) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const flagsNumber = stringToFlags(flags); <ide> if (arguments.length < 4) { <ide> function open(path, flags, mode, callback) { <ide> <ide> <ide> function openSync(path, flags, mode) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const flagsNumber = stringToFlags(flags); <ide> mode = validateMode(mode, 'mode', 0o666); <ide> function writeSync(fd, buffer, offset, length, position) { <ide> <ide> function rename(oldPath, newPath, callback) { <ide> callback = makeCallback(callback); <del> oldPath = getPathFromURL(oldPath); <add> oldPath = toPathIfFileURL(oldPath); <ide> validatePath(oldPath, 'oldPath'); <del> newPath = getPathFromURL(newPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(newPath, 'newPath'); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> function rename(oldPath, newPath, callback) { <ide> } <ide> <ide> function renameSync(oldPath, newPath) { <del> oldPath = getPathFromURL(oldPath); <add> oldPath = toPathIfFileURL(oldPath); <ide> validatePath(oldPath, 'oldPath'); <del> newPath = getPathFromURL(newPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(newPath, 'newPath'); <ide> const ctx = { path: oldPath, dest: newPath }; <ide> binding.rename(pathModule.toNamespacedPath(oldPath), <ide> function ftruncateSync(fd, len = 0) { <ide> <ide> function rmdir(path, callback) { <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> binding.rmdir(pathModule.toNamespacedPath(path), req); <ide> } <ide> <ide> function rmdirSync(path) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> binding.rmdir(pathModule.toNamespacedPath(path), undefined, ctx); <ide> function mkdir(path, options, callback) { <ide> mode = 0o777 <ide> } = options || {}; <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> <ide> validatePath(path); <ide> if (typeof recursive !== 'boolean') <ide> function mkdirSync(path, options) { <ide> if (typeof options === 'number' || typeof options === 'string') { <ide> options = { mode: options }; <ide> } <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> const { <ide> recursive = false, <ide> mode = 0o777 <ide> function mkdirSync(path, options) { <ide> function readdir(path, options, callback) { <ide> callback = makeCallback(typeof options === 'function' ? options : callback); <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> <ide> const req = new FSReqCallback(); <ide> function readdir(path, options, callback) { <ide> <ide> function readdirSync(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> const result = binding.readdir(pathModule.toNamespacedPath(path), <ide> function lstat(path, options, callback) { <ide> options = {}; <ide> } <ide> callback = makeStatsCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const req = new FSReqCallback(options.bigint); <ide> req.oncomplete = callback; <ide> function stat(path, options, callback) { <ide> options = {}; <ide> } <ide> callback = makeStatsCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const req = new FSReqCallback(options.bigint); <ide> req.oncomplete = callback; <ide> function fstatSync(fd, options = {}) { <ide> } <ide> <ide> function lstatSync(path, options = {}) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> const stats = binding.lstat(pathModule.toNamespacedPath(path), <ide> function lstatSync(path, options = {}) { <ide> } <ide> <ide> function statSync(path, options = {}) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> const stats = binding.stat(pathModule.toNamespacedPath(path), <ide> function statSync(path, options = {}) { <ide> function readlink(path, options, callback) { <ide> callback = makeCallback(typeof options === 'function' ? options : callback); <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path, 'oldPath'); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> function readlink(path, options, callback) { <ide> <ide> function readlinkSync(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path, 'oldPath'); <ide> const ctx = { path }; <ide> const result = binding.readlink(pathModule.toNamespacedPath(path), <ide> function symlink(target, path, type_, callback_) { <ide> const type = (typeof type_ === 'string' ? type_ : null); <ide> const callback = makeCallback(arguments[arguments.length - 1]); <ide> <del> target = getPathFromURL(target); <del> path = getPathFromURL(path); <add> target = toPathIfFileURL(target); <add> path = toPathIfFileURL(path); <ide> validatePath(target, 'target'); <ide> validatePath(path); <ide> <ide> function symlink(target, path, type_, callback_) { <ide> <ide> function symlinkSync(target, path, type) { <ide> type = (typeof type === 'string' ? type : null); <del> target = getPathFromURL(target); <del> path = getPathFromURL(path); <add> target = toPathIfFileURL(target); <add> path = toPathIfFileURL(path); <ide> validatePath(target, 'target'); <ide> validatePath(path); <ide> const flags = stringToSymlinkType(type); <ide> function symlinkSync(target, path, type) { <ide> function link(existingPath, newPath, callback) { <ide> callback = makeCallback(callback); <ide> <del> existingPath = getPathFromURL(existingPath); <del> newPath = getPathFromURL(newPath); <add> existingPath = toPathIfFileURL(existingPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(existingPath, 'existingPath'); <ide> validatePath(newPath, 'newPath'); <ide> <ide> function link(existingPath, newPath, callback) { <ide> } <ide> <ide> function linkSync(existingPath, newPath) { <del> existingPath = getPathFromURL(existingPath); <del> newPath = getPathFromURL(newPath); <add> existingPath = toPathIfFileURL(existingPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(existingPath, 'existingPath'); <ide> validatePath(newPath, 'newPath'); <ide> <ide> function linkSync(existingPath, newPath) { <ide> <ide> function unlink(path, callback) { <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> binding.unlink(pathModule.toNamespacedPath(path), req); <ide> } <ide> <ide> function unlinkSync(path) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> binding.unlink(pathModule.toNamespacedPath(path), undefined, ctx); <ide> function lchmodSync(path, mode) { <ide> <ide> <ide> function chmod(path, mode, callback) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> mode = validateMode(mode, 'mode'); <ide> callback = makeCallback(callback); <ide> function chmod(path, mode, callback) { <ide> } <ide> <ide> function chmodSync(path, mode) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> mode = validateMode(mode, 'mode'); <ide> <ide> function chmodSync(path, mode) { <ide> <ide> function lchown(path, uid, gid, callback) { <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> function lchown(path, uid, gid, callback) { <ide> } <ide> <ide> function lchownSync(path, uid, gid) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> function fchownSync(fd, uid, gid) { <ide> <ide> function chown(path, uid, gid, callback) { <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> function chown(path, uid, gid, callback) { <ide> } <ide> <ide> function chownSync(path, uid, gid) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> function chownSync(path, uid, gid) { <ide> <ide> function utimes(path, atime, mtime, callback) { <ide> callback = makeCallback(callback); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> <ide> const req = new FSReqCallback(); <ide> function utimes(path, atime, mtime, callback) { <ide> } <ide> <ide> function utimesSync(path, atime, mtime) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> binding.utimes(pathModule.toNamespacedPath(path), <ide> function watch(filename, options, listener) { <ide> const statWatchers = new Map(); <ide> <ide> function watchFile(filename, options, listener) { <del> filename = getPathFromURL(filename); <add> filename = toPathIfFileURL(filename); <ide> validatePath(filename); <ide> filename = pathModule.resolve(filename); <ide> let stat; <ide> function watchFile(filename, options, listener) { <ide> } <ide> <ide> function unwatchFile(filename, listener) { <del> filename = getPathFromURL(filename); <add> filename = toPathIfFileURL(filename); <ide> validatePath(filename); <ide> filename = pathModule.resolve(filename); <ide> const stat = statWatchers.get(filename); <ide> function realpathSync(p, options) { <ide> options = emptyObj; <ide> else <ide> options = getOptions(options, emptyObj); <del> p = getPathFromURL(p); <add> p = toPathIfFileURL(p); <ide> if (typeof p !== 'string') { <ide> p += ''; <ide> } <ide> function realpathSync(p, options) { <ide> <ide> realpathSync.native = function(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const ctx = { path }; <ide> const result = binding.realpath(path, options.encoding, undefined, ctx); <ide> function realpath(p, options, callback) { <ide> options = emptyObj; <ide> else <ide> options = getOptions(options, emptyObj); <del> p = getPathFromURL(p); <add> p = toPathIfFileURL(p); <ide> if (typeof p !== 'string') { <ide> p += ''; <ide> } <ide> function realpath(p, options, callback) { <ide> realpath.native = function(path, options, callback) { <ide> callback = makeCallback(callback || options); <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> function copyFile(src, dest, flags, callback) { <ide> throw new ERR_INVALID_CALLBACK(); <ide> } <ide> <del> src = getPathFromURL(src); <del> dest = getPathFromURL(dest); <add> src = toPathIfFileURL(src); <add> dest = toPathIfFileURL(dest); <ide> validatePath(src, 'src'); <ide> validatePath(dest, 'dest'); <ide> <ide> function copyFile(src, dest, flags, callback) { <ide> <ide> <ide> function copyFileSync(src, dest, flags) { <del> src = getPathFromURL(src); <del> dest = getPathFromURL(dest); <add> src = toPathIfFileURL(src); <add> dest = toPathIfFileURL(dest); <ide> validatePath(src, 'src'); <ide> validatePath(dest, 'dest'); <ide> <ide><path>lib/internal/fs/promises.js <ide> const { <ide> ERR_INVALID_ARG_VALUE, <ide> ERR_METHOD_NOT_IMPLEMENTED <ide> } = require('internal/errors').codes; <del>const { getPathFromURL } = require('internal/url'); <add>const { toPathIfFileURL } = require('internal/url'); <ide> const { isUint8Array } = require('internal/util/types'); <ide> const { <ide> copyObject, <ide> async function readFileHandle(filehandle, options) { <ide> // All of the functions are defined as async in order to ensure that errors <ide> // thrown cause promise rejections rather than being thrown synchronously. <ide> async function access(path, mode = F_OK) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> <ide> mode = mode | 0; <ide> async function access(path, mode = F_OK) { <ide> } <ide> <ide> async function copyFile(src, dest, flags) { <del> src = getPathFromURL(src); <del> dest = getPathFromURL(dest); <add> src = toPathIfFileURL(src); <add> dest = toPathIfFileURL(dest); <ide> validatePath(src, 'src'); <ide> validatePath(dest, 'dest'); <ide> flags = flags | 0; <ide> async function copyFile(src, dest, flags) { <ide> // Note that unlike fs.open() which uses numeric file descriptors, <ide> // fsPromises.open() uses the fs.FileHandle class. <ide> async function open(path, flags, mode) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> mode = validateMode(mode, 'mode', 0o666); <ide> return new FileHandle( <ide> async function write(handle, buffer, offset, length, position) { <ide> } <ide> <ide> async function rename(oldPath, newPath) { <del> oldPath = getPathFromURL(oldPath); <del> newPath = getPathFromURL(newPath); <add> oldPath = toPathIfFileURL(oldPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(oldPath, 'oldPath'); <ide> validatePath(newPath, 'newPath'); <ide> return binding.rename(pathModule.toNamespacedPath(oldPath), <ide> async function ftruncate(handle, len = 0) { <ide> } <ide> <ide> async function rmdir(path) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> return binding.rmdir(pathModule.toNamespacedPath(path), kUsePromises); <ide> } <ide> async function mkdir(path, options) { <ide> recursive = false, <ide> mode = 0o777 <ide> } = options || {}; <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> <ide> validatePath(path); <ide> if (typeof recursive !== 'boolean') <ide> async function mkdir(path, options) { <ide> <ide> async function readdir(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const result = await binding.readdir(pathModule.toNamespacedPath(path), <ide> options.encoding, !!options.withTypes, <ide> async function readdir(path, options) { <ide> <ide> async function readlink(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path, 'oldPath'); <ide> return binding.readlink(pathModule.toNamespacedPath(path), <ide> options.encoding, kUsePromises); <ide> } <ide> <ide> async function symlink(target, path, type_) { <ide> const type = (typeof type_ === 'string' ? type_ : null); <del> target = getPathFromURL(target); <del> path = getPathFromURL(path); <add> target = toPathIfFileURL(target); <add> path = toPathIfFileURL(path); <ide> validatePath(target, 'target'); <ide> validatePath(path); <ide> return binding.symlink(preprocessSymlinkDestination(target, type, path), <ide> async function fstat(handle, options = { bigint: false }) { <ide> } <ide> <ide> async function lstat(path, options = { bigint: false }) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const result = await binding.lstat(pathModule.toNamespacedPath(path), <ide> options.bigint, kUsePromises); <ide> return getStatsFromBinding(result); <ide> } <ide> <ide> async function stat(path, options = { bigint: false }) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> const result = await binding.stat(pathModule.toNamespacedPath(path), <ide> options.bigint, kUsePromises); <ide> return getStatsFromBinding(result); <ide> } <ide> <ide> async function link(existingPath, newPath) { <del> existingPath = getPathFromURL(existingPath); <del> newPath = getPathFromURL(newPath); <add> existingPath = toPathIfFileURL(existingPath); <add> newPath = toPathIfFileURL(newPath); <ide> validatePath(existingPath, 'existingPath'); <ide> validatePath(newPath, 'newPath'); <ide> return binding.link(pathModule.toNamespacedPath(existingPath), <ide> async function link(existingPath, newPath) { <ide> } <ide> <ide> async function unlink(path) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> return binding.unlink(pathModule.toNamespacedPath(path), kUsePromises); <ide> } <ide> async function fchmod(handle, mode) { <ide> } <ide> <ide> async function chmod(path, mode) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> mode = validateMode(mode, 'mode'); <ide> return binding.chmod(pathModule.toNamespacedPath(path), mode, kUsePromises); <ide> async function lchmod(path, mode) { <ide> } <ide> <ide> async function lchown(path, uid, gid) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> async function fchown(handle, uid, gid) { <ide> } <ide> <ide> async function chown(path, uid, gid) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> validateUint32(uid, 'uid'); <ide> validateUint32(gid, 'gid'); <ide> async function chown(path, uid, gid) { <ide> } <ide> <ide> async function utimes(path, atime, mtime) { <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> return binding.utimes(pathModule.toNamespacedPath(path), <ide> toUnixTimestamp(atime), <ide> async function futimes(handle, atime, mtime) { <ide> <ide> async function realpath(path, options) { <ide> options = getOptions(options, {}); <del> path = getPathFromURL(path); <add> path = toPathIfFileURL(path); <ide> validatePath(path); <ide> return binding.realpath(path, options.encoding, kUsePromises); <ide> } <ide><path>lib/internal/fs/streams.js <ide> const { <ide> getOptions, <ide> } = require('internal/fs/utils'); <ide> const { Readable, Writable } = require('stream'); <del>const { getPathFromURL } = require('internal/url'); <add>const { toPathIfFileURL } = require('internal/url'); <ide> const util = require('util'); <ide> <ide> const kMinPoolSpace = 128; <ide> function ReadStream(path, options) { <ide> Readable.call(this, options); <ide> <ide> // path will be ignored when fd is specified, so it can be falsy <del> this.path = getPathFromURL(path); <add> this.path = toPathIfFileURL(path); <ide> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'r' : options.flags; <ide> this.mode = options.mode === undefined ? 0o666 : options.mode; <ide> function WriteStream(path, options) { <ide> Writable.call(this, options); <ide> <ide> // path will be ignored when fd is specified, so it can be falsy <del> this.path = getPathFromURL(path); <add> this.path = toPathIfFileURL(path); <ide> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'w' : options.flags; <ide> this.mode = options.mode === undefined ? 0o666 : options.mode; <ide><path>lib/internal/fs/watchers.js <ide> const { <ide> } = require('internal/async_hooks'); <ide> const { toNamespacedPath } = require('path'); <ide> const { validateUint32 } = require('internal/validators'); <del>const { getPathFromURL } = require('internal/url'); <add>const { toPathIfFileURL } = require('internal/url'); <ide> const util = require('util'); <ide> const assert = require('assert'); <ide> <ide> StatWatcher.prototype.start = function(filename, persistent, interval) { <ide> // the sake of backwards compatibility <ide> this[kOldStatus] = -1; <ide> <del> filename = getPathFromURL(filename); <add> filename = toPathIfFileURL(filename); <ide> validatePath(filename, 'filename'); <ide> validateUint32(interval, 'interval'); <ide> const err = this._handle.start(toNamespacedPath(filename), interval); <ide> FSWatcher.prototype.start = function(filename, <ide> return; <ide> } <ide> <del> filename = getPathFromURL(filename); <add> filename = toPathIfFileURL(filename); <ide> validatePath(filename, 'filename'); <ide> <ide> const err = this._handle.start(toNamespacedPath(filename), <ide><path>lib/internal/modules/cjs/loader.js <ide> module.exports = Module; <ide> let asyncESM; <ide> let ModuleJob; <ide> let createDynamicModule; <del>let getURLFromFilePath; <add>let pathToFileURL; <ide> let decorateErrorStack; <ide> <ide> function lazyLoadESM() { <ide> function lazyLoadESM() { <ide> createDynamicModule = require( <ide> 'internal/modules/esm/create_dynamic_module'); <ide> decorateErrorStack = require('internal/util').decorateErrorStack; <del> getURLFromFilePath = require('internal/url').getURLFromFilePath; <add> pathToFileURL = require('internal/url').pathToFileURL; <ide> } <ide> <ide> const { <ide> Module.prototype.load = function(filename) { <ide> if (experimentalModules) { <ide> if (asyncESM === undefined) lazyLoadESM(); <ide> const ESMLoader = asyncESM.ESMLoader; <del> const url = getURLFromFilePath(filename); <add> const url = pathToFileURL(filename); <ide> const urlString = `${url}`; <ide> const exports = this.exports; <ide> if (ESMLoader.moduleMap.has(urlString) !== true) { <ide> Module.runMain = function() { <ide> if (experimentalModules) { <ide> if (asyncESM === undefined) lazyLoadESM(); <ide> asyncESM.loaderPromise.then((loader) => { <del> return loader.import(getURLFromFilePath(process.argv[1]).pathname); <add> return loader.import(pathToFileURL(process.argv[1]).pathname); <ide> }) <ide> .catch((e) => { <ide> decorateErrorStack(e); <ide><path>lib/internal/modules/esm/default_resolve.js <ide> const { <ide> } = require('internal/errors').codes; <ide> const { resolve: moduleWrapResolve } = internalBinding('module_wrap'); <ide> const StringStartsWith = Function.call.bind(String.prototype.startsWith); <del>const { getURLFromFilePath, getPathFromURL } = require('internal/url'); <add>const { pathToFileURL, fileURLToPath } = require('internal/url'); <ide> <ide> const realpathCache = new Map(); <ide> <ide> function resolve(specifier, parentURL) { <ide> let url; <ide> try { <ide> url = search(specifier, <del> parentURL || getURLFromFilePath(`${process.cwd()}/`).href); <add> parentURL || pathToFileURL(`${process.cwd()}/`).href); <ide> } catch (e) { <ide> if (typeof e.message === 'string' && <ide> StringStartsWith(e.message, 'Cannot find module')) <ide> function resolve(specifier, parentURL) { <ide> const isMain = parentURL === undefined; <ide> <ide> if (isMain ? !preserveSymlinksMain : !preserveSymlinks) { <del> const real = realpathSync(getPathFromURL(url), { <add> const real = realpathSync(fileURLToPath(url), { <ide> [internalFS.realpathCacheKey]: realpathCache <ide> }); <ide> const old = url; <del> url = getURLFromFilePath(real); <add> url = pathToFileURL(real); <ide> url.search = old.search; <ide> url.hash = old.hash; <ide> } <ide><path>lib/internal/modules/esm/translators.js <ide> const isWindows = process.platform === 'win32'; <ide> const winSepRegEx = /\//g; <ide> translators.set('cjs', async (url, isMain) => { <ide> debug(`Translating CJSModule ${url}`); <del> const pathname = internalURLModule.getPathFromURL(new URL(url)); <add> const pathname = internalURLModule.fileURLToPath(new URL(url)); <ide> const module = CJSModule._cache[ <ide> isWindows ? StringReplace(pathname, winSepRegEx, '\\') : pathname]; <ide> if (module && module.loaded) { <ide> translators.set('addon', async (url) => { <ide> return createDynamicModule(['default'], url, (reflect) => { <ide> debug(`Loading NativeModule ${url}`); <ide> const module = { exports: {} }; <del> const pathname = internalURLModule.getPathFromURL(new URL(url)); <add> const pathname = internalURLModule.fileURLToPath(new URL(url)); <ide> process.dlopen(module, _makeLong(pathname)); <ide> reflect.exports.default.set(module.exports); <ide> }); <ide> translators.set('json', async (url) => { <ide> debug(`Translating JSONModule ${url}`); <ide> return createDynamicModule(['default'], url, (reflect) => { <ide> debug(`Loading JSONModule ${url}`); <del> const pathname = internalURLModule.getPathFromURL(new URL(url)); <add> const pathname = internalURLModule.fileURLToPath(new URL(url)); <ide> const content = readFileSync(pathname, 'utf8'); <ide> try { <ide> const exports = JsonParse(stripBOM(content)); <ide><path>lib/internal/process/esm_loader.js <ide> const { <ide> setInitializeImportMetaObjectCallback <ide> } = internalBinding('module_wrap'); <ide> <del>const { getURLFromFilePath } = require('internal/url'); <add>const { pathToFileURL } = require('internal/url'); <ide> const Loader = require('internal/modules/esm/loader'); <ide> const path = require('path'); <ide> const { URL } = require('url'); <ide> const { <ide> <ide> function normalizeReferrerURL(referrer) { <ide> if (typeof referrer === 'string' && path.isAbsolute(referrer)) { <del> return getURLFromFilePath(referrer).href; <add> return pathToFileURL(referrer).href; <ide> } <ide> return new URL(referrer).href; <ide> } <ide> exports.setup = function() { <ide> const userLoader = process.binding('config').userLoader; <ide> if (userLoader) { <ide> const hooks = await ESMLoader.import( <del> userLoader, getURLFromFilePath(`${process.cwd()}/`).href); <add> userLoader, pathToFileURL(`${process.cwd()}/`).href); <ide> ESMLoader = new Loader(); <ide> ESMLoader.hook(hooks); <ide> exports.ESMLoader = ESMLoader; <ide><path>lib/internal/url.js <ide> const { <ide> ERR_MISSING_ARGS <ide> } = require('internal/errors').codes; <ide> const { <del> CHAR_PERCENT, <del> CHAR_PLUS, <ide> CHAR_AMPERSAND, <add> CHAR_BACKWARD_SLASH, <ide> CHAR_EQUAL, <add> CHAR_FORWARD_SLASH, <ide> CHAR_LOWERCASE_A, <ide> CHAR_LOWERCASE_Z, <add> CHAR_PERCENT, <add> CHAR_PLUS <ide> } = require('internal/constants'); <add>const path = require('path'); <ide> <ide> // Lazy loaded for startup performance. <ide> let querystring; <ide> function getPathFromURLPosix(url) { <ide> return decodeURIComponent(pathname); <ide> } <ide> <del>function getPathFromURL(path) { <del> if (path == null || !path[searchParams] || <del> !path[searchParams][searchParams]) { <del> return path; <del> } <add>function fileURLToPath(path) { <add> if (typeof path === 'string') <add> path = new URL(path); <add> else if (path == null || !path[searchParams] || <add> !path[searchParams][searchParams]) <add> throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path); <ide> if (path.protocol !== 'file:') <ide> throw new ERR_INVALID_URL_SCHEME('file'); <ide> return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path); <ide> function getPathFromURL(path) { <ide> // as this is the only character that won't be percent encoded by <ide> // default URL percent encoding when pathname is set. <ide> const percentRegEx = /%/g; <del>function getURLFromFilePath(filepath) { <del> const tmp = new URL('file://'); <del> if (filepath.includes('%')) <del> filepath = filepath.replace(percentRegEx, '%25'); <del> tmp.pathname = filepath; <del> return tmp; <add>const backslashRegEx = /\\/g; <add>function pathToFileURL(filepath) { <add> let resolved = path.resolve(filepath); <add> // path.resolve strips trailing slashes so we must add them back <add> const filePathLast = filepath.charCodeAt(filepath.length - 1); <add> if ((filePathLast === CHAR_FORWARD_SLASH || <add> isWindows && filePathLast === CHAR_BACKWARD_SLASH) && <add> resolved[resolved.length - 1] !== path.sep) <add> resolved += '/'; <add> const outURL = new URL('file://'); <add> if (resolved.includes('%')) <add> resolved = resolved.replace(percentRegEx, '%25'); <add> // in posix, "/" is a valid character in paths <add> if (!isWindows && resolved.includes('\\')) <add> resolved = resolved.replace(backslashRegEx, '%5C'); <add> outURL.pathname = resolved; <add> return outURL; <add>} <add> <add>function toPathIfFileURL(fileURLOrPath) { <add> if (fileURLOrPath == null || !fileURLOrPath[searchParams] || <add> !fileURLOrPath[searchParams][searchParams]) <add> return fileURLOrPath; <add> return fileURLToPath(fileURLOrPath); <ide> } <ide> <ide> function NativeURL(ctx) { <ide> setURLConstructor(constructUrl); <ide> <ide> module.exports = { <ide> toUSVString, <del> getPathFromURL, <del> getURLFromFilePath, <add> fileURLToPath, <add> pathToFileURL, <add> toPathIfFileURL, <ide> URL, <ide> URLSearchParams, <ide> domainToASCII, <ide><path>lib/url.js <ide> const { <ide> domainToUnicode, <ide> formatSymbol, <ide> encodeStr, <add> pathToFileURL, <add> fileURLToPath <ide> } = require('internal/url'); <ide> <ide> // Original url.parse() API <ide> module.exports = { <ide> URL, <ide> URLSearchParams, <ide> domainToASCII, <del> domainToUnicode <add> domainToUnicode, <add> <add> // Utilities <add> pathToFileURL, <add> fileURLToPath <ide> }; <ide><path>test/common/inspector-helper.js <ide> const http = require('http'); <ide> const fixtures = require('../common/fixtures'); <ide> const { spawn } = require('child_process'); <ide> const { parse: parseURL } = require('url'); <del>const { getURLFromFilePath } = require('internal/url'); <add>const { pathToFileURL } = require('internal/url'); <ide> const { EventEmitter } = require('events'); <ide> <ide> const _MAINSCRIPT = fixtures.path('loop.js'); <ide> class InspectorSession { <ide> const { scriptId, url } = message.params; <ide> this._scriptsIdsByUrl.set(scriptId, url); <ide> const fileUrl = url.startsWith('file:') ? <del> url : getURLFromFilePath(url).toString(); <add> url : pathToFileURL(url).toString(); <ide> if (fileUrl === this.scriptURL().toString()) { <ide> this.mainScriptId = scriptId; <ide> } <ide> class InspectorSession { <ide> } <ide> <ide> scriptURL() { <del> return getURLFromFilePath(this.scriptPath()); <add> return pathToFileURL(this.scriptPath()); <ide> } <ide> } <ide> <ide><path>test/parallel/test-url-pathtofileurl.js <add>'use strict'; <add>const { isWindows } = require('../common'); <add>const assert = require('assert'); <add>const url = require('url'); <add> <add>{ <add> const fileURL = url.pathToFileURL('test/').href; <add> assert.ok(fileURL.startsWith('file:///')); <add> assert.ok(fileURL.endsWith('/')); <add>} <add> <add>{ <add> const fileURL = url.pathToFileURL('test\\').href; <add> assert.ok(fileURL.startsWith('file:///')); <add> if (isWindows) <add> assert.ok(fileURL.endsWith('/')); <add> else <add> assert.ok(fileURL.endsWith('%5C')); <add>} <add> <add>{ <add> const fileURL = url.pathToFileURL('test/%').href; <add> assert.ok(fileURL.includes('%25')); <add>}
13
Python
Python
fix crash in repr of void subclasses
0ec2a4f581c32979862468b727cc96df4910d5ed
<ide><path>numpy/core/_dtype.py <ide> def _scalar_str(dtype, short): <ide> else: <ide> return "'%sU%d'" % (byteorder, dtype.itemsize / 4) <ide> <del> elif dtype.type == np.void: <add> # unlike the other types, subclasses of void are preserved - but <add> # historically the repr does not actually reveal the subclass <add> elif issubclass(dtype.type, np.void): <ide> if _isunsized(dtype): <ide> return "'V'" <ide> else: <ide><path>numpy/core/tests/test_dtype.py <ide> def test_empty_string_to_object(self): <ide> # Pull request #4722 <ide> np.array(["", ""]).astype(object) <ide> <add> def test_void_subclass_unsized(self): <add> dt = np.dtype(np.record) <add> assert_equal(repr(dt), "dtype('V')") <add> assert_equal(str(dt), '|V0') <add> assert_equal(dt.name, 'record') <add> <add> def test_void_subclass_sized(self): <add> dt = np.dtype((np.record, 2)) <add> assert_equal(repr(dt), "dtype('V2')") <add> assert_equal(str(dt), '|V2') <add> assert_equal(dt.name, 'record16') <add> <add> def test_void_subclass_fields(self): <add> dt = np.dtype((np.record, [('a', '<u2')])) <add> assert_equal(repr(dt), "dtype((numpy.record, [('a', '<u2')]))") <add> assert_equal(str(dt), "(numpy.record, [('a', '<u2')])") <add> assert_equal(dt.name, 'record16') <add> <add> <ide> class TestDtypeAttributeDeletion(object): <ide> <ide> def test_dtype_non_writable_attributes_deletion(self):
2
Ruby
Ruby
use content_tag in button_to helper
f7714eca47c5c57acb08ccbfb35ff224ac4d62b3
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb <ide> def button_to(name, options = {}, html_options = {}) <ide> remote = html_options.delete('remote') <ide> <ide> method = html_options.delete('method').to_s <del> method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : "" <add> method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe <ide> <ide> form_method = method == 'get' ? 'get' : 'post' <ide> form_options = html_options.delete('form') || {} <ide> def button_to(name, options = {}, html_options = {}) <ide> html_options = convert_options_to_data_attributes(options, html_options) <ide> html_options.merge!("type" => "submit", "value" => name || url) <ide> <del> "#{tag(:form, form_options, true)}<div>#{method_tag}#{tag("input", html_options)}#{request_token_tag}</div></form>".html_safe <add> inner_tags = method_tag.safe_concat tag('input', html_options).safe_concat request_token_tag <add> content_tag('form', content_tag('div', inner_tags), form_options) <ide> end <ide> <ide>
1
Text
Text
move mesteery to collaborators
eda54bae16007a391283a8ee0d52bcd6ee311b5c
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Joyee Cheung** <<joyeec9h3@gmail.com>> (she/her) <ide> * [mcollina](https://github.com/mcollina) - <ide> **Matteo Collina** <<matteo.collina@gmail.com>> (he/him) <del>* [Mesteery](https://github.com/Mesteery) - <del> **Mestery** <<mestery@protonmail.com>> (he/him) <ide> * [mhdawson](https://github.com/mhdawson) - <ide> **Michael Dawson** <<midawson@redhat.com>> (he/him) <ide> * [mmarchini](https://github.com/mmarchini) - <ide> For information about the governance of the Node.js project, see <ide> **Zijian Liu** <<lxxyxzj@gmail.com>> (he/him) <ide> * [mcollina](https://github.com/mcollina) - <ide> **Matteo Collina** <<matteo.collina@gmail.com>> (he/him) <add>* [Mesteery](https://github.com/Mesteery) - <add> **Mestery** <<mestery@protonmail.com>> (he/him) <ide> * [mhdawson](https://github.com/mhdawson) - <ide> **Michael Dawson** <<midawson@redhat.com>> (he/him) <ide> * [miladfarca](https://github.com/miladfarca) -
1
Text
Text
add info on project's usage of coverity
9ebdba49c72bbe2c100a7a99970767e6e929a6f6
<ide><path>doc/guides/offboarding.md <ide> emeritus or leaves the project. <ide> a team listing. For example, if someone is removed from @nodejs/build, <ide> they should also be removed from the Build WG README.md file in the <ide> <https://github.com/nodejs/build> repository. <add>* Open an issue in the [build](https://github.com/nodejs/build) repository <add> titled `Remove Collaborator from Coverity` asking that the collaborator <add> be removed from the Node.js coverity project if they had access. <ide><path>doc/guides/static-analysis.md <add># Static Analysis <add> <add>The project uses Coverity to scan Node.js source code and to report potential <add>issues in the C/C++ code base. <add> <add>Those who have been added to the Node.js coverity project can receive emails <add>when there are new issues reported as well as view all current issues <add>through [https://scan9.coverity.com/reports.htm](https://scan9.coverity.com/reports.htm). <add> <add>Any collaborator can ask to be added to the Node.js coverity project <add>by opening an issue in the [build](https://github.com/nodejs/build) repository <add>titled `Please add me to coverity`. A member of the build WG with admin <add>access will verify that the requestor is an existing collaborator as listed in <add>the [colloborators section](https://github.com/nodejs/node#collaborators) <add>on the nodejs/node project repo. Once validated the requestor will added <add>to to the coverity project. <ide><path>onboarding.md <ide> needs to be pointed out separately during the onboarding. <ide> project. The Foundation has travel funds to cover participants' expenses <ide> including accommodations, transportation, visa fees, etc. if needed. Check out <ide> the [summit](https://github.com/nodejs/summit) repository for details. <add>* If you are interested in helping to fix coverity reports consider requesting <add> access to the projects coverity project as outlined in [static-analysis][]. <ide> <ide> [Code of Conduct]: https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md <ide> [Labels]: doc/guides/collaborator-guide.md#labels <ide> needs to be pointed out separately during the onboarding. <ide> [`git-node`]: https://github.com/nodejs/node-core-utils/blob/HEAD/docs/git-node.md <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils <ide> [set up the credentials]: https://github.com/nodejs/node-core-utils#setting-up-github-credentials <add>[static-analysis]: doc/guides/static-analysis.md <ide> [two-factor authentication]: https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/ <ide> [using a TOTP mobile app]: https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ <ide> [who-to-cc]: doc/guides/collaborator-guide.md#who-to-cc-in-the-issue-tracker
3
Python
Python
add the all request, with warnings
2726522b1ef77362026426e56310bc7b362218b2
<ide><path>glances/outputs/glances_stdout_apidoc.py <ide> def update(self, <ide> print('.. code-block:: json') <ide> print('') <ide> print(' # curl {}/all'.format(API_URL)) <del> print(indent_stat(json.loads(stat.getAllViewsAsDict()))) <add> print(' Return a very big dictionnary (avoid using this request, performances will be poor)...') <ide> print('') <ide> <ide> # Return True to exit directly (no refresh)
1
Javascript
Javascript
expose current index in collectionviews
d4ff579ce3ec69673f3b003ce319959a3a3eab77
<ide><path>packages/sproutcore-views/lib/views/collection_view.js <ide> SC.CollectionView = SC.View.extend( <ide> for (idx = 0; idx < len; idx++) { <ide> item = addedObjects.objectAt(idx); <ide> view = this.createChildView(itemViewClass, { <del> content: item <add> content: item, <add> index: idx <ide> }); <ide> <ide> buffer = buffer + view.renderToBuffer().string();
1
Python
Python
airflow info fixed for python 3.8+
24a83706646612f17f776a1c76a35c373c5e9990
<ide><path>airflow/cli/commands/info_command.py <ide> <ide> import requests <ide> import tenacity <del>from typing_extensions import Protocol <ide> <ide> from airflow import configuration <add>from airflow.typing_compat import Protocol <ide> from airflow.version import version as airflow_version <ide> <ide> log = logging.getLogger(__name__)
1
Text
Text
update imperative routing docs to have better a11y
7f998950767670321d5ec12522275e86a0ae0c4e
<ide><path>docs/routing/imperatively.md <ide> The following example shows how to do basic page navigations with [`useRouter`]( <ide> ```jsx <ide> import { useRouter } from 'next/router' <ide> <del>function ReadMore() { <add>export default function ReadMore() { <ide> const router = useRouter() <ide> <ide> return ( <del> <span onClick={() => router.push('/about')}>Click here to read more</span> <add> <button onClick={() => router.push('/about')}> <add> Click here to read more <add> </button> <ide> ) <ide> } <del> <del>export default ReadMore <ide> ```
1
Javascript
Javascript
add missing typeof
b7bc2cc41793159279a8ada11fc5b56aa6c323cc
<ide><path>lib/EnvironmentPlugin.js <ide> EnvironmentPlugin.prototype.apply = function(compiler) { <ide> }); <ide> } <ide> <del> defs["process.env." + key] = value === 'undefined' ? 'undefined' : JSON.stringify(value); <add> defs["process.env." + key] = typeof value === 'undefined' ? 'undefined' : JSON.stringify(value); <ide> <ide> return defs; <ide> }.bind(this), {});
1
Javascript
Javascript
introduce universal switch
36cbe74f990369c793966b052bee4af3f2f4e401
<ide><path>Libraries/Components/Switch/Switch.js <add>/** <add> * Copyright 2004-present Facebook. All Rights Reserved. <add> * <add> * @providesModule Switch <add> * @flow <add> */ <add>'use strict'; <add> <add>var Platform = require('Platform'); <add>var NativeMethodsMixin = require('NativeMethodsMixin'); <add>var React = require('React'); <add>var StyleSheet = require('StyleSheet'); <add> <add>var requireNativeComponent = require('requireNativeComponent'); <add> <add>type DefaultProps = { <add> value: boolean; <add> disabled: boolean; <add>}; <add> <add>/** <add> * Universal two-state toggle component. <add> */ <add>var Switch = React.createClass({ <add> propTypes: { <add> /** <add> * The value of the switch. If true the switch will be turned on. <add> * Default value is false. <add> */ <add> value: React.PropTypes.bool, <add> /** <add> * If true the user won't be able to toggle the switch. <add> * Default value is false. <add> */ <add> disabled: React.PropTypes.bool, <add> /** <add> * Invoked with the new value when the value chages. <add> */ <add> onValueChange: React.PropTypes.func, <add> /** <add> * Used to locate this view in end-to-end tests. <add> */ <add> testID: React.PropTypes.string, <add> <add> /** <add> * Background color when the switch is turned off. <add> * @platform ios <add> */ <add> tintColor: React.PropTypes.string, <add> /** <add> * Background color when the switch is turned on. <add> * @platform ios <add> */ <add> onTintColor: React.PropTypes.string, <add> /** <add> * Color of the foreground switch grip. <add> * @platform ios <add> */ <add> thumbTintColor: React.PropTypes.string, <add> }, <add> <add> getDefaultProps: function(): DefaultProps { <add> return { <add> value: false, <add> disabled: false, <add> }; <add> }, <add> <add> mixins: [NativeMethodsMixin], <add> <add> _rctSwitch: {}, <add> _onChange: function(event: Object) { <add> this.props.onChange && this.props.onChange(event); <add> this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); <add> <add> // The underlying switch might have changed, but we're controlled, <add> // and so want to ensure it represents our value. <add> if (Platform.OS === 'android') { <add> this._rctSwitch.setNativeProps({on: this.props.value}); <add> } else { <add> this._rctSwitch.setNativeProps({value: this.props.value}); <add> } <add> }, <add> <add> render: function() { <add> var props = {...this.props}; <add> props.onStartShouldSetResponder = () => true; <add> props.onResponderTerminationRequest = () => false; <add> if (Platform.OS === 'android') { <add> props.enabled = !this.props.disabled; <add> props.on = this.props.value; <add> props.style = [styles.rctSwitchAndroid, this.props.style]; <add> } else if (Platform.OS === 'ios') { <add> props.style = [styles.rctSwitchIOS, this.props.style]; <add> } <add> return ( <add> <RCTSwitch <add> {...props} <add> ref={(ref) => { this._rctSwitch = ref; }} <add> onChange={this._onChange} <add> /> <add> ); <add> }, <add>}); <add> <add>var styles = StyleSheet.create({ <add> rctSwitchIOS: { <add> height: 31, <add> width: 51, <add> }, <add> rctSwitchAndroid: { <add> height: 27, <add> width: 40, <add> }, <add>}); <add> <add>if (Platform.OS === 'android') { <add> var RCTSwitch = requireNativeComponent('AndroidSwitch', null, { <add> nativeOnly: { onChange: true, on: true, enabled: true } <add> }); <add>} else { <add> var RCTSwitch = requireNativeComponent('RCTSwitch', Switch, { <add> nativeOnly: { onChange: true } <add> }); <add>} <add> <add>module.exports = Switch; <ide><path>Libraries/react-native/react-native.js <ide> var ReactNative = Object.assign(Object.create(require('React')), { <ide> SegmentedControlIOS: require('SegmentedControlIOS'), <ide> SliderIOS: require('SliderIOS'), <ide> SnapshotView: require('SnapshotView'), <add> Switch: require('Switch'), <ide> SwitchAndroid: require('SwitchAndroid'), <ide> SwitchIOS: require('SwitchIOS'), <ide> TabBarIOS: require('TabBarIOS'),
2
Mixed
Ruby
add support for unlogged postgresql tables
bfc4d8be0a61b795ee122c5f426e0873938d0e41
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb <ide> def visit_AddColumnDefinition(o) <ide> end <ide> <ide> def visit_TableDefinition(o) <del> create_sql = +"CREATE#{' TEMPORARY' if o.temporary} TABLE " <add> create_sql = +"CREATE#{table_modifier_in_create(o)} TABLE " <ide> create_sql << "IF NOT EXISTS " if o.if_not_exists <ide> create_sql << "#{quote_table_name(o.name)} " <ide> <ide> def to_sql(sql) <ide> sql <ide> end <ide> <add> # Returns any SQL string to go between CREATE and TABLE. May be nil. <add> def table_modifier_in_create(o) <add> " TEMPORARY" if o.temporary <add> end <add> <ide> def foreign_key_in_create(from_table, to_table, options) <ide> options = foreign_key_options(from_table, to_table, options) <ide> accept ForeignKeyDefinition.new(from_table, to_table, options) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_creation.rb <ide> def add_column_options!(sql, options) <ide> end <ide> super <ide> end <add> <add> # Returns any SQL string to go between CREATE and TABLE. May be nil. <add> def table_modifier_in_create(o) <add> # A table cannot be both TEMPORARY and UNLOGGED, since all TEMPORARY <add> # tables are already UNLOGGED. <add> if o.temporary <add> " TEMPORARY" <add> elsif o.unlogged <add> " UNLOGGED" <add> end <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb <ide> def xml(*args, **options) <ide> class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition <ide> include ColumnMethods <ide> <add> attr_reader :unlogged <add> <add> def initialize(*) <add> super <add> @unlogged = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables <add> end <add> <ide> private <ide> def integer_like_primary_key_type(type, options) <ide> if type == :bigint || options[:limit] == 8 <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> module ConnectionAdapters <ide> class PostgreSQLAdapter < AbstractAdapter <ide> ADAPTER_NAME = "PostgreSQL" <ide> <add> ## <add> # :singleton-method: <add> # PostgreSQL allows the creation of "unlogged" tables, which do not record <add> # data in the PostgreSQL Write-Ahead Log. This can make the tables faster, <add> # bug significantly increases the risk of data loss if the database <add> # crashes. As a result, this should not be used in production <add> # environments. If you would like all created tables to be unlogged you <add> # can add the following line to your test.rb file: <add> # <add> # ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = true <add> class_attribute :create_unlogged_tables, default: false <add> <ide> NATIVE_DATABASE_TYPES = { <ide> primary_key: "bigserial primary key", <ide> string: { name: "character varying" }, <ide><path>activerecord/test/cases/adapters/postgresql/create_unlogged_tables_test.rb <add># frozen_string_literal: true <add> <add>require "cases/helper" <add>require "support/schema_dumping_helper" <add> <add>class UnloggedTablesTest < ActiveRecord::PostgreSQLTestCase <add> include SchemaDumpingHelper <add> <add> TABLE_NAME = "things" <add> LOGGED_FIELD = "relpersistence" <add> LOGGED_QUERY = "SELECT #{LOGGED_FIELD} FROM pg_class WHERE relname = '#{TABLE_NAME}'" <add> LOGGED = "p" <add> UNLOGGED = "u" <add> TEMPORARY = "t" <add> <add> class Thing < ActiveRecord::Base <add> self.table_name = TABLE_NAME <add> end <add> <add> def setup <add> @connection = ActiveRecord::Base.connection <add> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = false <add> end <add> <add> teardown do <add> @connection.drop_table TABLE_NAME, if_exists: true <add> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = false <add> end <add> <add> def test_logged_by_default <add> @connection.create_table(TABLE_NAME) do |t| <add> end <add> assert_equal @connection.execute(LOGGED_QUERY).first[LOGGED_FIELD], LOGGED <add> end <add> <add> def test_unlogged_in_test_environment_when_unlogged_setting_enabled <add> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = true <add> <add> @connection.create_table(TABLE_NAME) do |t| <add> end <add> assert_equal @connection.execute(LOGGED_QUERY).first[LOGGED_FIELD], UNLOGGED <add> end <add> <add> def test_not_included_in_schema_dump <add> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = true <add> <add> @connection.create_table(TABLE_NAME) do |t| <add> end <add> assert_no_match(/unlogged/i, dump_table_schema(TABLE_NAME)) <add> end <add> <add> def test_not_changed_in_change_table <add> @connection.create_table(TABLE_NAME) do |t| <add> end <add> <add> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = true <add> <add> @connection.change_table(TABLE_NAME) do |t| <add> t.column :name, :string <add> end <add> assert_equal @connection.execute(LOGGED_QUERY).first[LOGGED_FIELD], LOGGED <add> end <add> <add> def test_gracefully_handles_temporary_tables <add> @connection.create_table(TABLE_NAME, temporary: true) do |t| <add> end <add> <add> # Temporary tables are already unlogged, though this query results in a <add> # different result ("t" vs. "u"). This test is really just checking that we <add> # didn't try to run `CREATE TEMPORARY UNLOGGED TABLE`, which would result in <add> # a PostgreSQL error. <add> assert_equal @connection.execute(LOGGED_QUERY).first[LOGGED_FIELD], TEMPORARY <add> end <add>end <ide><path>guides/source/configuring.md <ide> The MySQL adapter adds one additional configuration option: <ide> <ide> * `ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns as booleans. Defaults to `true`. <ide> <add>The PostgreSQL adapter adds one additional configuration option: <add> <add>* `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables` <add> controls whether database tables created should be "unlogged," which can speed <add> up performance but adds a risk of data loss if the database crashes. It is <add> highly recommended that you do not enable this in a production environment. <add> Defaults to `false` in all environments. <add> <ide> The SQLite3Adapter adapter adds one additional configuration option: <ide> <ide> * `ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer`
6
PHP
PHP
apply fixes from styleci
5b4b02e9d9494b91fece6b6cc29bb50edca5ee2a
<ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php <ide> protected function limiter() <ide> */ <ide> public function maxAttempts() <ide> { <del> return property_exists($this,'maxAttempts') ? $this->maxAttempts : 5; <add> return property_exists($this, 'maxAttempts') ? $this->maxAttempts : 5; <ide> } <ide> <ide> /** <ide> public function maxAttempts() <ide> */ <ide> public function decayMinutes() <ide> { <del> return property_exists($this,'decayMinutes') ? $this->decayMinutes : 1; <add> return property_exists($this, 'decayMinutes') ? $this->decayMinutes : 1; <ide> } <ide> }
1
Ruby
Ruby
simplify fossil checkouts
7e844cad1c23e0785fca22345e187c3a7c21b270
<ide><path>Library/Homebrew/download_strategy.rb <ide> def bzrpath <ide> class FossilDownloadStrategy < VCSDownloadStrategy <ide> def stage <ide> super <del> safe_system fossilpath, "open", @clone <del> safe_system fossilpath, "checkout", @ref if @ref_type && @ref <add> args = [fossilpath, "open", @clone] <add> args << @ref if @ref_type && @ref <add> safe_system(*args) <ide> end <ide> <ide> private
1
Python
Python
remove circular imports in layoutlm/__init__.py
ad7196524695f3bb3e178d57d280bd18fa175ca6
<ide><path>src/transformers/models/layoutlm/__init__.py <ide> is_tokenizers_available, <ide> is_torch_available, <ide> ) <del>from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig <del>from .tokenization_layoutlm import LayoutLMTokenizer <ide> <ide> <ide> _import_structure = {
1
Text
Text
add missing semicolon
72f3a7e4a7e07035f428bf2f8ce8ad31aa85f297
<ide><path>docs/api-guide/settings.md <ide> Default: <ide> <ide> ( <ide> 'rest_framework.renderers.JSONRenderer', <del> 'rest_framework.renderers.BrowsableAPIRenderer' <add> 'rest_framework.renderers.BrowsableAPIRenderer', <ide> 'rest_framework.renderers.TemplateHTMLRenderer' <ide> ) <ide>
1
Javascript
Javascript
use parameter setup
5af00a5efc88f431deed5d4dcba292c973d336fb
<ide><path>examples/js/geometries/TeapotGeometry.js <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> this.type = 'TeapotGeometry'; <ide> <del> this.size = size || 50; <add> this.parameters = { <add> size: size, <add> segments: segments, <add> bottom: bottom, <add> lid: lid, <add> body: body, <add> fitLid: fitLid, <add> blinn: blinn <add> }; <add> <add> size = size || 50; <ide> <ide> // number of segments per patch <del> this.segments = Math.max( 2, Math.floor( segments ) || 10 ); <add> segments = segments !== undefined ? Math.max( 2, Math.floor( segments ) || 10 ) : 10; <ide> <ide> // which parts should be visible <del> this.bottom = bottom === undefined ? true : bottom; <del> this.lid = lid === undefined ? true : lid; <del> this.body = body === undefined ? true : body; <add> bottom = bottom === undefined ? true : bottom; <add> lid = lid === undefined ? true : lid; <add> body = body === undefined ? true : body; <ide> <ide> // Should the lid be snug? It's not traditional, so off by default <del> this.fitLid = fitLid === undefined ? false : fitLid; <add> fitLid = fitLid === undefined ? false : fitLid; <ide> <ide> // Jim Blinn scaled the teapot down in size by about 1.3 for <ide> // some rendering tests. He liked the new proportions that he kept <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> // real teapot is more like 1.25, but since 1.3 is the traditional <ide> // value given, we use it here. <ide> var blinnScale = 1.3; <del> this.blinn = blinn === undefined ? true : blinn; <add> blinn = blinn === undefined ? true : blinn; <ide> <ide> // scale the size to be the real scaling factor <del> var maxHeight = 3.15 * ( this.blinn ? 1 : blinnScale ); <add> var maxHeight = 3.15 * ( blinn ? 1 : blinnScale ); <ide> <ide> var maxHeight2 = maxHeight / 2; <del> var trueSize = this.size / maxHeight2; <add> var trueSize = size / maxHeight2; <ide> <ide> var normals = [], uvs = []; <ide> // Bezier form <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> } <ide> <del> var minPatches = this.body ? 0 : 20; <del> var maxPatches = this.bottom ? 32 : 28; <add> var minPatches = body ? 0 : 20; <add> var maxPatches = bottom ? 32 : 28; <ide> <del> vertPerRow = this.segments + 1; <add> vertPerRow = segments + 1; <ide> <ide> eps = 0.0000001; <ide> <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> // lid is in the middle of the data, patches 20-27, <ide> // so ignore it for this part of the loop if the lid is not desired <del> if ( this.lid || ( surf < 20 || surf >= 28 ) ) { <add> if ( lid || ( surf < 20 || surf >= 28 ) ) { <ide> <ide> // get M * G * M matrix for x,y,z <ide> for ( i = 0 ; i < 3 ; i ++ ) { <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> // is the lid to be made larger, and is this a point on the lid <ide> // that is X or Y? <del> if ( this.fitLid && ( surf >= 20 && surf < 28 ) && ( i !== 2 ) ) { <add> if ( fitLid && ( surf >= 20 && surf < 28 ) && ( i !== 2 ) ) { <ide> <ide> // increase XY size by 7.7%, found empirically. I don't <ide> // increase Z so that the teapot will continue to fit in the <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> // Blinn "fixed" the teapot by dividing Z by blinnScale, and that's the <ide> // data we now use. The original teapot is taller. Fix it: <del> if ( ! this.blinn && ( i === 2 ) ) { <add> if ( ! blinn && ( i === 2 ) ) { <ide> <ide> g[ c * 4 + r ] *= blinnScale; <ide> <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> } <ide> <ide> // step along, get points, and output <del> for ( sstep = 0 ; sstep <= this.segments ; sstep ++ ) { <add> for ( sstep = 0 ; sstep <= segments ; sstep ++ ) { <ide> <del> s = sstep / this.segments; <add> s = sstep / segments; <ide> <del> for ( tstep = 0 ; tstep <= this.segments ; tstep ++ ) { <add> for ( tstep = 0 ; tstep <= segments ; tstep ++ ) { <ide> <del> t = tstep / this.segments; <add> t = tstep / segments; <ide> <ide> // point from basis <ide> // get power vectors and their derivatives <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> } <ide> <ide> // save the faces <del> for ( sstep = 0 ; sstep < this.segments ; sstep ++ ) { <add> for ( sstep = 0 ; sstep < segments ; sstep ++ ) { <ide> <del> for ( tstep = 0 ; tstep < this.segments ; tstep ++ ) { <add> for ( tstep = 0 ; tstep < segments ; tstep ++ ) { <ide> <ide> v1 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep; <ide> v2 = v1 + 1; <ide> THREE.TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, bli <ide> <ide> THREE.TeapotGeometry.prototype = Object.create( THREE.Geometry.prototype ); <ide> THREE.TeapotGeometry.prototype.constructor = THREE.TeapotGeometry; <add> <add>THREE.TeapotGeometry.prototype.clone = function () { <add> <add> var geometry = new THREE.TeapotGeometry( <add> this.parameters.size, <add> this.parameters.segments, <add> this.parameters.bottom, <add> this.parameters.lid, <add> this.parameters.body, <add> this.parameters.fitLid, <add> this.parameters.blinn <add> ); <add> <add> return geometry; <add> <add>}; <ide>\ No newline at end of file
1
Python
Python
update pavement.py to 1.10.0
767f044ac650051614c83d008514277e7a44633e
<ide><path>pavement.py <ide> #----------------------------------- <ide> <ide> # Source of the release notes <del>RELEASE_NOTES = 'doc/release/1.9.0-notes.rst' <add>RELEASE_NOTES = 'doc/release/1.10.0-notes.rst' <ide> <ide> # Start/end of the log (from git) <del>LOG_START = 'v1.8.0b1' <add>LOG_START = 'v1.9.0b1' <ide> LOG_END = 'master' <ide> <ide>
1
Ruby
Ruby
fix document formatting on actionmailbox [ci skip]
620ba4c12a6a075607c260fe30c95e51b51b878f
<ide><path>actionmailbox/app/controllers/action_mailbox/ingresses/mailgun/inbound_emails_controller.rb <ide> module ActionMailbox <ide> # config.action_mailbox.ingress = :mailgun <ide> # <ide> # 3. {Configure Mailgun}[https://documentation.mailgun.com/en/latest/user_manual.html#receiving-forwarding-and-storing-messages] <del> # to forward inbound emails to `/rails/action_mailbox/mailgun/inbound_emails/mime`. <add> # to forward inbound emails to +/rails/action_mailbox/mailgun/inbound_emails/mime+. <ide> # <ide> # If your application lived at <tt>https://example.com</tt>, you would specify the fully-qualified URL <ide> # <tt>https://example.com/rails/action_mailbox/mailgun/inbound_emails/mime</tt>. <ide><path>actionmailbox/app/jobs/action_mailbox/incineration_job.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionMailbox <del> # You can configure when this `IncinerationJob` will be run as a time-after-processing using the <del> # `config.action_mailbox.incinerate_after` or `ActionMailbox.incinerate_after` setting. <add> # You can configure when this +IncinerationJob+ will be run as a time-after-processing using the <add> # +config.action_mailbox.incinerate_after+ or +ActionMailbox.incinerate_after+ setting. <ide> # <del> # Since this incineration is set for the future, it'll automatically ignore any `InboundEmail`s <add> # Since this incineration is set for the future, it'll automatically ignore any <tt>InboundEmail</tt>s <ide> # that have already been deleted and discard itself if so. <ide> class IncinerationJob < ActiveJob::Base <ide> queue_as { ActionMailbox.queues[:incineration] } <ide><path>actionmailbox/app/models/action_mailbox/inbound_email.rb <ide> require "mail" <ide> <ide> module ActionMailbox <del> # The `InboundEmail` is an Active Record that keeps a reference to the raw email stored in Active Storage <add> # The +InboundEmail+ is an Active Record that keeps a reference to the raw email stored in Active Storage <ide> # and tracks the status of processing. By default, incoming emails will go through the following lifecycle: <ide> # <ide> # * Pending: Just received by one of the ingress controllers and scheduled for routing. <ide> # * Processing: During active processing, while a specific mailbox is running its #process method. <ide> # * Delivered: Successfully processed by the specific mailbox. <del> # * Failed: An exception was raised during the specific mailbox's execution of the `#process` method. <add> # * Failed: An exception was raised during the specific mailbox's execution of the +#process+ method. <ide> # * Bounced: Rejected processing by the specific mailbox and bounced to sender. <ide> # <del> # Once the `InboundEmail` has reached the status of being either `delivered`, `failed`, or `bounced`, <del> # it'll count as having been `#processed?`. Once processed, the `InboundEmail` will be scheduled for <add> # Once the +InboundEmail+ has reached the status of being either +delivered+, +failed+, or +bounced+, <add> # it'll count as having been +#processed?+. Once processed, the +InboundEmail+ will be scheduled for <ide> # automatic incineration at a later point. <ide> # <del> # When working with an `InboundEmail`, you'll usually interact with the parsed version of the source, <del> # which is available as a `Mail` object from `#mail`. But you can also access the raw source directly <del> # using the `#source` method. <add> # When working with an +InboundEmail+, you'll usually interact with the parsed version of the source, <add> # which is available as a +Mail+ object from +#mail+. But you can also access the raw source directly <add> # using the +#source+ method. <ide> # <ide> # Examples: <ide> # <ide><path>actionmailbox/app/models/action_mailbox/inbound_email/incineratable.rb <ide> # frozen_string_literal: true <ide> <del># Ensure that the `InboundEmail` is automatically scheduled for later incineration if the status has been <del># changed to `processed`. The later incineration will be invoked at the time specified by the <del># `ActionMailbox.incinerate_after` time using the `IncinerationJob`. <add># Ensure that the +InboundEmail+ is automatically scheduled for later incineration if the status has been <add># changed to +processed+. The later incineration will be invoked at the time specified by the <add># +ActionMailbox.incinerate_after+ time using the +IncinerationJob+. <ide> module ActionMailbox::InboundEmail::Incineratable <ide> extend ActiveSupport::Concern <ide> <ide><path>actionmailbox/app/models/action_mailbox/inbound_email/incineratable/incineration.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionMailbox <del> # Command class for carrying out the actual incineration of the `InboundMail` that's been scheduled <del> # for removal. Before the incineration – which really is just a call to `#destroy!` – is run, we verify <add> # Command class for carrying out the actual incineration of the +InboundMail+ that's been scheduled <add> # for removal. Before the incineration – which really is just a call to +#destroy!+ – is run, we verify <ide> # that it's both eligible (by virtue of having already been processed) and time to do so (that is, <del> # the `InboundEmail` was processed after the `incinerate_after` time). <add> # the +InboundEmail+ was processed after the +incinerate_after+ time). <ide> class InboundEmail::Incineratable::Incineration <ide> def initialize(inbound_email) <ide> @inbound_email = inbound_email <ide><path>actionmailbox/app/models/action_mailbox/inbound_email/message_id.rb <ide> # frozen_string_literal: true <ide> <del># The `Message-ID` as specified by rfc822 is supposed to be a unique identifier for that individual email. <del># That makes it an ideal tracking token for debugging and forensics, just like `X-Request-Id` does for <add># The +Message-ID+ as specified by rfc822 is supposed to be a unique identifier for that individual email. <add># That makes it an ideal tracking token for debugging and forensics, just like +X-Request-Id+ does for <ide> # web request. <ide> # <ide> # If an inbound email does not, against the rfc822 mandate, specify a Message-ID, one will be generated <del># using the approach from `Mail::MessageIdField`. <add># using the approach from <tt>Mail::MessageIdField</tt>. <ide> module ActionMailbox::InboundEmail::MessageId <ide> extend ActiveSupport::Concern <ide> <ide> module ActionMailbox::InboundEmail::MessageId <ide> end <ide> <ide> class_methods do <del> # Create a new `InboundEmail` from the raw `source` of the email, which be uploaded as a Active Storage <del> # attachment called `raw_email`. Before the upload, extract the Message-ID from the `source` and set <del> # it as an attribute on the new `InboundEmail`. <add> # Create a new +InboundEmail+ from the raw +source+ of the email, which be uploaded as a Active Storage <add> # attachment called +raw_email+. Before the upload, extract the Message-ID from the +source+ and set <add> # it as an attribute on the new +InboundEmail+. <ide> def create_and_extract_message_id!(source, **options) <ide> create! options.merge(message_id: extract_message_id(source)) do |inbound_email| <ide> inbound_email.raw_email.attach io: StringIO.new(source), filename: "message.eml", content_type: "message/rfc822" <ide><path>actionmailbox/app/models/action_mailbox/inbound_email/routable.rb <ide> # frozen_string_literal: true <ide> <del># A newly received `InboundEmail` will not be routed synchronously as part of ingress controller's receival. <del># Instead, the routing will be done asynchronously, using a `RoutingJob`, to ensure maximum parallel capacity. <add># A newly received +InboundEmail+ will not be routed synchronously as part of ingress controller's receival. <add># Instead, the routing will be done asynchronously, using a +RoutingJob+, to ensure maximum parallel capacity. <ide> # <del># By default, all newly created `InboundEmail` records that have the status of `pending`, which is the default, <add># By default, all newly created +InboundEmail+ records that have the status of +pending+, which is the default, <ide> # will be scheduled for automatic, deferred routing. <ide> module ActionMailbox::InboundEmail::Routable <ide> extend ActiveSupport::Concern <ide> module ActionMailbox::InboundEmail::Routable <ide> after_create_commit :route_later, if: :pending? <ide> end <ide> <del> # Enqueue a `RoutingJob` for this `InboundEmail`. <add> # Enqueue a +RoutingJob+ for this +InboundEmail+. <ide> def route_later <ide> ActionMailbox::RoutingJob.perform_later self <ide> end <ide> <del> # Route this `InboundEmail` using the routing rules declared on the `ApplicationMailbox`. <add> # Route this +InboundEmail+ using the routing rules declared on the +ApplicationMailbox+. <ide> def route <ide> ApplicationMailbox.route self <ide> end <ide><path>actionmailbox/lib/action_mailbox/base.rb <ide> <ide> module ActionMailbox <ide> # The base class for all application mailboxes. Not intended to be inherited from directly. Inherit from <del> # `ApplicationMailbox` instead, as that's where the app-specific routing is configured. This routing <add> # +ApplicationMailbox+ instead, as that's where the app-specific routing is configured. This routing <ide> # is specified in the following ways: <ide> # <ide> # class ApplicationMailbox < ActionMailbox::Base <ide> module ActionMailbox <ide> # routing :all => :backstop <ide> # end <ide> # <del> # Application mailboxes need to overwrite the `#process` method, which is invoked by the framework after <del> # callbacks have been run. The callbacks available are: `before_processing`, `after_processing`, and <del> # `around_processing`. The primary use case is ensure certain preconditions to processing are fulfilled <del> # using `before_processing` callbacks. <add> # Application mailboxes need to overwrite the +#process+ method, which is invoked by the framework after <add> # callbacks have been run. The callbacks available are: +before_processing+, +after_processing+, and <add> # +around_processing+. The primary use case is ensure certain preconditions to processing are fulfilled <add> # using +before_processing+ callbacks. <ide> # <del> # If a precondition fails to be met, you can halt the processing using the `#bounced!` method, <add> # If a precondition fails to be met, you can halt the processing using the +#bounced!+ method, <ide> # which will silently prevent any further processing, but not actually send out any bounce notice. You <ide> # can also pair this behavior with the invocation of an Action Mailer class responsible for sending out <del> # an actual bounce email. This is done using the `#bounce_with` method, which takes the mail object returned <add> # an actual bounce email. This is done using the +#bounce_with+ method, which takes the mail object returned <ide> # by an Action Mailer method, like so: <ide> # <ide> # class ForwardsMailbox < ApplicationMailbox <ide> module ActionMailbox <ide> # end <ide> # <ide> # During the processing of the inbound email, the status will be tracked. Before processing begins, <del> # the email will normally have the `pending` status. Once processing begins, just before callbacks <del> # and the `#process` method is called, the status is changed to `processing`. If processing is allowed to <del> # complete, the status is changed to `delivered`. If a bounce is triggered, then `bounced`. If an unhandled <del> # exception is bubbled up, then `failed`. <add> # the email will normally have the +pending+ status. Once processing begins, just before callbacks <add> # and the +#process+ method is called, the status is changed to +processing+. If processing is allowed to <add> # complete, the status is changed to +delivered+. If a bounce is triggered, then +bounced+. If an unhandled <add> # exception is bubbled up, then +failed+. <ide> # <del> # Exceptions can be handled at the class level using the familiar `Rescuable` approach: <add> # Exceptions can be handled at the class level using the familiar +Rescuable+ approach: <ide> # <ide> # class ForwardsMailbox < ApplicationMailbox <ide> # rescue_from(ApplicationSpecificVerificationError) { bounced! } <ide><path>actionmailbox/lib/action_mailbox/router/route.rb <ide> <ide> module ActionMailbox <ide> # Encapsulates a route, which can then be matched against an inbound_email and provide a lookup of the matching <del> # mailbox class. See examples for the different route addresses and how to use them in the `ActionMailbox::Base` <add> # mailbox class. See examples for the different route addresses and how to use them in the +ActionMailbox::Base+ <ide> # documentation. <ide> class Router::Route <ide> attr_reader :address, :mailbox_name <ide><path>actionmailbox/lib/action_mailbox/routing.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionMailbox <del> # See `ActionMailbox::Base` for how to specify routing. <add> # See +ActionMailbox::Base+ for how to specify routing. <ide> module Routing <ide> extend ActiveSupport::Concern <ide> <ide><path>actionmailbox/lib/action_mailbox/test_helper.rb <ide> <ide> module ActionMailbox <ide> module TestHelper <del> # Create an `InboundEmail` record using an eml fixture in the format of message/rfc822 <add> # Create an +InboundEmail+ record using an eml fixture in the format of message/rfc822 <ide> # referenced with +fixture_name+ located in +test/fixtures/files/fixture_name+. <ide> def create_inbound_email_from_fixture(fixture_name, status: :processing) <ide> create_inbound_email_from_source file_fixture(fixture_name).read, status: status <ide> end <ide> <del> # Create an `InboundEmail` by specifying it using `Mail.new` options. Example: <add> # Create an +InboundEmail+ by specifying it using +Mail.new+ options. Example: <ide> # <ide> # create_inbound_email_from_mail(from: "david@loudthinking.com", subject: "Hello!") <ide> def create_inbound_email_from_mail(status: :processing, **mail_options) <ide> create_inbound_email_from_source Mail.new(mail_options).to_s, status: status <ide> end <ide> <del> # Create an `InboundEmail` using the raw rfc822 `source` as text. <add> # Create an +InboundEmail+ using the raw rfc822 +source+ as text. <ide> def create_inbound_email_from_source(source, status: :processing) <ide> ActionMailbox::InboundEmail.create_and_extract_message_id! source, status: status <ide> end <ide> <ide> <del> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_fixture` <add> # Create an +InboundEmail+ from fixture using the same arguments as +create_inbound_email_from_fixture+ <ide> # and immediately route it to processing. <ide> def receive_inbound_email_from_fixture(*args) <ide> create_inbound_email_from_fixture(*args).tap(&:route) <ide> end <ide> <del> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_mail` <add> # Create an +InboundEmail+ from fixture using the same arguments as +create_inbound_email_from_mail+ <ide> # and immediately route it to processing. <ide> def receive_inbound_email_from_mail(**kwargs) <ide> create_inbound_email_from_mail(**kwargs).tap(&:route) <ide> end <ide> <del> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_source` <add> # Create an +InboundEmail+ from fixture using the same arguments as +create_inbound_email_from_source+ <ide> # and immediately route it to processing. <ide> def receive_inbound_email_from_source(**kwargs) <ide> create_inbound_email_from_source(**kwargs).tap(&:route)
11
Ruby
Ruby
initialize @compiled_at if it is not
eea61a030e96625c53c57b63f0a9449850cf78df
<ide><path>actionpack/lib/action_dispatch/middleware/static.rb <ide> def initialize(at, root) <ide> @compiled_at = Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank? <ide> @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) <ide> @file_server = ::Rack::File.new(root) <add> @compiled_at ||= nil <ide> end <ide> <ide> def match?(path)
1
Ruby
Ruby
set the status before of setting the response body
a62001c5429723a78c7f382e34f157af1a668d68
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> def encode_credentials(user_name, password) <ide> <ide> def authentication_request(controller, realm) <ide> controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}") <del> controller.response_body = "HTTP Basic: Access denied.\n" <ide> controller.status = 401 <add> controller.response_body = "HTTP Basic: Access denied.\n" <ide> end <ide> end <ide> <ide> def authentication_header(controller, realm) <ide> def authentication_request(controller, realm, message = nil) <ide> message ||= "HTTP Digest: Access denied.\n" <ide> authentication_header(controller, realm) <del> controller.response_body = message <ide> controller.status = 401 <add> controller.response_body = message <ide> end <ide> <ide> def secret_token(request)
1
Ruby
Ruby
fix nodoc in metal/live
829ec373dde05d834a142fc1f057195da85094b9
<ide><path>actionpack/lib/action_controller/metal/live.rb <ide> require 'action_dispatch/http/response' <ide> require 'delegate' <ide> <del>module ActionController # :nodoc: <add>module ActionController <ide> # Mix this module in to your controller, and all actions in that controller <ide> # will be able to stream data to the client as it's written. <ide> # <ide> module ActionController # :nodoc: <ide> # the main thread. Make sure your actions are thread safe, and this shouldn't <ide> # be a problem (don't share state across threads, etc). <ide> module Live <del> class Buffer < ActionDispatch::Response::Buffer # :nodoc: <add> class Buffer < ActionDispatch::Response::Buffer #:nodoc: <ide> def initialize(response) <ide> super(response, Queue.new) <ide> end <ide> def close <ide> end <ide> end <ide> <del> class Response < ActionDispatch::Response # :nodoc: <del> class Header < DelegateClass(Hash) # :nodoc: <add> class Response < ActionDispatch::Response #:nodoc: all <add> class Header < DelegateClass(Hash) <ide> def initialize(response, header) <ide> @response = response <ide> super(header)
1
PHP
PHP
remove un-necessary use statement
dbcc0c104aa46a8df553d97c4fe50c0a2164bc94
<ide><path>lib/Cake/Log/LogTrait.php <ide> */ <ide> namespace Cake\Log; <ide> <del>use Cake\Log\Log; <del> <ide> /** <ide> * A trait providing an object short-cut method <ide> * to logging.
1
Mixed
Javascript
fix default params for fs.write(sync)
0b5191f15d0f311c804d542b67e2e922d98834f8
<ide><path>doc/api/fs.md <ide> _Note: [`fs.watch()`][] is more efficient than `fs.watchFile` and <ide> `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and <ide> `fs.unwatchFile` when possible._ <ide> <del>## fs.write(fd, buffer, offset, length[, position], callback) <add>## fs.write(fd, buffer[, offset[, length[, position]]], callback) <ide> <!-- YAML <ide> added: v0.0.2 <ide> --> <ide> <ide> * `fd` {Integer} <del>* `buffer` {String | Buffer} <add>* `buffer` {Buffer} <ide> * `offset` {Integer} <ide> * `length` {Integer} <ide> * `position` {Integer} <ide> On Linux, positional writes don't work when the file is opened in append mode. <ide> The kernel ignores the position argument and always appends the data to <ide> the end of the file. <ide> <del>## fs.write(fd, data[, position[, encoding]], callback) <add>## fs.write(fd, string[, position[, encoding]], callback) <ide> <!-- YAML <ide> added: v0.11.5 <ide> --> <ide> <ide> * `fd` {Integer} <del>* `data` {String | Buffer} <add>* `string` {String} <ide> * `position` {Integer} <ide> * `encoding` {String} <ide> * `callback` {Function} <ide> <del>Write `data` to the file specified by `fd`. If `data` is not a Buffer instance <del>then the value will be coerced to a string. <add>Write `string` to the file specified by `fd`. If `string` is not a string, then <add>the value will be coerced to one. <ide> <ide> `position` refers to the offset from the beginning of the file where this data <ide> should be written. If `typeof position !== 'number'` the data will be written at <ide> added: v0.1.29 <ide> <ide> The synchronous version of [`fs.writeFile()`][]. Returns `undefined`. <ide> <del>## fs.writeSync(fd, buffer, offset, length[, position]) <add>## fs.writeSync(fd, buffer[, offset[, length[, position]]]) <ide> <!-- YAML <ide> added: v0.1.21 <ide> --> <ide> <ide> * `fd` {Integer} <del>* `buffer` {String | Buffer} <add>* `buffer` {Buffer} <ide> * `offset` {Integer} <ide> * `length` {Integer} <ide> * `position` {Integer} <ide> <del>## fs.writeSync(fd, data[, position[, encoding]]) <add>## fs.writeSync(fd, string[, position[, encoding]]) <ide> <!-- YAML <ide> added: v0.11.5 <ide> --> <ide> <ide> * `fd` {Integer} <del>* `data` {String | Buffer} <add>* `string` {String} <ide> * `position` {Integer} <ide> * `encoding` {String} <ide> <ide><path>lib/fs.js <ide> fs.readSync = function(fd, buffer, offset, length, position) { <ide> }; <ide> <ide> // usage: <del>// fs.write(fd, buffer, offset, length[, position], callback); <add>// fs.write(fd, buffer[, offset[, length[, position]]], callback); <ide> // OR <ide> // fs.write(fd, string[, position[, encoding]], callback); <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> req.oncomplete = wrapper; <ide> <ide> if (buffer instanceof Buffer) { <del> // if no position is passed then assume null <del> if (typeof position === 'function') { <del> callback = position; <add> callback = maybeCallback(callback || position || length || offset); <add> if (typeof offset !== 'number') { <add> offset = 0; <add> } <add> if (typeof length !== 'number') { <add> length = buffer.length - offset; <add> } <add> if (typeof position !== 'number') { <ide> position = null; <ide> } <del> callback = maybeCallback(callback); <ide> return binding.writeBuffer(fd, buffer, offset, length, position, req); <ide> } <ide> <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> }; <ide> <ide> // usage: <del>// fs.writeSync(fd, buffer, offset, length[, position]); <add>// fs.writeSync(fd, buffer[, offset[, length[, position]]]); <ide> // OR <ide> // fs.writeSync(fd, string[, position[, encoding]]); <ide> fs.writeSync = function(fd, buffer, offset, length, position) { <ide> if (buffer instanceof Buffer) { <ide> if (position === undefined) <ide> position = null; <add> if (typeof offset !== 'number') <add> offset = 0; <add> if (typeof length !== 'number') <add> length = buffer.length - offset; <ide> return binding.writeBuffer(fd, buffer, offset, length, position); <ide> } <ide> if (typeof buffer !== 'string') <ide><path>test/parallel/test-fs-write-buffer.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const path = require('path'); <del>const Buffer = require('buffer').Buffer; <ide> const fs = require('fs'); <del>const filename = path.join(common.tmpDir, 'write.txt'); <ide> const expected = Buffer.from('hello'); <ide> <ide> common.refreshTmpDir(); <ide> <del>fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <del> if (err) throw err; <del> <del> fs.write(fd, <del> expected, <del> 0, <del> expected.length, <del> null, <del> common.mustCall(function(err, written) { <del> if (err) throw err; <del> <del> assert.equal(expected.length, written); <del> fs.closeSync(fd); <del> <del> var found = fs.readFileSync(filename, 'utf8'); <del> assert.deepStrictEqual(expected.toString(), found); <del> fs.unlinkSync(filename); <del> })); <del>})); <add>// fs.write with all parameters provided: <add>{ <add> const filename = path.join(common.tmpDir, 'write1.txt'); <add> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <add> assert.ifError(err); <add> <add> const cb = common.mustCall(function(err, written) { <add> assert.ifError(err); <add> <add> assert.strictEqual(expected.length, written); <add> fs.closeSync(fd); <add> <add> var found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual(expected.toString(), found); <add> }); <add> <add> fs.write(fd, expected, 0, expected.length, null, cb); <add> })); <add>} <add> <add>// fs.write with a buffer, without the length parameter: <add>{ <add> const filename = path.join(common.tmpDir, 'write2.txt'); <add> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <add> assert.ifError(err); <add> <add> const cb = common.mustCall(function(err, written) { <add> assert.ifError(err); <add> <add> assert.strictEqual(2, written); <add> fs.closeSync(fd); <add> <add> const found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual('lo', found); <add> }); <add> <add> fs.write(fd, Buffer.from('hello'), 3, cb); <add> })); <add>} <add> <add>// fs.write with a buffer, without the offset and length parameters: <add>{ <add> const filename = path.join(common.tmpDir, 'write3.txt'); <add> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <add> assert.ifError(err); <add> <add> const cb = common.mustCall(function(err, written) { <add> assert.ifError(err); <add> <add> assert.strictEqual(expected.length, written); <add> fs.closeSync(fd); <add> <add> const found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual(expected.toString(), found); <add> }); <add> <add> fs.write(fd, expected, cb); <add> })); <add>} <add> <add>// fs.write with the offset passed as undefined followed by the callback: <add>{ <add> const filename = path.join(common.tmpDir, 'write4.txt'); <add> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <add> assert.ifError(err); <add> <add> const cb = common.mustCall(function(err, written) { <add> assert.ifError(err); <add> <add> assert.strictEqual(expected.length, written); <add> fs.closeSync(fd); <add> <add> const found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual(expected.toString(), found); <add> }); <add> <add> fs.write(fd, expected, undefined, cb); <add> })); <add>} <add> <add>// fs.write with offset and length passed as undefined followed by the callback: <add>{ <add> const filename = path.join(common.tmpDir, 'write5.txt'); <add> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <add> assert.ifError(err); <add> <add> const cb = common.mustCall(function(err, written) { <add> assert.ifError(err); <add> <add> assert.strictEqual(expected.length, written); <add> fs.closeSync(fd); <add> <add> const found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual(expected.toString(), found); <add> }); <add> <add> fs.write(fd, expected, undefined, undefined, cb); <add> })); <add>} <ide><path>test/parallel/test-fs-write-sync.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <del>var path = require('path'); <del>var fs = require('fs'); <del>var fn = path.join(common.tmpDir, 'write.txt'); <add>const common = require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const fs = require('fs'); <add>const filename = path.join(common.tmpDir, 'write.txt'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var foo = 'foo'; <del>var fd = fs.openSync(fn, 'w'); <add>// fs.writeSync with all parameters provided: <add>{ <add> const fd = fs.openSync(filename, 'w'); <ide> <del>var written = fs.writeSync(fd, ''); <del>assert.strictEqual(0, written); <add> let written = fs.writeSync(fd, ''); <add> assert.strictEqual(0, written); <ide> <del>fs.writeSync(fd, foo); <add> fs.writeSync(fd, 'foo'); <ide> <del>var bar = 'bár'; <del>written = fs.writeSync(fd, Buffer.from(bar), 0, Buffer.byteLength(bar)); <del>assert.ok(written > 3); <del>fs.closeSync(fd); <add> written = fs.writeSync(fd, Buffer.from('bár'), 0, Buffer.byteLength('bár')); <add> assert.ok(written > 3); <add> fs.closeSync(fd); <ide> <del>assert.equal(fs.readFileSync(fn), 'foobár'); <add> assert.strictEqual(fs.readFileSync(filename, 'utf-8'), 'foobár'); <add>} <add> <add>// fs.writeSync with a buffer, without the length parameter: <add>{ <add> const fd = fs.openSync(filename, 'w'); <add> <add> let written = fs.writeSync(fd, ''); <add> assert.strictEqual(0, written); <add> <add> fs.writeSync(fd, 'foo'); <add> <add> written = fs.writeSync(fd, Buffer.from('bár'), 0); <add> assert.ok(written > 3); <add> fs.closeSync(fd); <add> <add> assert.strictEqual(fs.readFileSync(filename, 'utf-8'), 'foobár'); <add>} <add> <add>// fs.writeSync with a buffer, without the offset and length parameters: <add>{ <add> const fd = fs.openSync(filename, 'w'); <add> <add> let written = fs.writeSync(fd, ''); <add> assert.strictEqual(0, written); <add> <add> fs.writeSync(fd, 'foo'); <add> <add> written = fs.writeSync(fd, Buffer.from('bár')); <add> assert.ok(written > 3); <add> fs.closeSync(fd); <add> <add> assert.strictEqual(fs.readFileSync(filename, 'utf-8'), 'foobár'); <add>}
4
Javascript
Javascript
fix jslint warnings and refactor small issues
89a6c4fc88f8624137ae4d0ed00e0a6a59cce8ea
<ide><path>src/crypto.js <ide> var ARCFourCipher = (function arcFourCipher() { <ide> var a = this.a, b = this.b, s = this.s; <ide> var output = new Uint8Array(n); <ide> for (i = 0; i < n; ++i) { <del> var tmp; <ide> a = (a + 1) & 0xFF; <ide> tmp = s[a]; <ide> b = (b + tmp) & 0xFF; <ide> var calculateMD5 = (function calculateMD5() { <ide> padded[i] = data[offset++]; <ide> padded[i++] = 0x80; <ide> n = paddedLength - 8; <del> for (; i < n; ++i) <del> padded[i] = 0; <add> while (i < n) <add> padded[i++] = 0; <ide> padded[i++] = (length << 3) & 0xFF; <ide> padded[i++] = (length >> 5) & 0xFF; <ide> padded[i++] = (length >> 13) & 0xFF; <ide> var AES128Cipher = (function aes128Cipher() { <ide> state[10] = state[2]; state[6] = t; state[2] = u; <ide> t = state[15]; u = state[11]; v = state[7]; state[15] = state[3]; <ide> state[11] = t; state[7] = u; state[3] = v; <del> // InvSubBytes <del> for (j = 0; j < 16; ++j) <add> for (j = 0; j < 16; ++j) { <add> // InvSubBytes <ide> state[j] = inv_s[state[j]]; <del> // AddRoundKey <del> for (j = 0; j < 16; ++j) <add> // AddRoundKey <ide> state[j] ^= key[j]; <add> } <ide> return state; <ide> } <ide> <ide> var CipherTransformFactory = (function cipherTransformFactory() { <ide> cipher = new ARCFourCipher(encryptionKey); <ide> var checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i)); <ide> n = encryptionKey.length; <del> var derrivedKey = new Uint8Array(n), k; <add> var derivedKey = new Uint8Array(n), k; <ide> for (j = 1; j <= 19; ++j) { <ide> for (k = 0; k < n; ++k) <del> derrivedKey[k] = encryptionKey[k] ^ j; <del> cipher = new ARCFourCipher(derrivedKey); <add> derivedKey[k] = encryptionKey[k] ^ j; <add> cipher = new ARCFourCipher(derivedKey); <ide> checkData = cipher.encryptBlock(checkData); <ide> } <ide> } else {
1
Python
Python
replace pystringobject by pybytesobject
46fd645bc147bf1dc7a91d6774ff87330a051917
<ide><path>numpy/f2py/cfuncs.py <ide> goto capi_fail;\\ <ide> if (PyBytes_Check(rv_cb_str)) {\\ <ide> str[len-1]='\\0';\\ <del> STRINGCOPYN((str),PyString_AS_STRING((PyStringObject*)rv_cb_str),(len));\\ <add> STRINGCOPYN((str),PyString_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\ <ide> } else {\\ <ide> PRINTPYOBJERR(rv_cb_str);\\ <ide> PyErr_SetString(#modulename#_error,\"string object expected\");\\
1
PHP
PHP
add tests for applying an order with magic finder
3bb1ad3f0b1f640faea40f3519db7ee7892804ff
<ide><path>Cake/Test/TestCase/ORM/TableTest.php <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Database\ConnectionManager; <add>use Cake\Database\Expression\OrderByExpression; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\ORM\Table; <ide> use Cake\ORM\TableRegistry; <ide> public function testMagicFindFirstOr() { <ide> $this->assertEquals($expected, $result->clause('where')); <ide> } <ide> <add>/** <add> * Test setting order by clauses on magic finders. <add> * <add> * @return void <add> */ <add> public function testMagicFindFirstOrderBy() { <add> $table = TableRegistry::get('Users'); <add> <add> $result = $table->findByAuthorIdOrPublished(1, 'Y', ['id' => 'DESC']); <add> $this->assertInstanceOf('Cake\ORM\Query', $result); <add> $this->assertEquals(1, $result->clause('limit')); <add> $expected = new OrderByExpression(['id' => 'DESC']); <add> $this->assertEquals($expected, $result->clause('order')); <add> } <add> <ide> <ide> /** <ide> * Test magic findAllByXX method. <ide> public function testMagicFindAll() { <ide> <ide> $result = $table->findAllByAuthorId(1); <ide> $this->assertInstanceOf('Cake\ORM\Query', $result); <del> $this->assertEquals(null, $result->clause('limit')); <add> $this->assertNull($result->clause('limit')); <ide> $expected = new QueryExpression( <ide> ['author_id' => 1], <ide> ['author_id' => 'integer'], <ide> public function testMagicFindAllAnd() { <ide> <ide> $result = $table->findAllByAuthorIdAndPublished(1, 'Y'); <ide> $this->assertInstanceOf('Cake\ORM\Query', $result); <del> $this->assertEquals(null, $result->clause('limit')); <add> $this->assertNull($result->clause('limit')); <ide> $expected = new QueryExpression( <ide> ['author_id' => 1, 'published' => 'Y'] <ide> ); <ide> public function testMagicFindAllOr() { <ide> <ide> $result = $table->findAllByAuthorIdOrPublished(1, 'Y'); <ide> $this->assertInstanceOf('Cake\ORM\Query', $result); <del> $this->assertEquals(null, $result->clause('limit')); <add> $this->assertNull($result->clause('limit')); <ide> $expected = new QueryExpression(); <ide> $expected->add( <ide> ['or' => ['author_id' => 1, 'published' => 'Y']] <ide> ); <ide> $this->assertEquals($expected, $result->clause('where')); <add> $this->assertNull($result->clause('order')); <add> } <add> <add>/** <add> * Test setting order by clauses on magic finders. <add> * <add> * @return void <add> */ <add> public function testMagicFindAllOrderBy() { <add> $table = TableRegistry::get('Users'); <add> <add> $result = $table->findAllByAuthorIdOrPublished(1, 'Y', ['id' => 'DESC']); <add> $this->assertInstanceOf('Cake\ORM\Query', $result); <add> $this->assertNull($result->clause('limit')); <add> $expected = new OrderByExpression(['id' => 'DESC']); <add> $this->assertEquals($expected, $result->clause('order')); <ide> } <ide> <ide> }
1
Text
Text
add the link to "python tricks" to index.md
651297810b61810be778f67559db3202fa9a4381
<ide><path>guide/english/book-recommendations/index.md <ide> title: Books to Read for Programmers <ide> - [Amazon Smile](https://smile.amazon.com/Core-Python-Applications-Programming-3rd/dp/0132678209) <ide> - ISBN-13: 978-0132678209 <ide> <add>*Python Tricks: A Buffet of Awesome Python Features by Dan Bader* <add>- [Amazon Smile](https://smile.amazon.com/Python-Tricks-Buffet-Awesome-Features-ebook/dp/B0785Q7GSY) <add>- ISBN-13: 978-1775093305 <add> <ide> ## Soft Skills <ide> <ide> *Soft Skills: The software developer's life manual*
1
Ruby
Ruby
use instance_eval instead of proc#bind
3fbc042b580f518d060671d0dd86ec2a4d14a42b
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> require 'mail' <ide> require 'action_mailer/collector' <ide> require 'active_support/core_ext/object/blank' <del>require 'active_support/core_ext/proc' <ide> require 'active_support/core_ext/string/inflections' <ide> require 'active_support/core_ext/hash/except' <ide> require 'action_mailer/log_subscriber' <ide> def mail(headers={}, &block) <ide> # Call all the procs (if any) <ide> class_default = self.class.default <ide> default_values = class_default.merge(class_default) do |k,v| <del> v.respond_to?(:call) ? v.bind(self).call : v <add> v.respond_to?(:to_proc) ? instance_eval(&v) : v <ide> end <ide> <ide> # Handle defaults
1
Javascript
Javascript
fix unused basedir
cf35b7121ffc72fbf6cd4a347aca6cdfec467248
<ide><path>examples/js/loaders/XLoader.js <ide> THREE.XLoader.prototype = { <ide> parseASCII: function () { <ide> <ide> var scope = this; <del> var baseDir = ""; <ide> if ( scope.url.lastIndexOf( "/" ) > 0 ) { <ide> <ide> scope.baseDir = scope.url.substr( 0, scope.url.lastIndexOf( "/" ) + 1 );
1
Text
Text
add xray updates
720d4219037895015108299563d31882639bfc11
<ide><path>docs/focus/2018-03-19.md <ide> - Published first draft of RFC for streamlining collaboration set-up, including the ability to give guests a URL that they can use to join your portal, and a "buddy list" for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Tree-sitter <ide> - Xray <add> - Optimized selections. We're moving 1k selections in a document with 10k edits in ~2ms, and we think there's still room for improvement. <add> - Made significant progress on a switch to a client/server architecture. <add> - See [this week's in-depth Xray update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_19.md) for more details. <ide> - Engineering Improvements <ide> - Process `.tsx` files within Atom as TypeScript in a kind of hacky way. [atom/atom#16944](https://github.com/atom/atom/pull/16944) <ide> - Reactor Duty <ide> - Add preliminary support for joining a portal via URL ([atom/teletype#109](https://github.com/atom/teletype/issues/109)) <ide> - Tree-sitter <ide> - Xray <add> - Continue to make progress on the [PR switching Xray to a client/server architecture](https://github.com/atom/xray/pull/46). Hopefully we can merge it this week. <add> - Investigate a switch from JSON to protocol buffers. <ide> - Engineering Improvements <ide> - Reactor Duty
1
Javascript
Javascript
add spec for timing
db0ec663413a44a569d18d3798a316d6ee1bd2e2
<ide><path>Libraries/Core/Timers/JSTimers.js <ide> const Platform = require('../../Utilities/Platform'); <ide> const Systrace = require('../../Performance/Systrace'); <ide> <ide> const invariant = require('invariant'); <del>const {Timing} = require('../../BatchedBridge/NativeModules'); <ide> const BatchedBridge = require('../../BatchedBridge/BatchedBridge'); <ide> <add>import NativeTiming from './NativeTiming'; <add> <ide> import type {ExtendedError} from '../Devtools/parseErrorStack'; <ide> <ide> let _performanceNow = null; <ide> function _freeCallback(timerID: number) { <ide> _clearIndex(index); <ide> const type = types[index]; <ide> if (type !== 'setImmediate' && type !== 'requestIdleCallback') { <del> Timing.deleteTimer(timerID); <add> deleteTimer(timerID); <ide> } <ide> } <ide> } <ide> const JSTimers = { <ide> () => func.apply(undefined, args), <ide> 'setTimeout', <ide> ); <del> Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ false); <add> createTimer(id, duration || 0, Date.now(), /* recurring */ false); <ide> return id; <ide> }, <ide> <ide> const JSTimers = { <ide> () => func.apply(undefined, args), <ide> 'setInterval', <ide> ); <del> Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ true); <add> createTimer(id, duration || 0, Date.now(), /* recurring */ true); <ide> return id; <ide> }, <ide> <ide> const JSTimers = { <ide> */ <ide> requestAnimationFrame: function(func: Function) { <ide> const id = _allocateCallback(func, 'requestAnimationFrame'); <del> Timing.createTimer(id, 1, Date.now(), /* recurring */ false); <add> createTimer(id, 1, Date.now(), /* recurring */ false); <ide> return id; <ide> }, <ide> <ide> const JSTimers = { <ide> */ <ide> requestIdleCallback: function(func: Function, options: ?Object) { <ide> if (requestIdleCallbacks.length === 0) { <del> Timing.setSendIdleEvents(true); <add> setSendIdleEvents(true); <ide> } <ide> <ide> const timeout = options && options.timeout; <ide> const JSTimers = { <ide> } <ide> delete requestIdleCallbackTimeouts[id]; <ide> if (requestIdleCallbacks.length === 0) { <del> Timing.setSendIdleEvents(false); <add> setSendIdleEvents(false); <ide> } <ide> }, timeout); <ide> requestIdleCallbackTimeouts[id] = timeoutId; <ide> const JSTimers = { <ide> } <ide> <ide> if (requestIdleCallbacks.length === 0) { <del> Timing.setSendIdleEvents(false); <add> setSendIdleEvents(false); <ide> } <ide> }, <ide> <ide> const JSTimers = { <ide> } <ide> <ide> if (requestIdleCallbacks.length === 0) { <del> Timing.setSendIdleEvents(false); <add> setSendIdleEvents(false); <ide> } <ide> <ide> if (errors) { <ide> const JSTimers = { <ide> }, <ide> }; <ide> <add>function createTimer( <add> callbackID: number, <add> duration: number, <add> jsSchedulingTime: number, <add> repeats: boolean, <add>): void { <add> invariant(NativeTiming, 'NativeTiming is available'); <add> NativeTiming.createTimer(callbackID, duration, jsSchedulingTime, repeats); <add>} <add> <add>function deleteTimer(timerID: number): void { <add> invariant(NativeTiming, 'NativeTiming is available'); <add> NativeTiming.deleteTimer(timerID); <add>} <add> <add>function setSendIdleEvents(sendIdleEvents: boolean): void { <add> invariant(NativeTiming, 'NativeTiming is available'); <add> NativeTiming.setSendIdleEvents(sendIdleEvents); <add>} <add> <ide> let ExportedJSTimers; <del>if (!Timing) { <add>if (!NativeTiming) { <ide> console.warn("Timing native module is not available, can't set timers."); <ide> // $FlowFixMe: we can assume timers are generally available <ide> ExportedJSTimers = ({ <ide><path>Libraries/Core/Timers/NativeTiming.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 <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> +createTimer: ( <add> callbackID: number, <add> duration: number, <add> jsSchedulingTime: number, <add> repeats: boolean, <add> ) => void; <add> +deleteTimer: (timerID: number) => void; <add> +setSendIdleEvents: (sendIdleEvents: boolean) => void; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('Timing');
2
Python
Python
improve signature for core operaotrs
3a1dd0b1816b2222ebddc21b0b1161f5029c1d65
<ide><path>airflow/operators/bash.py <ide> class BashOperator(BaseOperator): <ide> @apply_defaults <ide> def __init__( <ide> self, <add> *, <ide> bash_command: str, <ide> env: Optional[Dict[str, str]] = None, <ide> output_encoding: str = 'utf-8', <del> *args, **kwargs) -> None: <add> **kwargs) -> None: <ide> <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.bash_command = bash_command <ide> self.env = env <ide> self.output_encoding = output_encoding <ide><path>airflow/operators/check_operator.py <ide> class CheckOperator(SQLCheckOperator): <ide> Please use `airflow.operators.sql.SQLCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.SQLCheckOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> <ide> <ide> class IntervalCheckOperator(SQLIntervalCheckOperator): <ide> class IntervalCheckOperator(SQLIntervalCheckOperator): <ide> Please use `airflow.operators.sql.SQLIntervalCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.SQLIntervalCheckOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> <ide> <ide> class ThresholdCheckOperator(SQLThresholdCheckOperator): <ide> class ThresholdCheckOperator(SQLThresholdCheckOperator): <ide> Please use `airflow.operators.sql.SQLThresholdCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.SQLThresholdCheckOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> <ide> <ide> class ValueCheckOperator(SQLValueCheckOperator): <ide> class ValueCheckOperator(SQLValueCheckOperator): <ide> Please use `airflow.operators.sql.SQLValueCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.SQLValueCheckOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/dagrun_operator.py <ide> class TriggerDagRunOperator(BaseOperator): <ide> @apply_defaults <ide> def __init__( <ide> self, <add> *, <ide> trigger_dag_id: str, <ide> conf: Optional[Dict] = None, <ide> execution_date: Optional[Union[str, datetime.datetime]] = None, <del> *args, <ide> **kwargs <ide> ) -> None: <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.trigger_dag_id = trigger_dag_id <ide> self.conf = conf <ide> <ide><path>airflow/operators/dummy_operator.py <ide> class DummyOperator(BaseOperator): <ide> ui_color = '#e8f7e4' <ide> <ide> @apply_defaults <del> def __init__(self, *args, **kwargs) -> None: <del> super().__init__(*args, **kwargs) <add> def __init__(self, **kwargs) -> None: <add> super().__init__(**kwargs) <ide> <ide> def execute(self, context): <ide> pass <ide><path>airflow/operators/generic_transfer.py <ide> class GenericTransfer(BaseOperator): <ide> @apply_defaults <ide> def __init__( <ide> self, <add> *, <ide> sql: str, <ide> destination_table: str, <ide> source_conn_id: str, <ide> destination_conn_id: str, <ide> preoperator: Optional[Union[str, List[str]]] = None, <del> *args, **kwargs) -> None: <del> super().__init__(*args, **kwargs) <add> **kwargs) -> None: <add> super().__init__(**kwargs) <ide> self.sql = sql <ide> self.destination_table = destination_table <ide> self.source_conn_id = source_conn_id <ide><path>airflow/operators/google_api_to_s3_transfer.py <ide> class GoogleApiToS3Transfer(GoogleApiToS3Operator): <ide> `airflow.providers.amazon.aws.transfers.google_api_to_s3.GoogleApiToS3Operator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.amazon.aws.transfers.""" + <ide> "google_api_to_s3_transfer.GoogleApiToS3Operator`.", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/hive_to_druid.py <ide> class HiveToDruidTransfer(HiveToDruidOperator): <ide> `airflow.providers.apache.druid.transfers.hive_to_druid.HiveToDruidOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.apache.druid.transfers.hive_to_druid.HiveToDruidOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/hive_to_mysql.py <ide> class HiveToMySqlTransfer(HiveToMySqlOperator): <ide> `airflow.providers.apache.hive.transfers.hive_to_mysql.HiveToMySqlOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.apache.hive.transfers.hive_to_mysql.HiveToMySqlOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/mssql_to_hive.py <ide> class MsSqlToHiveTransfer(MsSqlToHiveOperator): <ide> `airflow.providers.apache.hive.transfers.mssql_to_hive.MsSqlToHiveOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.apache.hive.transfers.mssql_to_hive.MsSqlToHiveOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/mysql_to_hive.py <ide> class MySqlToHiveTransfer(MySqlToHiveOperator): <ide> Please use `airflow.providers.apache.hive.transfers.mysql_to_hive.MySqlToHiveOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.providers.apache.hive.transfers.mysql_to_hive.MySqlToHiveOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/presto_check_operator.py <ide> class PrestoCheckOperator(SQLCheckOperator): <ide> Please use `airflow.operators.sql.SQLCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.SQLCheckOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> <ide> <ide> class PrestoIntervalCheckOperator(SQLIntervalCheckOperator): <ide> class PrestoIntervalCheckOperator(SQLIntervalCheckOperator): <ide> Please use `airflow.operators.sql.SQLIntervalCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """ <ide> This class is deprecated.l <ide> Please use `airflow.operators.sql.SQLIntervalCheckOperator`. <ide> """, <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> <ide> <ide> class PrestoValueCheckOperator(SQLValueCheckOperator): <ide> class PrestoValueCheckOperator(SQLValueCheckOperator): <ide> Please use `airflow.operators.sql.SQLValueCheckOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """ <ide> This class is deprecated.l <ide> Please use `airflow.operators.sql.SQLValueCheckOperator`. <ide> """, <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/presto_to_mysql.py <ide> class PrestoToMySqlTransfer(PrestoToMySqlOperator): <ide> `airflow.providers.mysql.transfers.presto_to_mysql.PrestoToMySqlOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.mysql.transfers.presto_to_mysql.PrestoToMySqlOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/python.py <ide> class PythonOperator(BaseOperator): <ide> @apply_defaults <ide> def __init__( <ide> self, <add> *, <ide> python_callable: Callable, <ide> op_args: Optional[List] = None, <ide> op_kwargs: Optional[Dict] = None, <ide> class _PythonFunctionalOperator(BaseOperator): <ide> @apply_defaults <ide> def __init__( <ide> self, <add> *, <ide> python_callable: Callable, <ide> task_id: str, <ide> op_args: Tuple[Any], <ide> class PythonVirtualenvOperator(PythonOperator): <ide> @apply_defaults <ide> def __init__( # pylint: disable=too-many-arguments <ide> self, <add> *, <ide> python_callable: Callable, <ide> requirements: Optional[Iterable[str]] = None, <ide> python_version: Optional[str] = None, <ide><path>airflow/operators/redshift_to_s3_operator.py <ide> class RedshiftToS3Transfer(RedshiftToS3Operator): <ide> `airflow.providers.amazon.aws.transfers.redshift_to_s3.RedshiftToS3Operator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.amazon.aws.transfers.redshift_to_s3.RedshiftToS3Operator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/s3_to_hive_operator.py <ide> class S3ToHiveTransfer(S3ToHiveOperator): <ide> Please use `airflow.providers.apache.hive.transfers.s3_to_hive.S3ToHiveOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.providers.apache.hive.transfers.s3_to_hive.S3ToHiveOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/s3_to_redshift_operator.py <ide> class S3ToRedshiftTransfer(S3ToRedshiftOperator): <ide> `airflow.providers.amazon.aws.transfers.s3_to_redshift.S3ToRedshiftOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use <ide> `airflow.providers.amazon.aws.transfers.s3_to_redshift.S3ToRedshiftOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/sql.py <ide> class SQLCheckOperator(BaseOperator): <ide> <ide> @apply_defaults <ide> def __init__( <del> self, sql: str, conn_id: Optional[str] = None, *args, **kwargs <add> self, *, sql: str, conn_id: Optional[str] = None, **kwargs <ide> ) -> None: <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.conn_id = conn_id <ide> self.sql = sql <ide> <ide> def __init__( <ide> *args, <ide> **kwargs, <ide> ): <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.sql = sql <ide> self.conn_id = conn_id <ide> self.pass_value = str(pass_value) <ide> def __init__( <ide> *args, <ide> **kwargs, <ide> ): <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> if ratio_formula not in self.ratio_formulas: <ide> msg_template = ( <ide> "Invalid diff_method: {diff_method}. " <ide> def __init__( <ide> *args, <ide> **kwargs, <ide> ): <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.sql = sql <ide> self.conn_id = conn_id <ide> self.min_threshold = _convert_to_float_if_possible(min_threshold) <ide> def __init__( <ide> *args, <ide> **kwargs, <ide> ) -> None: <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide> self.conn_id = conn_id <ide> self.sql = sql <ide> self.parameters = parameters <ide><path>airflow/operators/sql_branch_operator.py <ide> class BranchSqlOperator(BranchSQLOperator): <ide> Please use `airflow.operators.sql.BranchSQLOperator`. <ide> """ <ide> <del> def __init__(self, *args, **kwargs): <add> def __init__(self, **kwargs): <ide> warnings.warn( <ide> """This class is deprecated. <ide> Please use `airflow.operators.sql.BranchSQLOperator`.""", <ide> DeprecationWarning, stacklevel=3 <ide> ) <del> super().__init__(*args, **kwargs) <add> super().__init__(**kwargs) <ide><path>airflow/operators/subdag_operator.py <ide> class SubDagOperator(BaseSensorOperator): <ide> @provide_session <ide> @apply_defaults <ide> def __init__(self, <add> *, <ide> subdag: DAG, <ide> session: Optional[Session] = None, <ide> propagate_skipped_state: Optional[SkippedStatePropagationOptions] = None, <del> *args, **kwargs) -> None: <del> super().__init__(*args, **kwargs) <add> **kwargs) -> None: <add> super().__init__(**kwargs) <ide> self.subdag = subdag <ide> self.propagate_skipped_state = propagate_skipped_state <ide>
19
PHP
PHP
escape inline sections
98555a47be612ab464e8fee12f79e439c6042d32
<ide><path>src/Illuminate/View/Concerns/ManagesLayouts.php <ide> public function startSection($section, $content = null) <ide> $this->sectionStack[] = $section; <ide> } <ide> } else { <del> $this->extendSection($section, $content); <add> $this->extendSection($section, e($content)); <ide> } <ide> } <ide>
1
Go
Go
move term creation into driver
592c2f6f9a472bda227a03c819f73b8edc7c3320
<ide><path>container.go <ide> func (container *Container) Start() (err error) { <ide> } <ide> <ide> populateCommand(container) <del> if err := execdriver.NewTerminal(container.command); err != nil { <del> return err <del> } <ide> <ide> // Setup logging of stdout and stderr to disk <ide> if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil { <ide><path>execdriver/lxc/driver.go <ide> func (d *driver) Name() string { <ide> } <ide> <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <del> if c.Terminal != nil { <del> if err := c.Terminal.Attach(pipes); err != nil { <del> return -1, err <del> } <add> if err := execdriver.SetTerminal(c, pipes); err != nil { <add> return -1, err <ide> } <ide> configPath, err := d.generateLXCConfig(c) <ide> if err != nil { <ide><path>execdriver/term.go <ide> import ( <ide> type Term interface { <ide> io.Closer <ide> Resize(height, width int) error <del> Attach(pipes *Pipes) error <ide> } <ide> <ide> type Pipes struct { <ide> func NewPipes(stdin io.ReadCloser, stdout, stderr io.WriteCloser, useStdin bool) <ide> return p <ide> } <ide> <del>func NewTerminal(command *Command) error { <add>func SetTerminal(command *Command, pipes *Pipes) error { <ide> var ( <ide> term Term <ide> err error <ide> ) <ide> if command.Tty { <del> term, err = NewTtyConsole(command) <add> term, err = NewTtyConsole(command, pipes) <ide> } else { <del> term, err = NewStdConsole(command) <add> term, err = NewStdConsole(command, pipes) <ide> } <ide> if err != nil { <ide> return err <ide> func NewTerminal(command *Command) error { <ide> } <ide> <ide> type TtyConsole struct { <del> command *Command <del> Master *os.File <del> Slave *os.File <add> Master *os.File <add> Slave *os.File <ide> } <ide> <del>func NewTtyConsole(command *Command) (*TtyConsole, error) { <add>func NewTtyConsole(command *Command, pipes *Pipes) (*TtyConsole, error) { <ide> ptyMaster, ptySlave, err := pty.Open() <ide> if err != nil { <ide> return nil, err <ide> } <ide> tty := &TtyConsole{ <del> Master: ptyMaster, <del> Slave: ptySlave, <del> command: command, <add> Master: ptyMaster, <add> Slave: ptySlave, <add> } <add> if err := tty.attach(command, pipes); err != nil { <add> tty.Close() <add> return nil, err <ide> } <ide> return tty, nil <ide> } <ide> func (t *TtyConsole) Resize(h, w int) error { <ide> return term.SetWinsize(t.Master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) <ide> } <ide> <del>func (t *TtyConsole) Attach(pipes *Pipes) error { <del> t.command.Stdout = t.Slave <del> t.command.Stderr = t.Slave <del> <del> t.command.Console = t.Slave.Name() <add>func (t *TtyConsole) attach(command *Command, pipes *Pipes) error { <add> command.Stdout = t.Slave <add> command.Stderr = t.Slave <add> command.Console = t.Slave.Name() <ide> <ide> go func() { <ide> defer pipes.Stdout.Close() <ide> io.Copy(pipes.Stdout, t.Master) <ide> }() <ide> <ide> if pipes.Stdin != nil { <del> t.command.Stdin = t.Slave <del> t.command.SysProcAttr.Setctty = true <add> command.Stdin = t.Slave <add> command.SysProcAttr.Setctty = true <ide> <ide> go func() { <ide> defer pipes.Stdin.Close() <ide> func (t *TtyConsole) Attach(pipes *Pipes) error { <ide> } <ide> <ide> func (t *TtyConsole) Close() error { <del> err := t.Slave.Close() <del> if merr := t.Master.Close(); err == nil { <del> err = merr <del> } <del> return err <add> t.Slave.Close() <add> return t.Master.Close() <ide> } <ide> <ide> type StdConsole struct { <del> command *Command <ide> } <ide> <del>func NewStdConsole(command *Command) (*StdConsole, error) { <del> return &StdConsole{command}, nil <add>func NewStdConsole(command *Command, pipes *Pipes) (*StdConsole, error) { <add> std := &StdConsole{} <add> <add> if err := std.attach(command, pipes); err != nil { <add> return nil, err <add> } <add> return std, nil <ide> } <ide> <del>func (s *StdConsole) Attach(pipes *Pipes) error { <del> s.command.Stdout = pipes.Stdout <del> s.command.Stderr = pipes.Stderr <add>func (s *StdConsole) attach(command *Command, pipes *Pipes) error { <add> command.Stdout = pipes.Stdout <add> command.Stderr = pipes.Stderr <ide> <ide> if pipes.Stdin != nil { <del> stdin, err := s.command.StdinPipe() <add> stdin, err := command.StdinPipe() <ide> if err != nil { <ide> return err <ide> }
3
Text
Text
move @vsemozhetbyt to collaborator emeriti
d088587b7b48792f59e2d0df91e224e7da860f2b
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Vladimir de Turckheim** &lt;vlad2t@hotmail.com&gt; (he/him) <ide> * [vkurchatkin](https://github.com/vkurchatkin) - <ide> **Vladimir Kurchatkin** &lt;vladimir.kurchatkin@gmail.com&gt; <del>* [vsemozhetbyt](https://github.com/vsemozhetbyt) - <del>**Vse Mozhet Byt** &lt;vsemozhetbyt@gmail.com&gt; (he/him) <ide> * [watilde](https://github.com/watilde) - <ide> **Daijiro Wachi** &lt;daijiro.wachi@gmail.com&gt; (he/him) <ide> * [watson](https://github.com/watson) - <ide> For information about the governance of the Node.js project, see <ide> **Christian Tellnes** &lt;christian@tellnes.no&gt; <ide> * [tunniclm](https://github.com/tunniclm) - <ide> **Mike Tunnicliffe** &lt;m.j.tunnicliffe@gmail.com&gt; <add>* [vsemozhetbyt](https://github.com/vsemozhetbyt) - <add>**Vse Mozhet Byt** &lt;vsemozhetbyt@gmail.com&gt; (he/him) <ide> <ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in <ide> maintaining the Node.js project.
1
Python
Python
add default args and type hints for problem 7
719c5562d9d3788a008fe7ec5ef9fcf605564ff1
<ide><path>project_euler/problem_07/sol1.py <ide> """ <add>Problem 7: https://projecteuler.net/problem=7 <add> <ide> By listing the first six prime numbers: <ide> <ide> 2, 3, 5, 7, 11, and 13 <ide> from math import sqrt <ide> <ide> <del>def is_prime(n): <del> if n == 2: <add>def is_prime(num: int) -> bool: <add> """Determines whether the given number is prime or not""" <add> if num == 2: <ide> return True <del> elif n % 2 == 0: <add> elif num % 2 == 0: <ide> return False <ide> else: <del> sq = int(sqrt(n)) + 1 <add> sq = int(sqrt(num)) + 1 <ide> for i in range(3, sq, 2): <del> if n % i == 0: <add> if num % i == 0: <ide> return False <ide> return True <ide> <ide> <del>def solution(n): <add>def solution(nth: int = 10001) -> int: <ide> """Returns the n-th prime number. <ide> <ide> >>> solution(6) <ide> def solution(n): <ide> 229 <ide> >>> solution(100) <ide> 541 <add> >>> solution() <add> 104743 <ide> """ <del> i = 0 <del> j = 1 <del> while i != n and j < 3: <del> j += 1 <del> if is_prime(j): <del> i += 1 <del> while i != n: <del> j += 2 <del> if is_prime(j): <del> i += 1 <del> return j <add> count = 0 <add> number = 1 <add> while count != nth and number < 3: <add> number += 1 <add> if is_prime(number): <add> count += 1 <add> while count != nth: <add> number += 2 <add> if is_prime(number): <add> count += 1 <add> return number <ide> <ide> <ide> if __name__ == "__main__": <ide><path>project_euler/problem_07/sol2.py <ide> """ <add>Problem 7: https://projecteuler.net/problem=7 <add> <ide> By listing the first six prime numbers: <ide> <ide> 2, 3, 5, 7, 11, and 13 <ide> """ <ide> <ide> <del>def isprime(number): <add>def isprime(number: int) -> bool: <add> """Determines whether the given number is prime or not""" <ide> for i in range(2, int(number ** 0.5) + 1): <ide> if number % i == 0: <ide> return False <ide> return True <ide> <ide> <del>def solution(n): <add>def solution(nth: int = 10001) -> int: <ide> """Returns the n-th prime number. <ide> <ide> >>> solution(6) <ide> def solution(n): <ide> 229 <ide> >>> solution(100) <ide> 541 <add> >>> solution() <add> 104743 <ide> >>> solution(3.4) <ide> 5 <ide> >>> solution(0) <ide> Traceback (most recent call last): <ide> ... <del> ValueError: Parameter n must be greater or equal to one. <add> ValueError: Parameter nth must be greater or equal to one. <ide> >>> solution(-17) <ide> Traceback (most recent call last): <ide> ... <del> ValueError: Parameter n must be greater or equal to one. <add> ValueError: Parameter nth must be greater or equal to one. <ide> >>> solution([]) <ide> Traceback (most recent call last): <ide> ... <del> TypeError: Parameter n must be int or passive of cast to int. <add> TypeError: Parameter nth must be int or passive of cast to int. <ide> >>> solution("asd") <ide> Traceback (most recent call last): <ide> ... <del> TypeError: Parameter n must be int or passive of cast to int. <add> TypeError: Parameter nth must be int or passive of cast to int. <ide> """ <ide> try: <del> n = int(n) <add> nth = int(nth) <ide> except (TypeError, ValueError): <del> raise TypeError("Parameter n must be int or passive of cast to int.") <del> if n <= 0: <del> raise ValueError("Parameter n must be greater or equal to one.") <add> raise TypeError( <add> "Parameter nth must be int or passive of cast to int." <add> ) from None <add> if nth <= 0: <add> raise ValueError("Parameter nth must be greater or equal to one.") <ide> primes = [] <ide> num = 2 <del> while len(primes) < n: <add> while len(primes) < nth: <ide> if isprime(num): <ide> primes.append(num) <ide> num += 1 <ide><path>project_euler/problem_07/sol3.py <ide> """ <add>Project 7: https://projecteuler.net/problem=7 <add> <ide> By listing the first six prime numbers: <ide> <ide> 2, 3, 5, 7, 11, and 13 <ide> import math <ide> <ide> <del>def primeCheck(number): <add>def prime_check(number: int) -> bool: <add> """Determines whether a given number is prime or not""" <ide> if number % 2 == 0 and number > 2: <ide> return False <ide> return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) <ide> def primeCheck(number): <ide> def prime_generator(): <ide> num = 2 <ide> while True: <del> if primeCheck(num): <add> if prime_check(num): <ide> yield num <ide> num += 1 <ide> <ide> <del>def solution(n): <add>def solution(nth: int = 10001) -> int: <ide> """Returns the n-th prime number. <ide> <ide> >>> solution(6) <ide> def solution(n): <ide> 229 <ide> >>> solution(100) <ide> 541 <add> >>> solution() <add> 104743 <ide> """ <del> return next(itertools.islice(prime_generator(), n - 1, n)) <add> return next(itertools.islice(prime_generator(), nth - 1, nth)) <ide> <ide> <ide> if __name__ == "__main__":
3
PHP
PHP
allow configuration of storage path
f219ab878c4781ffcd1915b2e276a302f8ec935b
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements ApplicationContract, HttpKernelIn <ide> */ <ide> protected $deferredServices = array(); <ide> <add> /** <add> * The custom storage path defined by the developer. <add> * <add> * @var string <add> */ <add> protected $storagePath; <add> <ide> /** <ide> * The environment file to load during bootstrapping. <ide> * <ide> public function publicPath() <ide> */ <ide> public function storagePath() <ide> { <del> return $this->basePath.'/storage'; <add> return $this->storagePath ?: $this->basePath.'/storage'; <add> } <add> <add> /** <add> * Set the storage directory. <add> * <add> * @param string $path <add> * @return $this <add> */ <add> public function useStoragePath($path) <add> { <add> $this->storagePath = $path; <add> <add> $this->instance('path.storage', $path); <add> <add> return $this; <ide> } <ide> <ide> /**
1
Go
Go
add system.stat support for darwin/macos
76a416ac37e5bd184990c93ed19aa6fa544b7b03
<ide><path>pkg/system/stat_darwin.go <add>package system <add> <add>import ( <add> "syscall" <add>) <add> <add>// fromStatT creates a system.StatT type from a syscall.Stat_t type <add>func fromStatT(s *syscall.Stat_t) (*StatT, error) { <add> return &StatT{size: s.Size, <add> mode: uint32(s.Mode), <add> uid: s.Uid, <add> gid: s.Gid, <add> rdev: uint64(s.Rdev), <add> mtim: s.Mtimespec}, nil <add>} <add> <add>// FromStatT loads a system.StatT from a syscall.Stat_t. <add>func FromStatT(s *syscall.Stat_t) (*StatT, error) { <add> return fromStatT(s) <add>} <add> <add>// Stat takes a path to a file and returns <add>// a system.StatT type pertaining to that file. <add>// <add>// Throws an error if the file does not exist <add>func Stat(path string) (*StatT, error) { <add> s := &syscall.Stat_t{} <add> if err := syscall.Stat(path, s); err != nil { <add> return nil, err <add> } <add> return fromStatT(s) <add>} <ide><path>pkg/system/stat_unsupported.go <del>// +build !linux,!windows,!freebsd,!solaris,!openbsd <add>// +build !linux,!windows,!freebsd,!solaris,!openbsd,!darwin <ide> <ide> package system <ide>
2
Text
Text
add legacy description
67d1707c39a7baacd8899ce9d0a61cbb188fc5a5
<ide><path>guide/english/certifications/index.md <ide> Upon completion of all six certificates, the freeCodeCamp [Full Stack Developmen <ide> For more information about freeCodeCamp, please visit [about.freecodecamp.org](https://about.freecodecamp.org/). <ide> <ide> For more information about the new certification program, see [this forum post](https://www.freecodecamp.org/forum/t/freecodecamps-new-certificates-heres-how-were-rolling-them-out/141618). <add> <add>### Legacy Certifications <add> <add>There are also Legacy Certifications which were deleted when they became outdated, but you can still find all the projects on freecodecamp, and the challenges can still be completed. If you were working on the cirriculum before it changed, you can still complete them and earn your legacy certificate.
1
Text
Text
add kogan.com to the list of users
71eed10759caeca9b59a17b82a28d285317ef312
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> * [Hootsuite](https://github.com/hootsuite) <ide> * ING <ide> * [Jampp](https://github.com/jampp) <add>* [Kogan.com](https://github.com/kogan) [[@geeknam](https://github.com/geeknam)] <ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)] <ide> * Lyft <ide> * [Sense360](https://github.com/Sense360) [[@kamilmroczek](https://github.com/KamilMroczek)]
1
Ruby
Ruby
remove deprecated time marshal core_ext file
0e8d297301305af9ac5d64e7cd2b0a418c139fce
<ide><path>activesupport/lib/active_support/core_ext/time/marshal.rb <del>require "active_support/deprecation" <del> <del>ActiveSupport::Deprecation.warn("This is deprecated and will be removed in Rails 5.1 with no replacement.")
1
Javascript
Javascript
use assert.rejects() and assert.throws()
c6c37e9e850fa2a30b12a0d0fd0dfe144eda0959
<ide><path>test/parallel/test-fs-mkdir.js <ide> function nextdir() { <ide> fs.mkdirSync(path.dirname(pathname)); <ide> fs.writeFileSync(pathname, '', 'utf8'); <ide> <del> try { <del> fs.mkdirSync(pathname, { recursive: true }); <del> throw new Error('unreachable'); <del> } catch (err) { <del> assert.notStrictEqual(err.message, 'unreachable'); <del> assert.strictEqual(err.code, 'EEXIST'); <del> assert.strictEqual(err.syscall, 'mkdir'); <del> } <add> assert.throws( <add> () => { fs.mkdirSync(pathname, { recursive: true }); }, <add> { <add> code: 'EEXIST', <add> message: /EEXIST: .*mkdir/, <add> name: 'Error', <add> syscall: 'mkdir', <add> } <add> ); <ide> } <ide> <ide> // mkdirpSync when part of the path is a file. <ide> function nextdir() { <ide> fs.mkdirSync(path.dirname(filename)); <ide> fs.writeFileSync(filename, '', 'utf8'); <ide> <del> try { <del> fs.mkdirSync(pathname, { recursive: true }); <del> throw new Error('unreachable'); <del> } catch (err) { <del> assert.notStrictEqual(err.message, 'unreachable'); <del> assert.strictEqual(err.code, 'ENOTDIR'); <del> assert.strictEqual(err.syscall, 'mkdir'); <del> } <add> assert.throws( <add> () => { fs.mkdirSync(pathname, { recursive: true }); }, <add> { <add> code: 'ENOTDIR', <add> message: /ENOTDIR: .*mkdir/, <add> name: 'Error', <add> syscall: 'mkdir', <add> } <add> ); <ide> } <ide> <ide> // `mkdirp` when folder does not yet exist. <ide> if (common.isMainThread && (common.isLinux || common.isOSX)) { <ide> fs.mkdirSync(pathname); <ide> process.chdir(pathname); <ide> fs.rmdirSync(pathname); <del> try { <del> fs.mkdirSync('X', { recursive: true }); <del> throw new Error('unreachable'); <del> } catch (err) { <del> assert.notStrictEqual(err.message, 'unreachable'); <del> assert.strictEqual(err.code, 'ENOENT'); <del> assert.strictEqual(err.syscall, 'mkdir'); <del> } <add> assert.throws( <add> () => { fs.mkdirSync('X', { recursive: true }); }, <add> { <add> code: 'ENOENT', <add> message: /ENOENT: .*mkdir/, <add> name: 'Error', <add> syscall: 'mkdir', <add> } <add> ); <ide> fs.mkdir('X', { recursive: true }, (err) => { <ide> assert.strictEqual(err.code, 'ENOENT'); <ide> assert.strictEqual(err.syscall, 'mkdir'); <ide><path>test/parallel/test-fs-promises.js <ide> async function getHandle(dest) { <ide> const dir = path.join(tmpDir, nextdir(), nextdir()); <ide> await mkdir(path.dirname(dir)); <ide> await writeFile(dir); <del> try { <del> await mkdir(dir, { recursive: true }); <del> throw new Error('unreachable'); <del> } catch (err) { <del> assert.notStrictEqual(err.message, 'unreachable'); <del> assert.strictEqual(err.code, 'EEXIST'); <del> assert.strictEqual(err.syscall, 'mkdir'); <del> } <add> assert.rejects( <add> mkdir(dir, { recursive: true }), <add> { <add> code: 'EEXIST', <add> message: /EEXIST: .*mkdir/, <add> name: 'Error', <add> syscall: 'mkdir', <add> } <add> ); <ide> } <ide> <ide> // `mkdirp` when part of the path is a file. <ide> async function getHandle(dest) { <ide> const dir = path.join(file, nextdir(), nextdir()); <ide> await mkdir(path.dirname(file)); <ide> await writeFile(file); <del> try { <del> await mkdir(dir, { recursive: true }); <del> throw new Error('unreachable'); <del> } catch (err) { <del> assert.notStrictEqual(err.message, 'unreachable'); <del> assert.strictEqual(err.code, 'ENOTDIR'); <del> assert.strictEqual(err.syscall, 'mkdir'); <del> } <add> assert.rejects( <add> mkdir(dir, { recursive: true }), <add> { <add> code: 'ENOTDIR', <add> message: /ENOTDIR: .*mkdir/, <add> name: 'Error', <add> syscall: 'mkdir', <add> } <add> ); <ide> } <ide> <ide> // mkdirp ./
2
PHP
PHP
remove crlf from to headers in mailtransport
407c4201763f0f816edbe39ffb8cd6fa773f33a0
<ide><path>lib/Cake/Network/Email/MailTransport.php <ide> public function send(CakeEmail $email) { <ide> $headers[$key] = str_replace(array("\r", "\n"), '', $header); <ide> } <ide> $headers = $this->_headersToString($headers, $eol); <del> $message = implode($eol, $email->message()); <ide> $subject = str_replace(array("\r", "\n"), '', $email->subject()); <add> $to = str_replace(array("\r", "\n"), '', $to); <add> <add> $message = implode($eol, $email->message()); <ide> <ide> $params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null; <ide> $this->_mail($to, $subject, $message, $headers, $params);
1
Go
Go
add test to zfs for disk quota
04b4e3e6d80d5d734edba90e55f41863b50ee45b
<ide><path>daemon/graphdriver/graphtest/graphtest_unix.go <ide> package graphtest <ide> import ( <ide> "fmt" <ide> "io/ioutil" <add> "math/rand" <ide> "os" <ide> "path" <add> "reflect" <ide> "syscall" <ide> "testing" <add> "unsafe" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <add> "github.com/docker/go-units" <ide> ) <ide> <ide> var ( <ide> func DriverTestCreateSnap(t *testing.T, drivername string) { <ide> t.Fatal(err) <ide> } <ide> } <add> <add>func writeRandomFile(path string, size uint64) error { <add> buf := make([]int64, size/8) <add> <add> r := rand.NewSource(0) <add> for i := range buf { <add> buf[i] = r.Int63() <add> } <add> <add> // Cast to []byte <add> header := *(*reflect.SliceHeader)(unsafe.Pointer(&buf)) <add> header.Len *= 8 <add> header.Cap *= 8 <add> data := *(*[]byte)(unsafe.Pointer(&header)) <add> <add> return ioutil.WriteFile(path, data, 0700) <add>} <add> <add>// DriverTestSetQuota Create a driver and test setting quota. <add>func DriverTestSetQuota(t *testing.T, drivername string) { <add> driver := GetDriver(t, drivername) <add> defer PutDriver(t) <add> <add> createBase(t, driver, "Base") <add> storageOpt := make(map[string]string, 1) <add> storageOpt["size"] = "50M" <add> if err := driver.Create("zfsTest", "Base", "", storageOpt); err != nil { <add> t.Fatal(err) <add> } <add> <add> mountPath, err := driver.Get("zfsTest", "") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> quota := uint64(50 * units.MiB) <add> err = writeRandomFile(path.Join(mountPath, "file"), quota*2) <add> if pathError, ok := err.(*os.PathError); ok && pathError.Err != syscall.EDQUOT { <add> t.Fatalf("expect write() to fail with %v, got %v", syscall.EDQUOT, err) <add> } <add> <add>} <ide><path>daemon/graphdriver/zfs/zfs_test.go <ide> func TestZfsCreateSnap(t *testing.T) { <ide> graphtest.DriverTestCreateSnap(t, "zfs") <ide> } <ide> <add>func TestZfsSetQuota(t *testing.T) { <add> graphtest.DriverTestSetQuota(t, "zfs") <add>} <add> <ide> func TestZfsTeardown(t *testing.T) { <ide> graphtest.PutDriver(t) <ide> }
2
Python
Python
fix trainable_weight lists
7d2f0b1ba8c1ebd4213f748878953d576626fe84
<ide><path>keras/engine/topology.py <ide> def __init__(self, input, output, name=None): <ide> name = prefix + '_' + str(K.get_uid(prefix)) <ide> self.name = name <ide> <add> # whether container weights are trainable <add> self.trainable = True <add> <ide> # Container-specific properties <ide> if type(input) in {list, tuple}: <ide> self.inputs = list(input) # tensor or list of tensors <ide> def regularizers(self): <ide> <ide> @property <ide> def trainable_weights(self): <add> if not self.trainable: <add> return [] <ide> weights = [] <ide> for layer in self.layers: <ide> weights += layer.trainable_weights <ide> def non_trainable_weights(self): <ide> weights = [] <ide> for layer in self.layers: <ide> weights += layer.non_trainable_weights <add> if not self.trainable: <add> trainable_weights = [] <add> for layer in self.layers: <add> trainable_weights += layer.trainable_weights <add> return trainable_weights + weights <ide> return weights <ide> <ide> def get_weights(self): <ide><path>keras/models.py <ide> def __init__(self, layers=[], name=None): <ide> self.model = None # internal Model instance <ide> self.inputs = [] # tensors <ide> self.outputs = [] # tensors (length 1) <add> self.trainable = True <ide> <ide> # model attributes <ide> self.inbound_nodes = [] <ide> def _gather_dict_attr(self, attr): <ide> <ide> @property <ide> def trainable_weights(self): <add> if not self.trainable: <add> return [] <ide> # support for legacy behavior <ide> return self._gather_list_attr('trainable_weights') <ide> <ide> @property <ide> def non_trainable_weights(self): <ide> # support for legacy behavior <del> return self._gather_list_attr('non_trainable_weights') <add> weights = self._gather_list_attr('non_trainable_weights') <add> if not self.trainable: <add> trainable_weights = self._gather_list_attr('trainable_weights') <add> return trainable_weights + weights <add> return weights <ide> <ide> @property <ide> def updates(self): <ide><path>tests/keras/engine/test_topology.py <ide> <ide> from keras.layers import Dense, Dropout, InputLayer <ide> from keras.engine import merge, Input, get_source_inputs <del>from keras.models import Model <add>from keras.models import Model, Sequential <ide> from keras import backend as K <ide> from keras.models import model_from_json, model_from_yaml <ide> from keras.utils.test_utils import keras_test <ide> <ide> <add>@keras_test <add>def test_trainable_weights(): <add> a = Input(shape=(2,)) <add> b = Dense(1)(a) <add> model = Model(a, b) <add> <add> weights = model.weights <add> assert model.trainable_weights == weights <add> assert model.non_trainable_weights == [] <add> <add> model.trainable = False <add> assert model.trainable_weights == [] <add> assert model.non_trainable_weights == weights <add> <add> model.trainable = True <add> assert model.trainable_weights == weights <add> assert model.non_trainable_weights == [] <add> <add> model.layers[1].trainable = False <add> assert model.trainable_weights == [] <add> assert model.non_trainable_weights == weights <add> <add> # sequential model <add> model = Sequential() <add> model.add(Dense(1, input_dim=2)) <add> weights = model.weights <add> <add> assert model.trainable_weights == weights <add> assert model.non_trainable_weights == [] <add> <add> model.trainable = False <add> assert model.trainable_weights == [] <add> assert model.non_trainable_weights == weights <add> <add> model.trainable = True <add> assert model.trainable_weights == weights <add> assert model.non_trainable_weights == [] <add> <add> model.layers[0].trainable = False <add> assert model.trainable_weights == [] <add> assert model.non_trainable_weights == weights <add> <add> <ide> @keras_test <ide> def test_learning_phase(): <ide> a = Input(shape=(32,), name='input_a')
3
Ruby
Ruby
assert the singleton instead of to truthy/falsy
59f6b99fc3a02f272d7ba4828317ebd8bd5a362f
<ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> require "#{app_path}/config/environment" <ide> require 'action_view/base' <ide> <del> assert ActionView::Resolver.caching? <add> assert_equal true, ActionView::Resolver.caching? <ide> end <ide> <ide> test "config.action_view.cache_template_loading without cache_classes default" do <ide> add_to_config "config.cache_classes = false" <ide> require "#{app_path}/config/environment" <ide> require 'action_view/base' <ide> <del> assert !ActionView::Resolver.caching? <add> assert_equal false, ActionView::Resolver.caching? <ide> end <ide> <ide> test "config.action_view.cache_template_loading = false" do <ide> def index <ide> require "#{app_path}/config/environment" <ide> require 'action_view/base' <ide> <del> assert !ActionView::Resolver.caching? <add> assert_equal false, ActionView::Resolver.caching? <ide> end <ide> <ide> test "config.action_view.cache_template_loading = true" do <ide> def index <ide> require "#{app_path}/config/environment" <ide> require 'action_view/base' <ide> <del> assert ActionView::Resolver.caching? <add> assert_equal true, ActionView::Resolver.caching? <ide> end <ide> <ide> test "config.action_view.cache_template_loading with cache_classes in an environment" do
1
Javascript
Javascript
add failing test for
1140e27ea947dc7bf6d8adcf9aed658d2b83155e
<ide><path>packages/@ember/-internals/glimmer/tests/integration/content-test.js <ide> moduleFor( <ide> <ide> this.assertContent('<b>Max</b><i>James</i>'); <ide> } <add> <add> ['@test empty content in trusted curlies [GH#14978]']() { <add> this.render('before {{{value}}} after', { <add> value: 'hello', <add> }); <add> <add> this.assertContent('before hello after'); <add> <add> this.runTask(() => this.rerender()); <add> <add> this.assertStableRerender(); <add> <add> this.runTask(() => set(this.context, 'value', undefined)); <add> <add> this.assertContent('before after'); <add> <add> this.runTask(() => set(this.context, 'value', 'hello')); <add> <add> this.assertContent('before hello after'); <add> <add> this.runTask(() => set(this.context, 'value', null)); <add> <add> this.assertContent('before after'); <add> <add> this.runTask(() => set(this.context, 'value', 'hello')); <add> <add> this.assertContent('before hello after'); <add> <add> this.runTask(() => set(this.context, 'value', '')); <add> <add> this.assertContent('before after'); <add> <add> this.runTask(() => set(this.context, 'value', 'hello')); <add> <add> this.assertContent('before hello after'); <add> } <ide> } <ide> ); <ide>
1
Javascript
Javascript
throw error with validationerrors property
992f5c807e6c06c89d8c1ef2b9a9c7e0daf0813b
<ide><path>lib/webpack.js <ide> function webpack(options, callback) { <ide> } else if(typeof options === "object") { <ide> var webpackOptionsValidationErrors = validateWebpackOptions(options); <ide> if(webpackOptionsValidationErrors.length) { <del> throw new Error("Passed 'options' object does not look like a valid webpack configuration"); <add> var validationError = new Error("Passed 'options' object does not look like a valid webpack configuration"); <add> validationError.validationErrors = webpackOptionsValidationErrors; <add> throw validationError; <ide> } <ide> new WebpackOptionsDefaulter().process(options); <ide>
1
Python
Python
update conftest fixture
109f202e8ff154cefef50b6b1f53da11c2e68392
<ide><path>spacy/tests/tokenizer/conftest.py <ide> import pytest <del>from spacy.en import English <add>from ...en import English <ide> <ide> <del>@pytest.fixture(scope="module") <del>def en_tokenizer(EN): <del> return EN.tokenizer <add>@pytest.fixture <add>def en_tokenizer(): <add> return English.Defaults.create_tokenizer()
1
Java
Java
remove remaining reactor event wrapping
547167e8b440feea5a71cd31df28224b171cf9d3
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/PubSubMessageService.java <ide> import org.springframework.web.messaging.event.EventConsumer; <ide> import org.springframework.web.messaging.event.EventRegistration; <ide> <del>import reactor.fn.Event; <del> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> protected void processMessage(Message<?> message) { <ide> byte[] payload = payloadConverter.convertToPayload(message.getPayload(), contentType); <ide> message = new GenericMessage<byte[]>(payload, headers); <ide> <del> getEventBus().send(getPublishKey(message), Event.wrap(message)); <add> getEventBus().send(getPublishKey(message), message); <ide> } <ide> catch (Exception ex) { <ide> logger.error("Failed to publish " + message, ex); <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/RelayStompService.java <ide> import org.springframework.web.messaging.stomp.StompHeaders; <ide> import org.springframework.web.messaging.stomp.StompMessage; <ide> <del>import reactor.fn.Event; <ide> import reactor.util.Assert; <ide> <ide> <ide> private void sendErrorMessage(String message) { <ide> StompHeaders headers = new StompHeaders(); <ide> headers.setMessage(message); <ide> StompMessage errorMessage = new StompMessage(StompCommand.ERROR, headers); <del> getEventBus().send(this.replyTo, Event.wrap(errorMessage)); <add> getEventBus().send(this.replyTo, errorMessage); <ide> } <ide> } <ide>
2
Text
Text
fix broken link in why react post
a64faf7bf7edeab22490c617d1c579e6103a5da0
<ide><path>docs/_posts/2013-06-05-why-react.md <ide> see as an advantage over templates for a few reasons: <ide> **no manual string concatenation** and therefore less surface area for XSS <ide> vulnerabilities. <ide> <del>We've also created [JSX](facebook.github.io/react/docs/syntax.html), an optional <add>We've also created [JSX](http://facebook.github.io/react/docs/syntax.html), an optional <ide> syntax extension, in case you prefer the readability of HTML to raw JavaScript. <ide> <ide> ## Reactive updates are dead simple.
1
Ruby
Ruby
add additional quiet check in update-report
92a42381df63456872e7bb0971a50bf91e209ad4
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def update_report <ide> "git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname", "*.*" <ide> ).lines.first.chomp <ide> <del> if new_tag != old_tag <del> Settings.write "latesttag", new_tag <del> new_repository_version = new_tag <del> end <add> new_repository_version = new_tag unless new_tag == old_tag <ide> end <ide> <ide> Homebrew.failed = true if ENV["HOMEBREW_UPDATE_FAILED"] <ide> def update_report <ide> puts_stdout_or_stderr <ide> ohai_stdout_or_stderr "Homebrew was updated to version #{new_repository_version}" <ide> if new_repository_version.split(".").last == "0" <add> Settings.write "latesttag", new_repository_version <ide> puts_stdout_or_stderr <<~EOS <ide> More detailed release notes are available on the Homebrew Blog: <ide> #{Formatter.url("https://brew.sh/blog/#{new_repository_version}")} <ide> EOS <del> else <add> elsif !args.quiet? <add> Settings.write "latesttag", new_repository_version <ide> puts_stdout_or_stderr <<~EOS <ide> The changelog can be found at: <ide> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_repository_version}")}
1
Javascript
Javascript
convert passive mount phase to tree traversal
d37d7a4bb4d6b55e2f393827f65082c7ea529ab7
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> import { <ide> Placement, <ide> Snapshot, <ide> Update, <add> Passive, <add> PassiveMask, <ide> } from './ReactFiberFlags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <add>import { <add> resetCurrentFiber as resetCurrentDebugFiberInDEV, <add> setCurrentFiber as setCurrentDebugFiberInDEV, <add>} from './ReactCurrentFiber'; <ide> <ide> import {onCommitUnmount} from './ReactFiberDevToolsHook.new'; <ide> import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; <ide> import { <ide> getCommitTime, <ide> recordLayoutEffectDuration, <ide> startLayoutEffectTimer, <add> recordPassiveEffectDuration, <add> startPassiveEffectTimer, <ide> } from './ReactProfilerTimer.new'; <ide> import {ProfileMode} from './ReactTypeOfMode'; <ide> import {commitUpdateQueue} from './ReactUpdateQueue.new'; <ide> if (__DEV__) { <ide> <ide> const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; <ide> <add>let nextEffect: Fiber | null = null; <add> <ide> const callComponentWillUnmountWithTimer = function(current, instance) { <ide> instance.props = current.memoizedProps; <ide> instance.state = current.memoizedState; <ide> function commitResetTextContent(current: Fiber) { <ide> resetTextContent(current.stateNode); <ide> } <ide> <add>export function commitPassiveMountEffects( <add> root: FiberRoot, <add> firstChild: Fiber, <add>): void { <add> nextEffect = firstChild; <add> commitPassiveMountEffects_begin(firstChild, root); <add>} <add> <add>function commitPassiveMountEffects_begin(subtreeRoot: Fiber, root: FiberRoot) { <add> while (nextEffect !== null) { <add> const fiber = nextEffect; <add> const firstChild = fiber.child; <add> if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { <add> ensureCorrectReturnPointer(firstChild, fiber); <add> nextEffect = firstChild; <add> } else { <add> commitPassiveMountEffects_complete(subtreeRoot, root); <add> } <add> } <add>} <add> <add>function commitPassiveMountEffects_complete( <add> subtreeRoot: Fiber, <add> root: FiberRoot, <add>) { <add> while (nextEffect !== null) { <add> const fiber = nextEffect; <add> if ((fiber.flags & Passive) !== NoFlags) { <add> if (__DEV__) { <add> setCurrentDebugFiberInDEV(fiber); <add> invokeGuardedCallback( <add> null, <add> commitPassiveMountOnFiber, <add> null, <add> root, <add> fiber, <add> ); <add> if (hasCaughtError()) { <add> const error = clearCaughtError(); <add> captureCommitPhaseError(fiber, error); <add> } <add> resetCurrentDebugFiberInDEV(); <add> } else { <add> try { <add> commitPassiveMountOnFiber(root, fiber); <add> } catch (error) { <add> captureCommitPhaseError(fiber, error); <add> } <add> } <add> } <add> <add> if (fiber === subtreeRoot) { <add> nextEffect = null; <add> return; <add> } <add> <add> const sibling = fiber.sibling; <add> if (sibling !== null) { <add> ensureCorrectReturnPointer(sibling, fiber.return); <add> nextEffect = sibling; <add> return; <add> } <add> <add> nextEffect = fiber.return; <add> } <add>} <add> <add>function commitPassiveMountOnFiber( <add> finishedRoot: FiberRoot, <add> finishedWork: Fiber, <add>): void { <add> switch (finishedWork.tag) { <add> case FunctionComponent: <add> case ForwardRef: <add> case SimpleMemoComponent: { <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> startPassiveEffectTimer(); <add> try { <add> commitHookEffectListMount(HookPassive | HookHasEffect, finishedWork); <add> } finally { <add> recordPassiveEffectDuration(finishedWork); <add> } <add> } else { <add> commitHookEffectListMount(HookPassive | HookHasEffect, finishedWork); <add> } <add> break; <add> } <add> } <add>} <add> <add>let didWarnWrongReturnPointer = false; <add>function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { <add> if (__DEV__) { <add> if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { <add> didWarnWrongReturnPointer = true; <add> console.error( <add> 'Internal React error: Return pointer is inconsistent ' + <add> 'with parent.', <add> ); <add> } <add> } <add> <add> // TODO: Remove this assignment once we're confident that it won't break <add> // anything, by checking the warning logs for the above invariant <add> fiber.return = expectedReturnFiber; <add>} <add> <ide> export { <ide> commitBeforeMutationLifeCycles, <ide> commitResetTextContent, <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> import { <ide> Placement, <ide> Snapshot, <ide> Update, <add> Passive, <add> PassiveMask, <ide> } from './ReactFiberFlags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <add>import { <add> resetCurrentFiber as resetCurrentDebugFiberInDEV, <add> setCurrentFiber as setCurrentDebugFiberInDEV, <add>} from './ReactCurrentFiber'; <ide> <ide> import {onCommitUnmount} from './ReactFiberDevToolsHook.old'; <ide> import {resolveDefaultProps} from './ReactFiberLazyComponent.old'; <ide> import { <ide> getCommitTime, <ide> recordLayoutEffectDuration, <ide> startLayoutEffectTimer, <add> recordPassiveEffectDuration, <add> startPassiveEffectTimer, <ide> } from './ReactProfilerTimer.old'; <ide> import {ProfileMode} from './ReactTypeOfMode'; <ide> import {commitUpdateQueue} from './ReactUpdateQueue.old'; <ide> if (__DEV__) { <ide> <ide> const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; <ide> <add>let nextEffect: Fiber | null = null; <add> <ide> const callComponentWillUnmountWithTimer = function(current, instance) { <ide> instance.props = current.memoizedProps; <ide> instance.state = current.memoizedState; <ide> function commitResetTextContent(current: Fiber) { <ide> resetTextContent(current.stateNode); <ide> } <ide> <add>export function commitPassiveMountEffects( <add> root: FiberRoot, <add> firstChild: Fiber, <add>): void { <add> nextEffect = firstChild; <add> commitPassiveMountEffects_begin(firstChild, root); <add>} <add> <add>function commitPassiveMountEffects_begin(subtreeRoot: Fiber, root: FiberRoot) { <add> while (nextEffect !== null) { <add> const fiber = nextEffect; <add> const firstChild = fiber.child; <add> if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { <add> ensureCorrectReturnPointer(firstChild, fiber); <add> nextEffect = firstChild; <add> } else { <add> commitPassiveMountEffects_complete(subtreeRoot, root); <add> } <add> } <add>} <add> <add>function commitPassiveMountEffects_complete( <add> subtreeRoot: Fiber, <add> root: FiberRoot, <add>) { <add> while (nextEffect !== null) { <add> const fiber = nextEffect; <add> if ((fiber.flags & Passive) !== NoFlags) { <add> if (__DEV__) { <add> setCurrentDebugFiberInDEV(fiber); <add> invokeGuardedCallback( <add> null, <add> commitPassiveMountOnFiber, <add> null, <add> root, <add> fiber, <add> ); <add> if (hasCaughtError()) { <add> const error = clearCaughtError(); <add> captureCommitPhaseError(fiber, error); <add> } <add> resetCurrentDebugFiberInDEV(); <add> } else { <add> try { <add> commitPassiveMountOnFiber(root, fiber); <add> } catch (error) { <add> captureCommitPhaseError(fiber, error); <add> } <add> } <add> } <add> <add> if (fiber === subtreeRoot) { <add> nextEffect = null; <add> return; <add> } <add> <add> const sibling = fiber.sibling; <add> if (sibling !== null) { <add> ensureCorrectReturnPointer(sibling, fiber.return); <add> nextEffect = sibling; <add> return; <add> } <add> <add> nextEffect = fiber.return; <add> } <add>} <add> <add>function commitPassiveMountOnFiber( <add> finishedRoot: FiberRoot, <add> finishedWork: Fiber, <add>): void { <add> switch (finishedWork.tag) { <add> case FunctionComponent: <add> case ForwardRef: <add> case SimpleMemoComponent: { <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> startPassiveEffectTimer(); <add> try { <add> commitHookEffectListMount(HookPassive | HookHasEffect, finishedWork); <add> } finally { <add> recordPassiveEffectDuration(finishedWork); <add> } <add> } else { <add> commitHookEffectListMount(HookPassive | HookHasEffect, finishedWork); <add> } <add> break; <add> } <add> } <add>} <add> <add>let didWarnWrongReturnPointer = false; <add>function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { <add> if (__DEV__) { <add> if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { <add> didWarnWrongReturnPointer = true; <add> console.error( <add> 'Internal React error: Return pointer is inconsistent ' + <add> 'with parent.', <add> ); <add> } <add> } <add> <add> // TODO: Remove this assignment once we're confident that it won't break <add> // anything, by checking the warning logs for the above invariant <add> fiber.return = expectedReturnFiber; <add>} <add> <ide> export { <ide> commitBeforeMutationLifeCycles, <ide> commitResetTextContent, <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> commitPassiveEffectDurations, <ide> commitResetTextContent, <ide> isSuspenseBoundaryBeingHidden, <add> commitPassiveMountEffects, <ide> } from './ReactFiberCommitWork.new'; <ide> import {enqueueUpdate} from './ReactUpdateQueue.new'; <ide> import {resetContextDependencies} from './ReactFiberNewContext.new'; <ide> let rootDoesHavePassiveEffects: boolean = false; <ide> let rootWithPendingPassiveEffects: FiberRoot | null = null; <ide> let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority; <ide> let pendingPassiveEffectsLanes: Lanes = NoLanes; <del>let pendingPassiveHookEffectsMount: Array<HookEffect | Fiber> = []; <ide> let pendingPassiveHookEffectsUnmount: Array<HookEffect | Fiber> = []; <ide> let pendingPassiveProfilerEffects: Array<Fiber> = []; <ide> <ide> export function enqueuePendingPassiveHookEffectMount( <ide> fiber: Fiber, <ide> effect: HookEffect, <ide> ): void { <del> pendingPassiveHookEffectsMount.push(effect, fiber); <ide> if (!rootDoesHavePassiveEffects) { <ide> rootDoesHavePassiveEffects = true; <ide> scheduleCallback(NormalSchedulerPriority, () => { <ide> export function enqueuePendingPassiveHookEffectUnmount( <ide> } <ide> } <ide> <del>function invokePassiveEffectCreate(effect: HookEffect): void { <del> const create = effect.create; <del> effect.destroy = create(); <del>} <del> <ide> function flushPassiveEffectsImpl() { <ide> if (rootWithPendingPassiveEffects === null) { <ide> return false; <ide> function flushPassiveEffectsImpl() { <ide> } <ide> } <ide> // Second pass: Create new passive effects. <del> const mountEffects = pendingPassiveHookEffectsMount; <del> pendingPassiveHookEffectsMount = []; <del> for (let i = 0; i < mountEffects.length; i += 2) { <del> const effect = ((mountEffects[i]: any): HookEffect); <del> const fiber = ((mountEffects[i + 1]: any): Fiber); <del> if (__DEV__) { <del> setCurrentDebugFiberInDEV(fiber); <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> startPassiveEffectTimer(); <del> invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect); <del> recordPassiveEffectDuration(fiber); <del> } else { <del> invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect); <del> } <del> if (hasCaughtError()) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> const error = clearCaughtError(); <del> captureCommitPhaseError(fiber, error); <del> } <del> resetCurrentDebugFiberInDEV(); <del> } else { <del> try { <del> const create = effect.create; <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> try { <del> startPassiveEffectTimer(); <del> effect.destroy = create(); <del> } finally { <del> recordPassiveEffectDuration(fiber); <del> } <del> } else { <del> effect.destroy = create(); <del> } <del> } catch (error) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> captureCommitPhaseError(fiber, error); <del> } <del> } <del> } <del> <del> // Note: This currently assumes there are no passive effects on the root fiber <del> // because the root is not part of its own effect list. <del> // This could change in the future. <del> let effect = root.current.firstEffect; <del> while (effect !== null) { <del> const nextNextEffect = effect.nextEffect; <del> // Remove nextEffect pointer to assist GC <del> effect.nextEffect = null; <del> if (effect.flags & Deletion) { <del> detachFiberAfterEffects(effect); <del> } <del> effect = nextNextEffect; <del> } <add> commitPassiveMountEffects(root, root.current); <ide> <add> // TODO: Move to commitPassiveMountEffects <ide> if (enableProfilerTimer && enableProfilerCommitHooks) { <ide> const profilerEffects = pendingPassiveProfilerEffects; <ide> pendingPassiveProfilerEffects = []; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> commitPassiveEffectDurations, <ide> commitResetTextContent, <ide> isSuspenseBoundaryBeingHidden, <add> commitPassiveMountEffects, <ide> } from './ReactFiberCommitWork.old'; <ide> import {enqueueUpdate} from './ReactUpdateQueue.old'; <ide> import {resetContextDependencies} from './ReactFiberNewContext.old'; <ide> let rootDoesHavePassiveEffects: boolean = false; <ide> let rootWithPendingPassiveEffects: FiberRoot | null = null; <ide> let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority; <ide> let pendingPassiveEffectsLanes: Lanes = NoLanes; <del>let pendingPassiveHookEffectsMount: Array<HookEffect | Fiber> = []; <ide> let pendingPassiveHookEffectsUnmount: Array<HookEffect | Fiber> = []; <ide> let pendingPassiveProfilerEffects: Array<Fiber> = []; <ide> <ide> export function enqueuePendingPassiveHookEffectMount( <ide> fiber: Fiber, <ide> effect: HookEffect, <ide> ): void { <del> pendingPassiveHookEffectsMount.push(effect, fiber); <ide> if (!rootDoesHavePassiveEffects) { <ide> rootDoesHavePassiveEffects = true; <ide> scheduleCallback(NormalSchedulerPriority, () => { <ide> export function enqueuePendingPassiveHookEffectUnmount( <ide> } <ide> } <ide> <del>function invokePassiveEffectCreate(effect: HookEffect): void { <del> const create = effect.create; <del> effect.destroy = create(); <del>} <del> <ide> function flushPassiveEffectsImpl() { <ide> if (rootWithPendingPassiveEffects === null) { <ide> return false; <ide> function flushPassiveEffectsImpl() { <ide> } <ide> } <ide> // Second pass: Create new passive effects. <del> const mountEffects = pendingPassiveHookEffectsMount; <del> pendingPassiveHookEffectsMount = []; <del> for (let i = 0; i < mountEffects.length; i += 2) { <del> const effect = ((mountEffects[i]: any): HookEffect); <del> const fiber = ((mountEffects[i + 1]: any): Fiber); <del> if (__DEV__) { <del> setCurrentDebugFiberInDEV(fiber); <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> startPassiveEffectTimer(); <del> invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect); <del> recordPassiveEffectDuration(fiber); <del> } else { <del> invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect); <del> } <del> if (hasCaughtError()) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> const error = clearCaughtError(); <del> captureCommitPhaseError(fiber, error); <del> } <del> resetCurrentDebugFiberInDEV(); <del> } else { <del> try { <del> const create = effect.create; <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> try { <del> startPassiveEffectTimer(); <del> effect.destroy = create(); <del> } finally { <del> recordPassiveEffectDuration(fiber); <del> } <del> } else { <del> effect.destroy = create(); <del> } <del> } catch (error) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> captureCommitPhaseError(fiber, error); <del> } <del> } <del> } <del> <del> // Note: This currently assumes there are no passive effects on the root fiber <del> // because the root is not part of its own effect list. <del> // This could change in the future. <del> let effect = root.current.firstEffect; <del> while (effect !== null) { <del> const nextNextEffect = effect.nextEffect; <del> // Remove nextEffect pointer to assist GC <del> effect.nextEffect = null; <del> if (effect.flags & Deletion) { <del> detachFiberAfterEffects(effect); <del> } <del> effect = nextNextEffect; <del> } <add> commitPassiveMountEffects(root, root.current); <ide> <add> // TODO: Move to commitPassiveMountEffects <ide> if (enableProfilerTimer && enableProfilerCommitHooks) { <ide> const profilerEffects = pendingPassiveProfilerEffects; <ide> pendingPassiveProfilerEffects = [];
4
Text
Text
change os x tag to macos
5532a7adecac64c6fc6a057f7b489f2c5f48d0f9
<ide><path>doc/onboarding-extras.md <ide> Please use these when possible / appropriate <ide> ### Other Labels <ide> <ide> * Operating system labels <del> * `os x`, `windows`, `smartos`, `aix` <add> * `macos`, `windows`, `smartos`, `aix` <ide> * No linux, linux is the implied default <ide> * Architecture labels <ide> * `arm`, `mips`, `s390`, `ppc`
1
Javascript
Javascript
add coverage for unused custom hook
793ef9b8553ca029fa10958137b001d3081ae18f
<ide><path>packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js <ide> const tests = { <ide> `, <ide> options: [{additionalHooks: 'useCustomEffect'}], <ide> }, <add> { <add> code: ` <add> function MyComponent(props) { <add> useCustomEffect(() => { <add> console.log(props.foo); <add> }, []); <add> } <add> `, <add> options: [{additionalHooks: 'useAnotherEffect'}], <add> }, <ide> { <ide> // Valid because we don't care about hooks outside of components. <ide> code: `
1
Javascript
Javascript
revert some of the changes from 29810c6cd1
15a055b6cd118baaa0f4f3cd01107500aa73e78b
<ide><path>spec/text-editor-component-spec.js <ide> describe('TextEditorComponent', () => { <ide> editor.moveRight() <ide> await component.getNextUpdatePromise() <ide> <del> await conditionPromise(() => <del> getComputedStyle(cursor1).opacity === '0' && getComputedStyle(cursor2).opacity === '0' <del> ) <del> await conditionPromise(() => <del> getComputedStyle(cursor1).opacity === '1' && getComputedStyle(cursor2).opacity === '1' <del> ) <del> await conditionPromise(() => <del> getComputedStyle(cursor1).opacity === '0' && getComputedStyle(cursor2).opacity === '0' <del> ) <add> expect(getComputedStyle(cursor1).opacity).toBe('1') <add> expect(getComputedStyle(cursor2).opacity).toBe('1') <ide> }) <ide> <ide> it('gives cursors at the end of lines the width of an "x" character', async () => {
1
Javascript
Javascript
fix bug where parent/ownerview was incorrect
25507d3b223e19b6ff0163c8d8ba4ea12465499f
<ide><path>packages/ember-htmlbars/lib/hooks/component.js <ide> export default function componentHook(renderNode, env, scope, _tagName, params, <ide> isAngleBracket = true; <ide> } <ide> <del> var read = env.hooks.getValue; <del> var parentView = read(scope.view); <add> var parentView = env.view; <ide> <ide> var manager = ComponentNodeManager.create(renderNode, env, { <ide> tagName, <ide><path>packages/ember/tests/component_registration_test.js <ide> import "ember"; <ide> <ide> import compile from "ember-template-compiler/system/compile"; <ide> import helpers from "ember-htmlbars/helpers"; <add>import { OutletView } from "ember-routing-views/views/outlet"; <ide> <ide> var App, registry, container; <ide> var originalHelpers; <ide> QUnit.module("Application Lifecycle - Component Registration", { <ide> teardown: cleanup <ide> }); <ide> <del>function boot(callback) { <add>function boot(callback, startURL="/") { <ide> Ember.run(function() { <ide> App = Ember.Application.create({ <ide> name: 'App', <ide> function boot(callback) { <ide> <ide> Ember.run(App, 'advanceReadiness'); <ide> Ember.run(function() { <del> router.handleURL('/'); <add> router.handleURL(startURL); <ide> }); <ide> } <ide> <ide> QUnit.test("Components trigger actions in the components context when called fro <ide> <ide> Ember.$('#fizzbuzz', "#wrapper").click(); <ide> }); <add> <add>QUnit.test("Components receive the top-level view as their ownerView", function(assert) { <add> Ember.TEMPLATES.application = compile("{{outlet}}"); <add> Ember.TEMPLATES.index = compile("{{my-component}}"); <add> Ember.TEMPLATES['components/my-component'] = compile('<div></div>'); <add> <add> let component; <add> <add> boot(function() { <add> registry.register('component:my-component', Ember.Component.extend({ <add> init() { <add> this._super(); <add> component = this; <add> } <add> })); <add> }); <add> <add> // Theses tests are intended to catch a regression where the owner view was <add> // not configured properly. Future refactors may break these tests, which <add> // should not be considered a breaking change to public APIs. <add> let ownerView = component.ownerView; <add> assert.ok(ownerView, "owner view was set"); <add> assert.ok(ownerView instanceof OutletView, "owner view has no parent view"); <add> assert.notStrictEqual(component, ownerView, "owner view is not itself"); <add> <add> assert.ok(ownerView._outlets, "owner view has an internal array of outlets"); <add>});
2
Python
Python
ensure alignment of nested struct dtypes
7ab154b90e9db0a3aab1af3a02502cfda25ecbe3
<ide><path>numpy/core/_internal.py <ide> else: <ide> _nbo = asbytes('>') <ide> <del>def _makenames_list(adict): <add>def _makenames_list(adict, align): <ide> from multiarray import dtype <ide> allfields = [] <ide> fnames = adict.keys() <ide> def _makenames_list(adict): <ide> num = int(obj[1]) <ide> if (num < 0): <ide> raise ValueError("invalid offset.") <del> format = dtype(obj[0]) <add> format = dtype(obj[0], align=align) <ide> if (format.itemsize == 0): <ide> raise ValueError("all itemsizes must be fixed.") <ide> if (n > 2): <ide> def _usefields(adict, align): <ide> except KeyError: <ide> names = None <ide> if names is None: <del> names, formats, offsets, titles = _makenames_list(adict) <add> names, formats, offsets, titles = _makenames_list(adict, align) <ide> else: <ide> formats = [] <ide> offsets = [] <ide><path>numpy/core/tests/test_dtype.py <ide> def test_aligned_size(self): <ide> assert_equal(dt.itemsize, 8) <ide> dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True) <ide> assert_equal(dt.itemsize, 8) <del> dt = np.dtype({'names':['f0','f1'], 'formats':['i4', 'u1'], <del> 'offsets':[0,4]}, align=True) <add> dt = np.dtype({'names':['f0','f1'], <add> 'formats':['i4', 'u1'], <add> 'offsets':[0,4]}, align=True) <ide> assert_equal(dt.itemsize, 8) <ide> dt = np.dtype({'f0': ('i4', 0), 'f1':('u1', 4)}, align=True) <ide> assert_equal(dt.itemsize, 8) <add> # Nesting should preserve that alignment <add> dt1 = np.dtype([('f0', 'i4'), <add> ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), <add> ('f2', 'i1')], align=True) <add> assert_equal(dt1.itemsize, 20) <add> dt2 = np.dtype({'names':['f0','f1','f2'], <add> 'formats':['i4', <add> [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], <add> 'i1'], <add> 'offsets':[0, 4, 16]}, align=True) <add> assert_equal(dt2.itemsize, 20) <add> dt3 = np.dtype({'f0': ('i4', 0), <add> 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4), <add> 'f2': ('i1', 16)}, align=True) <add> assert_equal(dt3.itemsize, 20) <add> assert_equal(dt1, dt2) <add> assert_equal(dt2, dt3) <add> # Nesting should preserve packing <add> dt1 = np.dtype([('f0', 'i4'), <add> ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), <add> ('f2', 'i1')], align=False) <add> assert_equal(dt1.itemsize, 11) <add> dt2 = np.dtype({'names':['f0','f1','f2'], <add> 'formats':['i4', <add> [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], <add> 'i1'], <add> 'offsets':[0, 4, 10]}, align=False) <add> assert_equal(dt2.itemsize, 11) <add> dt3 = np.dtype({'f0': ('i4', 0), <add> 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4), <add> 'f2': ('i1', 10)}, align=False) <add> assert_equal(dt3.itemsize, 11) <add> assert_equal(dt1, dt2) <add> assert_equal(dt2, dt3) <ide> <ide> def test_union_struct(self): <ide> # Should be able to create union dtypes
2
Javascript
Javascript
fix broken drawer layout
8e809e9b24eee6930427edf0b3e876bbda52da88
<ide><path>Libraries/ReactIOS/renderApplication.android.js <ide> var styles = StyleSheet.create({ <ide> // This is needed so the application covers the whole screen <ide> // and therefore the contents of the Portal are not clipped. <ide> appContainer: { <del> position: 'absolute', <add> backgroundColor: 'transparent', <add> bottom: 0, <ide> left: 0, <del> top: 0, <add> position: 'absolute', <ide> right: 0, <del> bottom: 0, <add> top: 0, <ide> }, <ide> }); <ide>
1
Javascript
Javascript
handle sync writable streams synchronously
82c7c84e2550e79b816f87cd1dff3fe4cafb6bbb
<ide><path>lib/_stream_writable.js <ide> function onwrite(stream, er) { <ide> <ide> if (er) { <ide> if (cb) { <add> // If _write(chunk,cb) calls cb() in this tick, we still defer <add> // the *user's* write callback to the next tick. <add> // Never present an external API that is *sometimes* async! <ide> if (sync) <ide> process.nextTick(function() { <ide> cb(er); <ide> function onwrite(stream, er) { <ide> state.length -= l; <ide> <ide> if (cb) { <del> // don't call the cb until the next tick if we're in sync mode. <del> // also, defer if we're about to write some more right now. <add> // Don't call the cb until the next tick if we're in sync mode. <add> // Also defer if we're about to write some more right now. <ide> if (sync || state.buffer.length) <ide> process.nextTick(cb); <ide> else <ide><path>lib/net.js <ide> Socket.prototype._write = function(dataEncoding, cb) { <ide> return this._destroy(errnoException(errno, 'write'), cb); <ide> <ide> writeReq.oncomplete = afterWrite; <del> writeReq.cb = cb; <del> <ide> this._bytesDispatched += writeReq.bytes; <add> <add> // If it was entirely flushed, we can write some more right now. <add> // However, if more is left in the queue, then wait until that clears. <add> if (this._handle.writeQueueSize === 0) <add> cb(); <add> else <add> writeReq.cb = cb; <ide> }; <ide> <ide> <ide> function afterWrite(status, handle, req) { <ide> if (self !== process.stderr && self !== process.stdout) <ide> debug('afterWrite call cb'); <ide> <del> req.cb.call(self); <add> if (req.cb) <add> req.cb.call(self); <ide> } <ide> <ide> <ide><path>test/simple/test-stream2-stderr-sync.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>// Make sure that sync writes to stderr get processed before exiting. <add> <add>var common = require('../common.js'); <add>var assert = require('assert'); <add> <add>function parent() { <add> var spawn = require('child_process').spawn; <add> var assert = require('assert'); <add> var i = 0; <add> children.forEach(function(_, c) { <add> var child = spawn(process.execPath, [__filename, '' + c]); <add> var err = ''; <add> <add> child.stderr.on('data', function(c) { <add> err += c; <add> }); <add> <add> child.on('close', function() { <add> assert.equal(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); <add> console.log('ok %d child #%d', ++i, c); <add> if (i === children.length) <add> console.log('1..' + i); <add> }); <add> }); <add>} <add> <add>function child0() { <add> // Just a very simple wrapper around TTY(2) <add> // Essentially the same as stderr, but without all the net stuff. <add> var Writable = require('stream').Writable; <add> var util = require('util'); <add> <add> // a lowlevel stderr writer <add> var TTY = process.binding('tty_wrap').TTY; <add> var handle = new TTY(2, false); <add> <add> util.inherits(W, Writable); <add> <add> function W(opts) { <add> Writable.call(this, opts); <add> } <add> <add> W.prototype._write = function(chunk, cb) { <add> var req = handle.writeUtf8String(chunk.toString() + '\n'); <add> // here's the problem. <add> // it needs to tell the Writable machinery that it's ok to write <add> // more, but that the current buffer length is handle.writeQueueSize <add> req.oncomplete = afterWrite <add> if (req.writeQueueSize === 0) <add> req.cb = cb; <add> else <add> cb(); <add> } <add> function afterWrite(status, handle, req) { <add> if (req.cb) <add> req.cb(); <add> } <add> <add> var w = new W <add> w.write('child 0'); <add> w.write('foo'); <add> w.write('bar'); <add> w.write('baz'); <add>} <add> <add>// using console.error <add>function child1() { <add> console.error('child 1'); <add> console.error('foo'); <add> console.error('bar'); <add> console.error('baz'); <add>} <add> <add>// using process.stderr <add>function child2() { <add> process.stderr.write('child 2\n'); <add> process.stderr.write('foo\n'); <add> process.stderr.write('bar\n'); <add> process.stderr.write('baz\n'); <add>} <add> <add>// using a net socket <add>function child3() { <add> var net = require('net'); <add> var socket = new net.Socket({ fd: 2 }); <add> socket.write('child 3\n'); <add> socket.write('foo\n'); <add> socket.write('bar\n'); <add> socket.write('baz\n'); <add>} <add> <add> <add>function child4() { <add> console.error('child 4\nfoo\nbar\nbaz'); <add>} <add> <add>function child5() { <add> process.stderr.write('child 5\nfoo\nbar\nbaz\n'); <add>} <add> <add>var children = [ child0, child1, child2, child3, child4, child5 ]; <add> <add>if (!process.argv[2]) { <add> parent(); <add>} else { <add> children[process.argv[2]](); <add> // immediate process.exit to kill any waiting stuff. <add> process.exit(); <add>}
3
Python
Python
fix typo in utils/flags/_conventions.py
c3bf4a7980d14e47f0a933151a0951f572ba85ff
<ide><path>official/utils/flags/_conventions.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> # ============================================================================== <del>"""Central location for shared arparse convention definitions.""" <add>"""Central location for shared argparse convention definitions.""" <ide> <ide> from __future__ import absolute_import <ide> from __future__ import division
1
Python
Python
commit glances 2.4rc2
6ef956e0615a28c3c4536a172c8b9a78b909ca7a
<ide><path>glances/__init__.py <ide> """Init the Glances software.""" <ide> <ide> __appname__ = 'glances' <del>__version__ = '2.4RC1' <add>__version__ = '2.4RC2' <ide> __author__ = 'Nicolas Hennion <nicolas@nicolargo.com>' <ide> __license__ = 'LGPL' <ide> <ide><path>setup.py <ide> def get_requires(): <ide> <ide> setup( <ide> name='Glances', <del> version='2.4RC1', <add> version='2.4RC2', <ide> description="A cross-platform curses-based monitoring tool", <ide> long_description=open('README.rst').read(), <ide> author='Nicolas Hennion', <ide> author_email='nicolas@nicolargo.com', <ide> url='https://github.com/nicolargo/glances', <del> # download_url='https://s3.amazonaws.com/glances/glances-2.4RC1.tar.gz', <add> # download_url='https://s3.amazonaws.com/glances/glances-2.4.tar.gz', <ide> license="LGPL", <ide> keywords="cli curses monitoring system", <ide> install_requires=get_requires(),
2
Java
Java
fix a typo in javadoc
a1fa0daad5ea42b46eacf0f330dec69acf1de320
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/RdbmsOperation.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * arguments. Subclasses should be JavaBeans, allowing easy configuration. <ide> * <ide> * <p>This class and subclasses throw runtime exceptions, defined in the <del> * <codeorg.springframework.dao package</code> (and as thrown by the <add> * {@code org.springframework.dao} package (and as thrown by the <ide> * {@code org.springframework.jdbc.core} package, which the classes <ide> * in this package use under the hood to perform raw JDBC operations). <ide> *
1
Javascript
Javascript
use template literals in test-string-decoder
3784b2d839c4918202359ec90bed40ede553f74c
<ide><path>test/parallel/test-string-decoder.js <ide> function test(encoding, input, expected, singleSequence) { <ide> output += decoder.end(); <ide> if (output !== expected) { <ide> const message = <del> 'Expected "' + unicodeEscape(expected) + '", ' + <del> 'but got "' + unicodeEscape(output) + '"\n' + <del> 'input: ' + input.toString('hex').match(hexNumberRE) + '\n' + <del> 'Write sequence: ' + JSON.stringify(sequence) + '\n' + <del> 'Full Decoder State: ' + inspect(decoder); <add> `Expected "${unicodeEscape(expected)}", ` + <add> `but got "${unicodeEscape(output)}"\n` + <add> `input: ${input.toString('hex').match(hexNumberRE)}\n` + <add> `Write sequence: ${JSON.stringify(sequence)}\n` + <add> `Full Decoder State: ${inspect(decoder)}`; <ide> assert.fail(output, expected, message); <ide> } <ide> });
1
Javascript
Javascript
add support for numbertree
8ad18959d72bb13c5f8b13c287bc99fcd37a8db1
<ide><path>src/core/obj.js <ide> var stringToPDFString = sharedUtil.stringToPDFString; <ide> var stringToUTF8String = sharedUtil.stringToUTF8String; <ide> var warn = sharedUtil.warn; <ide> var isValidUrl = sharedUtil.isValidUrl; <add>var Util = sharedUtil.Util; <ide> var Ref = corePrimitives.Ref; <ide> var RefSet = corePrimitives.RefSet; <ide> var RefSetCache = corePrimitives.RefSetCache; <ide> var XRef = (function XRefClosure() { <ide> })(); <ide> <ide> /** <del> * A NameTree is like a Dict but has some advantageous properties, see the <del> * spec (7.9.6) for more details. <del> * TODO: implement all the Dict functions and make this more efficent. <add> * A NameTree/NumberTree is like a Dict but has some advantageous properties, <add> * see the specification (7.9.6 and 7.9.7) for additional details. <add> * TODO: implement all the Dict functions and make this more efficient. <ide> */ <del>var NameTree = (function NameTreeClosure() { <del> function NameTree(root, xref) { <del> this.root = root; <del> this.xref = xref; <add>var NameOrNumberTree = (function NameOrNumberTreeClosure() { <add> function NameOrNumberTree(root, xref) { <add> throw new Error('Cannot initialize NameOrNumberTree.'); <ide> } <ide> <del> NameTree.prototype = { <del> getAll: function NameTree_getAll() { <add> NameOrNumberTree.prototype = { <add> getAll: function NameOrNumberTree_getAll() { <ide> var dict = {}; <ide> if (!this.root) { <ide> return dict; <ide> } <ide> var xref = this.xref; <del> // reading name tree <add> // Reading Name/Number tree. <ide> var processed = new RefSet(); <ide> processed.put(this.root); <ide> var queue = [this.root]; <ide> var NameTree = (function NameTreeClosure() { <ide> var kids = obj.get('Kids'); <ide> for (i = 0, n = kids.length; i < n; i++) { <ide> var kid = kids[i]; <del> if (processed.has(kid)) { <del> error('invalid destinations'); <del> } <add> assert(!processed.has(kid), <add> 'Duplicate entry in "' + this._type + '" tree.'); <ide> queue.push(kid); <ide> processed.put(kid); <ide> } <ide> continue; <ide> } <del> var names = obj.get('Names'); <del> if (names) { <del> for (i = 0, n = names.length; i < n; i += 2) { <del> dict[xref.fetchIfRef(names[i])] = xref.fetchIfRef(names[i + 1]); <add> var entries = obj.get(this._type); <add> if (isArray(entries)) { <add> for (i = 0, n = entries.length; i < n; i += 2) { <add> dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]); <ide> } <ide> } <ide> } <ide> return dict; <ide> }, <ide> <del> get: function NameTree_get(destinationId) { <add> get: function NameOrNumberTree_get(key) { <ide> if (!this.root) { <ide> return null; <ide> } <ide> <ide> var xref = this.xref; <del> var kidsOrNames = xref.fetchIfRef(this.root); <add> var kidsOrEntries = xref.fetchIfRef(this.root); <ide> var loopCount = 0; <del> var MAX_NAMES_LEVELS = 10; <add> var MAX_LEVELS = 10; <ide> var l, r, m; <ide> <ide> // Perform a binary search to quickly find the entry that <del> // contains the named destination we are looking for. <del> while (kidsOrNames.has('Kids')) { <del> loopCount++; <del> if (loopCount > MAX_NAMES_LEVELS) { <del> warn('Search depth limit for named destionations has been reached.'); <add> // contains the key we are looking for. <add> while (kidsOrEntries.has('Kids')) { <add> if (++loopCount > MAX_LEVELS) { <add> warn('Search depth limit reached for "' + this._type + '" tree.'); <ide> return null; <ide> } <ide> <del> var kids = kidsOrNames.get('Kids'); <add> var kids = kidsOrEntries.get('Kids'); <ide> if (!isArray(kids)) { <ide> return null; <ide> } <ide> var NameTree = (function NameTreeClosure() { <ide> var kid = xref.fetchIfRef(kids[m]); <ide> var limits = kid.get('Limits'); <ide> <del> if (destinationId < xref.fetchIfRef(limits[0])) { <add> if (key < xref.fetchIfRef(limits[0])) { <ide> r = m - 1; <del> } else if (destinationId > xref.fetchIfRef(limits[1])) { <add> } else if (key > xref.fetchIfRef(limits[1])) { <ide> l = m + 1; <ide> } else { <del> kidsOrNames = xref.fetchIfRef(kids[m]); <add> kidsOrEntries = xref.fetchIfRef(kids[m]); <ide> break; <ide> } <ide> } <ide> var NameTree = (function NameTreeClosure() { <ide> } <ide> } <ide> <del> // If we get here, then we have found the right entry. Now <del> // go through the named destinations in the Named dictionary <del> // until we find the exact destination we're looking for. <del> var names = kidsOrNames.get('Names'); <del> if (isArray(names)) { <add> // If we get here, then we have found the right entry. Now go through the <add> // entries in the dictionary until we find the key we're looking for. <add> var entries = kidsOrEntries.get(this._type); <add> if (isArray(entries)) { <ide> // Perform a binary search to reduce the lookup time. <ide> l = 0; <del> r = names.length - 2; <add> r = entries.length - 2; <ide> while (l <= r) { <ide> // Check only even indices (0, 2, 4, ...) because the <del> // odd indices contain the actual D array. <add> // odd indices contain the actual data. <ide> m = (l + r) & ~1; <del> if (destinationId < xref.fetchIfRef(names[m])) { <add> var currentKey = xref.fetchIfRef(entries[m]); <add> if (key < currentKey) { <ide> r = m - 2; <del> } else if (destinationId > xref.fetchIfRef(names[m])) { <add> } else if (key > currentKey) { <ide> l = m + 2; <ide> } else { <del> return xref.fetchIfRef(names[m + 1]); <add> return xref.fetchIfRef(entries[m + 1]); <ide> } <ide> } <ide> } <ide> return null; <ide> } <ide> }; <add> return NameOrNumberTree; <add>})(); <add> <add>var NameTree = (function NameTreeClosure() { <add> function NameTree(root, xref) { <add> this.root = root; <add> this.xref = xref; <add> this._type = 'Names'; <add> } <add> <add> Util.inherit(NameTree, NameOrNumberTree, {}); <add> <ide> return NameTree; <ide> })(); <ide> <add>var NumberTree = (function NumberTreeClosure() { <add> function NumberTree(root, xref) { <add> this.root = root; <add> this.xref = xref; <add> this._type = 'Nums'; <add> } <add> <add> Util.inherit(NumberTree, NameOrNumberTree, {}); <add> <add> return NumberTree; <add>})(); <add> <ide> /** <ide> * "A PDF file can refer to the contents of another file by using a File <ide> * Specification (PDF 1.1)", see the spec (7.11) for more details.
1
Javascript
Javascript
fix linting errors
cde81b6b9f3d39629ccacae5f9e82ba2527c4f29
<ide><path>benchmark/http_simple_auto.js <ide> var spawn = require('child_process').spawn; <ide> <ide> var port = parseInt(process.env.PORT || 8000); <ide> <del>var fixed = "C".repeat(20 * 1024); <add>var fixed = 'C'.repeat(20 * 1024); <ide> <ide> var stored = {}; <ide> var storedBuffer = {}; <ide> var server = http.createServer(function(req, res) { <ide> var n_chunks = parseInt(commands[3], 10); <ide> var status = 200; <ide> var n; <add> var i; <ide> <ide> if (command == 'bytes') { <ide> n = parseInt(arg, 10); <ide> if (n <= 0) <ide> throw new Error('bytes called with n <= 0'); <ide> if (stored[n] === undefined) { <del> stored[n] = "C".repeat(n); <add> stored[n] = 'C'.repeat(n); <ide> } <ide> body = stored[n]; <ide>
1
Python
Python
fix a docstring to reflect what the method does
cc3c16eaa09c7dc63592ae8bf4ee30f1af263be1
<ide><path>rest_framework/serializers.py <ide> def from_native(self, data, files): <ide> <ide> def save_object(self, obj, **kwargs): <ide> """ <del> Save the deserialized object and return it. <add> Save the deserialized object. <ide> """ <ide> if getattr(obj, '_nested_forward_relations', None): <ide> # Nested relationships need to be saved before we can save the
1
Python
Python
fix parser test
c013e5996f3aec8fe6813f1af4386637c29114ec
<ide><path>spacy/tests/parser/test_neural_parser.py <ide> def arc_eager(vocab): <ide> <ide> @pytest.fixture <ide> def tok2vec(): <del> return Tok2Vec(8, 100, preprocess=doc2feats()) <add> return Tok2Vec(8, 100) <ide> <ide> <ide> @pytest.fixture
1
Ruby
Ruby
prevent leaking sensitive payload
cbc56b6a9e8d471d23d94b3ee931c33002856fdf
<ide><path>actioncable/lib/action_cable/channel/base.rb <ide> def processable_action?(action) <ide> end <ide> <ide> def dispatch_action(action, data) <del> logger.info action_signature(action, data) <add> logger.debug action_signature(action, data) <ide> <ide> if method(action).arity == 1 <ide> public_send action, data
1
Text
Text
update irc to libera and fix lamp dead link
175db73ec7938e774d9e93d3afdfb35a24466b47
<ide><path>README.md <ide> Run the unit tests with a local server that supports PHP. Ensure that you run th <ide> <ide> - Windows: [WAMP download](http://www.wampserver.com/en/) <ide> - Mac: [MAMP download](https://www.mamp.info/en/downloads/) <del>- Linux: [Setting up LAMP](https://www.linux.com/learn/tutorials/288158-easy-lamp-server-installation) <add>- Linux: [Setting up LAMP](https://www.linux.com/training-tutorials/easy-lamp-server-installation/) <ide> - [Mongoose (most platforms)](https://code.google.com/p/mongoose/) <ide> <ide> <ide> Questions? <ide> ---------- <ide> <ide> If you have any questions, please feel free to ask on the <del>[Developing jQuery Core forum](https://forum.jquery.com/developing-jquery-core) or in #jquery on irc.freenode.net. <add>[Developing jQuery Core forum](https://forum.jquery.com/developing-jquery-core) or in #jquery on [libera](https://web.libera.chat/).
1
Python
Python
add check_ldouble for bento build
94fab366240aecdacc66d4d4a77aef5f6e2921a9
<ide><path>numpy/build_utils/waf.py <ide> import waflib.Tools.c_config <ide> from waflib import Logs, Utils <ide> <add>from common \ <add> import \ <add> LONG_DOUBLE_REPRESENTATION_SRC, pyod, \ <add> long_double_representation <add> <ide> DEFKEYS = waflib.Tools.c_config.DEFKEYS <ide> DEFINE_COMMENTS = "define_commentz" <ide> <ide> def check_inline(conf, **kw): <ide> conf.end_msg(inline) <ide> return inline <ide> <add>@waflib.Configure.conf <add>def check_ldouble_representation(conf, **kw): <add> msg = { <add> 'INTEL_EXTENDED_12_BYTES_LE': "Intel extended, little endian", <add> 'INTEL_EXTENDED_16_BYTES_LE': "Intel extended, little endian", <add> 'IEEE_QUAD_BE': "IEEE Quad precision, big endian", <add> 'IEEE_QUAD_LE': "IEEE Quad precision, little endian", <add> 'IEEE_DOUBLE_LE': "IEEE Double precision, little endian", <add> 'IEEE_DOUBLE_BE': "IEEE Double precision, big endian" <add> } <add> <add> code = LONG_DOUBLE_REPRESENTATION_SRC % {'type': 'long double'} <add> validate_arguments(conf, kw) <add> <add> conf.start_msg("Checking for long double representation... ") <add> try: <add> kw["code"] = code <add> ret = conf.run_c_code(**kw) <add> except conf.errors.ConfigurationError as e: <add> conf.end_msg(kw['errmsg'], 'YELLOW') <add> if Logs.verbose > 1: <add> raise <add> else: <add> conf.fatal('The configuration failed') <add> else: <add> task_gen = conf.test_bld.groups[0][0] <add> obj_filename = task_gen.tasks[0].outputs[0].abspath() <add> tp = long_double_representation(pyod(obj_filename)) <add> kw['success'] = ret <add> conf.end_msg(msg[tp]) <add> kw["define_name"] = "HAVE_LDOUBLE_%s" % tp <add> kw["define_comment"] = "/* Define for arch-specific long double representation */" <add> ret = kw["success"] <add> <add> conf.post_check(**kw) <add> if not kw.get('execute', False): <add> return ret == 0 <add> return ret <add> <ide> @waflib.Configure.conf <ide> def post_check(self, *k, **kw): <ide> "set the variables after a test was run successfully"
1
Javascript
Javascript
remove request body from $delete
8336b3a286f8469d4cd7c412c41ca8c1a31fecf0
<ide><path>src/ngResource/resource.js <ide> angular.module('ngResource', ['ng']). <ide> } <ide> }); <ide> <del> httpConfig.data = data; <add> if (hasBody) httpConfig.data = data; <ide> route.setUrlParams(httpConfig, extend({}, extractParams(data, action.params || {}), params), action.url); <ide> <ide> var promise = $http(httpConfig).then(function(response) { <ide><path>test/ngResource/resourceSpec.js <ide> describe("resource", function() { <ide> }); <ide> <ide> <add> it('should not include a request body when calling $delete', function() { <add> $httpBackend.expect('DELETE', '/fooresource', null).respond({}); <add> var Resource = $resource('/fooresource'); <add> var resource = new Resource({ foo: 'bar' }); <add> <add> resource.$delete(); <add> $httpBackend.flush(); <add> }); <add> <add> <ide> it("should build resource", function() { <ide> expect(typeof CreditCard).toBe('function'); <ide> expect(typeof CreditCard.get).toBe('function');
2