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
Text
Text
improve http2 documentation
3621889c800707f3ca720c8de5f05a798a1fe5a8
<ide><path>doc/api/http2.md <ide> support for HTTP/2 protocol features. It is specifically *not* designed for <ide> compatibility with the existing [HTTP/1][] module API. However, <ide> the [Compatibility API][] is. <ide> <add>The `http2` Core API is much more symmetric between client and server than the <add>`http` API. For instance, most events, like `error` and `socketError`, can be <add>emitted either by client-side code or server-side code. <add> <add>### Server-side example <add> <ide> The following illustrates a simple, plain-text HTTP/2 server using the <ide> Core API: <ide> <ide> ```js <ide> const http2 = require('http2'); <add>const fs = require('fs'); <ide> <del>// Create a plain-text HTTP/2 server <del>const server = http2.createServer(); <add>const server = http2.createSecureServer({ <add> key: fs.readFileSync('localhost-privkey.pem'), <add> cert: fs.readFileSync('localhost-cert.pem') <add>}); <add>server.on('error', (err) => console.error(err)); <add>server.on('socketError', (err) => console.error(err)); <ide> <ide> server.on('stream', (stream, headers) => { <ide> // stream is a Duplex <ide> server.on('stream', (stream, headers) => { <ide> stream.end('<h1>Hello World</h1>'); <ide> }); <ide> <del>server.listen(80); <add>server.listen(8443); <ide> ``` <ide> <del>Note that the above example is an HTTP/2 server that does not support SSL. <del>This is significant as most browsers support HTTP/2 only with SSL. <del>To make the above server be able to serve content to browsers, <del>replace `http2.createServer()` with <del>`http2.createSecureServer({key: /* your SSL key */, cert: /* your SSL cert */})`. <add>To generate the certificate and key for this example, run: <add> <add>```bash <add>openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ <add> -keyout localhost-privkey.pem -out localhost-cert.pem <add>``` <add> <add>### Client-side example <ide> <ide> The following illustrates an HTTP/2 client: <ide> <ide> ```js <ide> const http2 = require('http2'); <add>const fs = require('fs'); <add>const client = http2.connect('https://localhost:8443', { <add> ca: fs.readFileSync('localhost-cert.pem') <add>}); <add>client.on('socketError', (err) => console.error(err)); <add>client.on('error', (err) => console.error(err)); <ide> <del>const client = http2.connect('http://localhost:80'); <del> <del>// req is a Duplex <ide> const req = client.request({ ':path': '/' }); <ide> <del>req.on('response', (headers) => { <del> console.log(headers[':status']); <del> console.log(headers['date']); <add>req.on('response', (headers, flags) => { <add> for (const name in headers) { <add> console.log(`${name}: ${headers[name]}`); <add> } <ide> }); <ide> <del>let data = ''; <ide> req.setEncoding('utf8'); <del>req.on('data', (d) => data += d); <del>req.on('end', () => client.destroy()); <add>let data = ''; <add>req.on('data', (chunk) => { data += chunk; }); <add>req.on('end', () => { <add> console.log(`\n${data}`); <add> client.destroy(); <add>}); <ide> req.end(); <ide> ``` <ide>
1
Java
Java
improve tostring() for synthesized annotations
2fd39839f83e8923277cb89bcff0b5dc5a18abfc
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java <ide> private String annotationToString() { <ide> return string; <ide> } <ide> <add> /** <add> * This method currently does not address the following issues which we may <add> * choose to address at a later point in time. <add> * <add> * <ul> <add> * <li>non-ASCII, non-visible, and non-printable characters within a character <add> * or String literal are not escaped.</li> <add> * <li>formatting for float and double values does not take into account whether <add> * a value is not a number (NaN) or infinite.</li> <add> * </ul> <add> * @param value the attribute value to format <add> * @return the formatted string representation <add> */ <ide> private String toString(Object value) { <ide> if (value instanceof String) { <ide> return '"' + value.toString() + '"'; <ide> } <add> if (value instanceof Character) { <add> return '\'' + value.toString() + '\''; <add> } <add> if (value instanceof Byte) { <add> return String.format("(byte) 0x%02X", value); <add> } <add> if (value instanceof Long) { <add> return Long.toString(((Long) value)) + 'L'; <add> } <add> if (value instanceof Float) { <add> return Float.toString(((Float) value)) + 'f'; <add> } <add> if (value instanceof Double) { <add> return Double.toString(((Double) value)) + 'd'; <add> } <ide> if (value instanceof Enum) { <ide> return ((Enum<?>) value).name(); <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java <ide> private void assertToStringForWebMappingWithPathAndValue(RequestMapping webMappi <ide> <ide> // Formatting common to Spring and JDK 9+ <ide> assertThat(string) <del> .contains("value={\"/test\"}", "path={\"/test\"}", "name=\"bar\"") <add> .contains("value={\"/test\"}", "path={\"/test\"}", "name=\"bar\"", "ch='X'", "chars={'X'}") <ide> .endsWith(")"); <ide> <ide> if (webMapping instanceof SynthesizedAnnotation) { <ide> assertThat(string).as("Spring formatting") <ide> .startsWith("@org.springframework.core.annotation.MergedAnnotationsTests.RequestMapping(") <ide> .contains("method={GET, POST}", <ide> "clazz=org.springframework.core.annotation.MergedAnnotationsTests.RequestMethod.class", <del> "classes={org.springframework.core.annotation.MergedAnnotationsTests.RequestMethod.class}"); <add> "classes={int[][].class, org.springframework.core.annotation.MergedAnnotationsTests.RequestMethod[].class}", <add> "byteValue=(byte) 0xFF", "bytes={(byte) 0xFF}", <add> "shortValue=9876", "shorts={9876}", <add> "longValue=42L", "longs={42L}", <add> "floatValue=3.14f", "floats={3.14f}", <add> "doubleValue=99.999d", "doubles={99.999d}" <add> ); <ide> } <ide> else { <ide> assertThat(string).as("JDK 9-18 formatting") <ide> .startsWith("@org.springframework.core.annotation.MergedAnnotationsTests$RequestMapping(") <ide> .contains("method={method: get, method: post}", <ide> "clazz=org.springframework.core.annotation.MergedAnnotationsTests$RequestMethod.class", <del> "classes={org.springframework.core.annotation.MergedAnnotationsTests$RequestMethod.class}"); <add> "classes={int[][].class, org.springframework.core.annotation.MergedAnnotationsTests$RequestMethod[].class}", <add> "shortValue=9876", "shorts={9876}", <add> "floatValue=3.14f", "floats={3.14f}", <add> "doubleValue=99.999", "doubles={99.999}" <add> ); <add> if (JRE.currentVersion().ordinal() < JRE.JAVA_14.ordinal()) { <add> assertThat(string).as("JDK 9-13 formatting") <add> .contains("longValue=42", "longs={42}", <add> "byteValue=-1", "bytes={-1}" <add> ); <add> } <add> else { <add> assertThat(string).as("JDK 14+ formatting") <add> .contains("longValue=42L", "longs={42L}", <add> "byteValue=(byte)0xff", "bytes={(byte)0xff}" <add> ); <add> } <ide> } <ide> } <ide> <ide> public String toString() { <ide> <ide> RequestMethod[] method() default {}; <ide> <add> // --------------------------------------------------------------------- <add> // All remaining attributes declare default values that are used solely <add> // for the purpose of testing the toString() implementations for annotations. <ide> Class<?> clazz() default RequestMethod.class; <add> Class<?>[] classes() default {int[][].class, RequestMethod[].class}; <add> <add> char ch() default 'X'; <add> char[] chars() default {'X'}; <add> <add> byte byteValue() default (byte) 0xFF; <add> byte[] bytes() default {(byte) 0xFF}; <add> <add> short shortValue() default 9876; <add> short[] shorts() default {9876}; <add> <add> long longValue() default 42L; <add> long[] longs() default {42L}; <add> <add> float floatValue() default 3.14F; <add> float[] floats() default {3.14F}; <ide> <del> Class<?>[] classes() default {RequestMethod.class}; <add> double doubleValue() default 99.999D; <add> double[] doubles() default {99.999D}; <ide> } <ide> <ide> @Retention(RetentionPolicy.RUNTIME)
2
Text
Text
add myself to contributors
71710e2454bb0fceef400bf8c8bce9d8243af6b4
<ide><path>.github/contributors/pickfire.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [ ] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [x] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Ivan Tham Jun Hoe | <add>| Company name (if applicable) | Semut | <add>| Title or role (if applicable) | Data Analyst | <add>| Date | Apr 11, 2019 | <add>| GitHub username | pickfire | <add>| Website (optional) | https://pickfire.tk |
1
Python
Python
fix handling of kwargs in language.evaluate
87ddbdc33e362336b060e0cb95f8adb008d5f29f
<ide><path>spacy/language.py <ide> def evaluate( <ide> kwargs = component_cfg.get(name, {}) <ide> kwargs.setdefault("batch_size", batch_size) <ide> if not hasattr(pipe, "pipe"): <del> docs = (pipe(doc, **kwargs) for doc in docs) <add> docs = _pipe(pipe, docs, kwargs) <ide> else: <ide> docs = pipe.pipe(docs, **kwargs) <ide> for doc, gold in zip(docs, golds):
1
Text
Text
fix russian description and add translation
7ce8046792d2dbfe6a98ac8c2081bccffe58cc77
<ide><path>guide/russian/c/file-handling/index.md <ide> --- <ide> title: File Handling <del>localeTitle: Обработка файлов <add>localeTitle: Работа с файлами <ide> --- <del>## Обработка файлов <add>## Работа с файлами <ide> <ide> ### Введение <ide> <del>Если вы уже написали программу C `helloworld` , вы уже сделали файл IO в C! Поздравляем! : Тада: <add>Если вы уже написали программу `helloworld`, вы уже использовали файловый ввод/вывод (input/output, IO) в C! Поздравляем! :tada: <ide> <ide> ```c <ide> /* A simple hello world in C. */ <ide> localeTitle: Обработка файлов <ide> } <ide> ``` <ide> <del>Обработка файлов - важная часть программиста. В языке C мы используем указатель структуры типа файла для объявления файла <add>Работа с файлами - один из важнейших аспектов программирования. В языке C для объявления файла используется указатель на структуру типа FILE. <ide> <ide> ```c <ide> FILE *fp; <ide> ``` <ide> <del>C предоставляет ряд встроенных функций для выполнения основной операции с файлами <add>C предоставляет ряд встроенных функций для выполнения основных операций с файлами <ide> <del>**fopen ()** **\-** **создать новый файл или открыть существующий файл** <add>**fopen() - создать новый файл или открыть существующий файл** <ide> <del>**fclose ()** **\-** **закрыть файл** <add>**fclose() - закрыть файл** <ide> <del>**getc ()** **\-** **считывает символ из файла** <add>**getc() - считывает символ из файла** <ide> <del>**putc ()** **\-** **записывает символ в файл** <add>**putc() - записывает символ в файл** <ide> <del>**fscanf ()** **\-** **считывает набор данных из файла** <add>**fscanf() - считывает набор данных из файла** <ide> <del>**fprintf ()** **\-** **записывает набор данных в файл** <add>**fprintf - записывает набор данных в файл** <ide> <del>**getw ()** **\-** **считывает целое число из файла** <add>**getw() - считывает целое число из файла** <ide> <del>**putw ()** **\-** **записывает целое число в файл** <add>**putw() - записывает целое число в файл** <ide> <del>**fseek ()** **\-** **установить позицию для желаемой точки** <add>**fseek() - установить позицию в желаемую точку** <ide> <del>**ftell ()** **\-** **показывает текущую позицию в файле** <add>**ftell() - показывает текущую позицию в файле** <ide> <del>**rewind ()** **\-** **установить позицию в начальную точку** <add>**rewind() - установить позицию в начальную точку** <ide> <ide> ### Открытие файла <ide> <del>Функция **fopen ()** используется для создания файла или открытия существующего файла <add>Функция **fopen()** используется для создания файла или открытия существующего файла <ide> <ide> `c fp = fopen(const char filename,const char mode);` <ide> <del>В C существует много режимов открытия файла **r** **\-** **открыть файл в режиме чтения** <add>В C существует множество режимов открытия файла: <ide> <del>**w** **\-** **открывает или создает текстовый файл в режиме записи** <add>**r - открывает файл в режиме чтения** <ide> <del>**a** **\-** **открывает файл в режиме добавления** <add>**w - открывает файл в режиме записи (удаляя его содержимое) или создает его в случае отсутствия** <ide> <del>**r +** **\-** **открывает файл в режиме чтения и записи** <add>**a - открывает файл в режиме добавления в конец или создает его в случае отсутствия*** <ide> <del>**a +** **\-** **открывает файл в режиме чтения и записи** <add>**r+ - открывает файл в режиме чтения и записи** <ide> <del>**w +** **\-** **открывает файл в режиме чтения и записи** <add>**a+ - открывает файл в режиме чтения и записи (добавляет в случае существования)** <ide> <del>Вот пример чтения и записи данных в файл <del> <del>\`\` \`с #включают <del> <del># включают <add>**w+ - открывает файл в режиме чтения и записи (удаляя его содержимое)** <ide> <del>главный() { FILE \* fp; char ch; fp = fopen ("hello.txt", "w"); printf («Введите данные»); while ((ch = getchar ())! = EOF) { putc (ч, FP); } fclose (FP); fp = fopen ("hello.txt", "r"); <del> <del>while ((ch = getc (fp)! = EOF) Е ( "% С", ч); <add>Вот пример чтения и записи данных в файл <ide> <del>fclose (FP); } <add>```c <add>#include<stdio.h> <add>#include<conio.h> <add> <add>int main() <add>{ <add> FILE *fp; <add> char ch; <add> fp = fopen("hello.txt", "w"); <add> printf("Enter data"); <add> while( (ch = getchar()) != EOF) { <add> putc(ch,fp); <add> } <add> fclose(fp); <add> fp = fopen("hello.txt", "r"); <add> <add> while( (ch = getc(fp)! = EOF) <add> printf("%c",ch); <add> <add> fclose(fp); <add>} <ide> ``` <del>Now you might be thinking, "this justs prints text to my screen. How is this file IO?" <del> The answer isn't obvious at first, and needs some understanding about the UNIX system. <del> Under a UNIX system, everything is treated as a file, meaning you can read and write from it. <del> This means that your printer can be abstracted as a file since all you do with a printer is write with it. <del> It is also useful to think of these files as streams, since as you'll see later, you can redirect them with the shell. <add>Должно быть, вы думаете: "Это всего лишь выводит текст на экран. С какой стати это файловый ввод/вывод"? Ответ кажется поначалу неочевидным и требует некоторых знаний о системе UNIX. С точки зрения UNIX все является файлом, в том смысле, что вы можете читать из него и записывать в него. Это значит, что принтер может быть отождествлен с файлом, так как все, что вы делаете с принтером - пишете в него. Также полезно думать об этих файлах как о потоках, поскольку, как будет показано позже, их можно перенаправлять с помощью оболочки. <ide> <del> So how does this relate to `helloworld` and file IO? <add>Как все это связано с `helloworld` и файловым вводом/выводом? <ide> <del> When you call `printf`, you are really just writing to a special file called `stdout`, short for __standard output__. <del> `stdout` represents, well, the standard output as decided by your shell, which is usually the terminal. <del> This explains why it printed to your screen. <add> Когда вы вызываете `printf`, на самом деле происходит запись в специальный файл `stdout`, сокращение от __standard output (стандартный вывод)__. <add> `stdout` представляет собой, что неудивительно, средство стандартного вывода по выбору вашей оболочки, роль которой чаще всего играет терминал. Это объясняет почему он выводит символы на экран. <ide> <del> There are two other streams (ie files) that are available to you with effort, `stdin` and `stderr`. <del> `stdin` represents the __standard input__, which your shell usually attaches to the keyboard. <del> `stderr` represents the __standard error__ output, which your shell usually attaches to the terminal. <add> Существуют два других потока (т.е. файла) с которыми тоже при желании можно работать, `stdin` и `stderr`. <add> `stdin` представляет собой __standard input (стандартный ввод)__, которую оболочка обычно привязывает к клавиатуре. <add> `stderr` представляет собой __standard error (стандартный вывод ошибок)__ , который оболочка обычно привязывает к терминалу. <ide> <ide> ### Rudimentary File IO, or How I Learnt to Lay Pipes <ide> Enough theory, let's get down to business by writing some code! <ide> Then after running `greetings` the file `greet.txt` will contain: <ide> <ide> ### Дополнительная информация: <ide> <del>* [Страница Wikibooks в файле IO](https://en.wikibooks.org/wiki/C_Programming/File_IO) <ide>\ No newline at end of file <add>* [Страница Wikibooks в файле IO](https://en.wikibooks.org/wiki/C_Programming/File_IO)
1
Javascript
Javascript
move helper functions to the bottom of the file
bf69fd92bbe4ed035f3ed7692ea2e20b282d9829
<ide><path>src/tree-sitter-language-mode.js <ide> const TextMateLanguageMode = require('./text-mate-language-mode') <ide> <ide> let nextId = 0 <ide> const MAX_RANGE = new Range(Point.ZERO, Point.INFINITY).freeze() <del> <del>/** <del> * Return true iff `mouse` is smaller than `house`. Only correct if <del> * mouse and house overlap. <del> * <del> * @param mouse {Range} <del> * @param house {Range} <del> */ <del>const rangeIsSmaller = (mouse, house) => { <del> if (!house) return true <del> const mvec = vecFromRange(mouse) <del> const hvec = vecFromRange(house) <del> return Point.min(mvec, hvec) === mvec <del>} <del> <del>const vecFromRange = ({start, end}) => end.translate(start.negate()) <del> <ide> const PARSER_POOL = [] <ide> <ide> class TreeSitterLanguageMode { <ide> class NodeRangeSet { <ide> } <ide> } <ide> <add>// Return true iff `mouse` is smaller than `house`. Only correct if <add>// mouse and house overlap. <add>// <add>// * `mouse` {Range} <add>// * `house` {Range} <add>function rangeIsSmaller (mouse, house) { <add> if (!house) return true <add> const mvec = vecFromRange(mouse) <add> const hvec = vecFromRange(house) <add> return Point.min(mvec, hvec) === mvec <add>} <add> <add>function vecFromRange ({start, end}) { <add> return end.translate(start.negate()) <add>} <add> <ide> function rangeForNode (node) { <ide> return new Range(node.startPosition, node.endPosition) <ide> }
1
Ruby
Ruby
leave kegs keg-only if linking step fails
765ae9618050e415c039edabce02671581c1ffb1
<ide><path>Library/Homebrew/cmd/link.rb <ide> def link <ide> ARGV.kegs.each do |keg| <ide> print "Linking #{keg}... " <ide> puts if ARGV.verbose? <del> begin <del> puts "#{keg.link} symlinks created" <del> rescue Exception <del> puts <del> raise <del> end <add> puts "#{keg.link} symlinks created" <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/extend/pathname.rb <ide> def make_relative_symlink src <ide> <ide> self.dirname.mkpath <ide> Dir.chdir self.dirname do <del> # TODO use Ruby function so we get exceptions <del> # NOTE Ruby functions may work, but I had a lot of problems <del> rv = system 'ln', '-sf', src.relative_path_from(self.dirname), self.basename <del> unless rv and $? == 0 <del> raise <<-EOS.undent <del> Could not create symlink #{to_s}. <del> Check that you have permissions on #{self.dirname} <del> EOS <del> end <add> # NOTE only system ln -s will create RELATIVE symlinks <add> system 'ln', '-s', src.relative_path_from(self.dirname), self.basename <add> # ln outputs useful error message for us <add> raise "Could not create symlink: #{to_s}." unless $?.success? <ide> end <ide> end <ide> <ide><path>Library/Homebrew/formula_installer.rb <ide> def link <ide> f.linked_keg.unlink <ide> end <ide> <del> Keg.new(f.prefix).link <add> keg = Keg.new(f.prefix) <add> keg.link <ide> rescue Exception => e <ide> onoe "The linking step did not complete successfully" <ide> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" <ide> puts "You can try again using `brew link #{f.name}'" <add> keg.unlink <add> <ide> ohai e, e.backtrace if ARGV.debug? <ide> @show_summary_heading = true <ide> end
3
PHP
PHP
remove extra line
54d2c6b8e38e90da7466fb5f306e1dbbe08a28e9
<ide><path>tests/Queue/QueueWorkerTest.php <ide> public function test_job_is_not_released_if_it_has_exceeded_max_attempts() <ide> $e = new RuntimeException; <ide> <ide> $job = new WorkerFakeJob(function ($job) use ($e) { <del> <ide> // In normal use this would be incremented by being popped off the queue <ide> $job->attempts++; <ide>
1
Python
Python
remove base test that never run
cc6812d69d5dd0421e0b787cb7cde3c7e897275a
<ide><path>libcloud/test/backup/test_base.py <del># Licensed to the Apache Software Foundation (ASF) under one or more <del># contributor license agreements. See the NOTICE file distributed with <del># this work for additional information regarding copyright ownership. <del># The ASF licenses this file to You under the Apache License, Version 2.0 <del># (the "License"); you may not use this file except in compliance with <del># the License. You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del> <del>from __future__ import with_statement <del> <del>import sys <del> <del>from libcloud.test import unittest <del>from libcloud.backup.base import BackupDriver <del> <del> <del>class BaseTestCase(unittest.TestCase): <del> def setUp(self): <del> self.driver = BackupDriver('none', 'none') <del> <del> <del>if __name__ == '__main__': <del> sys.exit(unittest.main()) <ide><path>libcloud/test/container/test_base.py <del># Licensed to the Apache Software Foundation (ASF) under one or more <del># contributor license agreements. See the NOTICE file distributed with <del># this work for additional information regarding copyright ownership. <del># The ASF licenses this file to You under the Apache License, Version 2.0 <del># (the "License"); you may not use this file except in compliance with <del># the License. You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del> <del>from __future__ import with_statement <del> <del>import sys <del> <del>from libcloud.test import unittest <del>from libcloud.container.base import ContainerDriver <del> <del> <del>class BaseTestCase(unittest.TestCase): <del> def setUp(self): <del> self.driver = ContainerDriver('none', 'none') <del> <del> <del>if __name__ == '__main__': <del> sys.exit(unittest.main())
2
Text
Text
update documentation links
686d29b5d4e2dcb6709c16e31b79ecde90763156
<ide><path>README.md <ide> Redux co-maintainer [Mark Erikson](https://twitter.com/acemarke) has put togethe <ide> <ide> ## Documentation <ide> <del>- [Introduction](http://redux.js.org/introduction/index.html) <del>- [Basics](http://redux.js.org/basics/index.html) <del>- [Advanced](http://redux.js.org/advanced/index.html) <del>- [Recipes](http://redux.js.org/recipes/index.html) <del>- [FAQ](http://redux.js.org/FAQ.html) <del>- [Troubleshooting](http://redux.js.org/Troubleshooting.html) <del>- [Glossary](http://redux.js.org/Glossary.html) <del>- [API Reference](http://redux.js.org/api/index.html) <add>- [Introduction](http://redux.js.org/introduction) <add>- [Basics](http://redux.js.org/basics) <add>- [Advanced](http://redux.js.org/advanced) <add>- [Recipes](http://redux.js.org/recipes) <add>- [FAQ](http://redux.js.org/faq) <add>- [Troubleshooting](http://redux.js.org/troubleshooting) <add>- [Glossary](http://redux.js.org/glossary) <add>- [API Reference](http://redux.js.org/api) <ide> <ide> For PDF, ePub, and MOBI exports for offline reading, and instructions on how to create them, please see: [paulkogel/redux-offline-docs](https://github.com/paulkogel/redux-offline-docs). <ide>
1
Ruby
Ruby
use rails default banner
04eb5b6e3428a2db773303b339bc776767635aee
<ide><path>railties/lib/generator/base.rb <ide> def self.source_root <ide> end <ide> end <ide> <add> protected <add> <add> # Use Rails default banner. <add> # <add> def self.banner <add> "#{$0} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]" <add> end <add> <ide> # Small macro to ruby as an option to the generator with proper default <ide> # value plus an instance helper method. <ide> # <ide><path>railties/lib/generator/generators/app.rb <ide> module Rails::Generators <ide> class App < Base <ide> DATABASES = %w( mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db ) <ide> <del> namespace :rails <add> namespace "rails:app" <ide> add_shebang_option! <ide> <ide> argument :app_path, :type => :string
2
Text
Text
fix typo in n-api.md
fd54b10500724a7f59f448635f2ec96759495339
<ide><path>doc/api/n-api.md <ide> Taking the earlier example, adding calls to [`napi_open_handle_scope`][] and <ide> is valid throughout the execution of the loop: <ide> <ide> ```C <del>for (int i = 0; i < 1000000; i++) {napi_ <add>for (int i = 0; i < 1000000; i++) { <ide> napi_handle_scope scope; <ide> napi_status status = napi_open_handle_scope(env, &scope); <ide> if (status != napi_ok) {
1
Go
Go
fix regression pulling linux images
8437d0a3298abf8bf3632a2764b945956ece422f
<ide><path>distribution/pull_v2.go <ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s <ide> ) <ide> <ide> // https://github.com/docker/docker/issues/24766 - Err on the side of caution, <del> // explicitly blocking images intended for linux from the Windows daemon <del> if runtime.GOOS == "windows" && unmarshalledConfig.OS == "linux" { <del> return "", "", fmt.Errorf("image operating system %q cannot be used on this platform", unmarshalledConfig.OS) <add> // explicitly blocking images intended for linux from the Windows daemon. On <add> // Windows, we do this before the attempt to download, effectively serialising <add> // the download slightly slowing it down. We have to do it this way, as <add> // chances are the download of layers itself would fail due to file names <add> // which aren't suitable for NTFS. At some point in the future, if a similar <add> // check to block Windows images being pulled on Linux is implemented, it <add> // may be necessary to perform the same type of serialisation. <add> if runtime.GOOS == "windows" { <add> configJSON, unmarshalledConfig, err = receiveConfig(configChan, errChan) <add> if err != nil { <add> return "", "", err <add> } <add> <add> if unmarshalledConfig.RootFS == nil { <add> return "", "", errRootFSInvalid <add> } <add> <add> if unmarshalledConfig.OS == "linux" { <add> return "", "", fmt.Errorf("image operating system %q cannot be used on this platform", unmarshalledConfig.OS) <add> } <ide> } <ide> <ide> downloadRootFS = *image.NewRootFS() <ide> <ide> rootFS, release, err := p.config.DownloadManager.Download(ctx, downloadRootFS, descriptors, p.config.ProgressOutput) <ide> if err != nil { <add> if configJSON != nil { <add> // Already received the config <add> return "", "", err <add> } <ide> select { <ide> case err = <-errChan: <ide> return "", "", err <ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s <ide> } <ide> defer release() <ide> <del> configJSON, unmarshalledConfig, err = receiveConfig(configChan, errChan) <del> if err != nil { <del> return "", "", err <del> } <add> if configJSON == nil { <add> configJSON, unmarshalledConfig, err = receiveConfig(configChan, errChan) <add> if err != nil { <add> return "", "", err <add> } <ide> <del> if unmarshalledConfig.RootFS == nil { <del> return "", "", errRootFSInvalid <add> if unmarshalledConfig.RootFS == nil { <add> return "", "", errRootFSInvalid <add> } <ide> } <ide> <ide> // The DiffIDs returned in rootFS MUST match those in the config. <ide><path>integration-cli/docker_cli_pull_test.go <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPullNoCredentialsNotFound(c *check <ide> c.Assert(err, check.NotNil, check.Commentf(out)) <ide> c.Assert(out, checker.Contains, "Error: image busybox:latest not found") <ide> } <add> <add>// Regression test for https://github.com/docker/docker/issues/26429 <add>func (s *DockerSuite) TestPullLinuxImageFailsOnWindows(c *check.C) { <add> testRequires(c, DaemonIsWindows, Network) <add> _, _, err := dockerCmdWithError("pull", "ubuntu") <add> c.Assert(err.Error(), checker.Contains, "cannot be used on this platform") <add>}
2
PHP
PHP
remove unneeded code from form class
044443435ff79305afdda2efdbcb28994438768f
<ide><path>src/Form/Form.php <ide> */ <ide> namespace Cake\Form; <ide> <del>use Cake\Event\Event; <ide> use Cake\Event\EventDispatcherInterface; <ide> use Cake\Event\EventDispatcherTrait; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\Form\Schema; <del>use Cake\Validation\Validator; <ide> use Cake\Validation\ValidatorAwareInterface; <ide> use Cake\Validation\ValidatorAwareTrait; <ide> <ide> * ### Building a form <ide> * <ide> * This class is most useful when subclassed. In a subclass you <del> * should define the `_buildSchema`, `_buildValidator` and optionally, <add> * should define the `_buildSchema`, `validationDefault` and optionally, <ide> * the `_execute` methods. These allow you to declare your form's <ide> * fields, validation and primary action respectively. <ide> * <del> * You can also define the validation and schema by chaining method <del> * calls off of `$form->schema()` and `$form->validator()`. <del> * <ide> * Forms are conventionally placed in the `App\Form` namespace. <ide> */ <ide> class Form implements EventListenerInterface, EventDispatcherInterface, ValidatorAwareInterface <ide> { <add> use EventDispatcherTrait; <add> use ValidatorAwareTrait; <add> <ide> /** <ide> * Schema class. <ide> * <ide> * @var string <ide> */ <ide> protected $_schemaClass = Schema::class; <ide> <del> use EventDispatcherTrait; <del> use ValidatorAwareTrait; <del> <ide> /** <ide> * The alias this object is assigned to validators as. <ide> * <ide> public function __construct(EventManager $eventManager = null) <ide> */ <ide> public function implementedEvents() <ide> { <del> return [ <del> 'Form.buildValidator' => 'buildValidator', <del> ]; <add> if (method_exists($this, 'buildValidator')) { <add> return [ <add> self::BUILD_VALIDATOR_EVENT => 'buildValidator', <add> ]; <add> } <add> <add> return []; <ide> } <ide> <ide> /** <ide> protected function _buildSchema(Schema $schema) <ide> return $schema; <ide> } <ide> <del> /** <del> * Callback method for Form.buildValidator event. <del> * <del> * @param \Cake\Event\Event $event The Form.buildValidator event instance. <del> * @param \Cake\Validation\Validator $validator The validator to customize. <del> * @param string $name Validator name <del> * @return void <del> */ <del> public function buildValidator(Event $event, Validator $validator, $name) <del> { <del> $this->setValidator($name, $validator); <del> } <del> <ide> /** <ide> * Used to check if $data passes this form's validation. <ide> * <ide> public function buildValidator(Event $event, Validator $validator, $name) <ide> public function validate(array $data) <ide> { <ide> $validator = $this->getValidator(); <del> if (!$validator->count()) { <del> $validator = $this->getValidator(); <del> } <ide> $this->_errors = $validator->errors($data); <ide> <ide> return count($this->_errors) === 0;
1
Javascript
Javascript
remove state dependency from frame creation
b59c7cfed0dfb9645b83696ef0bee67110cb9f25
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> import { <ide> runTestInTestFrame <ide> } from '../utils/frame.js'; <ide> <del>const testWorker = createWorker('test-evaluator'); <del>const testTimeout = 5000; <del> <del>function* ExecuteChallengeSaga() { <add>export function* executeChallengeSaga() { <ide> const consoleProxy = yield channel(); <ide> try { <ide> const { js, bonfire, backend } = challengeTypes; <ide> function* ExecuteChallengeSaga() { <ide> yield put(initLogs()); <ide> yield put(initConsole('// running tests')); <ide> yield fork(logToConsole, consoleProxy); <add> const proxyLogger = args => consoleProxy.put(args); <ide> <ide> const state = yield select(); <ide> <ide> let testResults; <ide> switch (challengeType) { <ide> case js: <ide> case bonfire: <del> testResults = yield ExecuteJSChallengeSaga(state, consoleProxy); <add> testResults = yield executeJSChallengeSaga(state, proxyLogger); <ide> break; <ide> case backend: <del> testResults = yield ExecuteBackendChallengeSaga(state, consoleProxy); <add> testResults = yield executeBackendChallengeSaga(state, proxyLogger); <ide> break; <ide> default: <del> testResults = yield ExecuteDOMChallengeSaga(state, consoleProxy); <add> testResults = yield executeDOMChallengeSaga(state, proxyLogger); <ide> } <ide> <ide> yield put(updateTests(testResults)); <ide> function* logToConsole(channel) { <ide> }); <ide> } <ide> <del>function* ExecuteJSChallengeSaga(state, proxyLogger) { <add>function* executeJSChallengeSaga(state, proxyLogger) { <ide> const { build, sources } = yield call(buildJSChallenge, state); <ide> const code = sources && 'index' in sources ? sources['index'] : ''; <ide> <del> const log = args => proxyLogger.put(args); <del> testWorker.on('LOG', log); <add> const testWorker = createWorker('test-evaluator'); <add> testWorker.on('LOG', proxyLogger); <ide> <ide> try { <del> return yield call(executeTests, (testString, testTimeout) => <del> testWorker <del> .execute( <add> return yield call(executeTests, async(testString, testTimeout) => { <add> try { <add> return await testWorker.execute( <ide> { script: build + '\n' + testString, code, sources }, <ide> testTimeout <del> ) <del> .then(result => { <del> testWorker.killWorker(); <del> return result; <del> }) <del> ); <add> ); <add> } finally { <add> testWorker.killWorker(); <add> } <add> }); <ide> } finally { <del> testWorker.remove('LOG', log); <add> testWorker.remove('LOG', proxyLogger); <ide> } <ide> } <ide> <del>function createTestFrame(state, ctx, proxyLogger) { <del> return new Promise(resolve => { <del> const frameTest = createTestFramer(document, state, resolve, proxyLogger); <del> frameTest(ctx); <del> }); <add>function createTestFrame(ctx, proxyLogger) { <add> return new Promise(resolve => <add> createTestFramer(document, resolve, proxyLogger)(ctx) <add> ); <ide> } <ide> <del>function* ExecuteDOMChallengeSaga(state, proxyLogger) { <add>function* executeDOMChallengeSaga(state, proxyLogger) { <ide> const ctx = yield call(buildDOMChallenge, state); <del> <del> yield call(createTestFrame, state, ctx, proxyLogger); <add> yield call(createTestFrame, ctx, proxyLogger); <ide> // wait for a code execution on a "ready" event in jQuery challenges <ide> yield delay(100); <ide> <ide> return yield call(executeTests, (testString, testTimeout) => <del> Promise.race([ <del> runTestInTestFrame(document, testString), <del> new Promise((_, reject) => <del> setTimeout(() => reject('timeout'), testTimeout) <del> ) <del> ]) <add> runTestInTestFrame(document, testString, testTimeout) <ide> ); <ide> } <ide> <ide> // TODO: use a web worker <del>function* ExecuteBackendChallengeSaga(state, proxyLogger) { <add>function* executeBackendChallengeSaga(state, proxyLogger) { <ide> const ctx = yield call(buildBackendChallenge, state); <del> <del> yield call(createTestFrame, state, ctx, proxyLogger); <add> yield call(createTestFrame, ctx, proxyLogger); <ide> <ide> return yield call(executeTests, (testString, testTimeout) => <del> Promise.race([ <del> runTestInTestFrame(document, testString), <del> new Promise((_, reject) => <del> setTimeout(() => reject('timeout'), testTimeout) <del> ) <del> ]) <add> runTestInTestFrame(document, testString, testTimeout) <ide> ); <ide> } <ide> <ide> function* executeTests(testRunner) { <ide> const tests = yield select(challengeTestsSelector); <add> const testTimeout = 5000; <ide> const testResults = []; <ide> for (const { text, testString } of tests) { <ide> const newTest = { text, testString }; <ide> function* updateMainSaga() { <ide> return; <ide> } <ide> const state = yield select(); <del> const frameMain = yield call(createMainFramer, document, state); <ide> const ctx = yield call(buildDOMChallenge, state); <add> const frameMain = yield call(createMainFramer, document); <ide> yield call(frameMain, ctx); <ide> } catch (err) { <ide> console.error(err); <ide> function* updateMainSaga() { <ide> <ide> export function createExecuteChallengeSaga(types) { <ide> return [ <del> takeLatest(types.executeChallenge, ExecuteChallengeSaga), <add> takeLatest(types.executeChallenge, executeChallengeSaga), <ide> takeLatest( <ide> [ <ide> types.updateFile, <ide><path>client/src/templates/Challenges/utils/frame.js <ide> import { configure, shallow, mount } from 'enzyme'; <ide> import Adapter16 from 'enzyme-adapter-react-16'; <ide> import { setConfig } from 'react-hot-loader'; <ide> <del>import { isJSEnabledSelector } from '../redux'; <del> <ide> // we use two different frames to make them all essentially pure functions <ide> // main iframe is responsible rendering the preview and is where we proxy the <ide> // console.log <ide> const createHeader = (id = mainId) => ` <ide> </script> <ide> `; <ide> <del>export const runTestInTestFrame = async function(document, test) { <add>export const runTestInTestFrame = async function(document, test, timeout) { <ide> const { contentDocument: frame } = document.getElementById(testId); <ide> // Enable Stateless Functional Component. Otherwise, enzyme-adapter-react-16 <ide> // does not work correctly. <ide> setConfig({ pureSFC: true }); <del> const result = await frame.__runTest(test); <del> setConfig({ pureSFC: false }); <del> return result; <add> try { <add> return await Promise.race([ <add> new Promise((_, reject) => setTimeout(() => reject('timeout'), timeout)), <add> frame.__runTest(test) <add> ]); <add> } finally { <add> setConfig({ pureSFC: false }); <add> } <ide> }; <ide> <del>const createFrame = (document, state, id) => ctx => { <del> const isJSEnabled = isJSEnabledSelector(state); <add>const createFrame = (document, id) => ctx => { <ide> const frame = document.createElement('iframe'); <ide> frame.id = id; <del> if (!isJSEnabled) { <del> frame.sandbox = 'allow-same-origin'; <del> } <ide> return { <ide> ...ctx, <ide> element: frame <ide> const mountFrame = document => ({ element, ...rest }) => { <ide> const buildProxyConsole = proxyLogger => ctx => { <ide> const oldLog = ctx.window.console.log.bind(ctx.window.console); <ide> ctx.window.console.log = function proxyConsole(...args) { <del> proxyLogger.put(args); <add> proxyLogger(args); <ide> return oldLog(...args); <ide> }; <ide> return ctx; <ide> const writeContentToFrame = ctx => { <ide> return ctx; <ide> }; <ide> <del>export const createMainFramer = (document, state) => <add>export const createMainFramer = document => <ide> flow( <del> createFrame(document, state, mainId), <add> createFrame(document, mainId), <ide> mountFrame(document), <ide> writeContentToFrame <ide> ); <ide> <del>export const createTestFramer = (document, state, frameReady, proxyConsole) => <add>export const createTestFramer = (document, frameReady, proxyConsole) => <ide> flow( <del> createFrame(document, state, testId), <add> createFrame(document, testId), <ide> mountFrame(document), <ide> writeTestDepsToDocument(frameReady), <ide> buildProxyConsole(proxyConsole),
2
Javascript
Javascript
add msg validation to test-buffer-compare
6af10907a2fd82ac9f1a159920815c69a76e17ee
<ide><path>test/parallel/test-buffer-compare.js <ide> assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0)), 0); <ide> assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1); <ide> assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1); <ide> <del>assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc')); <add>assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), <add> /^TypeError: Arguments must be Buffers or Uint8Arrays$/); <ide> <del>assert.throws(() => Buffer.compare('abc', Buffer.alloc(1))); <add>assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), <add> /^TypeError: Arguments must be Buffers or Uint8Arrays$/); <ide> <del>assert.throws(() => Buffer.alloc(1).compare('abc')); <add>assert.throws(() => Buffer.alloc(1).compare('abc'), <add> /^TypeError: Argument must be a Buffer or Uint8Array$/);
1
Python
Python
fix doc.to_utf8 on gpu
6f3bb6f77cb3691281fde1f18a75038bb3a15890
<ide><path>spacy/ml/_character_embed.py <ide> def forward(model, docs, is_train): <ide> # for the tip. <ide> nCv = model.ops.xp.arange(nC) <ide> for doc in docs: <del> doc_ids = doc.to_utf8_array(nr_char=nC) <add> doc_ids = model.ops.asarray(doc.to_utf8_array(nr_char=nC)) <ide> doc_vectors = model.ops.alloc3f(len(doc), nC, nM) <ide> # Let's say I have a 2d array of indices, and a 3d table of data. What numpy <ide> # incantation do I chant to get
1
Mixed
Text
add a way to know when a resize occurs
7ea36aead33d90803027d668a15d0f698fb3d4b2
<ide><path>docs/01-Chart-Configuration.md <ide> maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio <ide> events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering <ide> onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements <ide> legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. <add>onResize | Function | null | Called when a resize occurs. Gets passed two arguemnts: the chart instance and the new size. <ide> <ide> ### Title Configuration <ide> <ide><path>docs/09-Advanced.md <ide> Plugins will be called at the following times <ide> * End of update (before render occurs) <ide> * Start of draw <ide> * End of draw <add>* Before datasets draw <add>* After datasets draw <add>* Resize <ide> * Before an animation is started <ide> <ide> Plugins should derive from Chart.PluginBase and implement the following interface <ide> Plugins should derive from Chart.PluginBase and implement the following interfac <ide> beforeInit: function(chartInstance) { }, <ide> afterInit: function(chartInstance) { }, <ide> <add> resize: function(chartInstance, newChartSize) { }, <add> <ide> beforeUpdate: function(chartInstance) { }, <ide> afterScaleUpdate: function(chartInstance) { } <ide> afterUpdate: function(chartInstance) { }, <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> resize: function resize(silent) { <del> var canvas = this.chart.canvas; <del> var newWidth = helpers.getMaximumWidth(this.chart.canvas); <del> var newHeight = (this.options.maintainAspectRatio && isNaN(this.chart.aspectRatio) === false && isFinite(this.chart.aspectRatio) && this.chart.aspectRatio !== 0) ? newWidth / this.chart.aspectRatio : helpers.getMaximumHeight(this.chart.canvas); <add> var me = this; <add> var chart = me.chart; <add> var canvas = chart.canvas; <add> var newWidth = helpers.getMaximumWidth(canvas); <add> var aspectRatio = chart.aspectRatio; <add> var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas); <add> <add> var sizeChanged = chart.width !== newWidth || chart.height !== newHeight; <add> <add> if (!sizeChanged) { <add> return me; <add> } <ide> <del> var sizeChanged = this.chart.width !== newWidth || this.chart.height !== newHeight; <add> canvas.width = chart.width = newWidth; <add> canvas.height = chart.height = newHeight; <ide> <del> if (!sizeChanged) <del> return this; <add> helpers.retinaScale(chart); <ide> <del> canvas.width = this.chart.width = newWidth; <del> canvas.height = this.chart.height = newHeight; <add> // Notify any plugins about the resize <add> var newSize = { width: newWidth, height: newHeight }; <add> Chart.pluginService.notifyPlugins('resize', [me, newSize]); <ide> <del> helpers.retinaScale(this.chart); <add> // Notify of resize <add> if (me.options.onResize) { <add> me.options.onResize(me, newSize); <add> } <ide> <ide> if (!silent) { <del> this.stop(); <del> this.update(this.options.responsiveAnimationDuration); <add> me.stop(); <add> me.update(me.options.responsiveAnimationDuration); <ide> } <ide> <del> return this; <add> return me; <ide> }, <ide> <ide> ensureScalesHaveIDs: function ensureScalesHaveIDs() {
3
PHP
PHP
remove unneeded else
4a9249fe23be41850d5b0e23f19dce729e63f1d8
<ide><path>src/Console/ConsoleOptionParser.php <ide> public function parse($argv) <ide> while (($token = array_shift($this->_tokens)) !== null) { <ide> if (isset($this->_subcommands[$token])) { <ide> continue; <del> } elseif (substr($token, 0, 2) === '--') { <add> } <add> if (substr($token, 0, 2) === '--') { <ide> $params = $this->_parseLongOption($token, $params); <ide> } elseif (substr($token, 0, 1) === '-') { <ide> $params = $this->_parseShortOption($token, $params); <ide><path>src/Database/Expression/CaseExpression.php <ide> protected function _addExpressions($conditions, $values, $types) <ide> $value = $keyValues[$k]; <ide> array_push($this->_values, $value); <ide> continue; <del> } elseif ($value instanceof ExpressionInterface) { <add> } <add> if ($value instanceof ExpressionInterface) { <ide> array_push($this->_values, $value); <ide> continue; <ide> } <ide><path>src/Database/Log/QueryLogger.php <ide> protected function _interpolate($query) <ide> $params = array_map(function ($p) { <ide> if ($p === null) { <ide> return 'NULL'; <del> } elseif (is_bool($p)) { <add> } <add> if (is_bool($p)) { <ide> return $p ? '1' : '0'; <ide> } <ide> return is_string($p) ? "'$p'" : $p; <ide><path>src/Database/Type/FloatType.php <ide> public function marshal($value) <ide> } <ide> if (is_numeric($value)) { <ide> return (float)$value; <del> } elseif (is_string($value) && $this->_useLocaleParser) { <add> } <add> if (is_string($value) && $this->_useLocaleParser) { <ide> return $this->_parseValue($value); <ide> } <ide> if (is_array($value)) { <ide><path>src/Error/Debugger.php <ide> public static function trimPath($path) <ide> <ide> if (strpos($path, APP) === 0) { <ide> return str_replace(APP, 'APP/', $path); <del> } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) { <add> } <add> if (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) { <ide> return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path); <del> } elseif (strpos($path, ROOT) === 0) { <add> } <add> if (strpos($path, ROOT) === 0) { <ide> return str_replace(ROOT, 'ROOT', $path); <ide> } <ide> <ide><path>src/Event/EventManager.php <ide> protected function _detachSubscriber(EventListenerInterface $subscriber, $eventK <ide> $events = (array)$subscriber->implementedEvents(); <ide> if (!empty($eventKey) && empty($events[$eventKey])) { <ide> return; <del> } elseif (!empty($eventKey)) { <add> } <add> if (!empty($eventKey)) { <ide> $events = [$eventKey => $events[$eventKey]]; <ide> } <ide> foreach ($events as $key => $function) { <ide><path>src/Filesystem/File.php <ide> public function name() <ide> } <ide> if (isset($this->info['extension'])) { <ide> return basename($this->name, '.' . $this->info['extension']); <del> } elseif ($this->name) { <add> } <add> if ($this->name) { <ide> return $this->name; <ide> } <ide> return false; <ide><path>src/Network/Request.php <ide> protected static function _url($config) <ide> { <ide> if (!empty($_SERVER['PATH_INFO'])) { <ide> return $_SERVER['PATH_INFO']; <del> } elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) { <add> } <add> if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) { <ide> $uri = $_SERVER['REQUEST_URI']; <ide> } elseif (isset($_SERVER['REQUEST_URI'])) { <ide> $qPosition = strpos($_SERVER['REQUEST_URI'], '?'); <ide> public function referer($local = false) <ide> $ref = '/' . $ref; <ide> } <ide> return $ref; <del> } elseif (!$local) { <add> } <add> if (!$local) { <ide> return $ref; <ide> } <ide> } <ide><path>src/ORM/Association/HasMany.php <ide> protected function _unlink(array $foreignKey, Table $target, array $conditions = <ide> $ok = $ok && $target->delete($assoc, $options); <ide> } <ide> return $ok; <del> } else { <del> $target->deleteAll($conditions); <del> return true; <ide> } <del> } else { <del> $updateFields = array_fill_keys($foreignKey, null); <del> $target->updateAll($updateFields, $conditions); <del> return true; <ide> <add> $target->deleteAll($conditions); <add> return true; <ide> } <add> <add> $updateFields = array_fill_keys($foreignKey, null); <add> $target->updateAll($updateFields, $conditions); <add> return true; <ide> } <ide> <ide> /** <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> protected function _scope($query) <ide> <ide> if (is_array($config['scope'])) { <ide> return $query->where($config['scope']); <del> } elseif (is_callable($config['scope'])) { <add> } <add> if (is_callable($config['scope'])) { <ide> return $config['scope']($query); <ide> } <ide> <ide><path>src/Routing/Route/Route.php <ide> public function match(array $url, array $context = []) <ide> $numeric = is_numeric($key); <ide> if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) { <ide> continue; <del> } elseif ($numeric) { <add> } <add> if ($numeric) { <ide> $pass[] = $value; <ide> unset($url[$key]); <ide> continue; <ide><path>src/Routing/Router.php <ide> public static function url($url = null, $full = false) <ide> $output = static::fullBaseUrl() . $output; <ide> } <ide> return $output; <del> } elseif (is_array($url)) { <add> } <add> if (is_array($url)) { <ide> if (isset($url['_full']) && $url['_full'] === true) { <ide> $full = true; <ide> unset($url['_full']); <ide><path>src/Shell/Task/ExtractTask.php <ide> protected function _getPaths() <ide> $this->err('Extract Aborted'); <ide> $this->_stop(); <ide> return; <del> } elseif (strtoupper($response) === 'D' && count($this->_paths)) { <add> } <add> if (strtoupper($response) === 'D' && count($this->_paths)) { <ide> $this->out(); <ide> return; <del> } elseif (strtoupper($response) === 'D') { <add> } <add> if (strtoupper($response) === 'D') { <ide> $this->err('<warning>No directories selected.</warning> Please choose a directory.'); <ide> } elseif (is_dir($response)) { <ide> $this->_paths[] = $response; <ide> public function main() <ide> $this->err('Extract Aborted'); <ide> $this->_stop(); <ide> return; <del> } elseif ($this->_isPathUsable($response)) { <add> } <add> if ($this->_isPathUsable($response)) { <ide> $this->_output = $response . DS; <ide> break; <del> } else { <del> $this->err(''); <del> $this->err( <del> '<error>The directory path you supplied was ' . <del> 'not found. Please try again.</error>' <del> ); <ide> } <add> <add> $this->err(''); <add> $this->err( <add> '<error>The directory path you supplied was ' . <add> 'not found. Please try again.</error>' <add> ); <ide> $this->out(); <ide> } <ide> } <ide><path>src/TestSuite/TestCase.php <ide> public function assertHtml($expected, $string, $fullDebug = false) <ide> $attrs[] = $matches[1]; <ide> $explanations[] = sprintf('Regex "%s" matches', $matches[1]); <ide> continue; <add> } <add> <add> $quotes = '["\']'; <add> if (is_numeric($attr)) { <add> $attr = $val; <add> $val = '.+?'; <add> $explanations[] = sprintf('Attribute "%s" present', $attr); <add> } elseif (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { <add> $val = str_replace( <add> ['.*', '.+'], <add> ['.*?', '.+?'], <add> $matches[1] <add> ); <add> $quotes = $val !== $matches[1] ? '["\']' : '["\']?'; <add> <add> $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val); <ide> } else { <del> $quotes = '["\']'; <del> if (is_numeric($attr)) { <del> $attr = $val; <del> $val = '.+?'; <del> $explanations[] = sprintf('Attribute "%s" present', $attr); <del> } elseif (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { <del> $val = str_replace( <del> ['.*', '.+'], <del> ['.*?', '.+?'], <del> $matches[1] <del> ); <del> $quotes = $val !== $matches[1] ? '["\']' : '["\']?'; <del> <del> $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val); <del> } else { <del> $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val); <del> $val = preg_quote($val, '/'); <del> } <del> $attrs[] = '[\s]+' . preg_quote($attr, '/') . '=' . $quotes . $val . $quotes; <add> $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val); <add> $val = preg_quote($val, '/'); <ide> } <add> $attrs[] = '[\s]+' . preg_quote($attr, '/') . '=' . $quotes . $val . $quotes; <ide> $i++; <ide> } <ide> if ($attrs) { <ide><path>src/Utility/Text.php <ide> public static function truncate($text, $length = 100, array $options = []) <ide> <ide> $truncate .= mb_substr($tag[3], 0, $left + $entitiesLength); <ide> break; <del> } else { <del> $truncate .= $tag[3]; <del> $totalLength += $contentLength; <ide> } <add> <add> $truncate .= $tag[3]; <add> $totalLength += $contentLength; <ide> if ($totalLength >= $length) { <ide> break; <ide> } <ide><path>src/View/Form/EntityContext.php <ide> public function val($field) <ide> <ide> if ($entity instanceof EntityInterface) { <ide> return $entity->get(array_pop($parts)); <del> } elseif (is_array($entity)) { <add> } <add> if (is_array($entity)) { <ide> $key = array_pop($parts); <ide> return isset($entity[$key]) ? $entity[$key] : null; <ide> } <ide><path>src/View/Helper/FormHelper.php <ide> protected function _secure($lock, $field, $value = null) <ide> if (!in_array($field, $this->fields)) { <ide> if ($value !== null) { <ide> return $this->fields[$field] = $value; <del> } elseif (isset($this->fields[$field]) && $value === null) { <add> } <add> if (isset($this->fields[$field]) && $value === null) { <ide> unset($this->fields[$field]); <ide> } <ide> $this->fields[] = $field; <ide><path>src/View/Helper/RssHelper.php <ide> public function item($att = [], $elements = []) <ide> } <ide> $elements[$key] = implode('', $categories); <ide> continue 2; <del> } elseif (is_array($val) && isset($val['domain'])) { <add> } <add> if (is_array($val) && isset($val['domain'])) { <ide> $attrib['domain'] = $val['domain']; <ide> } <ide> break; <ide><path>src/View/SerializedView.php <ide> public function render($view = null, $layout = null) <ide> <ide> if ($serialize !== false) { <ide> return $this->_serialize($serialize); <del> } elseif ($view !== false && $this->_getViewFileName($view)) { <add> } <add> if ($view !== false && $this->_getViewFileName($view)) { <ide> return parent::render($view, false); <ide> } <ide> }
19
Text
Text
add v3.10.0 to changelog
24e4292d0720bdad45c84b5cb30f0e7ea6d391cd
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.10.0-beta.5 (April 29, 2019) <add>### v3.10.0 (May 13, 2019) <ide> <add>- [#17836](https://github.com/emberjs/ember.js/pull/17836) [BREAKING] Explicitly drop support for Node 6 <add>- [#17719](https://github.com/emberjs/ember.js/pull/17719) / [#17745](https://github.com/emberjs/ember.js/pull/17745) [FEATURE] Support for nested components in angle bracket invocation syntax (see [emberjs/rfcs#0457](https://github.com/emberjs/rfcs/blob/master/text/0457-nested-lookups.md)). <add>- [#17735](https://github.com/emberjs/ember.js/pull/17735) / [#17772](https://github.com/emberjs/ember.js/pull/17772) / [#17811](https://github.com/emberjs/ember.js/pull/17811) / [#17814](https://github.com/emberjs/ember.js/pull/17814) [FEATURE] Implement the Angle Bracket Invocations For Built-in Components RFC (see [emberjs/rfcs#0459](https://github.com/emberjs/rfcs/blob/master/text/0459-angle-bracket-built-in-components.md)). <add>- [#17548](https://github.com/emberjs/ember.js/pull/17548) / [#17604](https://github.com/emberjs/ember.js/pull/17604) / [#17690](https://github.com/emberjs/ember.js/pull/17690) / [#17827](https://github.com/emberjs/ember.js/pull/17827) / [#17828](https://github.com/emberjs/ember.js/pull/17828) [FEATURE] Implement the Decorators RFC (see [emberjs/rfcs#0408](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md)). <add>- [#17256](https://github.com/emberjs/ember.js/pull/17256) / [#17664](https://github.com/emberjs/ember.js/pull/17664) [FEATURE] Implement RouteInfo Metadata RFC (see [emberjs/rfcs#0398](https://github.com/emberjs/rfcs/blob/master/text/0398-RouteInfo-Metadata.md)). <ide> - [#17938](https://github.com/emberjs/ember.js/pull/17938) [BUGFIX] Expose mechanism to detect if a property is a computed <ide> - [#17974](https://github.com/emberjs/ember.js/pull/17974) [BUGFIX] Ensure inheritable observers on object proxies are string based <del> <del>### v3.10.0-beta.4 (April 22, 2019) <del> <ide> - [#17930](https://github.com/emberjs/ember.js/pull/17930) [BUGFIX] Update assertion for events in tagless component to include method names <del> <del>### v3.10.0-beta.3 (April 15, 2019) <del> <ide> - [#17859](https://github.com/emberjs/ember.js/pull/17859) [BUGFIX] Fixes a regression in the legacy build <ide> - [#17891](https://github.com/emberjs/ember.js/pull/17891) [BUGFIX] Loosen "engines" restriction for Node versions <ide> - [#17900](https://github.com/emberjs/ember.js/pull/17900) [BUGFIX] Fix version for APP_CTRL_ROUTER_PROPS deprecation flag <del> <del>### v3.9.1 (April 09, 2019) <del> <del>- [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes, depending on its position. <del>- [#17874](https://github.com/emberjs/ember.js/pull/17874) [BUGFIX] Fix issue with `event.stopPropagation()` in component event handlers when jQuery is disabled. <del>- [#17876](https://github.com/emberjs/ember.js/pull/17876) [BUGFIX] Fix issue with multiple `{{action}}` modifiers on the same element when jQuery is disabled. <del> <del>### v3.10.0-beta.2 (April 08, 2019) <del> <ide> - [#17846](https://github.com/emberjs/ember.js/pull/17846) [BUGFIX] Fix issues with template-only components causing errors in subsequent updates. <del>- [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes unexpectedly, depending on its position. <ide> - [#17872](https://github.com/emberjs/ember.js/pull/17872) [BUGFIX] Fix issue where `{{link-to}}` is causing unexpected local variable shadowing assertions. <del>- [#17874](https://github.com/emberjs/ember.js/pull/17874) [BUGFIX] Fix issue with `event.stopPropagation()` in component event handlers when jQuery is disabled. <del>- [#17876](https://github.com/emberjs/ember.js/pull/17876) [BUGFIX] Fix issue with multiple `{{action}}` modifiers on the same element when jQuery is disabled. <ide> - [#17841](https://github.com/emberjs/ember.js/pull/17841) [BUGFIX] Ensure `@sort` works on non-`Ember.Object`s. <ide> - [#17855](https://github.com/emberjs/ember.js/pull/17855) [BUGFIX] Expose (private) computed `_getter` functions. <ide> - [#17860](https://github.com/emberjs/ember.js/pull/17860) [BUGFIX] Add assertions for required parameters in computed macros, when used as a decorator. <ide> - [#17868](https://github.com/emberjs/ember.js/pull/17868) [BUGFIX] Fix controller injection via decorators. <del> <del>### v3.10.0-beta.1 (April 02, 2019) <del> <del>- [#17836](https://github.com/emberjs/ember.js/pull/17836) [BREAKING] Explicitly drop support for Node 6 <del>- [#17719](https://github.com/emberjs/ember.js/pull/17719) / [#17745](https://github.com/emberjs/ember.js/pull/17745) [FEATURE] Support for nested components in angle bracket invocation syntax (see [emberjs/rfcs#0457](https://github.com/emberjs/rfcs/blob/master/text/0457-nested-lookups.md)). <del>- [#17735](https://github.com/emberjs/ember.js/pull/17735) / [#17772](https://github.com/emberjs/ember.js/pull/17772) / [#17811](https://github.com/emberjs/ember.js/pull/17811) / [#17814](https://github.com/emberjs/ember.js/pull/17814) [FEATURE] Implement the Angle Bracket Invocations For Built-in Components RFC (see [emberjs/rfcs#0459](https://github.com/emberjs/rfcs/blob/master/text/0459-angle-bracket-built-in-components.md)). <del>- [#17548](https://github.com/emberjs/ember.js/pull/17548) / [#17604](https://github.com/emberjs/ember.js/pull/17604) / [#17690](https://github.com/emberjs/ember.js/pull/17690) / [#17827](https://github.com/emberjs/ember.js/pull/17827) / [#17828](https://github.com/emberjs/ember.js/pull/17828) [FEATURE] Implement the Decorators RFC (see [emberjs/rfcs#0408](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md)). <del>- [#17256](https://github.com/emberjs/ember.js/pull/17256) / [#17664](https://github.com/emberjs/ember.js/pull/17664) [FEATURE] Implement RouteInfo Metadata RFC (see [emberjs/rfcs#0398](https://github.com/emberjs/rfcs/blob/master/text/0398-RouteInfo-Metadata.md)). <ide> - [#17747](https://github.com/emberjs/ember.js/pull/17747) [BUGFIX] Correct component-test blueprint for ember-cli-mocha <ide> - [#17788](https://github.com/emberjs/ember.js/pull/17788) [BUGFIX] Fix native DOM events in Glimmer Angle Brackets <ide> - [#17833](https://github.com/emberjs/ember.js/pull/17833) [BUGFIX] Reverts the naming of setClassicDecorator externally <del>- [#17841](https://github.com/emberjs/ember.js/pull/17841) [BUGFIX] Ensure @sort works on non-Ember.Objects. <del>- [#17818](https://github.com/emberjs/ember.js/pull/17818) [BUGFIX] Fix event dispatcher to not rely on `elementId`. <ide> - [#17818](https://github.com/emberjs/ember.js/pull/17818) [BUGFIX] Fix event dispatcher to not rely on `elementId`. <add>- [#17740](https://github.com/emberjs/ember.js/pull/17740) [BUGFIX] Fix octane component blueprint and octane blueprint tests <ide> - [#17411](https://github.com/emberjs/ember.js/pull/17411) / [#17732](https://github.com/emberjs/ember.js/pull/17732) / [#17412](https://github.com/emberjs/ember.js/pull/17412) Update initializer blueprints for ember-mocha 0.14 <ide> - [#17702](https://github.com/emberjs/ember.js/pull/17702) Extend from glimmer component for octane blueprint <del>- [#17740](https://github.com/emberjs/ember.js/pull/17740) Fix octane component blueprint and octane blueprint tests <add> <add>### v3.9.1 (April 09, 2019) <add> <add>- [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes, depending on its position. <add>- [#17874](https://github.com/emberjs/ember.js/pull/17874) [BUGFIX] Fix issue with `event.stopPropagation()` in component event handlers when jQuery is disabled. <add>- [#17876](https://github.com/emberjs/ember.js/pull/17876) [BUGFIX] Fix issue with multiple `{{action}}` modifiers on the same element when jQuery is disabled. <ide> <ide> ### v3.8.1 (April 02, 2019) <ide>
1
Ruby
Ruby
remove wrong usage for `arel_table` [ci skip]
1536a2bddbd4b775dbc1916841c137140a29d71a
<ide><path>activerecord/lib/active_record/core.rb <ide> def ===(object) # :nodoc: <ide> end <ide> <ide> # Returns an instance of <tt>Arel::Table</tt> loaded with the current table name. <del> # <del> # class Post < ActiveRecord::Base <del> # scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) } <del> # end <ide> def arel_table # :nodoc: <ide> @arel_table ||= Arel::Table.new(table_name, klass: self) <ide> end
1
Python
Python
fix last element in hidden_states for xglm
4b2774832d1d70ea03d85b2b93e42d7f328d5150
<ide><path>src/transformers/models/xglm/modeling_flax_xglm.py <ide> def __call__( <ide> last_hidden_states = outputs[0] <ide> last_hidden_states = self.layer_norm(last_hidden_states) <ide> <add> hidden_states = None <add> if output_hidden_states: <add> hidden_states = outputs[1] <add> hidden_states = hidden_states[:-1] + (last_hidden_states,) <add> <ide> if not return_dict: <del> outputs = (last_hidden_states,) + outputs[1:] <add> outputs = (last_hidden_states, hidden_states) + (outputs[2:] if output_hidden_states else outputs[1:]) <ide> return tuple(v for v in outputs if v is not None) <ide> <ide> return FlaxBaseModelOutputWithPastAndCrossAttentions( <ide> last_hidden_state=last_hidden_states, <del> hidden_states=outputs.hidden_states, <add> hidden_states=hidden_states, <ide> attentions=outputs.attentions, <ide> cross_attentions=outputs.cross_attentions, <ide> )
1
Go
Go
log error from unmountvolumes on cleanup
a20fea1823ccfb40d235607e8f7ce7ceff1b5afe
<ide><path>daemon/container.go <ide> func (container *Container) cleanup() { <ide> container.daemon.unregisterExecCommand(eConfig) <ide> } <ide> <del> container.unmountVolumes(false) <add> if err := container.unmountVolumes(false); err != nil { <add> logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err) <add> } <ide> } <ide> <ide> // killSig sends the container the given signal. This wrapper for the <ide><path>pkg/system/syscall_unix.go <ide> import "syscall" <ide> <ide> // Unmount is a platform-specific helper function to call <ide> // the unmount syscall. <del>func Unmount(dest string) { <del> syscall.Unmount(dest, 0) <add>func Unmount(dest string) error { <add> return syscall.Unmount(dest, 0) <ide> } <ide><path>pkg/system/syscall_windows.go <ide> package system <ide> <ide> // Unmount is a platform-specific helper function to call <ide> // the unmount syscall. Not supported on Windows <del>func Unmount(dest string) { <add>func Unmount(dest string) error { <add> return nil <ide> }
3
Javascript
Javascript
remove unnecessary string copies
2ac0aff2839a75aecd2c0c0166ea26c317ef4438
<ide><path>lib/path.js <ide> const win32 = { <ide> } <ide> } <ide> } else if (code === 47/*/*/ || code === 92/*\*/) { <del> return path[0]; <add> // `path` contains just a path separator, exit early to avoid <add> // unnecessary work <add> return path; <ide> } <ide> <ide> for (var i = len - 1; i >= offset; --i) { <ide> const win32 = { <ide> if (len === 3) { <ide> // `path` contains just a drive root, exit early to avoid <ide> // unnecessary work <del> ret.root = ret.dir = path.slice(0, 3); <add> ret.root = ret.dir = path; <ide> return ret; <ide> } <ide> isAbsolute = true; <ide> const win32 = { <ide> } else { <ide> // `path` contains just a drive root, exit early to avoid <ide> // unnecessary work <del> ret.root = ret.dir = path.slice(0, 2); <add> ret.root = ret.dir = path; <ide> return ret; <ide> } <ide> } <ide> } <ide> } else if (code === 47/*/*/ || code === 92/*\*/) { <ide> // `path` contains just a path separator, exit early to avoid <ide> // unnecessary work <del> ret.root = ret.dir = path[0]; <add> ret.root = ret.dir = path; <ide> return ret; <ide> } <ide>
1
Text
Text
add amp docs to readme
016c197b7f3dabedbc354fc73c794da34338ec08
<ide><path>packages/next/README.md <ide> - [One Level Lower](#one-level-lower) <ide> - [Summary](#summary) <ide> - [Browser support](#browser-support) <add>- [AMP Support](#amp-support) <ide> - [Static HTML export](#static-html-export) <ide> - [Usage](#usage) <ide> - [Copying custom files](#copying-custom-files) <ide> Next.js supports IE11 and all modern browsers out of the box using [`@babel/pres <ide> <ide> The [polyfills](https://github.com/zeit/next.js/tree/canary/examples/with-polyfills) example demonstrates the recommended approach to implement polyfills. <ide> <add>## AMP Support <add> <add>### Enabling AMP Support <add> <add>To enable AMP support for a page, first enable experimental AMP support in your `next.config.js` and then import `withAmp` from `next/amp` and wrap your page's component in it. <add> <add>```js <add>// next.config.js <add>module.exports = { <add> experimental: { amp: true } <add>} <add> <add>// pages/about.js <add>import { withAmp } from 'next/amp' <add> <add>export default withAmp(function AboutPage(props) { <add> return ( <add> <h3>My AMP About Page!</h3> <add> ) <add>}) <add>``` <add> <add>### AMP Page Modes <add> <add>AMP pages can specify two modes: <add> <add>- AMP-only (default) <add> - Pages have no Next.js or React client-side runtime <add> - Pages are automatically optimized with [AMP Optimizer](https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer), an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%) <add> - Pages have a user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page <add> - Opt-in via `withAmp(Component)` <add>- Hybrid <add> - Pages are able to be rendered as traditional HTML (default) and AMP HTML (by adding `?amp=1` to the URL) <add> - The AMP version of the page is not optimized with AMP Optimizer so that it is indexable by search-engines <add> - Opt-in via `withAmp(Component, { hybrid: true })` <add> <add>Both of these page modes provide a consistently fast experience for users accessing pages through search engines. <add> <add>### AMP Behavior with `next export` <add> <add>When using `next export` to statically pre-render pages Next.js will detect if the page supports AMP and change the exporting behavior based on that. <add> <add>Hybrid AMP (`pages/about.js`) would output: <add> <add>- `out/about/index.html` - with client-side React runtime <add>- `out/about.amp/index.html` - AMP page <add> <add>AMP-only (`pages/about.js`) would output: <add> <add>- `out/about/index.html` - Optimized AMP page <add>- `out/about.amp/index.html` - AMP page <add> <add>During export Next.js automatically detects if a page is AMP-only and apply dirty/clean optimizations. The dirty version will be output to `page/index.html` and the clean version will be output to `page.amp/index.html`. We also automatically insert the `<link rel="amphtml" href="/page.amp" />` and `<link rel="canonical" href="/" />` tags for you. <add> <add>### Adding AMP Components <add> <add>The AMP community provides [many components](https://amp.dev/documentation/components/) to make AMP pages more interactive. You can add these components to your page by using `next/head`: <add> <add>```js <add>// pages/hello.js <add>import Head from 'next/head' <add>import { withAmp } from 'next/amp' <add> <add>export default withAmp(function MyAmpPage() { <add> return ( <add> <div> <add> <Head> <add> <script <add> async <add> key="amp-timeago" <add> custom-element="amp-timeago" <add> src="https://cdn.ampproject.org/v0/amp-timeago-0.1.js" <add> /> <add> </Head> <add> <add> <p>Some time: {date.toJSON()}</p> <add> <amp-timeago <add> width="0" <add> height="15" <add> datetime={date.toJSON()} <add> layout="responsive" <add> > <add> . <add> </amp-timeago> <add> </div> <add> ) <add>}) <add>``` <add> <add>### AMP Validation <add> <add>AMP pages are automatically validated with [amphtml-validator](https://www.npmjs.com/package/amphtml-validator) during development. Errors and warnings will appear in the terminal where you started Next.js. <add> <add>Pages are also validated during `next export` and any warnings / errors will be printed to the terminal. <add>Any AMP errors will cause `next export` to exit with status code `1` because the export is not valid AMP. <add> <ide> ## Static HTML export <ide> <ide> <details>
1
Text
Text
add activity theme
dcd7591c6e8b7035711b381a4f41c5cfafaa40d6
<ide><path>docs/IntegrationWithExistingApps.md <ide> public class MyReactActivity extends Activity implements DefaultHardwareBackBtnH <ide> } <ide> } <ide> ``` <add>We need set the theme of `MyReactActivity` to `Theme.AppCompat.Light.NoActionBar` beause some components rely on this theme. <add>```xml <add><activity <add> android:name=".MyReactActivity" <add> android:label="@string/app_name" <add> android:theme="@style/Theme.AppCompat.Light.NoActionBar"> <add></activity> <add>``` <add> <add> <ide> <ide> > A `ReactInstanceManager` can be shared amongst multiple activities and/or fragments. You will want to make your own `ReactFragment` or `ReactActivity` and have a singleton *holder* that holds a `ReactInstanceManager`. When you need the `ReactInstanceManager` (e.g., to hook up the `ReactInstanceManager` to the lifecycle of those Activities or Fragments) use the one provided by the singleton. <ide>
1
Python
Python
add changes to run tests again
9f6c1cc11f58cb6ce48e188b6457c2ab5f2e8515
<ide><path>numpy/core/_add_newdocs.py <ide> <ide> See Also <ide> -------- <del> vectorize : evaluates pyfunc over input arrays using broadcasting rules of numpy <add> vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy. <ide> <ide> Notes <ide> -----
1
Ruby
Ruby
fix url connections for sqlite3
fbb79b517f3127ba620fedd01849f9628b78d6ce
<ide><path>activerecord/lib/active_record/connection_adapters/connection_specification.rb <ide> def connection_url_to_hash(url) # :nodoc: <ide> config = URI.parse url <ide> adapter = config.scheme <ide> adapter = "postgresql" if adapter == "postgres" <add> <add> database = if adapter == 'sqlite3' <add> if '/:memory:' == config.path <add> ':memory:' <add> else <add> config.path <add> end <add> else <add> config.path.sub(%r{^/},"") <add> end <add> <ide> spec = { :adapter => adapter, <ide> :username => config.user, <ide> :password => config.password, <ide> :port => config.port, <del> :database => config.path.sub(%r{^/},""), <add> :database => database, <ide> :host => config.host } <ide> <ide> spec.reject!{ |_,value| value.blank? } <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb <ide> # encoding: utf-8 <ide> require "cases/helper" <ide> require 'models/owner' <add>require 'tempfile' <ide> <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> def setup <ide> ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber) <ide> end <ide> <add> def test_connect_with_url <add> original_connection = ActiveRecord::Base.remove_connection <add> tf = Tempfile.open 'whatever' <add> url = "sqlite3://#{tf.path}" <add> ActiveRecord::Base.establish_connection(url) <add> assert ActiveRecord::Base.connection <add> ensure <add> tf.close <add> tf.unlink <add> ActiveRecord::Base.establish_connection(original_connection) <add> end <add> <add> def test_connect_memory_with_url <add> original_connection = ActiveRecord::Base.remove_connection <add> url = "sqlite3:///:memory:" <add> ActiveRecord::Base.establish_connection(url) <add> assert ActiveRecord::Base.connection <add> ensure <add> ActiveRecord::Base.establish_connection(original_connection) <add> end <add> <ide> def test_valid_column <ide> column = @conn.columns('items').find { |col| col.name == 'id' } <ide> assert @conn.valid_type?(column.type)
2
Ruby
Ruby
mark some methods as protected
bdece49b05d4fdf5bfec1ad71ca6232e43ddb4ab
<ide><path>Library/Homebrew/version.rb <ide> def to_s <ide> @elem.to_s <ide> end <ide> <add> protected <add> <add> attr_reader :elem <add> <ide> def string? <del> @elem.is_a? String <add> elem.is_a? String <ide> end <ide> <ide> def numeric? <del> @elem.is_a? Numeric <add> elem.is_a? Numeric <ide> end <del> <del> protected <del> <del> attr_reader :elem <ide> end <ide> <ide> class Version
1
Javascript
Javascript
keep track of openedpath when relativizing
0c839a91fb0bbae547647aaec94916eefbe71a1a
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> // Returns a {Promise} which resolves to the relative {String} path. <ide> relativizeToWorkingDirectory (_path) { <ide> return this.getRepo() <del> .then(repo => this.relativize(_path, repo.workdir())) <add> .then((repo) => { <add> const workingDirectory = repo.workdir() <add> let openedWorkingDirectory = null <add> const opened = this.openedPath.replace(/\/\.git$/, '') <add> if (path.relative(opened, workingDirectory) != '') { <add> openedWorkingDirectory = opened <add> } <add> return this.relativize(_path, workingDirectory, openedWorkingDirectory) <add> } <add> ) <ide> } <ide> <ide> // Public: Makes a path relative to the repository's working directory. <ide> export default class GitRepositoryAsync { <ide> // * `workingDirectory` The {String} working directory path. <ide> // <ide> // Returns the relative {String} path. <del> relativize (_path, workingDirectory) { <del> // Cargo-culted from git-utils. The original implementation also handles <del> // this.openedWorkingDirectory, which is set by git-utils when the <del> // repository is opened. Those branches of the if tree aren't included here <del> // yet, but if we determine we still need that here it should be simple to <del> // port. <del> // <add> relativize (_path, workingDirectory, openedWorkingDirectory) { <ide> // The original implementation also handled null workingDirectory as it <ide> // pulled it from a sync function that could return null. We require it <ide> // to be passed here. <ide> export default class GitRepositoryAsync { <ide> // prefix. Standardize by stripping that out. <ide> _path = _path.replace(/^\/private\//, '/') <ide> workingDirectory = workingDirectory.replace(/^\/private\//, '/') <add> if (openedWorkingDirectory) { <add> openedWorkingDirectory = openedWorkingDirectory.replace(/^\/private\//, '/') <add> } <ide> <ide> if (process.platform === 'win32') { <ide> _path = _path.replace(/\\/g, '/') <ide> export default class GitRepositoryAsync { <ide> } <ide> } <ide> <del> if (!/\/$/.test(workingDirectory)) { <del> workingDirectory = `${workingDirectory}/` <add> if (openedWorkingDirectory) { <add> workingDirectory = openedWorkingDirectory <ide> } <ide> <add> workingDirectory = workingDirectory.replace(/\/$/, '') <add> <ide> const originalPath = _path <ide> if (this.isCaseInsensitive) { <ide> _path = _path.toLowerCase() <ide> workingDirectory = workingDirectory.toLowerCase() <ide> } <ide> <ide> if (_path.indexOf(workingDirectory) === 0) { <del> return originalPath.substring(workingDirectory.length) <add> return originalPath.substring(workingDirectory.length + 1) <ide> } else if (_path === workingDirectory) { <ide> return '' <ide> }
1
PHP
PHP
fix missed use of version
6d3ae3b83cc0ad7f2551ad4d35819cb56129cb30
<ide><path>lib/Cake/Test/Case/Event/CakeEventManagerTest.php <ide> public function testDispatchWithKeyName() { <ide> */ <ide> public function testDispatchReturnValue() { <ide> $this->skipIf( <del> version_compare(PHPUnit_Runner_Version::VERSION, '3.7', '<'), <add> version_compare(PHPUnit_Runner_Version::id(), '3.7', '<'), <ide> 'These tests fail in PHPUnit 3.6' <ide> ); <ide> $manager = new CakeEventManager;
1
Javascript
Javascript
increase disconnect timeout
751f058f3095e5c9487925a92ee7cbdd15d043ba
<ide><path>karma-shared.conf.js <ide> module.exports = function(config, specificOptions) { <ide> logLevel: config.LOG_INFO, <ide> logColors: true, <ide> browsers: ['Chrome'], <del> browserDisconnectTimeout: 5000, <add> browserDisconnectTimeout: 10000, <ide> <ide> <ide> // config for Travis CI
1
Javascript
Javascript
add optional name prop to rntester example
66615171620f626953e9f93c94fcb2ecb40381c3
<ide><path>packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js <ide> module.exports = ([ <ide> }, <ide> }, <ide> { <add> name: 'maxLength', <ide> title: "Live Re-Write (<sp> -> '_') + maxLength", <ide> render: function(): React.Node { <ide> return <RewriteExample />; <ide> module.exports = ([ <ide> }, <ide> }, <ide> { <add> name: 'clearInput', <ide> title: 'Live Re-Write (no spaces allowed) and clear', <ide> render: function(): React.Node { <ide> return <RewriteInvalidCharactersAndClearExample />; <ide><path>packages/rn-tester/js/types/RNTesterTypes.js <ide> import * as React from 'react'; <ide> <ide> export type RNTesterExampleModuleItem = $ReadOnly<{| <add> name?: string, <ide> title: string, <ide> platform?: string, <ide> description?: string,
2
Go
Go
add samehostdaemon req
8a9878081f8e14a54067f249bc98ae66f0b61ba3
<ide><path>integration-cli/docker_api_ipcmode_test.go <ide> func (s *DockerSuite) TestAPIIpcModeNone(c *check.C) { <ide> * such pair on the host. <ide> */ <ide> func (s *DockerSuite) TestAPIIpcModePrivate(c *check.C) { <del> testRequires(c, DaemonIsLinux) <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> testIpcNonePrivateShareable(c, "private", true, false) <ide> } <ide> <ide> func (s *DockerSuite) TestAPIIpcModePrivate(c *check.C) { <ide> * also exists on the host. <ide> */ <ide> func (s *DockerSuite) TestAPIIpcModeShareable(c *check.C) { <del> testRequires(c, DaemonIsLinux) <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> testIpcNonePrivateShareable(c, "shareable", true, true) <ide> } <ide> <ide> func (s *DockerSuite) TestAPIIpcModePrivateAndContainer(c *check.C) { <ide> * can use IPC of the host system. <ide> */ <ide> func (s *DockerSuite) TestAPIIpcModeHost(c *check.C) { <del> testRequires(c, DaemonIsLinux, NotUserNamespace) <add> testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) <ide> <ide> cfg := container.Config{ <ide> Image: "busybox", <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func testDaemonIpcPrivateShareable(d *daemon.Daemon, c *check.C, mustExist bool) <ide> <ide> // TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended. <ide> func (s *DockerDaemonSuite) TestDaemonIpcModeShareable(c *check.C) { <del> testRequires(c, DaemonIsLinux) <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> <ide> s.d.StartWithBusybox(c, "--default-ipc-mode", "shareable") <ide> testDaemonIpcPrivateShareable(s.d, c, true) <ide> } <ide> <ide> // TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended. <ide> func (s *DockerDaemonSuite) TestDaemonIpcModePrivate(c *check.C) { <del> testRequires(c, DaemonIsLinux) <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> <ide> s.d.StartWithBusybox(c, "--default-ipc-mode", "private") <ide> testDaemonIpcPrivateShareable(s.d, c, false) <ide> func testDaemonIpcFromConfig(s *DockerDaemonSuite, c *check.C, mode string, must <ide> <ide> // TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended. <ide> func (s *DockerDaemonSuite) TestDaemonIpcModePrivateFromConfig(c *check.C) { <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> testDaemonIpcFromConfig(s, c, "private", false) <ide> } <ide> <ide> // TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended. <ide> func (s *DockerDaemonSuite) TestDaemonIpcModeShareableFromConfig(c *check.C) { <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <ide> testDaemonIpcFromConfig(s, c, "shareable", true) <ide> } <ide> <ide> func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { <del> testRequires(c, DaemonIsLinux) <del> <ide> d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ <ide> Experimental: testEnv.ExperimentalDaemon(), <ide> }) <ide> func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { <ide> // arguments for default IPC mode, and bails out with incorrect ones. <ide> // Both CLI option (--default-ipc-mode) and config parameter are tested. <ide> func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *check.C) { <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <add> <ide> ipcModes := []struct { <ide> mode string <ide> valid bool
2
Ruby
Ruby
call the class method to define the callbacks
0af978d33489c3ab54084c26d1354837b16f0cf5
<ide><path>activerecord/lib/active_record/associations.rb <ide> def has_and_belongs_to_many1(name, scope = nil, options = {}, &extension) <ide> middle_options) <ide> middle_reflection = hm_builder.build self <ide> <del> hm_builder.define_callbacks self, middle_reflection <add> Builder::HasMany.define_callbacks self, middle_reflection <ide> <ide> Reflection.add_reflection self, middle_reflection.name, middle_reflection <ide>
1
Javascript
Javascript
move array internals to ember-metal
27de208c87685aa3ea4e51ac967d23da15e0181c
<ide><path>packages/ember-extension-support/lib/data_adapter.js <ide> import { getOwner } from 'ember-utils'; <del>import { get, run, objectAt } from 'ember-metal'; <add>import { <add> get, <add> run, <add> objectAt, <add> addArrayObserver, <add> removeArrayObserver <add>} from 'ember-metal'; <ide> import { <ide> String as StringUtils, <ide> Namespace, <ide> Object as EmberObject, <ide> A as emberA, <del> addArrayObserver, <del> removeArrayObserver <ide> } from 'ember-runtime'; <ide> <ide> /** <ide><path>packages/ember-metal/lib/array.js <add>import { notifyPropertyChange } from "./property_events"; <add>import { eachProxyArrayDidChange, eachProxyArrayWillChange } from "./each_proxy"; <add>import { peekMeta } from "./meta"; <add>import { sendEvent, removeListener, addListener } from "./events"; <add>import { peekCacheFor } from "./computed"; <add>import { get } from "./property_get"; <add> <ide> export function objectAt(content, idx) { <ide> if (typeof content.objectAt === 'function') { <ide> return content.objectAt(idx); <ide> } else { <ide> return content[idx]; <ide> } <ide> } <add> <add>function arrayObserversHelper(obj, target, opts, operation, notify) { <add> let willChange = (opts && opts.willChange) || 'arrayWillChange'; <add> let didChange = (opts && opts.didChange) || 'arrayDidChange'; <add> let hasObservers = get(obj, 'hasArrayObservers'); <add> <add> operation(obj, '@array:before', target, willChange); <add> operation(obj, '@array:change', target, didChange); <add> <add> if (hasObservers === notify) { <add> notifyPropertyChange(obj, 'hasArrayObservers'); <add> } <add> <add> return obj; <add>} <add> <add>export function addArrayObserver(array, target, opts) { <add> return arrayObserversHelper(array, target, opts, addListener, false); <add>} <add> <add>export function removeArrayObserver(array, target, opts) { <add> return arrayObserversHelper(array, target, opts, removeListener, true); <add>} <add> <add>export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { <add> // if no args are passed assume everything changes <add> if (startIdx === undefined) { <add> startIdx = 0; <add> removeAmt = addAmt = -1; <add> } else { <add> if (removeAmt === undefined) { <add> removeAmt = -1; <add> } <add> <add> if (addAmt === undefined) { <add> addAmt = -1; <add> } <add> } <add> <add> eachProxyArrayWillChange(array, startIdx, removeAmt, addAmt); <add> <add> sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); <add> <add> return array; <add>} <add> <add>export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) { <add> // if no args are passed assume everything changes <add> if (startIdx === undefined) { <add> startIdx = 0; <add> removeAmt = addAmt = -1; <add> } else { <add> if (removeAmt === undefined) { <add> removeAmt = -1; <add> } <add> <add> if (addAmt === undefined) { <add> addAmt = -1; <add> } <add> } <add> <add> if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) { <add> notifyPropertyChange(array, 'length'); <add> } <add> <add> notifyPropertyChange(array, '[]'); <add> <add> eachProxyArrayDidChange(array, startIdx, removeAmt, addAmt); <add> <add> sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]); <add> <add> let meta = peekMeta(array); <add> let cache = peekCacheFor(array); <add> if (cache !== undefined) { <add> let length = get(array, 'length'); <add> let addedAmount = (addAmt === -1 ? 0 : addAmt); <add> let removedAmount = (removeAmt === -1 ? 0 : removeAmt); <add> let delta = addedAmount - removedAmount; <add> let previousLength = length - delta; <add> <add> let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx; <add> if (cache.has('firstObject') && normalStartIdx === 0) { <add> notifyPropertyChange(array, 'firstObject', meta); <add> } <add> <add> if (cache.has('lastObject')) { <add> let previousLastIndex = previousLength - 1; <add> let lastAffectedIndex = normalStartIdx + removedAmount; <add> if (previousLastIndex < lastAffectedIndex) { <add> notifyPropertyChange(array, 'lastObject', meta); <add> } <add> } <add> } <add> <add> return array; <add>} <ide><path>packages/ember-metal/lib/index.js <ide> export { <ide> set, <ide> trySet <ide> } from './property_set'; <del>export { objectAt } from './array'; <add>export { <add> objectAt, <add> addArrayObserver, <add> removeArrayObserver, <add> arrayContentWillChange, <add> arrayContentDidChange <add>} from './array'; <ide> export { <ide> eachProxyFor, <ide> eachProxyArrayWillChange, <ide><path>packages/ember-runtime/lib/index.js <ide> export { default as isEqual } from './is-equal'; <ide> export { <ide> default as Array, <ide> isEmberArray, <del> addArrayObserver, <del> removeArrayObserver, <ide> NativeArray, <ide> A, <ide> MutableArray, <ide><path>packages/ember-runtime/lib/mixins/array.js <ide> import { <ide> isNone, <ide> aliasMethod, <ide> Mixin, <del> notifyPropertyChange, <del> addListener, <del> removeListener, <del> sendEvent, <ide> hasListeners, <del> peekMeta, <ide> eachProxyFor, <del> eachProxyArrayWillChange, <del> eachProxyArrayDidChange, <ide> beginPropertyChanges, <ide> endPropertyChanges, <del> peekCacheFor <add> addArrayObserver, <add> removeArrayObserver, <add> arrayContentWillChange, <add> arrayContentDidChange <ide> } from 'ember-metal'; <ide> import { assert, deprecate } from 'ember-debug'; <ide> import Enumerable from './enumerable'; <ide> import copy from '../copy'; <ide> import { Error as EmberError } from 'ember-debug'; <ide> import MutableEnumerable from './mutable_enumerable'; <ide> <del>function arrayObserversHelper(obj, target, opts, operation, notify) { <del> let willChange = (opts && opts.willChange) || 'arrayWillChange'; <del> let didChange = (opts && opts.didChange) || 'arrayDidChange'; <del> let hasObservers = get(obj, 'hasArrayObservers'); <del> <del> operation(obj, '@array:before', target, willChange); <del> operation(obj, '@array:change', target, didChange); <del> <del> if (hasObservers === notify) { <del> notifyPropertyChange(obj, 'hasArrayObservers'); <del> } <del> <del> return obj; <del>} <del> <del>export function addArrayObserver(array, target, opts) { <del> return arrayObserversHelper(array, target, opts, addListener, false); <del>} <del> <del>export function removeArrayObserver(array, target, opts) { <del> return arrayObserversHelper(array, target, opts, removeListener, true); <del>} <del> <del>export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { <del> // if no args are passed assume everything changes <del> if (startIdx === undefined) { <del> startIdx = 0; <del> removeAmt = addAmt = -1; <del> } else { <del> if (removeAmt === undefined) { <del> removeAmt = -1; <del> } <del> <del> if (addAmt === undefined) { <del> addAmt = -1; <del> } <del> } <del> <del> eachProxyArrayWillChange(array, startIdx, removeAmt, addAmt); <del> <del> sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); <del> <del> return array; <del>} <del> <del>export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) { <del> // if no args are passed assume everything changes <del> if (startIdx === undefined) { <del> startIdx = 0; <del> removeAmt = addAmt = -1; <del> } else { <del> if (removeAmt === undefined) { <del> removeAmt = -1; <del> } <del> <del> if (addAmt === undefined) { <del> addAmt = -1; <del> } <del> } <del> <del> if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) { <del> notifyPropertyChange(array, 'length'); <del> } <del> <del> notifyPropertyChange(array, '[]'); <del> <del> eachProxyArrayDidChange(array, startIdx, removeAmt, addAmt); <del> <del> sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]); <del> <del> let meta = peekMeta(array); <del> let cache = peekCacheFor(array); <del> if (cache !== undefined) { <del> let length = get(array, 'length'); <del> let addedAmount = (addAmt === -1 ? 0 : addAmt); <del> let removedAmount = (removeAmt === -1 ? 0 : removeAmt); <del> let delta = addedAmount - removedAmount; <del> let previousLength = length - delta; <del> <del> let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx; <del> if (cache.has('firstObject') && normalStartIdx === 0) { <del> notifyPropertyChange(array, 'firstObject', meta); <del> } <del> <del> if (cache.has('lastObject')) { <del> let previousLastIndex = previousLength - 1; <del> let lastAffectedIndex = normalStartIdx + removedAmount; <del> if (previousLastIndex < lastAffectedIndex) { <del> notifyPropertyChange(array, 'lastObject', meta); <del> } <del> } <del> } <del> <del> return array; <del>} <del> <ide> const EMBER_ARRAY = symbol('EMBER_ARRAY'); <ide> <ide> export function isEmberArray(obj) { <ide><path>packages/ember-runtime/lib/system/array_proxy.js <ide> import { <ide> objectAt, <ide> computed, <ide> alias, <del> PROPERTY_DID_CHANGE <add> PROPERTY_DID_CHANGE, <add> addArrayObserver, <add> removeArrayObserver <ide> } from 'ember-metal'; <ide> import { <ide> isArray <ide> } from '../utils'; <ide> import EmberObject from './object'; <ide> import { MutableArray } from '../mixins/array'; <del>import { <del> addArrayObserver, <del> removeArrayObserver <del>} from '../mixins/array'; <ide> import { assert } from 'ember-debug'; <ide> <ide> const ARRAY_OBSERVER_MAPPING = { <ide><path>packages/ember-runtime/tests/helpers/array.js <ide> import ArrayProxy from '../../system/array_proxy'; <ide> import EmberArray, { <ide> A as emberA, <del> MutableArray, <del> arrayContentDidChange, <del> arrayContentWillChange, <del> addArrayObserver, <del> removeArrayObserver, <add> MutableArray <ide> } from '../../mixins/array'; <ide> import { generateGuid, guidFor } from 'ember-utils'; <del>import { get, set } from 'ember-metal'; <del>import { computed } from 'ember-metal'; <add>import { <add> get, <add> set, <add> computed, <add> addArrayObserver, <add> removeArrayObserver, <add> arrayContentWillChange, <add> arrayContentDidChange <add>} from 'ember-metal'; <ide> import EmberObject from '../../system/object'; <ide> import Copyable from '../../mixins/copyable'; <ide> import { moduleFor } from 'internal-test-helpers'; <ide><path>packages/ember-runtime/tests/mixins/array_test.js <ide> import { <ide> objectAt, <ide> addObserver, <ide> observer as emberObserver, <del> computed <del>} from 'ember-metal'; <del>import { testBoth } from 'internal-test-helpers'; <del>import EmberObject from '../../system/object'; <del>import EmberArray, { <add> computed, <ide> addArrayObserver, <ide> removeArrayObserver, <ide> arrayContentDidChange, <ide> arrayContentWillChange <del>} from '../../mixins/array'; <add>} from 'ember-metal'; <add>import { testBoth } from 'internal-test-helpers'; <add>import EmberObject from '../../system/object'; <add>import EmberArray from '../../mixins/array'; <ide> import { A as emberA } from '../../mixins/array'; <ide> <ide> /*
8
Java
Java
return handlerresult in handleradapter#handle()
9516c9992f4ed53bbb0be801bed31b6280eaff8c
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/DispatcherHandler.java <ide> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse resp <ide> } <ide> <ide> HandlerAdapter handlerAdapter = getHandlerAdapter(handler); <del> Publisher<HandlerResult> resultPublisher = handlerAdapter.handle(request, response, handler); <ide> <del> return Streams.wrap(resultPublisher).concatMap((HandlerResult result) -> { <add> try { <add> HandlerResult result = handlerAdapter.handle(request, response, handler); <ide> for (HandlerResultHandler resultHandler : resultHandlers) { <ide> if (resultHandler.supports(result)) { <ide> return resultHandler.handleResult(request, response, result); <ide> } <ide> } <ide> return Streams.fail(new IllegalStateException( <ide> "No HandlerResultHandler for " + result.getValue())); <del> }); <add> } <add> catch(Exception ex) { <add> return Streams.fail(ex); <add> } <add> <ide> } <ide> <ide> protected Object getHandler(ServerHttpRequest request) { <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/HandlerAdapter.java <ide> */ <ide> package org.springframework.reactive.web.dispatch; <ide> <del>import org.reactivestreams.Publisher; <del> <ide> import org.springframework.reactive.web.http.ServerHttpRequest; <ide> import org.springframework.reactive.web.http.ServerHttpResponse; <ide> <ide> public interface HandlerAdapter { <ide> <ide> boolean supports(Object handler); <ide> <del> Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, Object handler); <add> HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, Object handler) throws Exception; <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/SimpleHandlerResultHandler.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.reactive.web.dispatch; <add> <add>import org.reactivestreams.Publisher; <add> <add>import org.springframework.core.Ordered; <add>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.reactive.web.http.ServerHttpResponse; <add> <add>/** <add> * Supports {@link HandlerResult} with a {@code Publisher<Void>} value. <add> * <add> * @author Sebastien Deleuze <add> */ <add>public class SimpleHandlerResultHandler implements Ordered, HandlerResultHandler { <add> <add> private int order = Ordered.LOWEST_PRECEDENCE; <add> <add> @Override <add> public int getOrder() { <add> return this.order; <add> } <add> <add> @Override <add> public boolean supports(HandlerResult result) { <add> Object value = result.getValue(); <add> return value != null && Publisher.class.isAssignableFrom(value.getClass()); <add> } <add> <add> @Override <add> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result) { <add> return (Publisher<Void>)result.getValue(); <add> } <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/handler/HttpHandlerAdapter.java <ide> package org.springframework.reactive.web.dispatch.handler; <ide> <ide> import org.reactivestreams.Publisher; <del>import reactor.rx.Streams; <ide> <ide> import org.springframework.reactive.web.dispatch.HandlerAdapter; <ide> import org.springframework.reactive.web.dispatch.HandlerResult; <ide> * handler mappings. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Sebastien Deleuze <ide> */ <ide> public class HttpHandlerAdapter implements HandlerAdapter { <ide> <ide> public boolean supports(Object handler) { <ide> } <ide> <ide> @Override <del> public Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, Object handler) { <del> HttpHandler httpHandler = (HttpHandler) handler; <del> Publisher<Void> publisher = httpHandler.handle(request, response); <del> return Streams.wrap(publisher).map(aVoid -> null); <add> public HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, Object handler) { <add> HttpHandler httpHandler = (HttpHandler)handler; <add> Publisher<Void> completion = httpHandler.handle(request, response); <add> return new HandlerResult(httpHandler, completion); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestMappingHandlerAdapter.java <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <del>import org.reactivestreams.Publisher; <del>import reactor.rx.Streams; <del> <ide> import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.reactive.codec.decoder.JacksonJsonDecoder; <ide> import org.springframework.reactive.codec.decoder.JsonObjectDecoder; <ide> public boolean supports(Object handler) { <ide> } <ide> <ide> @Override <del> public Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, <del> Object handler) { <add> public HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, <add> Object handler) throws Exception { <ide> <ide> final InvocableHandlerMethod invocable = new InvocableHandlerMethod((HandlerMethod) handler); <ide> invocable.setHandlerMethodArgumentResolvers(this.argumentResolvers); <ide> <del> Object result; <del> try { <del> result = invocable.invokeForRequest(request); <del> } <del> catch (Exception ex) { <del> return Streams.fail(ex); <del> } <add> Object result = invocable.invokeForRequest(request); <ide> <del> return Streams.just(new HandlerResult(invocable, result)); <add> return new HandlerResult(invocable, result); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/ResponseBodyResultHandler.java <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <ide> import java.lang.reflect.Method; <add>import java.lang.reflect.Type; <ide> import java.nio.ByteBuffer; <ide> import java.nio.charset.Charset; <ide> import java.util.ArrayList; <ide> <ide> import org.reactivestreams.Publisher; <ide> import reactor.rx.Promise; <del>import reactor.rx.Stream; <ide> import reactor.rx.Streams; <ide> import rx.Observable; <ide> import rx.RxReactiveStreams; <ide> import rx.Single; <ide> <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.Ordered; <add>import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.annotation.AnnotatedElementUtils; <ide> import org.springframework.http.HttpHeaders; <ide> public class ResponseBodyResultHandler implements HandlerResultHandler, Ordered <ide> private final List<MessageToByteEncoder<?>> serializers; <ide> private final List<MessageToByteEncoder<ByteBuffer>> postProcessors; <ide> <del> private int order = Ordered.LOWEST_PRECEDENCE; <add> private int order = 0; <ide> <ide> <ide> public ResponseBodyResultHandler(List<MessageToByteEncoder<?>> serializers) { <ide> public int getOrder() { <ide> public boolean supports(HandlerResult result) { <ide> Object handler = result.getHandler(); <ide> if (handler instanceof HandlerMethod) { <del> Method method = ((HandlerMethod) handler).getMethod(); <del> return AnnotatedElementUtils.isAnnotated(method, ResponseBody.class.getName()); <add> HandlerMethod handlerMethod = (HandlerMethod) handler; <add> Type publisherVoidType = new ParameterizedTypeReference<Publisher<Void>>(){}.getType(); <add> return AnnotatedElementUtils.isAnnotated(handlerMethod.getMethod(), ResponseBody.class.getName()) && <add> !handlerMethod.getReturnType().getGenericParameterType().equals(publisherVoidType); <ide> } <ide> return false; <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/dispatch/handler/SimpleUrlHandlerMappingIntegrationTests.java <ide> import org.springframework.http.RequestEntity; <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.reactive.web.dispatch.DispatcherHandler; <add>import org.springframework.reactive.web.dispatch.SimpleHandlerResultHandler; <ide> import org.springframework.reactive.web.http.AbstractHttpHandlerIntegrationTests; <ide> import org.springframework.reactive.web.http.HttpHandler; <ide> import org.springframework.reactive.web.http.ServerHttpRequest; <ide> protected HttpHandler createHttpHandler() { <ide> StaticWebApplicationContext wac = new StaticWebApplicationContext(); <ide> wac.registerSingleton("hm", TestHandlerMapping.class); <ide> wac.registerSingleton("ha", HttpHandlerAdapter.class); <add> wac.registerSingleton("hhrh", SimpleHandlerResultHandler.class); <ide> wac.refresh(); <ide> <ide> DispatcherHandler dispatcherHandler = new DispatcherHandler(); <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/dispatch/method/annotation/ResponseBodyResultHandlerTests.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.reactive.web.dispatch.method.annotation; <add> <add>import java.util.Collections; <add> <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add>import org.junit.Test; <add>import org.reactivestreams.Publisher; <add> <add>import org.springframework.reactive.web.dispatch.HandlerResult; <add>import org.springframework.web.bind.annotation.ResponseBody; <add>import org.springframework.web.method.HandlerMethod; <add> <add>/** <add> * @author Sebastien Deleuze <add> */ <add>public class ResponseBodyResultHandlerTests { <add> <add> @Test <add> public void supports() throws NoSuchMethodException { <add> ResponseBodyResultHandler resultHandler = new ResponseBodyResultHandler(Collections.emptyList()); <add> TestController controller = new TestController(); <add> <add> HandlerMethod notAnnotatedMethod = new HandlerMethod(controller, TestController.class.getMethod("notAnnotated")); <add> assertFalse(resultHandler.supports(new HandlerResult(notAnnotatedMethod, null))); <add> <add> HandlerMethod publisherStringMethod = new HandlerMethod(controller, TestController.class.getMethod("publisherString")); <add> assertTrue(resultHandler.supports(new HandlerResult(publisherStringMethod, null))); <add> <add> HandlerMethod publisherVoidMethod = new HandlerMethod(controller, TestController.class.getMethod("publisherVoid")); <add> assertFalse(resultHandler.supports(new HandlerResult(publisherVoidMethod, null))); <add> } <add> <add> <add> private static class TestController { <add> <add> public Publisher<String> notAnnotated() { <add> return null; <add> } <add> <add> @ResponseBody <add> public Publisher<String> publisherString() { <add> return null; <add> } <add> <add> @ResponseBody <add> public Publisher<Void> publisherVoid() { <add> return null; <add> } <add> } <add> <add>}
8
Python
Python
use best pickle protocol
f825fc1a1fbda86a6a9a8c4d70ff02bd5d81f0ff
<ide><path>celery/worker/state.py <ide> <ide> from collections import defaultdict <ide> <add>from kombu.serialization import pickle_protocol <ide> from kombu.utils import cached_property <ide> <ide> from celery import __version__ <ide> class Persistent(object): <ide> <ide> """ <ide> storage = shelve <add> protocol = pickle_protocol <ide> _is_open = False <ide> <ide> def __init__(self, filename, clock=None): <ide> def sync(self, d): <ide> return d <ide> <ide> def open(self): <del> return self.storage.open(self.filename, writeback=True) <add> return self.storage.open( <add> self.filename, protocol=self.protocol, writeback=True, <add> ) <ide> <ide> def close(self): <ide> if self._is_open:
1
Text
Text
add date to changelog
d78460490be08435ee50025ea792ec4d5a5a999e
<ide><path>CHANGELOG.md <del>## 18.1.0 (TODO) <add>## 18.1.0 (April 26, 2022) <ide> <ide> ### React DOM <ide>
1
Text
Text
add styleguide for specs
0f43b246b4ef5c1759c81440e8b0b2abbf9230d3
<ide><path>CONTRIBUTING.md <ide> For more information on how to work with Atom's official packages, see <ide> [JavaScript](https://github.com/styleguide/javascript), <ide> and [CSS](https://github.com/styleguide/css) styleguides. <ide> * Include thoughtfully-worded, well-structured <del> [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder. Run them using `apm test`. <add> [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder. Run them using `apm test`. See the [Specs Styleguide](#specs-styleguide) below. <ide> * Document new code based on the <ide> [Documentation Styleguide](#documentation-styleguide) <ide> * End files with a newline. <ide> For more information on how to work with Atom's official packages, see <ide> * Add an explicit `return` when your function ends with a `for`/`while` loop and <ide> you don't want it to return a collected array. <ide> <add>## Specs Styleguide <add> <add>- Include thoughtfully-worded, well-structured <add> [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder. <add>- treat `describe` as a noun or situation. <add>- trea `it` as a statement about state or how an operation changes state. <add> <add>### Example <add> <add>```coffee <add>describe 'a dog' <add> it 'barks' <add> # spec here <add> describe 'when the dog is happy' <add> it 'wags its tail' <add> # spec here <add>``` <add> <ide> ## Documentation Styleguide <ide> <ide> * Use [AtomDoc](https://github.com/atom/atomdoc).
1
Mixed
Ruby
avoid double cast in types that only override cast
28ebf3c81c1cf083cc920822157d63e7b480ee93
<ide><path>activemodel/CHANGELOG.md <add>* Custom attribute types that inherit from Active Model built-in types and do <add> not override the `serialize` method will now benefit from an optimization <add> when serializing attribute values for the database. <add> <add> For example, with a custom type like the following: <add> <add> ```ruby <add> class DowncasedString < ActiveModel::Type::String <add> def cast(value) <add> super&.downcase <add> end <add> end <add> <add> ActiveRecord::Type.register(:downcased_string, DowncasedString) <add> <add> class User < ActiveRecord::Base <add> attribute :email, :downcased_string <add> end <add> <add> user = User.new(email: "FooBar@example.com") <add> ``` <add> <add> Serializing the `email` attribute for the database will be roughly twice as <add> fast. More expensive `cast` operations will likely see greater improvements. <add> <add> *Jonathan Hefner* <add> <ide> * `has_secure_password` now supports password challenges via a <ide> `password_challenge` accessor and validation. <ide> <ide><path>activemodel/lib/active_model/type/big_integer.rb <ide> module Type <ide> # All casting and serialization are performed in the same way as the <ide> # standard ActiveModel::Type::Integer type. <ide> class BigInteger < Integer <del> include SerializeCastValue <del> <ide> def serialize_cast_value(value) # :nodoc: <ide> value <ide> end <ide><path>activemodel/lib/active_model/type/boolean.rb <ide> module Type <ide> # - Empty strings are coerced to +nil+. <ide> # - All other values will be coerced to +true+. <ide> class Boolean < Value <del> include SerializeCastValue <del> <ide> FALSE_VALUES = [ <ide> false, 0, <ide> "0", :"0", <ide> def serialize(value) # :nodoc: <ide> cast(value) <ide> end <ide> <add> def serialize_cast_value(value) # :nodoc: <add> value <add> end <add> <ide> private <ide> def cast_value(value) <ide> if value == "" <ide><path>activemodel/lib/active_model/type/date.rb <ide> module Type <ide> # String values are parsed using the ISO 8601 date format. Any other values <ide> # are cast using their +to_date+ method, if it exists. <ide> class Date < Value <del> include SerializeCastValue <ide> include Helpers::Timezone <ide> include Helpers::AcceptsMultiparameterTime.new <ide> <ide><path>activemodel/lib/active_model/type/date_time.rb <ide> module Type <ide> # attribute :start, :datetime, precision: 4 <ide> # end <ide> class DateTime < Value <del> include SerializeCastValue <ide> include Helpers::Timezone <del> include Helpers::TimeValue <ide> include Helpers::AcceptsMultiparameterTime.new( <ide> defaults: { 4 => 0, 5 => 0 } <ide> ) <add> include Helpers::TimeValue <ide> <ide> def type <ide> :datetime <ide> end <ide> <del> alias :serialize_cast_value :serialize_time_value # :nodoc: <del> <ide> private <ide> def cast_value(value) <ide> return apply_seconds_precision(value) unless value.is_a?(::String) <ide><path>activemodel/lib/active_model/type/decimal.rb <ide> module Type <ide> # attribute :weight, :decimal, precision: 24 <ide> # end <ide> class Decimal < Value <del> include SerializeCastValue <ide> include Helpers::Numeric <ide> BIGDECIMAL_PRECISION = 18 <ide> <ide><path>activemodel/lib/active_model/type/float.rb <ide> module Type <ide> # - <tt>"-Infinity"</tt> is cast to <tt>-Float::INFINITY</tt>. <ide> # - <tt>"NaN"</tt> is cast to <tt>Float::NAN</tt>. <ide> class Float < Value <del> include SerializeCastValue <ide> include Helpers::Numeric <ide> <ide> def type <ide><path>activemodel/lib/active_model/type/helpers/accepts_multiparameter_time.rb <ide> module Helpers # :nodoc: all <ide> class AcceptsMultiparameterTime < Module <ide> module InstanceMethods <ide> def serialize(value) <del> super(cast(value)) <add> serialize_cast_value(cast(value)) <add> end <add> <add> def serialize_cast_value(value) <add> value <ide> end <ide> <ide> def cast(value) <ide><path>activemodel/lib/active_model/type/helpers/numeric.rb <ide> def serialize(value) <ide> cast(value) <ide> end <ide> <add> def serialize_cast_value(value) <add> value <add> end <add> <ide> def cast(value) <ide> # Checks whether the value is numeric. Spaceship operator <ide> # will return nil if value is not numeric. <ide><path>activemodel/lib/active_model/type/helpers/time_value.rb <ide> module ActiveModel <ide> module Type <ide> module Helpers # :nodoc: all <ide> module TimeValue <del> def serialize(value) <add> def serialize_cast_value(value) <ide> value = apply_seconds_precision(value) <ide> <ide> if value.acts_like?(:time) <ide> def serialize(value) <ide> <ide> value <ide> end <del> alias :serialize_time_value :serialize <ide> <ide> def apply_seconds_precision(value) <ide> return value unless precision && value.respond_to?(:nsec) <ide><path>activemodel/lib/active_model/type/immutable_string.rb <ide> module Type <ide> # <ide> # person.active # => "aye" <ide> class ImmutableString < Value <del> include SerializeCastValue <del> <ide> def initialize(**args) <ide> @true = -(args.delete(:true)&.to_s || "t") <ide> @false = -(args.delete(:false)&.to_s || "f") <ide> def serialize(value) <ide> end <ide> end <ide> <add> def serialize_cast_value(value) # :nodoc: <add> value <add> end <add> <ide> private <ide> def cast_value(value) <ide> case value <ide><path>activemodel/lib/active_model/type/integer.rb <ide> module Type <ide> # attribute :age, :integer, limit: 6 <ide> # end <ide> class Integer < Value <del> include SerializeCastValue <ide> include Helpers::Numeric <ide> <ide> # Column storage size in bytes. <ide><path>activemodel/lib/active_model/type/serialize_cast_value.rb <ide> module ActiveModel <ide> module Type <ide> module SerializeCastValue # :nodoc: <del> def self.included(klass) <del> unless klass.respond_to?(:included_serialize_cast_value) <del> klass.singleton_class.attr_accessor :included_serialize_cast_value <del> klass.silence_redefinition_of_method(:itself_if_class_included_serialize_cast_value) <del> klass.attr_reader :itself_if_class_included_serialize_cast_value <add> module DefaultImplementation <add> def serialize_cast_value(value) <add> value <ide> end <del> klass.included_serialize_cast_value = true <add> end <add> <add> def self.included(klass) <add> klass.include DefaultImplementation unless klass.method_defined?(:serialize_cast_value) <ide> end <ide> <ide> def self.serialize(type, value) <del> # Verify that `type.class` explicitly included SerializeCastValue. <ide> # Using `type.equal?(type.itself_if_...)` is a performant way to also <ide> # ensure that `type` is not just a DelegateClass instance (e.g. <ide> # ActiveRecord::Type::Serialized) unintentionally delegating <ide> # SerializeCastValue methods. <del> if type.equal?((type.itself_if_class_included_serialize_cast_value rescue nil)) <add> if type.equal?((type.itself_if_serialize_cast_value_compatible rescue nil)) <ide> type.serialize_cast_value(value) <ide> else <ide> type.serialize(value) <ide> end <ide> end <ide> <add> attr_reader :itself_if_serialize_cast_value_compatible <add> <ide> def initialize(...) <del> @itself_if_class_included_serialize_cast_value = self if self.class.included_serialize_cast_value <ide> super <add> @itself_if_serialize_cast_value_compatible = self if serialize_cast_value_compatible? <ide> end <ide> <del> def serialize_cast_value(value) <del> value <add> def serialize_cast_value_compatible? <add> ancestors = self.class.ancestors <add> ancestors.index(method(:serialize_cast_value).owner) <= ancestors.index(method(:serialize).owner) <ide> end <ide> end <ide> end <ide><path>activemodel/lib/active_model/type/string.rb <ide> module Type <ide> # However, it accounts for mutable strings, so dirty tracking can properly <ide> # check if a string has changed. <ide> class String < ImmutableString <del> include SerializeCastValue <del> <ide> def changed_in_place?(raw_old_value, new_value) <ide> if new_value.is_a?(::String) <ide> raw_old_value != new_value <ide><path>activemodel/lib/active_model/type/time.rb <ide> module Type <ide> # attribute :start, :time, precision: 4 <ide> # end <ide> class Time < Value <del> include SerializeCastValue <ide> include Helpers::Timezone <del> include Helpers::TimeValue <ide> include Helpers::AcceptsMultiparameterTime.new( <ide> defaults: { 1 => 2000, 2 => 1, 3 => 1, 4 => 0, 5 => 0 } <ide> ) <add> include Helpers::TimeValue <ide> <ide> def type <ide> :time <ide> def user_input_in_time_zone(value) <ide> super(value) <ide> end <ide> <del> alias :serialize_cast_value :serialize_time_value # :nodoc: <del> <ide> private <ide> def cast_value(value) <ide> return apply_seconds_precision(value) unless value.is_a?(::String) <ide><path>activemodel/test/cases/type/serialize_cast_value_test.rb <ide> class DoesNotIncludeModule <ide> def serialize(value) <ide> "serialize(#{value})" <ide> end <del> <del> def serialize_cast_value(value) <del> raise "this should never be called" <del> end <ide> end <ide> <ide> class IncludesModule < DoesNotIncludeModule <ide> include SerializeCastValue <ide> <ide> def serialize_cast_value(value) <del> super("serialize_cast_value(#{value})") <add> "serialize_cast_value(#{super})" <ide> end <ide> end <ide> <del> test "calls #serialize when a class does not include SerializeCastValue" do <del> assert_equal "serialize(foo)", SerializeCastValue.serialize(DoesNotIncludeModule.new, "foo") <add> test "provides a default #serialize_cast_value implementation" do <add> type = Class.new(DoesNotIncludeModule) { include SerializeCastValue } <add> assert_equal "foo", type.new.serialize_cast_value("foo") <ide> end <ide> <del> test "calls #serialize_cast_value when a class directly includes SerializeCastValue" do <del> assert_equal "serialize_cast_value(foo)", SerializeCastValue.serialize(IncludesModule.new, "foo") <add> test "uses #serialize when a class does not include SerializeCastValue" do <add> assert_serializes_using :serialize, DoesNotIncludeModule.new <ide> end <ide> <del> test "calls #serialize when a subclass does not directly include SerializeCastValue" do <del> subclass = Class.new(IncludesModule) <del> assert_equal "serialize(foo)", SerializeCastValue.serialize(subclass.new, "foo") <add> test "uses #serialize_cast_value when a class includes SerializeCastValue" do <add> assert_serializes_using :serialize_cast_value, IncludesModule.new <ide> end <ide> <del> test "calls #serialize_cast_value when a subclass re-includes SerializeCastValue" do <add> test "uses #serialize_cast_value when a subclass inherits both #serialize and #serialize_cast_value" do <ide> subclass = Class.new(IncludesModule) <del> subclass.include SerializeCastValue <del> assert_equal "serialize_cast_value(foo)", SerializeCastValue.serialize(subclass.new, "foo") <add> assert_serializes_using :serialize_cast_value, subclass.new <ide> end <ide> <del> test "calls #serialize when a delegate class does not include SerializeCastValue" do <del> delegate_class = DelegateClass(IncludesModule) <del> assert_equal "serialize(foo)", SerializeCastValue.serialize(delegate_class.new(IncludesModule.new), "foo") <add> test "uses #serialize when a subclass defines a newer #serialize implementation" do <add> subclass = Class.new(IncludesModule) { def serialize(value); super; end } <add> assert_serializes_using :serialize, subclass.new <add> end <add> <add> test "uses #serialize_cast_value when a subclass defines a newer #serialize_cast_value implementation" do <add> subclass = Class.new(IncludesModule) { def serialize_cast_value(value); super; end } <add> assert_serializes_using :serialize_cast_value, subclass.new <add> end <add> <add> test "uses #serialize when a subclass defines a newer #serialize implementation via a module" do <add> mod = Module.new { def serialize(value); super; end } <add> subclass = Class.new(IncludesModule) { include mod } <add> assert_serializes_using :serialize, subclass.new <ide> end <ide> <del> test "calls #serialize_cast_value when a delegate class includes SerializeCastValue" do <add> test "uses #serialize_cast_value when a subclass defines a newer #serialize_cast_value implementation via a module" do <add> mod = Module.new { def serialize_cast_value(value); super; end } <add> subclass = Class.new(IncludesModule) { include mod } <add> assert_serializes_using :serialize_cast_value, subclass.new <add> end <add> <add> test "uses #serialize when a delegate class does not include SerializeCastValue" do <ide> delegate_class = DelegateClass(IncludesModule) <del> delegate_class.include SerializeCastValue <del> assert_equal "serialize_cast_value(foo)", SerializeCastValue.serialize(delegate_class.new(IncludesModule.new), "foo") <add> assert_serializes_using :serialize, delegate_class.new(IncludesModule.new) <add> end <add> <add> test "uses #serialize_cast_value when a delegate class prepends SerializeCastValue" do <add> delegate_class = DelegateClass(IncludesModule) { prepend SerializeCastValue } <add> assert_serializes_using :serialize_cast_value, delegate_class.new(IncludesModule.new) <ide> end <add> <add> test "uses #serialize_cast_value when a delegate class subclass includes SerializeCastValue" do <add> delegate_subclass = Class.new(DelegateClass(IncludesModule)) { include SerializeCastValue } <add> assert_serializes_using :serialize_cast_value, delegate_subclass.new(IncludesModule.new) <add> end <add> <add> private <add> def assert_serializes_using(method_name, type) <add> assert_equal "#{method_name}(foo)", SerializeCastValue.serialize(type, "foo") <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/type/date.rb <ide> module ActiveRecord <ide> module Type <ide> class Date < ActiveModel::Type::Date <del> include ActiveModel::Type::SerializeCastValue <ide> include Internal::Timezone <ide> end <ide> end <ide><path>activerecord/lib/active_record/type/date_time.rb <ide> module ActiveRecord <ide> module Type <ide> class DateTime < ActiveModel::Type::DateTime <del> include ActiveModel::Type::SerializeCastValue <ide> include Internal::Timezone <ide> end <ide> end <ide><path>activerecord/lib/active_record/type/decimal_without_scale.rb <ide> module ActiveRecord <ide> module Type <ide> class DecimalWithoutScale < ActiveModel::Type::BigInteger # :nodoc: <del> include ActiveModel::Type::SerializeCastValue <del> <ide> def type <ide> :decimal <ide> end <ide><path>activerecord/lib/active_record/type/text.rb <ide> module ActiveRecord <ide> module Type <ide> class Text < ActiveModel::Type::String # :nodoc: <del> include ActiveModel::Type::SerializeCastValue <del> <ide> def type <ide> :text <ide> end <ide><path>activerecord/lib/active_record/type/time.rb <ide> module ActiveRecord <ide> module Type <ide> class Time < ActiveModel::Type::Time <del> include ActiveModel::Type::SerializeCastValue <ide> include Internal::Timezone <ide> <ide> class Value < DelegateClass(::Time) # :nodoc: <ide><path>activerecord/lib/active_record/type/unsigned_integer.rb <ide> module ActiveRecord <ide> module Type <ide> class UnsignedInteger < ActiveModel::Type::Integer # :nodoc: <del> include ActiveModel::Type::SerializeCastValue <del> <ide> private <ide> def max_value <ide> super * 2
22
Javascript
Javascript
add direct anchors for error codes
c3d26e801a40e1595b859df1d7730cfe526edc45
<ide><path>tools/doc/html.js <ide> function getSection(lexed) { <ide> return ''; <ide> } <ide> <add>function getMark(anchor) { <add> return `<span><a class="mark" href="#${anchor}" id="${anchor}">#</a></span>`; <add>} <ide> <ide> function buildToc(lexed, filename, cb) { <ide> var toc = []; <ide> function buildToc(lexed, filename, cb) { <ide> <ide> depth = tok.depth; <ide> const realFilename = path.basename(realFilenames[0], '.md'); <del> const id = getId(`${realFilename}_${tok.text.trim()}`); <add> const apiName = tok.text.trim(); <add> const id = getId(`${realFilename}_${apiName}`); <ide> toc.push(new Array((depth - 1) * 2 + 1).join(' ') + <ide> `* <span class="stability_${tok.stability}">` + <ide> `<a href="#${id}">${tok.text}</a></span>`); <del> tok.text += `<span><a class="mark" href="#${id}"` + <del> `id="${id}">#</a></span>`; <add> tok.text += getMark(id); <add> if (realFilename === 'errors' && apiName.startsWith('ERR_')) { <add> tok.text += getMark(apiName); <add> } <ide> }); <ide> <ide> toc = marked.parse(toc.join('\n'));
1
Text
Text
add note about ajax and csrf-token [ci skip]
f7d81c924fd498ae6fd1852070db0553a10b0c41
<ide><path>guides/source/security.md <ide> Or the attacker places the code into the onmouseover event handler of an image: <ide> <img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." /> <ide> ``` <ide> <del>There are many other possibilities, like using a `<script>` tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we disallow cross-site `<script>` tags. Only Ajax requests may have JavaScript responses since XmlHttpRequest is subject to the browser Same-Origin policy - meaning only your site can initiate the request. <add>There are many other possibilities, like using a `<script>` tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we disallow cross-site `<script>` tags. Only Ajax requests may have JavaScript responses since `XMLHttpRequest` is subject to the browser Same-Origin policy - meaning only your site can initiate the request. <ide> <ide> To protect against all other forged requests, we introduce a _required security token_ that our site knows but other sites don't know. We include the security token in requests and verify it on the server. This is a one-liner in your application controller, and is the default for newly created rails applications: <ide> <ide> protect_from_forgery with: :exception <ide> <ide> This will automatically include a security token in all forms and Ajax requests generated by Rails. If the security token doesn't match what was expected, an exception will be thrown. <ide> <add>NOTE: By default, Rails includes jQuery and a [unobtrusive scripting adapter for jQuery](https://github.com/rails/jquery-ujs), <add>which adds a header called `X-CSRF-Token` on every non-GET Ajax call made by jQuery with the security token. <add>Without this header, your non-GET requests won't be accepted by Rails. If you want to use another library <add>to make Ajax calls, you will have to find how add the security token as a default header for Ajax calls in <add>your library. To get the token have a look at the `<meta name='csrf-token' content='THE-TOKEN'>` tag printed <add>by `<%= csrf_meta_tags %>` in your application view. <add> <ide> It is common to use persistent cookies to store user information, with `cookies.permanent` for example. In this case, the cookies will not be cleared and the out of the box CSRF protection will not be effective. If you are using a different cookie store than the session for this information, you must handle what to do with it yourself: <ide> <ide> ```ruby
1
PHP
PHP
add test for app fixtures
8b4f12e73571027e2325245b7c9c31bb4ee7bcf3
<ide><path>tests/TestCase/TestSuite/Fixture/FixtureHelperTest.php <ide> use Cake\TestSuite\Fixture\TestFixture; <ide> use Cake\TestSuite\TestCase; <ide> use Company\TestPluginThree\Test\Fixture\ArticlesFixture as CompanyArticlesFixture; <add>use TestApp\Test\Fixture\ArticlesFixture as AppArticlesFixture; <ide> use TestPlugin\Test\Fixture\ArticlesFixture as PluginArticlesFixture; <ide> use TestPlugin\Test\Fixture\Blog\CommentsFixture as PluginCommentsFixture; <ide> use UnexpectedValueException; <ide> public function testLoadFixtures(): void <ide> 'plugin.TestPlugin.Articles', <ide> 'plugin.TestPlugin.Blog/Comments', <ide> 'plugin.Company/TestPluginThree.Articles', <add> 'app.Articles', <ide> ]); <ide> $this->assertNotEmpty($fixtures); <ide> $this->assertInstanceOf(ArticlesFixture::class, $fixtures[ArticlesFixture::class]); <ide> $this->assertInstanceOf(PluginArticlesFixture::class, $fixtures[PluginArticlesFixture::class]); <ide> $this->assertInstanceOf(PluginCommentsFixture::class, $fixtures[PluginCommentsFixture::class]); <ide> $this->assertInstanceOf(CompanyArticlesFixture::class, $fixtures[CompanyArticlesFixture::class]); <add> $this->assertInstanceOf(AppArticlesFixture::class, $fixtures[AppArticlesFixture::class]); <ide> } <ide> <ide> /**
1
PHP
PHP
fix mistake with previous commit
23c5805763e3603966f6876a77f1418cc57b16de
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php <ide> public function truncate($table, $reset = false) { <ide> if (isset($this->_sequenceMap[$table]) && $reset != true) { <ide> foreach ($this->_sequenceMap[$table] as $sequence) { <ide> $quoted = $this->name($sequence); <del> $this->_execute("ALTER SEQUENCE {$sequence} RESTART WITH 1"); <add> $this->_execute("ALTER SEQUENCE {$quoted} RESTART WITH 1"); <ide> } <ide> } <ide> return true;
1
PHP
PHP
add test for implicit binding
b4de11725cc1e4157938864961deeaa889b54d46
<ide><path>tests/Routing/ImplicitRouteBindingTest.php <add><?php <add> <add>namespace Illuminate\Tests\Routing; <add> <add>use Illuminate\Container\Container; <add>use Illuminate\Database\Eloquent\Model; <add>use Illuminate\Routing\ImplicitRouteBinding; <add>use Illuminate\Routing\Route; <add>use PHPUnit\Framework\TestCase; <add> <add>class ImplicitRouteBindingTest extends TestCase <add>{ <add> public function test_it_can_resolve_the_implicit_route_bindings_for_the_given_route() <add> { <add> $action = ['uses' => function (ImplicitRouteBindingUser $user) { <add> return $user; <add> }]; <add> <add> $route = new Route('GET', '/test', $action); <add> $route->parameters = ['user' => new ImplicitRouteBindingUser]; <add> <add> $route->prepareForSerialization(); <add> <add> $container = Container::getInstance(); <add> <add> ImplicitRouteBinding::resolveForRoute($container, $route); <add> <add> $this->assertTrue(true); <add> } <add>} <add> <add>class ImplicitRouteBindingUser extends Model <add>{ <add> // <add>}
1
Python
Python
fix all pydocstyle lint errors
449f371743acc6ee7883cc1842a3a2034fa4cbd5
<ide><path>celery/app/control.py <ide> def election(self, id, topic, action=None, connection=None): <ide> <ide> def revoke(self, task_id, destination=None, terminate=False, <ide> signal=TERM_SIGNAME, **kwargs): <del> """Tell all (or specific) workers to revoke a task by id <del> (or list of ids). <add> """Tell all (or specific) workers to revoke a task by id (or list of ids). <ide> <ide> If a task is revoked, the workers will ignore the task and <ide> not execute it after all. <ide> def revoke(self, task_id, destination=None, terminate=False, <ide> <ide> def terminate(self, task_id, <ide> destination=None, signal=TERM_SIGNAME, **kwargs): <del> """Tell all (or specific) workers to terminate a task by id <del> (or list of ids). <add> """Tell all (or specific) workers to terminate a task by id (or list of ids). <ide> <ide> See Also: <ide> This is just a shortcut to :meth:`revoke` with the terminate
1
Python
Python
add log output to crashes
a4b4854e2ff0f3de69caa5e46d001575b9e22273
<ide><path>tools/test.py <ide> def HasRun(self, output): <ide> <ide> if output.HasCrashed(): <ide> self.severity = 'crashed' <del> exit_code = output.output.exit_code <del> self.traceback = "oh no!\nexit code: " + PrintCrashed(exit_code) <ide> <del> if output.HasTimedOut(): <add> elif output.HasTimedOut(): <ide> self.severity = 'fail' <ide> <ide> else:
1
Python
Python
remove print statement from test
9ed65915e66c124bd02f722c6b213293804f7264
<ide><path>numpy/ma/tests/test_core.py <ide> def test_empty(self): <ide> b = empty(len(a), dtype=datatype) <ide> assert_equal(b.shape, a.shape) <ide> assert_equal(b.fill_value, a.fill_value) <del> print "test_empty passed!" <ide> <ide> <ide> #..............................................................................
1
Javascript
Javascript
add ie-specific 'unselectable' attribute
a0265fe8b71a841b82111918407799e42e668d67
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> itemID: MUST_USE_ATTRIBUTE, <ide> itemRef: MUST_USE_ATTRIBUTE, <ide> // property is supported for OpenGraph in meta tags. <del> property: null <add> property: null, <add> // IE-only attribute that controls focus behavior <add> unselectable: MUST_USE_ATTRIBUTE <ide> }, <ide> DOMAttributeNames: { <ide> acceptCharset: 'accept-charset',
1
PHP
PHP
assert proper array access for _datetimeselected()
eb13242680731f8c1cf82786670f5fe40d06f6f3
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function minute($fieldName, $attributes = array()) { <ide> */ <ide> protected function _dateTimeSelected($select, $fieldName, $attributes) { <ide> if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) { <del> if (is_array($value) && isset($value[$select])) { <del> $attributes['value'] = $value[$select]; <add> if (is_array($value)) { <add> $attributes['value'] = isset($value[$select]) ? $value[$select] : null; <ide> } else { <ide> if (empty($value)) { <ide> if (!$attributes['empty']) {
1
PHP
PHP
add conditional methods to dispatchable traits
174c234b2d7e5108db1395ad5b681e50e0a7794d
<ide><path>src/Illuminate/Foundation/Bus/Dispatchable.php <ide> public static function dispatch() <ide> return new PendingDispatch(new static(...func_get_args())); <ide> } <ide> <add> /** <add> * Dispatch the job with the given arguments if the given truth test passes. <add> * <add> * @param bool $boolean <add> * @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent <add> */ <add> public static function dispatchIf($boolean, ...$arguments) <add> { <add> return $boolean <add> ? new PendingDispatch(new static(...$arguments)) <add> : new Fluent; <add> } <add> <add> /** <add> * Dispatch the job with the given arguments unless the given truth test passes. <add> * <add> * @param bool $boolean <add> * @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent <add> */ <add> public static function dispatchUnless($boolean, ...$arguments) <add> { <add> return ! $boolean <add> ? new PendingDispatch(new static(...$arguments)) <add> : new Fluent; <add> } <add> <ide> /** <ide> * Dispatch a command to its appropriate handler in the current process. <ide> * <ide><path>src/Illuminate/Foundation/Events/Dispatchable.php <ide> public static function dispatch() <ide> return event(new static(...func_get_args())); <ide> } <ide> <add> /** <add> * Dispatch the event with the given arguments if the given truth test passes. <add> * <add> * @param bool $boolean <add> * @return void <add> */ <add> public static function dispatchIf($boolean, ...$arguments) <add> { <add> if ($boolean) { <add> return event(new static(...$arguments)); <add> } <add> } <add> <add> /** <add> * Dispatch the event with the given arguments unless the given truth test passes. <add> * <add> * @param bool $boolean <add> * @return void <add> */ <add> public static function dispatchUnless($boolean, ...$arguments) <add> { <add> if (! $boolean) { <add> return event(new static(...$arguments)); <add> } <add> } <add> <ide> /** <ide> * Broadcast the event with the given arguments. <ide> *
2
Ruby
Ruby
switch fcgi handler over to rack
926844e869b747fa1e9474fd95f9b97fa04ae092
<ide><path>railties/lib/fcgi_handler.rb <ide> def process_request(cgi) <ide> <ide> with_signal_handler 'USR1' do <ide> begin <del> Dispatcher.dispatch(cgi) <add> ::Rack::Handler::FastCGI.serve(cgi, Dispatcher.new) <ide> rescue SignalException, SystemExit <ide> raise <ide> rescue Exception => error
1
Text
Text
add v4.8.0-beta.5 to changelog
81c10c76d5f074d9113a921e1117c290bda21fe9
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.8.0-beta.5 (October 3, 2022) <add> <add>- [#20212](https://github.com/emberjs/ember.js/pull/20212) [BUGFIX] Remove incorrect exports from preview routing types <add> <ide> ### v4.8.0-beta.4 (September 26, 2022) <ide> <ide> - [#20201](https://github.com/emberjs/ember.js/pull/20201) [BUGFIX] Fix type definition for `Route`
1
PHP
PHP
apply suggestions from code review
b292276fc336688f695b2bc9cac79fd44146b34f
<ide><path>src/Core/ServiceProvider.php <ide> public function getContainer(): PsrContainerInterface <ide> /** <ide> * Delegate to the bootstrap() method <ide> * <del> * This method primarily exists as a shim between the interface <del> * that league/container has and the one we want to offer in CakePHP. <add> * This method wraps the league/container function so users <add> * only need to use the CakePHP bootstrap() interface. <ide> * <ide> * @return void <ide> */
1
Ruby
Ruby
localize dependencycollector monkey-patches too
ad0f9d603f5b04cb0c4e9d75fab36f4118bff942
<ide><path>Library/Homebrew/dev-cmd/extract.rb <ide> def with_monkey_patch <ide> define_method(:method_missing) { |*| } <ide> end <ide> <add> DependencyCollector.class_eval do <add> if method_defined?(:parse_symbol_spec) <add> alias_method :old_parse_symbol_spec, :parse_symbol_spec <add> end <add> define_method(:parse_symbol_spec) { |*| } <add> end <add> <add> DependencyCollector::Compat.class_eval do <add> if method_defined?(:parse_string_spec) <add> alias_method :old_parse_string_spec, :parse_string_spec <add> end <add> define_method(:parse_string_spec) { |*| } <add> end <add> <ide> yield <ide> ensure <ide> BottleSpecification.class_eval do <ide> def with_monkey_patch <ide> undef :old_method_missing <ide> end <ide> end <del>end <del> <del>class DependencyCollector <del> def parse_symbol_spec(*); end <ide> <del> module Compat <del> def parse_string_spec(spec, tags) <del> super <add> DependencyCollector.class_eval do <add> if method_defined?(:old_parse_symbol_spec) <add> alias_method :parse_symbol_spec, :old_parse_symbol_spec <add> undef :old_parse_symbol_spec <ide> end <ide> end <ide> <del> prepend Compat <add> DependencyCollector::Compat.class_eval do <add> if method_defined?(:old_parse_string_spec) <add> alias_method :parse_string_spec, :old_parse_string_spec <add> undef :old_parse_string_spec <add> end <add> end <ide> end <ide> <ide> module Homebrew
1
Python
Python
set version to v2.2.0.dev15
eba708404dc2743cca691a4339410d551d0a839f
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.0.dev14" <add>__version__ = "2.2.0.dev15" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) in Python" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion"
1
Text
Text
add missing space in migrations guide [ci skip]
32d0d971ebcd74fdfc7dcc580b58d3292778b4d4
<ide><path>guides/source/active_record_migrations.md <ide> As always, what has been generated for you is just a starting point. You can add <ide> or remove from it as you see fit by editing the <ide> `db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb` file. <ide> <del>Also, the generator accepts column type as `references`(also available as <add>Also, the generator accepts column type as `references` (also available as <ide> `belongs_to`). For instance: <ide> <ide> ```bash
1
Go
Go
remove unused commandlinetoargv
bd2e288e56ebf50c9038f3069d07a5e3085030f1
<ide><path>pkg/system/syscall_unix.go <ide> import "golang.org/x/sys/unix" <ide> func Unmount(dest string) error { <ide> return unix.Unmount(dest, 0) <ide> } <del> <del>// CommandLineToArgv should not be used on Unix. <del>// It simply returns commandLine in the only element in the returned array. <del>func CommandLineToArgv(commandLine string) ([]string, error) { <del> return []string{commandLine}, nil <del>} <ide><path>pkg/system/syscall_windows.go <ide> func Unmount(_ string) error { <ide> return nil <ide> } <ide> <del>// CommandLineToArgv wraps the Windows syscall to turn a commandline into an argument array. <del>func CommandLineToArgv(commandLine string) ([]string, error) { <del> var argc int32 <del> <del> argsPtr, err := windows.UTF16PtrFromString(commandLine) <del> if err != nil { <del> return nil, err <del> } <del> <del> argv, err := windows.CommandLineToArgv(argsPtr, &argc) <del> if err != nil { <del> return nil, err <del> } <del> defer windows.LocalFree(windows.Handle(uintptr(unsafe.Pointer(argv)))) <del> <del> newArgs := make([]string, argc) <del> for i, v := range (*argv)[:argc] { <del> newArgs[i] = windows.UTF16ToString((*v)[:]) <del> } <del> <del> return newArgs, nil <del>} <del> <ide> // HasWin32KSupport determines whether containers that depend on win32k can <ide> // run on this machine. Win32k is the driver used to implement windowing. <ide> func HasWin32KSupport() bool {
2
Text
Text
remove reference to travis bot
95fc1e41b95f981f926a2b351374af1eb2bc8e2a
<ide><path>docs/Cask-Cookbook.md <ide> cask "<cask-token>" do <ide> [`<cask-token>`](#token-reference) should match the Cask filename, without the `.rb` extension, <ide> enclosed in single quotes. <ide> <del>There are currently some arbitrary limitations on Cask tokens which are in the process of being removed. The Travis bot will catch any errors during the transition. <add>There are currently some arbitrary limitations on Cask tokens which are in the process of being removed. GitHub Actions will catch any errors during the transition. <ide> <ide> ## Stanza order <ide>
1
Javascript
Javascript
fix compiler logging test
b89853ea12534c8ce8b74fa4ea3f89e01cfb4f9a
<ide><path>test/Compiler.test.js <ide> const path = require("path"); <ide> const webpack = require("../"); <ide> const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter"); <ide> const MemoryFs = require("memory-fs"); <add>const captureStdio = require("./helpers/captureStdio"); <ide> <ide> describe("Compiler", () => { <ide> jest.setTimeout(20000); <ide> describe("Compiler", () => { <ide> }); <ide> }); <ide> describe("infrastructure logging", () => { <del> const CONSOLE_METHODS = [ <del> "error", <del> "warn", <del> "info", <del> "log", <del> "debug", <del> "trace", <del> "profile", <del> "profileEnd", <del> "group", <del> "groupEnd", <del> "groupCollapsed" <del> ]; <del> const spies = {}; <add> let capture; <ide> beforeEach(() => { <del> for (const method of CONSOLE_METHODS) { <del> if (console[method]) { <del> spies[method] = jest.spyOn(console, method).mockImplementation(); <del> } <del> } <add> capture = captureStdio(process.stderr); <ide> }); <ide> afterEach(() => { <del> for (const method in spies) { <del> spies[method].mockRestore(); <del> delete spies[method]; <del> } <add> capture.restore(); <ide> }); <ide> class MyPlugin { <ide> apply(compiler) { <ide> describe("Compiler", () => { <ide> }); <ide> compiler.outputFileSystem = new MemoryFs(); <ide> compiler.run((err, stats) => { <del> expect(spies.group).toHaveBeenCalledTimes(1); <del> expect(spies.group).toHaveBeenCalledWith("[MyPlugin] Group"); <del> expect(spies.groupCollapsed).toHaveBeenCalledTimes(1); <del> expect(spies.groupCollapsed).toHaveBeenCalledWith( <del> "[MyPlugin] Collaped group" <del> ); <del> expect(spies.error).toHaveBeenCalledTimes(1); <del> expect(spies.error).toHaveBeenCalledWith("<e> [MyPlugin] Error"); <del> expect(spies.warn).toHaveBeenCalledTimes(1); <del> expect(spies.warn).toHaveBeenCalledWith("<w> [MyPlugin] Warning"); <del> expect(spies.info).toHaveBeenCalledTimes(1); <del> expect(spies.info).toHaveBeenCalledWith("<i> [MyPlugin] Info"); <del> expect(spies.log).toHaveBeenCalledTimes(3); <del> expect(spies.log).toHaveBeenCalledWith("[MyPlugin] Log"); <del> expect(spies.log).toHaveBeenCalledWith( <del> "[MyPlugin] Log inside collapsed group" <del> ); <del> expect(spies.debug).toHaveBeenCalledTimes(0); <del> expect(spies.groupEnd).toHaveBeenCalledTimes(2); <add> expect(capture.toString().replace(/[\d.]+ms/, "Xms")) <add> .toMatchInlineSnapshot(` <add>"<-> [MyPlugin] Group <add> <e> [MyPlugin] Error <add> <w> [MyPlugin] Warning <add> <i> [MyPlugin] Info <add> [MyPlugin] Log <add> <-> [MyPlugin] Collaped group <add> [MyPlugin] Log inside collapsed group <add><t> [MyPlugin] Time: Xms <add>" <add>`); <ide> done(); <ide> }); <ide> }); <ide> describe("Compiler", () => { <ide> }); <ide> compiler.outputFileSystem = new MemoryFs(); <ide> compiler.run((err, stats) => { <del> expect(spies.group).toHaveBeenCalledTimes(1); <del> expect(spies.group).toHaveBeenCalledWith("[MyPlugin] Group"); <del> expect(spies.groupCollapsed).toHaveBeenCalledTimes(1); <del> expect(spies.groupCollapsed).toHaveBeenCalledWith( <del> "[MyPlugin] Collaped group" <del> ); <del> expect(spies.error).toHaveBeenCalledTimes(1); <del> expect(spies.error).toHaveBeenCalledWith("<e> [MyPlugin] Error"); <del> expect(spies.warn).toHaveBeenCalledTimes(1); <del> expect(spies.warn).toHaveBeenCalledWith("<w> [MyPlugin] Warning"); <del> expect(spies.info).toHaveBeenCalledTimes(1); <del> expect(spies.info).toHaveBeenCalledWith("<i> [MyPlugin] Info"); <del> expect(spies.log).toHaveBeenCalledTimes(3); <del> expect(spies.log).toHaveBeenCalledWith("[MyPlugin] Log"); <del> expect(spies.log).toHaveBeenCalledWith( <del> "[MyPlugin] Log inside collapsed group" <del> ); <del> expect(spies.debug).toHaveBeenCalledTimes(1); <del> expect(spies.debug).toHaveBeenCalledWith("[MyPlugin] Debug"); <del> expect(spies.groupEnd).toHaveBeenCalledTimes(2); <add> expect(capture.toString().replace(/[\d.]+ms/, "Xms")) <add> .toMatchInlineSnapshot(` <add>"<-> [MyPlugin] Group <add> <e> [MyPlugin] Error <add> <w> [MyPlugin] Warning <add> <i> [MyPlugin] Info <add> [MyPlugin] Log <add> [MyPlugin] Debug <add> <-> [MyPlugin] Collaped group <add> [MyPlugin] Log inside collapsed group <add><t> [MyPlugin] Time: Xms <add>" <add>`); <ide> done(); <ide> }); <ide> }); <ide> describe("Compiler", () => { <ide> }); <ide> compiler.outputFileSystem = new MemoryFs(); <ide> compiler.run((err, stats) => { <del> expect(spies.group).toHaveBeenCalledTimes(0); <del> expect(spies.groupCollapsed).toHaveBeenCalledTimes(0); <del> expect(spies.error).toHaveBeenCalledTimes(0); <del> expect(spies.warn).toHaveBeenCalledTimes(0); <del> expect(spies.info).toHaveBeenCalledTimes(0); <del> expect(spies.log).toHaveBeenCalledTimes(0); <del> expect(spies.debug).toHaveBeenCalledTimes(0); <del> expect(spies.groupEnd).toHaveBeenCalledTimes(0); <add> expect(capture.toString()).toMatchInlineSnapshot(`""`); <ide> done(); <ide> }); <ide> });
1
Javascript
Javascript
eliminate context code based on process.browser
7ebcc5bec9d0da258311a12634e16b3479f13b44
<ide><path>build/webpack.js <ide> export default async function getBaseWebpackConfig (dir: string, {dev = false, i <ide> // required not to cache removed files <ide> useHashIndex: false <ide> }), <add> // Removes server/client code by minifier <add> new webpack.DefinePlugin({ <add> 'process.browser': JSON.stringify(!isServer) <add> }), <ide> // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory <ide> !isServer && dev && new webpack.DefinePlugin({ <ide> 'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir) <ide><path>test/integration/production/pages/process-env.js <add> <add>if (process.browser) { <add> global.__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__ = true <add>} <add> <add>if (!process.browser) { <add> global.__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__ = true <add>} <add> <ide> export default () => ( <ide> <div id='node-env'>{process.env.NODE_ENV}</div> <ide> ) <ide><path>test/integration/production/test/process-env.js <ide> /* global describe, it, expect */ <ide> import webdriver from 'next-webdriver' <add>import { readFile } from 'fs' <add>import { promisify } from 'util' <add>import { join } from 'path' <add> <add>const readFileAsync = promisify(readFile) <add>const readNextBuildFile = (relativePath) => readFileAsync(join(__dirname, '../.next', relativePath), 'utf8') <ide> <ide> export default (context) => { <ide> describe('process.env', () => { <ide> export default (context) => { <ide> browser.close() <ide> }) <ide> }) <add> <add> describe('process.browser', () => { <add> it('should eliminate server only code on the client', async () => { <add> const buildId = await readNextBuildFile('./BUILD_ID') <add> const clientCode = await readNextBuildFile(`./static/${buildId}/pages/process-env.js`) <add> expect(clientCode).toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__/) <add> expect(clientCode).not.toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__/) <add> }) <add> <add> it('should eliminate client only code on the server', async () => { <add> const buildId = await readNextBuildFile('./BUILD_ID') <add> const serverCode = await readNextBuildFile(`./server/static/${buildId}/pages/process-env.js`) <add> expect(serverCode).not.toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__/) <add> expect(serverCode).toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__/) <add> }) <add> }) <ide> }
3
Python
Python
make pyflakes fixes in numpy/f2py
b80d1f979efb528e855263a38b389cebd3eb90e1
<ide><path>numpy/f2py/__init__.py <ide> #!/usr/bin/env python <add>"""Fortran to Python Interface Generator. <add> <add>""" <ide> from __future__ import division, absolute_import, print_function <ide> <ide> __all__ = ['run_main', 'compile', 'f2py_testing'] <ide> <del>import os <ide> import sys <del>import subprocess <ide> <ide> from . import f2py2e <ide> from . import f2py_testing <ide> from . import diagnose <ide> <del>from .info import __doc__ <del> <ide> run_main = f2py2e.run_main <ide> main = f2py2e.main <ide> <ide><path>numpy/f2py/auxfuncs.py <ide> from . import __version__ <ide> from . import cfuncs <ide> <add>__all__ = [ <add> 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle', <add> 'getargs2', 'getcallprotoargument', 'getcallstatement', <add> 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode', <add> 'getusercode1', 'hasbody', 'hascallstatement', 'hascommon', <add> 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote', <add> 'isallocatable', 'isarray', 'isarrayofstrings', 'iscomplex', <add> 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn', <add> 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction', <add> 'isfunction_wrap', 'isint1array', 'isinteger', 'isintent_aux', <add> 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict', <add> 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace', <add> 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical', <add> 'islogicalfunction', 'islong_complex', 'islong_double', <add> 'islong_doublefunction', 'islong_long', 'islong_longfunction', <add> 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isrequired', <add> 'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring', <add> 'isstringarray', 'isstringfunction', 'issubroutine', <add> 'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char', <add> 'isunsigned_chararray', 'isunsigned_long_long', <add> 'isunsigned_long_longarray', 'isunsigned_short', <add> 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', <add> 'replace', 'show', 'stripcomma', 'throw_error', <add>] <add> <add> <ide> f2py_version = __version__.version <ide> <ide> <del>errmess=sys.stderr.write <del>#outmess=sys.stdout.write <del>show=pprint.pprint <add>errmess = sys.stderr.write <add>show = pprint.pprint <ide> <ide> options={} <ide> debugoptions=[] <ide><path>numpy/f2py/capi_maps.py <ide> import re <ide> import os <ide> import sys <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> debugcapi, dictappend, errmess, gentitle, getcallprotoargument, <add> getcallstatement, getfortranname, getpymethoddef, getrestdoc, <add> getusercode, getusercode1, hasinitvalue, hasnote, hasresultnote, <add> isarray, iscomplex, iscomplexarray, iscomplexfunction, isexternal, <add> isfunction, isintent_aux, isintent_callback, isintent_dict, <add> isintent_hide, isintent_in, isintent_inout, isintent_out, ismodule, <add> isoptional, isrequired, isscalar, isstring, isstringarray, <add> isstringfunction, issubroutine, l_and, l_not, l_or, outmess <add>) <add> <ide> from .crackfortran import markoutercomma <ide> from . import cb_rules <ide> <add>__all__ = [ <add> 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign', <add> 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map', <add> 'cb_sign2map', 'cb_routsign2map', 'common_sign2map' <add>] <add> <add> <ide> # Numarray and Numeric users should set this False <ide> using_newcore = True <ide> <ide><path>numpy/f2py/cb_rules.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <del>import pprint <del>import sys <del> <ide> from . import __version__ <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> applyrules, debugcapi, dictappend, errmess, getargs, hasnote, isarray, <add> iscomplex, iscomplexarray, iscomplexfunction, isfunction, isintent_c, <add> isintent_hide, isintent_in, isintent_inout, isintent_nothide, <add> isintent_out, isoptional, isrequired, isscalar, isstring, <add> isstringfunction, issubroutine, l_and, l_not, l_or, outmess, replace, <add> stripcomma, throw_error <add>) <ide> from . import cfuncs <ide> <ide> f2py_version = __version__.version <ide> <del>errmess=sys.stderr.write <del>outmess=sys.stdout.write <del>show=pprint.pprint <ide> <ide> <ide> ################## Rules for callback function ############## <ide><path>numpy/f2py/common_rules.py <ide> from . import __version__ <ide> f2py_version = __version__.version <ide> <del>import pprint <del>import sys <del>errmess=sys.stderr.write <del>outmess=sys.stdout.write <del>show=pprint.pprint <del> <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> hasbody, hascommon, hasnote, isintent_hide, outmess <add>) <ide> from . import capi_maps <ide> from . import func2subr <ide> from .crackfortran import rmbadname <del>############## <ide> <ide> def findcommonblocks(block,top=1): <ide> ret = [] <ide><path>numpy/f2py/crackfortran.py <ide> import string <ide> import fileinput <ide> import re <del>import pprint <ide> import os <ide> import copy <ide> import platform <ide> <ide> from . import __version__ <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> errmess, hascommon, isdouble, iscomplex, isexternal,isinteger, <add> isintent_aux, isintent_c, isintent_callback, isintent_in, <add> isintent_inout, isintent_inplace,islogical, isoptional,isscalar, <add> isstring, isstringarray, l_or, show <add>) <add> <ide> <ide> f2py_version = __version__.version <ide> <ide> # Global flags: <del>strictf77=1 # Ignore `!' comments unless line[0]=='!' <del>sourcecodeform='fix' # 'fix','free' <del>quiet=0 # Be verbose if 0 (Obsolete: not used any more) <del>verbose=1 # Be quiet if 0, extra verbose if > 1. <del>tabchar=4*' ' <del>pyffilename='' <del>f77modulename='' <del>skipemptyends=0 # for old F77 programs without 'program' statement <del>ignorecontains=1 <del>dolowercase=1 <del>debug=[] <add>strictf77 = 1 # Ignore `!' comments unless line[0]=='!' <add>sourcecodeform = 'fix' # 'fix','free' <add>quiet = 0 # Be verbose if 0 (Obsolete: not used any more) <add>verbose = 1 # Be quiet if 0, extra verbose if > 1. <add>tabchar = 4*' ' <add>pyffilename = '' <add>f77modulename = '' <add>skipemptyends = 0 # for old F77 programs without 'program' statement <add>ignorecontains = 1 <add>dolowercase = 1 <add>debug = [] <ide> <ide> # Global variables <del>groupcounter=0 <del>grouplist={groupcounter:[]} <del>neededmodule=-1 <del>expectbegin=1 <del>skipblocksuntil=-1 <del>usermodules=[] <del>f90modulevars={} <del>gotnextfile=1 <del>filepositiontext='' <del>currentfilename='' <del>skipfunctions=[] <del>skipfuncs=[] <del>onlyfuncs=[] <del>include_paths=[] <add>beginpattern = '' <add>currentfilename = '' <add>expectbegin = 1 <add>f90modulevars = {} <add>filepositiontext = '' <add>gotnextfile = 1 <add>groupcache = None <add>groupcounter = 0 <add>grouplist = {groupcounter:[]} <add>groupname = '' <add>include_paths = [] <add>neededmodule = -1 <add>onlyfuncs = [] <ide> previous_context = None <add>skipblocksuntil = -1 <add>skipfuncs = [] <add>skipfunctions = [] <add>usermodules = [] <ide> <ide> <ide> def reset_global_f2py_vars(): <del> global groupcounter, grouplist, neededmodule, expectbegin, \ <del> skipblocksuntil, usermodules, f90modulevars, gotnextfile, \ <del> filepositiontext, currentfilename, skipfunctions, skipfuncs, \ <del> onlyfuncs, include_paths, previous_context, \ <del> strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename, \ <del> f77modulename, skipemptyends, ignorecontains, dolowercase, debug <add> global groupcounter, grouplist, neededmodule, expectbegin <add> global skipblocksuntil, usermodules, f90modulevars, gotnextfile <add> global filepositiontext, currentfilename, skipfunctions, skipfuncs <add> global onlyfuncs, include_paths, previous_context <add> global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename <add> global f77modulename, skipemptyends, ignorecontains, dolowercase, debug <ide> <ide> # flags <ide> strictf77 = 1 <ide> def reset_global_f2py_vars(): <ide> previous_context = None <ide> <ide> <del>###### Some helper functions <del>def show(o,f=0):pprint.pprint(o) <del>errmess=sys.stderr.write <ide> def outmess(line,flag=1): <ide> global filepositiontext <del> if not verbose: return <add> <add> if not verbose: <add> return <ide> if not quiet: <del> if flag:sys.stdout.write(filepositiontext) <add> if flag: <add> sys.stdout.write(filepositiontext) <ide> sys.stdout.write(line) <add> <ide> re._MAXCACHE=50 <ide> defaultimplicitrules={} <ide> for c in "abcdefghopqrstuvwxyz$_": defaultimplicitrules[c]={'typespec':'real'} <ide> def readfortrancode(ffile,dowithline=show,istop=1): <ide> 2) Call dowithline(line) on every line. <ide> 3) Recursively call itself when statement \"include '<filename>'\" is met. <ide> """ <del> global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ <del> beginpattern, quiet, verbose, dolowercase, include_paths <add> global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77 <add> global beginpattern, quiet, verbose, dolowercase, include_paths <add> <ide> if not istop: <ide> saveglobals=gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ <ide> beginpattern, quiet, verbose, dolowercase <ide> def crackline(line,reset=0): <ide> <ide> Cracked data is saved in grouplist[0]. <ide> """ <del> global beginpattern, groupcounter, groupname, groupcache, grouplist, gotnextfile,\ <del> filepositiontext, currentfilename, neededmodule, expectbegin, skipblocksuntil,\ <del> skipemptyends, previous_context <add> global beginpattern, groupcounter, groupname, groupcache, grouplist <add> global filepositiontext, currentfilename, neededmodule, expectbegin <add> global skipblocksuntil, skipemptyends, previous_context, gotnextfile <add> <ide> if ';' in line and not (f2pyenhancementspattern[0].match(line) or <ide> multilinepattern[0].match(line)): <ide> for l in line.split(';'): <ide> def _resolvenameargspattern(line): <ide> return None, [], None, None <ide> <ide> def analyzeline(m, case, line): <del> global groupcounter, groupname, groupcache, grouplist, filepositiontext,\ <del> currentfilename, f77modulename, neededinterface, neededmodule, expectbegin,\ <del> gotnextfile, previous_context <add> global groupcounter, groupname, groupcache, grouplist, filepositiontext <add> global currentfilename, f77modulename, neededinterface, neededmodule <add> global expectbegin, gotnextfile, previous_context <add> <ide> block=m.group('this') <ide> if case != 'multiline': <ide> previous_context = None <ide> def removespaces(expr): <ide> expr2=expr2+expr[i] <ide> expr2=expr2+expr[-1] <ide> return expr2 <add> <ide> def markinnerspaces(line): <del> l='';f=0 <del> cc='\'' <del> cc1='"' <del> cb='' <add> l = ''; <add> f = 0 <add> cc = '\'' <add> cb = '' <ide> for c in line: <del> if cb=='\\' and c in ['\\', '\'', '"']: <del> l=l+c <del> cb=c <add> if cb == '\\' and c in ['\\', '\'', '"']: <add> l = l + c <add> cb = c <ide> continue <del> if f==0 and c in ['\'', '"']: cc=c; cc1={'\'':'"','"':'\''}[c] <del> if c==cc:f=f+1 <del> elif c==cc:f=f-1 <del> elif c==' ' and f==1: l=l+'@_@'; continue <del> l=l+c;cb=c <add> if f == 0 and c in ['\'', '"']: <add> cc = c <add> if c == cc: <add> f = f + 1 <add> elif c == cc: <add> f = f - 1 <add> elif c==' ' and f == 1: <add> l = l + '@_@' <add> continue <add> l = l + c <add> cb = c <ide> return l <add> <ide> def updatevars(typespec, selector, attrspec, entitydecl): <ide> global groupcache, groupcounter <add> <ide> last_name = None <ide> kindselect, charselect, typename=cracktypespec(typespec, selector) <ide> if attrspec: <ide> def getblockname(block,unknown='unknown'): <ide> <ide> def setmesstext(block): <ide> global filepositiontext <add> <ide> try: <ide> filepositiontext='In: %s:%s\n'%(block['from'], block['name']) <ide> except: <ide> def get_usedict(block): <ide> <ide> def get_useparameters(block, param_map=None): <ide> global f90modulevars <add> <ide> if param_map is None: <ide> param_map = {} <ide> usedict = get_usedict(block) <ide> def get_useparameters(block, param_map=None): <ide> <ide> def postcrack2(block,tab='',param_map=None): <ide> global f90modulevars <add> <ide> if not f90modulevars: <ide> return block <ide> if isinstance(block, list): <ide> def postcrack(block,args=None,tab=''): <ide> determine expression types if in argument list <ide> """ <ide> global usermodules, onlyfunctions <add> <ide> if isinstance(block, list): <ide> gret=[] <ide> uret=[] <ide> def postcrack(block,args=None,tab=''): <ide> str(block)) <ide> if 'name' in block and not block['name']=='unknown_interface': <ide> outmess('%sBlock: %s\n'%(tab, block['name']), 0) <del> blocktype=block['block'] <del> block=analyzeargs(block) <del> block=analyzecommon(block) <del> block['vars']=analyzevars(block) <del> block['sortvars']=sortvarnames(block['vars']) <add> block = analyzeargs(block) <add> block = analyzecommon(block) <add> block['vars'] = analyzevars(block) <add> block['sortvars'] = sortvarnames(block['vars']) <ide> if 'args' in block and block['args']: <del> args=block['args'] <del> block['body']=analyzebody(block, args, tab=tab) <add> args = block['args'] <add> block['body'] = analyzebody(block, args, tab=tab) <ide> <ide> userisdefined=[] <ide> ## fromuser = [] <ide> def analyzecommon(block): <ide> <ide> def analyzebody(block,args,tab=''): <ide> global usermodules, skipfuncs, onlyfuncs, f90modulevars <add> <ide> setmesstext(block) <ide> body=[] <ide> for b in block['body']: <ide> def get_parameters(vars, global_params={}): <ide> v[m.start():m.end()].lower().replace('d', 'e')) <ide> v = ''.join(tt) <ide> if iscomplex(vars[n]): <del> if v[0]=='(' and v[-1]==')': <add> if v[0] == '(' and v[-1] == ')': <add> # FIXME, unused l looks like potential bug <ide> l = markoutercomma(v[1:-1]).split('@,@') <ide> try: <ide> params[n] = eval(v, g_params, params) <ide> def _eval_scalar(value, params): <ide> <ide> def analyzevars(block): <ide> global f90modulevars <add> <ide> setmesstext(block) <ide> implicitrules, attrrules=buildimplicitrules(block) <ide> vars=copy.copy(block['vars']) <ide> def determineexprtype(expr,vars,rules={}): <ide> ###### <ide> def crack2fortrangen(block,tab='\n', as_interface=False): <ide> global skipfuncs, onlyfuncs <add> <ide> setmesstext(block) <ide> ret='' <ide> if isinstance(block, list): <ide> def crack2fortrangen(block,tab='\n', as_interface=False): <ide> prefix='' <ide> name='' <ide> args='' <del> blocktype=block['block'] <del> if blocktype=='program': return '' <add> blocktype = block['block'] <add> if blocktype == 'program': <add> return '' <ide> argsl = [] <ide> if 'name' in block: <ide> name=block['name'] <ide> def crack2fortrangen(block,tab='\n', as_interface=False): <ide> for k in list(block['f2pyenhancements'].keys()): <ide> f2pyenhancements = '%s%s%s %s'%(f2pyenhancements, tab+tabchar, k, block['f2pyenhancements'][k]) <ide> intent_lst = block.get('intent', [])[:] <del> if blocktype=='function' and 'callback' in intent_lst: <add> if blocktype == 'function' and 'callback' in intent_lst: <ide> intent_lst.remove('callback') <ide> if intent_lst: <ide> f2pyenhancements = '%s%sintent(%s) %s'%\ <ide> def crack2fortrangen(block,tab='\n', as_interface=False): <ide> entry_stmts = '%s%sentry %s(%s)' \ <ide> % (entry_stmts, tab+tabchar, k, ','.join(i)) <ide> body = body + entry_stmts <del> if blocktype=='block data' and name=='_BLOCK_DATA_': <add> if blocktype == 'block data' and name == '_BLOCK_DATA_': <ide> name = '' <ide> ret='%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s'%(tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name) <ide> return ret <ide> def vars2fortran(block,vars,args,tab='', as_interface=False): <ide> <ide> def crackfortran(files): <ide> global usermodules <add> <ide> outmess('Reading fortran codes...\n', 0) <ide> readfortrancode(files, crackline) <ide> outmess('Post-processing...\n', 0) <ide> def crackfortran(files): <ide> <ide> def crack2fortran(block): <ide> global f2py_version <add> <ide> pyf=crack2fortrangen(block)+'\n' <ide> header="""! -*- f90 -*- <ide> ! Note: the context of this file is case sensitive. <ide><path>numpy/f2py/diagnose.py <ide> <ide> def run_command(cmd): <ide> print('Running %r:' % (cmd)) <del> s = os.system(cmd) <add> os.system(cmd) <ide> print('------') <add> <ide> def run(): <ide> _path = os.getcwd() <ide> os.chdir(tempfile.gettempdir()) <ide><path>numpy/f2py/f2py2e.py <ide> <ide> f2py_version = __version__.version <ide> errmess = sys.stderr.write <del>#outmess=sys.stdout.write <add># outmess=sys.stdout.write <ide> show = pprint.pprint <ide> outmess = auxfuncs.outmess <ide> <ide> Requires: Python 2.3 or higher. <ide> License: NumPy license (see LICENSE.txt in the NumPy source code) <ide> Copyright 1999 - 2011 Pearu Peterson all rights reserved. <del>http://cens.ioc.ee/projects/f2py2e/"""%(f2py_version, numpy_version) <add>http://cens.ioc.ee/projects/f2py2e/""" % (f2py_version, numpy_version) <add> <ide> <ide> def scaninputline(inputline): <del> files, funcs, skipfuncs, onlyfuncs, debug=[], [], [], [], [] <del> f, f2, f3, f4, f5, f6, f7, f8, f9=1, 0, 0, 0, 0, 0, 0, 0, 0 <add> files, skipfuncs, onlyfuncs, debug = [], [], [], [] <add> f, f2, f3, f5, f6, f7, f8, f9 = 1, 0, 0, 0, 0, 0, 0, 0 <ide> verbose = 1 <del> dolc=-1 <add> dolc = -1 <ide> dolatexdoc = 0 <ide> dorestdoc = 0 <ide> wrapfuncs = 1 <ide> buildpath = '.' <ide> include_paths = [] <del> signsfile, modulename=None, None <del> options = {'buildpath':buildpath, <add> signsfile, modulename = None, None <add> options = {'buildpath': buildpath, <ide> 'coutput': None, <ide> 'f2py_wrapper_output': None} <ide> for l in inputline: <del> if l=='': pass <del> elif l=='only:': f=0 <del> elif l=='skip:': f=-1 <del> elif l==':': f=1;f4=0 <del> elif l[:8]=='--debug-': debug.append(l[8:]) <del> elif l=='--lower': dolc=1 <del> elif l=='--build-dir': f6=1 <del> elif l=='--no-lower': dolc=0 <del> elif l=='--quiet': verbose = 0 <del> elif l=='--verbose': verbose += 1 <del> elif l=='--latex-doc': dolatexdoc=1 <del> elif l=='--no-latex-doc': dolatexdoc=0 <del> elif l=='--rest-doc': dorestdoc=1 <del> elif l=='--no-rest-doc': dorestdoc=0 <del> elif l=='--wrap-functions': wrapfuncs=1 <del> elif l=='--no-wrap-functions': wrapfuncs=0 <del> elif l=='--short-latex': options['shortlatex']=1 <del> elif l=='--coutput': f8=1 <del> elif l=='--f2py-wrapper-output': f9=1 <del> elif l=='--overwrite-signature': options['h-overwrite']=1 <del> elif l=='-h': f2=1 <del> elif l=='-m': f3=1 <del> elif l[:2]=='-v': <add> if l == '': <add> pass <add> elif l == 'only:': <add> f = 0 <add> elif l == 'skip:': <add> f = -1 <add> elif l == ':': <add> f = 1 <add> elif l[:8] == '--debug-': <add> debug.append(l[8:]) <add> elif l == '--lower': <add> dolc = 1 <add> elif l == '--build-dir': <add> f6 = 1 <add> elif l == '--no-lower': <add> dolc = 0 <add> elif l == '--quiet': <add> verbose = 0 <add> elif l == '--verbose': <add> verbose += 1 <add> elif l == '--latex-doc': <add> dolatexdoc = 1 <add> elif l == '--no-latex-doc': <add> dolatexdoc = 0 <add> elif l == '--rest-doc': <add> dorestdoc = 1 <add> elif l == '--no-rest-doc': <add> dorestdoc = 0 <add> elif l == '--wrap-functions': <add> wrapfuncs = 1 <add> elif l == '--no-wrap-functions': <add> wrapfuncs = 0 <add> elif l == '--short-latex': <add> options['shortlatex'] = 1 <add> elif l == '--coutput': <add> f8 = 1 <add> elif l == '--f2py-wrapper-output': <add> f9 = 1 <add> elif l == '--overwrite-signature': <add> options['h-overwrite'] = 1 <add> elif l == '-h': <add> f2 = 1 <add> elif l == '-m': <add> f3 = 1 <add> elif l[:2] == '-v': <ide> print(f2py_version) <ide> sys.exit() <del> elif l=='--show-compilers': <del> f5=1 <del> elif l[:8]=='-include': <add> elif l == '--show-compilers': <add> f5 = 1 <add> elif l[:8] == '-include': <ide> cfuncs.outneeds['userincludes'].append(l[9:-1]) <del> cfuncs.userincludes[l[9:-1]]='#include '+l[8:] <add> cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:] <ide> elif l[:15] in '--include_paths': <del> outmess('f2py option --include_paths is deprecated, use --include-paths instead.\n') <del> f7=1 <add> outmess( <add> 'f2py option --include_paths is deprecated, use --include-paths instead.\n') <add> f7 = 1 <ide> elif l[:15] in '--include-paths': <del> f7=1 <del> elif l[0]=='-': <del> errmess('Unknown option %s\n'%repr(l)) <add> f7 = 1 <add> elif l[0] == '-': <add> errmess('Unknown option %s\n' % repr(l)) <ide> sys.exit() <del> elif f2: f2=0;signsfile=l <del> elif f3: f3=0;modulename=l <del> elif f6: f6=0;buildpath=l <del> elif f7: f7=0;include_paths.extend(l.split(os.pathsep)) <del> elif f8: f8=0;options["coutput"]=l <del> elif f9: f9=0;options["f2py_wrapper_output"]=l <del> elif f==1: <add> elif f2: <add> f2 = 0 <add> signsfile = l <add> elif f3: <add> f3 = 0 <add> modulename = l <add> elif f6: <add> f6 = 0 <add> buildpath = l <add> elif f7: <add> f7 = 0 <add> include_paths.extend(l.split(os.pathsep)) <add> elif f8: <add> f8 = 0 <add> options["coutput"] = l <add> elif f9: <add> f9 = 0 <add> options["f2py_wrapper_output"] = l <add> elif f == 1: <ide> try: <ide> open(l).close() <ide> files.append(l) <ide> except IOError as detail: <del> errmess('IOError: %s. Skipping file "%s".\n'%(str(detail), l)) <del> elif f==-1: skipfuncs.append(l) <del> elif f==0: onlyfuncs.append(l) <add> errmess('IOError: %s. Skipping file "%s".\n' % <add> (str(detail), l)) <add> elif f == -1: <add> skipfuncs.append(l) <add> elif f == 0: <add> onlyfuncs.append(l) <ide> if not f5 and not files and not modulename: <ide> print(__usage__) <ide> sys.exit() <ide> if not os.path.isdir(buildpath): <ide> if not verbose: <del> outmess('Creating build directory %s'%(buildpath)) <add> outmess('Creating build directory %s' % (buildpath)) <ide> os.mkdir(buildpath) <ide> if signsfile: <ide> signsfile = os.path.join(buildpath, signsfile) <ide> if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options: <del> errmess('Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n'%(signsfile)) <add> errmess( <add> 'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile)) <ide> sys.exit() <ide> <del> options['debug']=debug <del> options['verbose']=verbose <del> if dolc==-1 and not signsfile: options['do-lower']=0 <del> else: options['do-lower']=dolc <del> if modulename: options['module']=modulename <del> if signsfile: options['signsfile']=signsfile <del> if onlyfuncs: options['onlyfuncs']=onlyfuncs <del> if skipfuncs: options['skipfuncs']=skipfuncs <add> options['debug'] = debug <add> options['verbose'] = verbose <add> if dolc == -1 and not signsfile: <add> options['do-lower'] = 0 <add> else: <add> options['do-lower'] = dolc <add> if modulename: <add> options['module'] = modulename <add> if signsfile: <add> options['signsfile'] = signsfile <add> if onlyfuncs: <add> options['onlyfuncs'] = onlyfuncs <add> if skipfuncs: <add> options['skipfuncs'] = skipfuncs <ide> options['dolatexdoc'] = dolatexdoc <ide> options['dorestdoc'] = dorestdoc <ide> options['wrapfuncs'] = wrapfuncs <del> options['buildpath']=buildpath <del> options['include_paths']=include_paths <add> options['buildpath'] = buildpath <add> options['include_paths'] = include_paths <ide> return files, options <ide> <add> <ide> def callcrackfortran(files, options): <del> rules.options=options <del> funcs=[] <del> crackfortran.debug=options['debug'] <del> crackfortran.verbose=options['verbose'] <add> rules.options = options <add> crackfortran.debug = options['debug'] <add> crackfortran.verbose = options['verbose'] <ide> if 'module' in options: <del> crackfortran.f77modulename=options['module'] <add> crackfortran.f77modulename = options['module'] <ide> if 'skipfuncs' in options: <del> crackfortran.skipfuncs=options['skipfuncs'] <add> crackfortran.skipfuncs = options['skipfuncs'] <ide> if 'onlyfuncs' in options: <del> crackfortran.onlyfuncs=options['onlyfuncs'] <del> crackfortran.include_paths[:]=options['include_paths'] <del> crackfortran.dolowercase=options['do-lower'] <del> postlist=crackfortran.crackfortran(files) <add> crackfortran.onlyfuncs = options['onlyfuncs'] <add> crackfortran.include_paths[:] = options['include_paths'] <add> crackfortran.dolowercase = options['do-lower'] <add> postlist = crackfortran.crackfortran(files) <ide> if 'signsfile' in options: <del> outmess('Saving signatures to file "%s"\n'%(options['signsfile'])) <del> pyf=crackfortran.crack2fortran(postlist) <del> if options['signsfile'][-6:]=='stdout': <add> outmess('Saving signatures to file "%s"\n' % (options['signsfile'])) <add> pyf = crackfortran.crack2fortran(postlist) <add> if options['signsfile'][-6:] == 'stdout': <ide> sys.stdout.write(pyf) <ide> else: <del> f=open(options['signsfile'], 'w') <add> f = open(options['signsfile'], 'w') <ide> f.write(pyf) <ide> f.close() <ide> if options["coutput"] is None: <ide> def callcrackfortran(files, options): <ide> mod["f2py_wrapper_output"] = options["f2py_wrapper_output"] <ide> return postlist <ide> <add> <ide> def buildmodules(lst): <ide> cfuncs.buildcfuncs() <ide> outmess('Building modules...\n') <del> modules, mnames, isusedby=[], [], {} <add> modules, mnames, isusedby = [], [], {} <ide> for i in range(len(lst)): <ide> if '__user__' in lst[i]['name']: <ide> cb_rules.buildcallbacks(lst[i]) <ide> else: <ide> if 'use' in lst[i]: <ide> for u in lst[i]['use'].keys(): <ide> if u not in isusedby: <del> isusedby[u]=[] <add> isusedby[u] = [] <ide> isusedby[u].append(lst[i]['name']) <ide> modules.append(lst[i]) <ide> mnames.append(lst[i]['name']) <ide> ret = {} <ide> for i in range(len(mnames)): <ide> if mnames[i] in isusedby: <del> outmess('\tSkipping module "%s" which is used by %s.\n'%(mnames[i], ','.join(['"%s"'%s for s in isusedby[mnames[i]]]))) <add> outmess('\tSkipping module "%s" which is used by %s.\n' % ( <add> mnames[i], ','.join(['"%s"' % s for s in isusedby[mnames[i]]]))) <ide> else: <del> um=[] <add> um = [] <ide> if 'use' in modules[i]: <ide> for u in modules[i]['use'].keys(): <ide> if u in isusedby and u in mnames: <ide> um.append(modules[mnames.index(u)]) <ide> else: <del> outmess('\tModule "%s" uses nonexisting "%s" which will be ignored.\n'%(mnames[i], u)) <add> outmess( <add> '\tModule "%s" uses nonexisting "%s" which will be ignored.\n' % (mnames[i], u)) <ide> ret[mnames[i]] = {} <ide> dict_append(ret[mnames[i]], rules.buildmodule(modules[i], um)) <ide> return ret <ide> <add> <ide> def dict_append(d_out, d_in): <ide> for (k, v) in d_in.items(): <ide> if k not in d_out: <ide> def dict_append(d_out, d_in): <ide> else: <ide> d_out[k].append(v) <ide> <add> <ide> def run_main(comline_list): <ide> """Run f2py as if string.join(comline_list,' ') is used as a command line. <ide> In case of using -h flag, return None. <ide> """ <ide> crackfortran.reset_global_f2py_vars() <del> f2pydir=os.path.dirname(os.path.abspath(cfuncs.__file__)) <add> f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__)) <ide> fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h') <ide> fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c') <del> files, options=scaninputline(comline_list) <del> auxfuncs.options=options <del> postlist=callcrackfortran(files, options) <del> isusedby={} <add> files, options = scaninputline(comline_list) <add> auxfuncs.options = options <add> postlist = callcrackfortran(files, options) <add> isusedby = {} <ide> for i in range(len(postlist)): <ide> if 'use' in postlist[i]: <ide> for u in postlist[i]['use'].keys(): <ide> if u not in isusedby: <del> isusedby[u]=[] <add> isusedby[u] = [] <ide> isusedby[u].append(postlist[i]['name']) <ide> for i in range(len(postlist)): <del> if postlist[i]['block']=='python module' and '__user__' in postlist[i]['name']: <add> if postlist[i]['block'] == 'python module' and '__user__' in postlist[i]['name']: <ide> if postlist[i]['name'] in isusedby: <del> #if not quiet: <del> outmess('Skipping Makefile build for module "%s" which is used by %s\n'%(postlist[i]['name'], ','.join(['"%s"'%s for s in isusedby[postlist[i]['name']]]))) <add> # if not quiet: <add> outmess('Skipping Makefile build for module "%s" which is used by %s\n' % ( <add> postlist[i]['name'], ','.join(['"%s"' % s for s in isusedby[postlist[i]['name']]]))) <ide> if 'signsfile' in options: <del> if options['verbose']>1: <del> outmess('Stopping. Edit the signature file and then run f2py on the signature file: ') <del> outmess('%s %s\n'%(os.path.basename(sys.argv[0]), options['signsfile'])) <add> if options['verbose'] > 1: <add> outmess( <add> 'Stopping. Edit the signature file and then run f2py on the signature file: ') <add> outmess('%s %s\n' % <add> (os.path.basename(sys.argv[0]), options['signsfile'])) <ide> return <ide> for i in range(len(postlist)): <del> if postlist[i]['block']!='python module': <add> if postlist[i]['block'] != 'python module': <ide> if 'python module' not in options: <del> errmess('Tip: If your original code is Fortran source then you must use -m option.\n') <del> raise TypeError('All blocks must be python module blocks but got %s'%(repr(postlist[i]['block']))) <del> auxfuncs.debugoptions=options['debug'] <del> f90mod_rules.options=options <del> auxfuncs.wrapfuncs=options['wrapfuncs'] <add> errmess( <add> 'Tip: If your original code is Fortran source then you must use -m option.\n') <add> raise TypeError('All blocks must be python module blocks but got %s' % ( <add> repr(postlist[i]['block']))) <add> auxfuncs.debugoptions = options['debug'] <add> f90mod_rules.options = options <add> auxfuncs.wrapfuncs = options['wrapfuncs'] <ide> <del> ret=buildmodules(postlist) <add> ret = buildmodules(postlist) <ide> <ide> for mn in ret.keys(): <del> dict_append(ret[mn], {'csrc':fobjcsrc,'h':fobjhsrc}) <add> dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc}) <ide> return ret <ide> <del>def filter_files(prefix,suffix,files,remove_prefix=None): <add> <add>def filter_files(prefix, suffix, files, remove_prefix=None): <ide> """ <ide> Filter files by prefix and suffix. <ide> """ <ide> filtered, rest = [], [] <del> match = re.compile(prefix+r'.*'+suffix+r'\Z').match <add> match = re.compile(prefix + r'.*' + suffix + r'\Z').match <ide> if remove_prefix: <ide> ind = len(prefix) <ide> else: <ide> ind = 0 <ide> for file in [x.strip() for x in files]: <del> if match(file): filtered.append(file[ind:]) <del> else: rest.append(file) <add> if match(file): <add> filtered.append(file[ind:]) <add> else: <add> rest.append(file) <ide> return filtered, rest <ide> <add> <ide> def get_prefix(module): <ide> p = os.path.dirname(os.path.dirname(module.__file__)) <ide> return p <ide> <add> <ide> def run_compile(): <ide> """ <ide> Do it all in one call! <ide> def run_compile(): <ide> del sys.argv[i] <ide> <ide> remove_build_dir = 0 <del> try: i = sys.argv.index('--build-dir') <del> except ValueError: i=None <add> try: <add> i = sys.argv.index('--build-dir') <add> except ValueError: <add> i = None <ide> if i is not None: <del> build_dir = sys.argv[i+1] <del> del sys.argv[i+1] <add> build_dir = sys.argv[i + 1] <add> del sys.argv[i + 1] <ide> del sys.argv[i] <ide> else: <ide> remove_build_dir = 1 <ide> def run_compile(): <ide> if sysinfo_flags: <ide> sysinfo_flags = [f[7:] for f in sysinfo_flags] <ide> <del> _reg2 = re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include') <add> _reg2 = re.compile( <add> r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include') <ide> f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] <ide> sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] <ide> f2py_flags2 = [] <ide> fl = 0 <ide> for a in sys.argv[1:]: <ide> if a in ['only:', 'skip:']: <ide> fl = 1 <del> elif a==':': <add> elif a == ':': <ide> fl = 0 <del> if fl or a==':': <add> if fl or a == ':': <ide> f2py_flags2.append(a) <del> if f2py_flags2 and f2py_flags2[-1]!=':': <add> if f2py_flags2 and f2py_flags2[-1] != ':': <ide> f2py_flags2.append(':') <ide> f2py_flags.extend(f2py_flags2) <ide> <ide> sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] <del> _reg3 = re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)') <add> _reg3 = re.compile( <add> r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)') <ide> flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] <ide> sys.argv = [_m for _m in sys.argv if _m not in flib_flags] <del> _reg4 = re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))') <add> _reg4 = re.compile( <add> r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))') <ide> fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)] <ide> sys.argv = [_m for _m in sys.argv if _m not in fc_flags] <ide> <ide> if 1: <ide> del_list = [] <ide> for s in flib_flags: <ide> v = '--fcompiler=' <del> if s[:len(v)]==v: <add> if s[:len(v)] == v: <ide> from numpy.distutils import fcompiler <ide> fcompiler.load_all_fcompiler_classes() <ide> allowed_keys = list(fcompiler.fcompiler_class.keys()) <ide> nv = ov = s[len(v):].lower() <ide> if ov not in allowed_keys: <del> vmap = {} # XXX <add> vmap = {} # XXX <ide> try: <ide> nv = vmap[ov] <ide> except KeyError: <ide> def run_compile(): <ide> for s in del_list: <ide> i = flib_flags.index(s) <ide> del flib_flags[i] <del> assert len(flib_flags)<=2, repr(flib_flags) <add> assert len(flib_flags) <= 2, repr(flib_flags) <ide> <ide> _reg5 = re.compile(r'[-][-](verbose)') <ide> setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] <ide> def run_compile(): <ide> <ide> for optname in ['--include_paths', '--include-paths']: <ide> if optname in sys.argv: <del> i = sys.argv.index (optname) <del> f2py_flags.extend (sys.argv[i:i+2]) <del> del sys.argv[i+1], sys.argv[i] <add> i = sys.argv.index(optname) <add> f2py_flags.extend(sys.argv[i:i + 2]) <add> del sys.argv[i + 1], sys.argv[i] <ide> sources = sys.argv[1:] <ide> <ide> if '-m' in sys.argv: <ide> i = sys.argv.index('-m') <del> modulename = sys.argv[i+1] <del> del sys.argv[i+1], sys.argv[i] <add> modulename = sys.argv[i + 1] <add> del sys.argv[i + 1], sys.argv[i] <ide> sources = sys.argv[1:] <ide> else: <ide> from numpy.distutils.command.build_src import get_f2py_modulename <ide> def run_compile(): <ide> libraries, sources = filter_files('-l', '', sources, remove_prefix=1) <ide> undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1) <ide> define_macros, sources = filter_files('-D', '', sources, remove_prefix=1) <del> using_numarray = 0 <del> using_numeric = 0 <ide> for i in range(len(define_macros)): <ide> name_value = define_macros[i].split('=', 1) <del> if len(name_value)==1: <add> if len(name_value) == 1: <ide> name_value.append(None) <del> if len(name_value)==2: <add> if len(name_value) == 2: <ide> define_macros[i] = tuple(name_value) <ide> else: <ide> print('Invalid use of -D:', name_value) <ide> <ide> from numpy.distutils.system_info import get_info <ide> <del> num_include_dir = None <ide> num_info = {} <del> #import numpy <del> #n = 'numpy' <del> #p = get_prefix(numpy) <del> #from numpy.distutils.misc_util import get_numpy_include_dirs <del> #num_info = {'include_dirs': get_numpy_include_dirs()} <del> <ide> if num_info: <ide> include_dirs.extend(num_info.get('include_dirs', [])) <ide> <ide> def run_compile(): <ide> for n in sysinfo_flags: <ide> i = get_info(n) <ide> if not i: <del> outmess('No %s resources found in system'\ <add> outmess('No %s resources found in system' <ide> ' (try `f2py --help-link`)\n' % (repr(n))) <del> dict_append(ext_args,**i) <add> dict_append(ext_args, **i) <ide> <ide> ext = Extension(**ext_args) <ide> sys.argv = [sys.argv[0]] + setup_flags <ide> def run_compile(): <ide> '--build-base', build_dir, <ide> '--build-platlib', '.']) <ide> if fc_flags: <del> sys.argv.extend(['config_fc']+fc_flags) <add> sys.argv.extend(['config_fc'] + fc_flags) <ide> if flib_flags: <del> sys.argv.extend(['build_ext']+flib_flags) <add> sys.argv.extend(['build_ext'] + flib_flags) <ide> <del> setup(ext_modules = [ext]) <add> setup(ext_modules=[ext]) <ide> <ide> if remove_build_dir and os.path.exists(build_dir): <ide> import shutil <del> outmess('Removing build directory %s\n'%(build_dir)) <add> outmess('Removing build directory %s\n' % (build_dir)) <ide> shutil.rmtree(build_dir) <ide> <add> <ide> def main(): <ide> if '--help-link' in sys.argv[1:]: <ide> sys.argv.remove('--help-link') <ide> def main(): <ide> else: <ide> run_main(sys.argv[1:]) <ide> <del>#if __name__ == "__main__": <add># if __name__ == "__main__": <ide> # main() <ide> <ide> <ide><path>numpy/f2py/f90mod_rules.py <ide> <ide> f2py_version='See `f2py -v`' <ide> <del>import pprint <del>import sys <del>errmess=sys.stderr.write <del>outmess=sys.stdout.write <del>show=pprint.pprint <del> <del>from .auxfuncs import * <ide> import numpy as np <add> <add>from .auxfuncs import ( <add> applyrules, dictappend, hasbody,hasnote, isallocatable, isfunction, <add> isintent_hide, ismodule, isprivate, isroutine,isstringarray, l_or, <add> outmess <add>) <ide> from . import capi_maps <ide> from . import func2subr <ide> from .crackfortran import undo_rmbadname, undo_rmbadname1 <ide><path>numpy/f2py/func2subr.py <ide> <ide> __version__ = "$Revision: 1.16 $"[10:-1] <ide> <del>f2py_version='See `f2py -v`' <add>f2py_version = 'See `f2py -v`' <ide> <del>import pprint <ide> import copy <del>import sys <del>errmess=sys.stderr.write <del>outmess=sys.stdout.write <del>show=pprint.pprint <ide> <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> getfortranname, isexternal, isfunction, isfunction_wrap, isintent_in, <add> isintent_out, islogicalfunction,ismoduleroutine, isscalar, <add> issubroutine, issubroutine_wrap, outmess, show <add>) <add> <add> <ide> def var2fixfortran(vars,a,fa=None,f90mode=None): <ide> if fa is None: <ide> fa = a <ide> def add(line,ret=ret): <ide> args = [newname]+rout['args'] <ide> <ide> l = var2fixfortran(vars, name, newname, f90mode) <del> return_char_star = 0 <ide> if l[:13]=='character*(*)': <del> return_char_star = 1 <ide> if f90mode: l = 'character(len=10)'+l[13:] <ide> else: l = 'character*10'+l[13:] <ide> charselect = vars[name]['charselector'] <ide><path>numpy/f2py/rules.py <ide> from . import __version__ <ide> f2py_version = __version__.version <ide> <del>import pprint <del>import sys <add>import os <ide> import time <ide> import copy <ide> <del>from .auxfuncs import * <add>from .auxfuncs import ( <add> applyrules, debugcapi, dictappend, errmess, gentitle, getargs2, <add> hascallstatement, hasexternals, hasinitvalue, hasnote, hasresultnote, <add> isarray, isarrayofstrings, iscomplex, iscomplexarray, <add> iscomplexfunction, iscomplexfunction_warn, isdummyroutine, isexternal, <add> isfunction, isfunction_wrap, isint1array, isintent_aux, isintent_c, <add> isintent_callback, isintent_copy, isintent_hide, isintent_inout, <add> isintent_nothide, isintent_out, isintent_overwrite, islogical, <add> islong_complex, islong_double, islong_doublefunction, islong_long, <add> islong_longfunction, ismoduleroutine, isoptional, isrequired, isscalar, <add> issigned_long_longarray, isstring, isstringarray, isstringfunction, <add> issubroutine, issubroutine_wrap, isthreadsafe, isunsigned, <add> isunsigned_char, isunsigned_chararray, isunsigned_long_long, <add> isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray, <add> l_and, l_not, l_or, outmess, replace, stripcomma, <add>) <add> <ide> from . import capi_maps <del>from .capi_maps import * <ide> from . import cfuncs <ide> from . import common_rules <ide> from . import use_rules <ide> from . import f90mod_rules <ide> from . import func2subr <ide> <del>errmess = sys.stderr.write <del>outmess = sys.stdout.write <del>show = pprint.pprint <del> <ide> options={} <ide> sepdict={} <ide> #for k in ['need_cfuncs']: sepdict[k]=',' <ide> def buildmodule(m, um): <ide> outmess('\tBuilding module "%s"...\n'%(m['name'])) <ide> ret = {} <ide> mod_rules=defmod_rules[:] <del> vrd=modsign2map(m) <add> vrd = capi_maps.modsign2map(m) <ide> rd=dictappend({'f2py_version':f2py_version}, vrd) <ide> funcwrappers = [] <ide> funcwrappers2 = [] # F90 codes <ide> def buildapi(rout): <ide> args, depargs=getargs2(rout) <ide> capi_maps.depargs=depargs <ide> var=rout['vars'] <del> auxvars = [a for a in var.keys() if isintent_aux(var[a])] <add> # auxvars = [a for a in var.keys() if isintent_aux(var[a])] <ide> <ide> if ismoduleroutine(rout): <ide> outmess('\t\t\tConstructing wrapper function "%s.%s"...\n'%(rout['modulename'], rout['name'])) <ide> else: <ide> outmess('\t\tConstructing wrapper function "%s"...\n'%(rout['name'])) <ide> # Routine <del> vrd=routsign2map(rout) <add> vrd = capi_maps.routsign2map(rout) <ide> rd=dictappend({}, vrd) <ide> for r in rout_rules: <ide> if ('_check' in r and r['_check'](rout)) or ('_check' not in r): <ide> def buildapi(rout): <ide> nth, nthk=0, 0 <ide> savevrd={} <ide> for a in args: <del> vrd=sign2map(a, var[a]) <add> vrd=capi_maps.sign2map(a, var[a]) <ide> if isintent_aux(var[a]): <ide> _rules = aux_rules <ide> else: <ide><path>numpy/f2py/use_rules.py <ide> <ide> f2py_version='See `f2py -v`' <ide> <del>import pprint <del>import sys <del>errmess=sys.stderr.write <del>outmess=sys.stdout.write <del>show=pprint.pprint <ide> <del>from .auxfuncs import * <del>############## <add>from .auxfuncs import ( <add> applyrules,dictappend, gentitle, hasnote, outmess <add>) <add> <ide> <ide> usemodule_rules={ <ide> 'body':""" <ide> def buildusevar(name, realname, vars, usemodulename): <ide> vrd['texnamename']=name <ide> for i in nummap.keys(): <ide> vrd['texnamename']=vrd['texnamename'].replace(repr(i), nummap[i]) <del> if hasnote(vars[realname]): vrd['note']=vars[realname]['note'] <del> rd=dictappend({}, vrd) <del> var=vars[realname] <add> if hasnote(vars[realname]): <add> vrd['note']=vars[realname]['note'] <add> rd = dictappend({}, vrd) <ide> <ide> print(name, realname, vars[realname]) <del> ret=applyrules(usemodule_rules, rd) <add> ret = applyrules(usemodule_rules, rd) <ide> return ret
12
Go
Go
fix flaky testservicewithdefaultaddresspoolinit
f3a3ea0d3c7f4d4da035db871d3c8a8bbb51371f
<ide><path>integration/network/service_test.go <ide> func TestServiceWithPredefinedNetwork(t *testing.T) { <ide> swarm.ServiceWithNetwork(hostName), <ide> ) <ide> <del> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.RunningTasksCount(c, serviceID, instances), swarm.ServicePoll) <ide> <ide> _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) <ide> assert.NilError(t, err) <ide> func TestServiceRemoveKeepsIngressNetwork(t *testing.T) { <ide> }), <ide> ) <ide> <del> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.RunningTasksCount(c, serviceID, instances), swarm.ServicePoll) <ide> <ide> ctx := context.Background() <ide> _, _, err := c.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) <ide> func TestServiceRemoveKeepsIngressNetwork(t *testing.T) { <ide> assert.Assert(t, ok, "ingress-sbox not present in ingress network") <ide> } <ide> <del>func serviceRunningCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result { <del> return func(log poll.LogT) poll.Result { <del> services, err := client.ServiceList(context.Background(), types.ServiceListOptions{}) <del> if err != nil { <del> return poll.Error(err) <del> } <del> <del> if len(services) != int(instances) { <del> return poll.Continue("Service count at %d waiting for %d", len(services), instances) <del> } <del> return poll.Success() <del> } <del>} <del> <ide> func swarmIngressReady(client client.NetworkAPIClient) func(log poll.LogT) poll.Result { <ide> return func(log poll.LogT) poll.Result { <ide> netInfo, err := client.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ <ide> func TestServiceWithDataPathPortInit(t *testing.T) { <ide> skip.If(t, testEnv.OSType == "windows") <ide> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "DataPathPort was added in API v1.40") <ide> defer setupTest(t)() <del> var ops = []func(*daemon.Daemon){} <ide> var datapathPort uint32 = 7777 <del> ops = append(ops, daemon.WithSwarmDataPathPort(datapathPort)) <del> d := swarm.NewSwarm(t, testEnv, ops...) <del> <add> d := swarm.NewSwarm(t, testEnv, daemon.WithSwarmDataPathPort(datapathPort)) <ide> c := d.NewClientT(t) <del> defer c.Close() <del> <add> ctx := context.Background() <ide> // Create a overlay network <ide> name := "saanvisthira" + t.Name() <del> network.CreateNoError(context.Background(), t, c, name, <add> overlayID := network.CreateNoError(context.Background(), t, c, name, <ide> network.WithDriver("overlay")) <ide> <ide> var instances uint64 = 1 <ide> serviceID := swarm.CreateService(t, d, <ide> swarm.ServiceWithReplicas(instances), <add> swarm.ServiceWithName(name), <ide> swarm.ServiceWithNetwork(name), <ide> ) <ide> <del> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.RunningTasksCount(c, serviceID, instances), swarm.ServicePoll) <ide> <ide> info := d.Info(t) <ide> assert.Equal(t, info.Swarm.Cluster.DataPathPort, datapathPort) <del> err := c.ServiceRemove(context.Background(), serviceID) <add> err := c.ServiceRemove(ctx, serviceID) <add> assert.NilError(t, err) <add> poll.WaitOn(t, noServices(ctx, c), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.NoTasks(ctx, c), swarm.ServicePoll) <add> err = c.NetworkRemove(ctx, overlayID) <add> assert.NilError(t, err) <add> c.Close() <add> err = d.SwarmLeave(t, true) <ide> assert.NilError(t, err) <del> d.SwarmLeave(t, true) <ide> d.Stop(t) <ide> <ide> // Clean up , set it back to original one to make sure other tests don't fail <ide> // call without datapath port option. <del> ops = []func(*daemon.Daemon){} <del> d = swarm.NewSwarm(t, testEnv, ops...) <del> c = d.NewClientT(t) <del> <add> d = swarm.NewSwarm(t, testEnv) <add> nc := d.NewClientT(t) <add> defer nc.Close() <ide> // Create a overlay network <del> name = "saanvisthira" + t.Name() <del> network.CreateNoError(context.Background(), t, c, name, <add> name = "not-saanvisthira" + t.Name() <add> overlayID = network.CreateNoError(ctx, t, nc, name, <ide> network.WithDriver("overlay")) <ide> <ide> serviceID = swarm.CreateService(t, d, <ide> swarm.ServiceWithReplicas(instances), <add> swarm.ServiceWithName(name), <ide> swarm.ServiceWithNetwork(name), <ide> ) <ide> <del> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.RunningTasksCount(nc, serviceID, instances), swarm.ServicePoll) <ide> <ide> info = d.Info(t) <ide> var defaultDataPathPort uint32 = 4789 <ide> assert.Equal(t, info.Swarm.Cluster.DataPathPort, defaultDataPathPort) <del> err = c.ServiceRemove(context.Background(), serviceID) <add> err = nc.ServiceRemove(ctx, serviceID) <add> assert.NilError(t, err) <add> assert.NilError(t, err) <add> poll.WaitOn(t, noServices(ctx, nc), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.NoTasks(ctx, nc), swarm.ServicePoll) <add> err = nc.NetworkRemove(ctx, overlayID) <add> assert.NilError(t, err) <add> err = d.SwarmLeave(t, true) <ide> assert.NilError(t, err) <del> d.SwarmLeave(t, true) <ide> defer d.Stop(t) <ide> } <ide> <ide> func TestServiceWithDefaultAddressPoolInit(t *testing.T) { <ide> skip.If(t, testEnv.OSType == "windows") <ide> defer setupTest(t)() <del> var ops = []func(*daemon.Daemon){} <del> ipAddr := []string{"20.20.0.0/16"} <del> ops = append(ops, daemon.WithSwarmDefaultAddrPool(ipAddr)) <del> ops = append(ops, daemon.WithSwarmDefaultAddrPoolSubnetSize(24)) <del> d := swarm.NewSwarm(t, testEnv, ops...) <add> d := swarm.NewSwarm(t, testEnv, <add> daemon.WithSwarmDefaultAddrPool([]string{"20.20.0.0/16"}), <add> daemon.WithSwarmDefaultAddrPoolSubnetSize(24)) <ide> <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <add> ctx := context.Background() <ide> <ide> // Create a overlay network <ide> name := "sthira" + t.Name() <del> overlayID := network.CreateNoError(context.Background(), t, cli, name, <add> overlayID := network.CreateNoError(ctx, t, cli, name, <ide> network.WithDriver("overlay"), <ide> network.WithCheckDuplicate(), <ide> ) <ide> func TestServiceWithDefaultAddressPoolInit(t *testing.T) { <ide> swarm.ServiceWithNetwork(name), <ide> ) <ide> <del> poll.WaitOn(t, serviceRunningCount(cli, serviceID, instances), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.RunningTasksCount(cli, serviceID, instances), swarm.ServicePoll) <ide> <del> _, _, err := cli.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) <add> _, _, err := cli.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) <ide> assert.NilError(t, err) <ide> <del> out, err := cli.NetworkInspect(context.Background(), overlayID, types.NetworkInspectOptions{Verbose: true}) <add> out, err := cli.NetworkInspect(ctx, overlayID, types.NetworkInspectOptions{Verbose: true}) <ide> assert.NilError(t, err) <ide> t.Logf("%s: NetworkInspect: %+v", t.Name(), out) <ide> assert.Assert(t, len(out.IPAM.Config) > 0) <ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "20.20.0.0/24") <ide> <del> err = cli.ServiceRemove(context.Background(), serviceID) <add> err = cli.ServiceRemove(ctx, serviceID) <add> poll.WaitOn(t, noServices(ctx, cli), swarm.ServicePoll) <add> poll.WaitOn(t, swarm.NoTasks(ctx, cli), swarm.ServicePoll) <add> assert.NilError(t, err) <add> err = cli.NetworkRemove(ctx, overlayID) <add> assert.NilError(t, err) <add> err = d.SwarmLeave(t, true) <ide> assert.NilError(t, err) <del> d.SwarmLeave(t, true) <del> d.Stop(t) <del> <del> // Clean up , set it back to original one to make sure other tests don't fail <del> ipAddr = []string{"10.0.0.0/8"} <del> ops = append(ops, daemon.WithSwarmDefaultAddrPool(ipAddr)) <del> ops = append(ops, daemon.WithSwarmDefaultAddrPoolSubnetSize(24)) <del> d = swarm.NewSwarm(t, testEnv, ops...) <del> d.SwarmLeave(t, true) <ide> defer d.Stop(t) <add> <ide> }
1
PHP
PHP
remove parenthesis around sql identifiers
52608e2d51e2cdf05225131335dc48cc9b1f09b6
<ide><path>src/Database/Expression/ComparisonExpression.php <ide> public function sql(ValueBinder $binder): string <ide> $field = $field->sql($binder); <ide> } <ide> <del> if ($this->_value instanceof ExpressionInterface) { <add> if ($this->_value instanceof IdentifierExpression) { <add> $template = '%s %s %s'; <add> $value = $this->_value->sql($binder); <add> } elseif ($this->_value instanceof ExpressionInterface) { <ide> $template = '%s %s (%s)'; <ide> $value = $this->_value->sql($binder); <ide> } else { <ide> protected function _stringExpression(ValueBinder $binder): array <ide> { <ide> $template = '%s '; <ide> <del> if ($this->_field instanceof ExpressionInterface) { <add> if ($this->_field instanceof ExpressionInterface && !$this->_field instanceof IdentifierExpression) { <ide> $template = '(%s) '; <ide> } <ide> <ide><path>tests/TestCase/Database/Expression/AggregateExpressionTest.php <ide> public function testFilter(): void <ide> { <ide> $f = (new AggregateExpression('MyFunction'))->filter(['this' => new IdentifierExpression('that')]); <ide> $this->assertEqualsSql( <del> 'MyFunction() FILTER (WHERE this = (that))', <add> 'MyFunction() FILTER (WHERE this = that)', <ide> $f->sql(new ValueBinder()) <ide> ); <ide> <ide> $f->filter(function (QueryExpression $q) { <ide> return $q->add(['this2' => new IdentifierExpression('that2')]); <ide> }); <ide> $this->assertEqualsSql( <del> 'MyFunction() FILTER (WHERE (this = (that) AND this2 = (that2)))', <add> 'MyFunction() FILTER (WHERE (this = that AND this2 = that2))', <ide> $f->sql(new ValueBinder()) <ide> ); <ide> <ide> $f->over(); <ide> $this->assertEqualsSql( <del> 'MyFunction() FILTER (WHERE (this = (that) AND this2 = (that2))) OVER ()', <add> 'MyFunction() FILTER (WHERE (this = that AND this2 = that2)) OVER ()', <ide> $f->sql(new ValueBinder()) <ide> ); <ide> } <ide><path>tests/TestCase/Database/Expression/ComparisonExpressionTest.php <ide> namespace Cake\Test\TestCase\Database\Expression; <ide> <ide> use Cake\Database\Expression\ComparisonExpression; <add>use Cake\Database\Expression\IdentifierExpression; <ide> use Cake\Database\Expression\QueryExpression; <add>use Cake\Database\ValueBinder; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> * Tests Comparison class <ide> */ <ide> class ComparisonExpressionTest extends TestCase <ide> { <add> /** <add> * Test sql generation using IdentifierExpression <add> */ <add> public function testIdentifiers(): void <add> { <add> $expr = new ComparisonExpression('field', new IdentifierExpression('other_field')); <add> $this->assertEqualsSql('field = other_field', $expr->sql(new ValueBinder())); <add> <add> $expr = new ComparisonExpression(new IdentifierExpression('field'), new IdentifierExpression('other_field')); <add> $this->assertEqualsSql('field = other_field', $expr->sql(new ValueBinder())); <add> <add> $expr = new ComparisonExpression(new IdentifierExpression('field'), new QueryExpression(['other_field'])); <add> $this->assertEqualsSql('field = (other_field)', $expr->sql(new ValueBinder())); <add> <add> $expr = new ComparisonExpression(new IdentifierExpression('field'), 'value'); <add> $this->assertEqualsSql('field = :c0', $expr->sql(new ValueBinder())); <add> <add> $expr = new ComparisonExpression(new QueryExpression(['field']), new IdentifierExpression('other_field')); <add> $this->assertEqualsSql('field = other_field', $expr->sql(new ValueBinder())); <add> } <add> <ide> /** <ide> * Tests that cloning Comparion instance clones it's value and field expressions. <ide> */ <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testDeleteStripAliasesFromConditions(): void <ide> 'DELETE FROM <authors> WHERE \(' . <ide> '<id> = :c0 OR \(<name>\) IS NULL OR \(<email>\) IS NOT NULL OR \(' . <ide> '<name> not in \(:c1,:c2\) AND \(' . <del> '\(<name>\) = :c3 OR <name> = :c4 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c5\)' . <add> '<name> = :c3 OR <name> = :c4 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c5\)' . <ide> '\)' . <ide> '\)' . <ide> '\)', <ide> public function testUpdateWithExpression(): void <ide> $result = $query->sql(); <ide> <ide> $this->assertQuotedQuery( <del> 'UPDATE <comments> SET <article_id> = \(<user_id>\) WHERE <id> = :', <add> 'UPDATE <comments> SET <article_id> = <user_id> WHERE <id> = :', <ide> $result, <ide> !$this->autoQuote <ide> ); <ide> public function testUpdateStripAliasesFromConditions(): void <ide> 'UPDATE <authors> SET <name> = :c0 WHERE \(' . <ide> '<id> = :c1 OR \(<name>\) IS NULL OR \(<email>\) IS NOT NULL OR \(' . <ide> '<name> not in \(:c2,:c3\) AND \(' . <del> '\(<name>\) = :c4 OR <name> = :c5 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c6\)' . <add> '<name> = :c4 OR <name> = :c5 OR \(SELECT <e>\.<name> WHERE <e>\.<name> = :c6\)' . <ide> '\)' . <ide> '\)' . <ide> '\)',
4
Text
Text
fix old broken links and update for new repo
af17a4460ef4a77de663ba45f94c8b65a3646f20
<ide><path>CONTRIBUTING.md <ide> Contributions to Chart.js are welcome and encouraged, but please have a look thr <ide> Using issues <ide> ------------ <ide> <del>The [issue tracker](https://github.com/nnnick/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests. <add>The [issue tracker](https://github.com/chartjs/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests. <ide> <del>If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#writing-new-chart-types) in the documentation, and some of the [community extensions](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#community-extensions) that have been created already. <add>If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#creating-plugins). <ide> <ide> To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look. <ide> <ide> Clear, concise pull requests are excellent at continuing the project's community <ide> <ide> Be advised that **Chart.js 1.0.2 is in feature-complete status**. Pull requests adding new features to the 1.x branch will be disregarded. <ide> <del>Guidlines: <add>Guidelines: <ide> <ide> - Please create an issue first: <ide> - For bugs, we can discuss the fixing approach <ide> - For enhancements, we can discuss if it is within the project scope and avoid duplicate effort <del> - Please make changes to the files in [`/src`](https://github.com/nnnick/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory, this avoids merge conflicts <add> - Please make changes to the files in [`/src`](https://github.com/chartjs/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory, this avoids merge conflicts <ide> - Tabs for indentation, not spaces please <del> - If adding new functionality, please also update the relevant `.md` file in [`/docs`](https://github.com/nnnick/Chart.js/tree/master/docs) <add> - If adding new functionality, please also update the relevant `.md` file in [`/docs`](https://github.com/chartjs/Chart.js/tree/master/docs) <ide> - Please make your commits in logical sections with clear commit messages <ide> <ide> Joining the project <ide> ------------- <del> - Active committers and contributors are invited to introduce yourself and request commit access to this project. Please send an email to hello@nickdownie.com or file an issue. <add> - Active committers and contributors are invited to introduce yourself and request commit access to this project. Please send an email to hello@nickdownie.com or file an issue. <add> - We have a very active Slack community that you can join at https://chartjs-slack-automation.herokuapp.com. If you think you can help, we'd love to have you! <ide> <ide> License <ide> ------- <ide> <del>By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/nnnick/Chart.js/blob/master/LICENSE.md). <add>By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/chartjs/Chart.js/blob/master/LICENSE.md).
1
Ruby
Ruby
make cache directory for clean file
ea0fca9511222976047f444ea8038d104b921632
<ide><path>Library/Homebrew/cleanup.rb <ide> def clean! <ide> cleanup_old_cache_db <ide> rm_ds_store <ide> prune_prefix_symlinks_and_directories <add> HOMEBREW_CACHE.mkpath <ide> FileUtils.touch PERIODIC_CLEAN_FILE <ide> else <ide> args.each do |arg|
1
Go
Go
remove redundant warning
a8250a0b20006bae669f9d127eaf00d4284e1d9f
<ide><path>pkg/sysinfo/sysinfo.go <ide> func New(quiet bool) *SysInfo { <ide> } <ide> } else { <ide> _, err := ioutil.ReadFile(path.Join(cgroupCpuMountpoint, "cpu.cfs_period_us")) <del> logrus.Warnf("%s", cgroupCpuMountpoint) <ide> sysInfo.CpuCfsPeriod = err == nil <ide> if !sysInfo.CpuCfsPeriod && !quiet { <del> logrus.Warnf("WARING: Your kernel does not support cgroup cfs period") <add> logrus.Warn("Your kernel does not support cgroup cfs period") <ide> } <ide> _, err = ioutil.ReadFile(path.Join(cgroupCpuMountpoint, "cpu.cfs_quota_us")) <del> logrus.Warnf("%s", cgroupCpuMountpoint) <ide> sysInfo.CpuCfsQuota = err == nil <ide> if !sysInfo.CpuCfsQuota && !quiet { <ide> logrus.Warn("Your kernel does not support cgroup cfs quotas")
1
Text
Text
use relative links
d5535bf564e70ab1c0199a5c18fa842e8b499209
<ide><path>share/doc/homebrew/Acceptable-Formulae.md <ide> own! <ide> <ide> ### We try hard to avoid dupes in Homebrew/homebrew <ide> Stuff that comes with OS X or libraries that are provided by <del>[RubyGems, CPAN or PyPi](https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Gems,-Eggs-and-Perl-Modules.md) <add>[RubyGems, CPAN or PyPi](Gems,-Eggs-and-Perl-Modules.md) <ide> should not be duplicated. There are good reasons for this: <ide> <ide> * Duplicate libraries regularly break builds <ide><path>share/doc/homebrew/FAQ.md <ide> creating a separate user account especially for use of Homebrew. <ide> <ide> ### Why isn’t a particular command documented? <ide> <del>If it’s not in `man brew`, it’s probably an external command. These are documented [here](https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/External-Commands.md). <add>If it’s not in `man brew`, it’s probably an external command. These are documented [here](External-Commands.md). <ide> <ide> ### Why haven’t you pulled my pull request? <ide> If it’s been a while, bump it with a “bump” comment. Sometimes we miss requests and there are plenty of them. Maybe we were thinking on something. It will encourage consideration. In the meantime if you could rebase the pull request so that it can be cherry-picked more easily we will love you for a long time. <ide><path>share/doc/homebrew/Python-for-Formula-Authors.md <ide> The first line copies all of the executables to bin. The second line writes stub <ide> <ide> All Python dependencies of applications that are not packaged by Homebrew (and those dependencies' Python dependencies, recursively) **should** be unconditionally downloaded as `Resource`s and installed into the application keg's `libexec/"vendor"` path. This prevents the state of the system Python packages from being affected by installing an app with Homebrew and guarantees that apps use versions of their dependencies that are known to work together. `libexec/"vendor"` is preferred to `libexec` so that formulæ don't accidentally install executables belonging to their dependencies, which can cause linking conflicts. <ide> <del>Each dependency **should** be explicitly installed; please do not rely on setup.py or pip to perform automatic dependency resolution, for the [reasons described here](https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Acceptable-Formulae.md#we-dont-like-install-scripts-that-download-things). <add>Each dependency **should** be explicitly installed; please do not rely on setup.py or pip to perform automatic dependency resolution, for the [reasons described here](Acceptable-Formulae.md#we-dont-like-install-scripts-that-download-things). <ide> <ide> You can use [homebrew-pypi-poet](https://pypi.python.org/pypi/homebrew-pypi-poet) to help you write resource stanzas. To use it, set up a virtualenv and install your package and all its dependencies. Then, `pip install homebrew-pypi-poet` into the same virtualenv. `poet -f foo` will draft a complete formula for you, or `poet foo` will just generate the resource stanzas. <ide>
3
Python
Python
use pathlib.path instead of os.path
a035ebd32aad197908312ad4bebed4726855ee63
<ide><path>spacy/link.py <ide> import pip <ide> import site <ide> import plac <add>from pathlib import Path <ide> from . import util <ide> <ide> <ide> def link(origin, link_name, force=False): <ide> either the name of a pip package, or the local path to the model data <ide> directory. Linking models allows loading them via spacy.load(link_name).""" <ide> if is_package(origin): <del> link_package(origin, link_name) <add> link_package(origin, link_name, force) <ide> else: <ide> symlink(origin, link_name, force) <ide> <ide> def link_package(origin, link_name, force=False): <ide> package_path = site.getsitepackages()[0] <ide> meta = get_meta(package_path, origin) <ide> data_dir = origin + '-' + meta['version'] <del> model_path = os.path.join(package_path, origin, data_dir) <add> model_path = Path(package_path) / origin / data_dir <ide> symlink(model_path, link_name, force) <ide> <ide> <ide> def symlink(model_path, link_name, force): <del> if not os.path.isdir(model_path): <add> if not model_path.exists(): <ide> util.sys_exit( <ide> "The data should be located in {p}".format(p=model_path), <ide> title="Can't locate model data") <ide> <ide> data_path = str(util.get_data_path()) <del> link_path = os.path.join(os.path.abspath(__file__ + '/../../'), data_path, link_name) <add> link_path = Path(__file__).parent.parent / data_path / link_name <ide> <del> if os.path.isdir(link_path): <add> if link_path.exists(): <ide> if force: <del> os.unlink(link_path) <add> os.unlink(str(link_path)) <ide> else: <ide> util.sys_exit( <ide> "To overwrite an existing link, use the --force flag.", <ide> title="Link {l} already exists".format(l=link_name)) <del> model_path = os.path.abspath(model_path) <del> os.symlink(model_path, link_path) <add> <add> os.symlink(str(model_path), str(link_path)) <ide> util.print_msg( <del> "{a} --> {b}".format(a=model_path, b=link_path), <add> "{a} --> {b}".format(a=str(model_path), b=str(link_path)), <ide> "You can now load the model via spacy.load('{l}').".format(l=link_name), <ide> title="Linking successful") <ide>
1
Python
Python
fix imports in conversion scripts
053efc5d2d2e87833e9b7290a0dd83fa77cd6ae8
<ide><path>src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...utils import logging <del>from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert <add>from transformers import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py <ide> import torch <ide> from packaging import version <ide> <del>from ...utils import logging <del>from . import BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer <del>from .modeling_bart import _make_linear_from_emb <add>from transformers import ( <add> BartConfig, <add> BartForConditionalGeneration, <add> BartForSequenceClassification, <add> BartModel, <add> BartTokenizer, <add>) <add>from transformers.models.bart.modeling_bart import _make_linear_from_emb <add>from transformers.utils import logging <ide> <ide> <ide> FAIRSEQ_MODELS = ["bart.large", "bart.large.mnli", "bart.large.cnn", "bart_xsum/model.pt"] <ide><path>src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py <ide> import tensorflow as tf <ide> import torch <ide> <del>from ...utils import logging <del>from . import BertConfig, BertModel <add>from transformers import BertConfig, BertModel <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...utils import logging <del>from . import BertConfig, BertForPreTraining, load_tf_weights_in_bert <add>from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py <ide> import tensorflow as tf <ide> import torch <ide> <del>from . import BertModel <add>from transformers import BertModel <ide> <ide> <ide> def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str): <ide><path>src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...models.bart import BartConfig, BartForConditionalGeneration <del>from ...utils import logging <add>from transformers import BartConfig, BartForConditionalGeneration <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...file_utils import WEIGHTS_NAME <add>from transformers.file_utils import WEIGHTS_NAME <ide> <ide> <ide> DIALOGPT_MODELS = ["small", "medium", "large"] <ide><path>src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py <ide> import torch <ide> from torch.serialization import default_restore_location <ide> <del>from ...models.bert import BertConfig <del>from . import DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader <add>from .transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader <ide> <ide> <ide> CheckpointState = collections.namedtuple( <ide><path>src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...utils import logging <del>from . import ElectraConfig, ElectraForMaskedLM, ElectraForPreTraining, load_tf_weights_in_electra <add>from transformers import ElectraConfig, ElectraForMaskedLM, ElectraForPreTraining, load_tf_weights_in_electra <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py <ide> from fairseq import hub_utils <ide> from fairseq.data.dictionary import Dictionary <ide> <del>from ...file_utils import WEIGHTS_NAME <del>from ...tokenization_utils_base import TOKENIZER_CONFIG_FILE <del>from ...utils import logging <del>from . import VOCAB_FILES_NAMES, FSMTConfig, FSMTForConditionalGeneration <add>from transfomers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES <add>from transformers import FSMTConfig, FSMTForConditionalGeneration <add>from transformers.file_utils import WEIGHTS_NAME <add>from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_warning() <ide><path>src/transformers/models/funnel/__init__.py <ide> <ide> _import_structure = { <ide> "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], <add> "convert_funnel_original_tf_checkpoint_to_pytorch": [], <ide> "tokenization_funnel": ["FunnelTokenizer"], <ide> } <ide> <ide><path>src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py <ide> <ide> <ide> import argparse <del>import logging <ide> <ide> import torch <ide> <del>from . import FunnelConfig, FunnelForPreTraining, load_tf_weights_in_funnel <add>from transformers import FunnelConfig, FunnelForPreTraining, load_tf_weights_in_funnel <add>from transformers.utils import logging <ide> <ide> <del>logging.basicConfig(level=logging.INFO) <add>logging.set_verbosity_info() <ide> <ide> <ide> def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path): <ide><path>src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...file_utils import CONFIG_NAME, WEIGHTS_NAME <del>from ...utils import logging <del>from . import GPT2Config, GPT2Model, load_tf_weights_in_gpt2 <add>from transformers import GPT2Config, GPT2Model, load_tf_weights_in_gpt2 <add>from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py <ide> import pytorch_lightning as pl <ide> import torch <ide> <del>from . import LongformerForQuestionAnswering, LongformerModel <add>from transformers import LongformerForQuestionAnswering, LongformerModel <ide> <ide> <ide> class LightningModel(pl.LightningModule): <ide><path>src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py <ide> <ide> <ide> import argparse <del>import logging <ide> <ide> import torch <ide> <del>from . import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert <add>from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert <add>from transformers.utils import logging <ide> <ide> <del>logging.basicConfig(level=logging.INFO) <add>logging.set_verbosity_info() <ide> <ide> <ide> def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path): <ide><path>src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py <ide> from pathlib import Path <ide> from typing import List, Tuple <ide> <del>from .convert_marian_to_pytorch import ( <add>from transformers.models.marian.convert_marian_to_pytorch import ( <ide> FRONT_MATTER_TEMPLATE, <ide> _parse_readme, <ide> convert_all_sentencepiece_models, <ide><path>src/transformers/models/marian/convert_marian_to_pytorch.py <ide> import torch <ide> from tqdm import tqdm <ide> <del>from ...hf_api import HfApi <del>from . import MarianConfig, MarianMTModel, MarianTokenizer <add>from transformers import MarianConfig, MarianMTModel, MarianTokenizer <add>from transformers.hf_api import HfApi <ide> <ide> <ide> def remove_suffix(text: str, suffix: str): <ide><path>src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ..bart import BartForConditionalGeneration <del>from ..bart.convert_bart_original_pytorch_checkpoint_to_pytorch import remove_ignore_keys_ <del>from . import MBartConfig <add>from transformers import BartForConditionalGeneration, MBartConfig <add>from transformers.models.bart.convert_bart_original_pytorch_checkpoint_to_pytorch import remove_ignore_keys_ <ide> <ide> <ide> def convert_fairseq_mbart_checkpoint_from_disk(checkpoint_path, hf_config_path="facebook/mbart-large-en-ro"): <ide><path>src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...utils import logging <del>from . import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert <add>from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py <ide> import torch <ide> from tqdm import tqdm <ide> <del>from . import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer <del>from .configuration_pegasus import DEFAULTS, task_specific_params <add>from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer <add>from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params <ide> <ide> <ide> PATTERNS = [ <ide><path>src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <add>from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging <add> <ide> # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here <ide> # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively <ide> from transformers_old.modeling_prophetnet import ( <ide> XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, <ide> ) <ide> <del>from . import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging <del> <ide> <ide> logger = logging.get_logger(__name__) <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py <ide> import numpy as np <ide> import torch <ide> <del>from ...utils import logging <del>from . import ReformerConfig, ReformerModelWithLMHead <add>from transformers import ReformerConfig, ReformerModelWithLMHead <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py <ide> from fairseq.modules import TransformerSentenceEncoderLayer <ide> from packaging import version <ide> <del>from ...models.bert.modeling_bert import BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput <del>from ...utils import logging <del>from .modeling_roberta import RobertaConfig, RobertaForMaskedLM, RobertaForSequenceClassification <add>from transformers import RobertaConfig, RobertaForMaskedLM, RobertaForSequenceClassification <add>from transformers.models.bert.modeling_bert import ( <add> BertIntermediate, <add> BertLayer, <add> BertOutput, <add> BertSelfAttention, <add> BertSelfOutput, <add>) <add>from transformers.utils import logging <ide> <ide> <ide> if version.parse(fairseq.__version__) < version.parse("0.9.0"): <ide><path>src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py <ide> <ide> import argparse <ide> <del>from ...utils import logging <del>from . import T5Config, T5ForConditionalGeneration, load_tf_weights_in_t5 <add>from transformers import T5Config, T5ForConditionalGeneration, load_tf_weights_in_t5 <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py <ide> <ide> import argparse <ide> <del>from ...utils import logging <del>from . import ( <add>from transformers import ( <ide> TapasConfig, <ide> TapasForMaskedLM, <ide> TapasForQuestionAnswering, <ide> TapasTokenizer, <ide> load_tf_weights_in_tapas, <ide> ) <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...file_utils import CONFIG_NAME, WEIGHTS_NAME <del>from ...utils import logging <del>from . import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl <del>from . import tokenization_transfo_xl as data_utils <del>from .tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES <add>from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl <add>from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME <add>from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils <add>from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py <ide> import numpy <ide> import torch <ide> <del>from ...file_utils import CONFIG_NAME, WEIGHTS_NAME <del>from ...utils import logging <del>from .tokenization_xlm import VOCAB_FILES_NAMES <add>from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME <add>from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES <add>from transformers.utils import logging <ide> <ide> <ide> logging.set_verbosity_info() <ide><path>src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py <ide> <ide> import torch <ide> <del>from ...file_utils import CONFIG_NAME, WEIGHTS_NAME <del>from ...utils import logging <del>from . import ( <add>from transformers import ( <ide> XLNetConfig, <ide> XLNetForQuestionAnswering, <ide> XLNetForSequenceClassification, <ide> XLNetLMHeadModel, <ide> load_tf_weights_in_xlnet, <ide> ) <add>from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME <add>from transformers.utils import logging <ide> <ide> <ide> GLUE_TASKS_NUM_LABELS = {
28
Java
Java
improve empty body check
4560dc2818ae1d5e1bc5ceef89f1b6870700eb1f
<ide><path>spring-web/src/main/java/org/springframework/web/client/MessageBodyClientHttpResponseWrapper.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2019 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> public boolean hasMessageBody() throws IOException { <ide> * @return {@code true} if the response has a zero-length message body, {@code false} otherwise <ide> * @throws IOException in case of I/O errors <ide> */ <add> @SuppressWarnings("ConstantConditions") <ide> public boolean hasEmptyMessageBody() throws IOException { <ide> InputStream body = this.response.getBody(); <add> // Per contract body shouldn't be null, but check anyway.. <add> if (body == null) { <add> return true; <add> } <ide> if (body.markSupported()) { <ide> body.mark(1); <ide> if (body.read() == -1) { <ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java <ide> public void invalidData() { <ide> .verifyError(DecodingException.class)); <ide> } <ide> <del> @Test // #22042 <add> @Test // gh-22042 <ide> public void decodeWithNullLiteral() { <ide> Flux<Object> result = this.decoder.decode(Flux.concat(stringBuffer("null")), <ide> ResolvableType.forType(Pojo.class), MediaType.APPLICATION_JSON, Collections.emptyMap()); <ide><path>spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2019 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> public void emptyMessageBody() throws IOException { <ide> assertNull(result); <ide> } <ide> <add> @Test // gh-22265 <add> @SuppressWarnings("unchecked") <add> public void nullMessageBody() throws IOException { <add> HttpMessageConverter<String> converter = mock(HttpMessageConverter.class); <add> HttpHeaders responseHeaders = new HttpHeaders(); <add> extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter)); <add> given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value()); <add> given(response.getHeaders()).willReturn(responseHeaders); <add> given(response.getBody()).willReturn(null); <add> <add> Object result = extractor.extractData(response); <add> assertNull(result); <add> } <add> <ide> @Test <ide> @SuppressWarnings("unchecked") <ide> public void normal() throws IOException {
3
Go
Go
update getexternaladdress to prefer ipv4
f845b98ca675c9e848a27f135eac9cd31aac78e5
<ide><path>integration/container/nat_test.go <ide> func TestNetworkNat(t *testing.T) { <ide> startServerContainer(t, msg, 8080) <ide> <ide> endpoint := getExternalAddress(t) <del> conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", endpoint.String(), 8080)) <add> conn, err := net.Dial("tcp", net.JoinHostPort(endpoint.String(), "8080")) <ide> assert.NilError(t, err) <ide> defer conn.Close() <ide> <ide> func startServerContainer(t *testing.T, msg string, port int) string { <ide> return cID <ide> } <ide> <add>// getExternalAddress() returns the external IP-address from eth0. If eth0 has <add>// multiple IP-addresses, it returns the first IPv4 IP-address; if no IPv4 <add>// address is present, it returns the first IP-address found. <ide> func getExternalAddress(t *testing.T) net.IP { <ide> t.Helper() <ide> iface, err := net.InterfaceByName("eth0") <ide> func getExternalAddress(t *testing.T) net.IP { <ide> assert.NilError(t, err) <ide> assert.Check(t, 0 != len(ifaceAddrs)) <ide> <add> if len(ifaceAddrs) > 1 { <add> // Prefer IPv4 address if multiple addresses found, as rootlesskit <add> // does not handle IPv6 currently https://github.com/moby/moby/pull/41908#issuecomment-774200001 <add> for _, a := range ifaceAddrs { <add> ifaceIP, _, err := net.ParseCIDR(a.String()) <add> assert.NilError(t, err) <add> if ifaceIP.To4() != nil { <add> return ifaceIP <add> } <add> } <add> } <ide> ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String()) <ide> assert.NilError(t, err) <ide>
1
Ruby
Ruby
remove extra test case
db03f13255bae7312e661c9bed56be4709fd51f8
<ide><path>activesupport/test/clean_backtrace_test.rb <ide> def setup <ide> @bc.add_filter { |line| line.gsub("/my/prefix", '') } <ide> end <ide> <del> test "backtrace should not contain prefix when it has been filtered out" do <del> assert_equal "/my/class.rb", @bc.clean([ "/my/prefix/my/class.rb" ]).first <add> test "backtrace should filter all lines in a backtrace, removing prefixes" do <add> assert_equal \ <add> ["/my/class.rb", "/my/module.rb"], <add> @bc.clean(["/my/prefix/my/class.rb", "/my/prefix/my/module.rb"]) <ide> end <ide> <ide> test "backtrace cleaner should allow removing filters" do <ide> def setup <ide> assert_equal "/my/other_prefix/my/class.rb", @bc.clean([ "/my/other_prefix/my/class.rb" ]).first <ide> end <ide> <del> test "backtrace should filter all lines in a backtrace" do <del> assert_equal \ <del> ["/my/class.rb", "/my/module.rb"], <del> @bc.clean([ "/my/prefix/my/class.rb", "/my/prefix/my/module.rb" ]) <del> end <ide> end <ide> <ide> class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
1
Javascript
Javascript
remove invalid comma from animated example
11985d5c7721b0f9c9f46a04515799db0eeb44eb
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> var event = function( <ide> * componentDidMount() { <ide> * Animated.timing( // Uses easing functions <ide> * this.state.fadeAnim, // The value to drive <del> * {toValue: 1}, // Configuration <add> * {toValue: 1} // Configuration <ide> * ).start(); // Don't forget start! <ide> * } <ide> * render() {
1
Javascript
Javascript
fix formatting of custom usage field
828ad89e8aa194a1b8a10bec9e03ebc8506b0cb2
<ide><path>src/ng/directive/ngSwitch.js <ide> * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM <ide> * <ide> * @usage <add> * <add> * ``` <ide> * <ANY ng-switch="expression"> <ide> * <ANY ng-switch-when="matchValue1">...</ANY> <ide> * <ANY ng-switch-when="matchValue2">...</ANY> <ide> * <ANY ng-switch-default>...</ANY> <ide> * </ANY> <add> * ``` <ide> * <ide> * <ide> * @scope
1
Javascript
Javascript
move securepair stuff into tls.js
0b0faceb198c68669d078f00ebda0d80c3793866
<ide><path>lib/crypto.js <ide> exports.Verify = Verify; <ide> exports.createVerify = function(algorithm) { <ide> return (new Verify).init(algorithm); <ide> }; <del> <del> <del>var securepair = require('securepair'); <del>exports.createPair = securepair.createSecurePair; <ide><path>lib/securepair.js <del>var util = require('util'); <del>var events = require('events'); <del>var stream = require('stream'); <del>var assert = process.assert; <del> <del> <del>var debugLevel = parseInt(process.env.NODE_DEBUG, 16); <del>var debug; <del>if (debugLevel & 0x2) { <del> debug = function() { util.error.apply(this, arguments); }; <del>} else { <del> debug = function() { }; <del>} <del> <del> <del>/* Lazy Loaded crypto object */ <del>var SecureStream = null; <del> <del>/** <del> * Provides a pair of streams to do encrypted communication. <del> */ <del> <del>function SecurePair(credentials, isServer, requestCert, rejectUnauthorized) { <del> if (!(this instanceof SecurePair)) { <del> return new SecurePair(credentials, isServer, requestCert, rejectUnauthorized); <del> } <del> <del> var self = this; <del> <del> try { <del> SecureStream = process.binding('crypto').SecureStream; <del> } <del> catch (e) { <del> throw new Error('node.js not compiled with openssl crypto support.'); <del> } <del> <del> events.EventEmitter.call(this); <del> <del> this._secureEstablished = false; <del> this._isServer = isServer ? true : false; <del> this._encWriteState = true; <del> this._clearWriteState = true; <del> this._done = false; <del> <del> var crypto = require('crypto'); <del> <del> if (!credentials) { <del> this.credentials = crypto.createCredentials(); <del> } else { <del> this.credentials = credentials; <del> } <del> <del> if (!this._isServer) { <del> // For clients, we will always have either a given ca list or be using <del> // default one <del> requestCert = true; <del> } <del> <del> this._secureEstablished = false; <del> this._encInPending = []; <del> this._clearInPending = []; <del> <del> this._rejectUnauthorized = rejectUnauthorized ? true : false; <del> this._requestCert = requestCert ? true : false; <del> <del> this._ssl = new SecureStream(this.credentials.context, <del> this._isServer ? true : false, <del> this._requestCert, <del> this._rejectUnauthorized); <del> <del> <del> /* Acts as a r/w stream to the cleartext side of the stream. */ <del> this.cleartext = new stream.Stream(); <del> this.cleartext.readable = true; <del> this.cleartext.writable = true; <del> <del> /* Acts as a r/w stream to the encrypted side of the stream. */ <del> this.encrypted = new stream.Stream(); <del> this.encrypted.readable = true; <del> this.encrypted.writable = true; <del> <del> this.cleartext.write = function(data) { <del> if (typeof data == 'string') data = Buffer(data); <del> debug('clearIn data'); <del> self._clearInPending.push(data); <del> self._cycle(); <del> return self._cleartextWriteState; <del> }; <del> <del> this.cleartext.pause = function() { <del> debug('paused cleartext'); <del> self._cleartextWriteState = false; <del> }; <del> <del> this.cleartext.resume = function() { <del> debug('resumed cleartext'); <del> self._cleartextWriteState = true; <del> }; <del> <del> this.cleartext.end = function(err) { <del> debug('cleartext end'); <del> if (!self._done) { <del> self._ssl.shutdown(); <del> self._cycle(); <del> } <del> self._destroy(err); <del> }; <del> <del> this.encrypted.write = function(data) { <del> debug('encIn data'); <del> self._encInPending.push(data); <del> self._cycle(); <del> return self._encryptedWriteState; <del> }; <del> <del> this.encrypted.pause = function() { <del> if (typeof data == 'string') data = Buffer(data); <del> debug('pause encrypted'); <del> self._encryptedWriteState = false; <del> }; <del> <del> this.encrypted.resume = function() { <del> debug('resume encrypted'); <del> self._encryptedWriteState = true; <del> }; <del> <del> this.encrypted.end = function(err) { <del> debug('encrypted end'); <del> if (!self._done) { <del> self._ssl.shutdown(); <del> self._cycle(); <del> } <del> self._destroy(err); <del> }; <del> <del> this.cleartext.on('end', function(err) { <del> debug('clearIn end'); <del> if (!self._done) { <del> self._ssl.shutdown(); <del> self._cycle(); <del> } <del> self._destroy(err); <del> }); <del> <del> this.cleartext.on('close', function() { <del> debug('source close'); <del> self.emit('close'); <del> self._destroy(); <del> }); <del> <del> this.cleartext.on('drain', function() { <del> debug('source drain'); <del> self._cycle(); <del> self.encrypted.resume(); <del> }); <del> <del> this.encrypted.on('drain', function() { <del> debug('target drain'); <del> self._cycle(); <del> self.cleartext.resume(); <del> }); <del> <del> process.nextTick(function() { <del> self._ssl.start(); <del> self._cycle(); <del> }); <del>} <del> <del>util.inherits(SecurePair, events.EventEmitter); <del> <del> <del>exports.createSecurePair = function(credentials, <del> isServer, <del> requestCert, <del> rejectUnauthorized) { <del> var pair = new SecurePair(credentials, <del> isServer, <del> requestCert, <del> rejectUnauthorized); <del> return pair; <del>}; <del> <del> <del>/** <del> * Attempt to cycle OpenSSLs buffers in various directions. <del> * <del> * An SSL Connection can be viewed as four separate piplines, <del> * interacting with one has no connection to the behavoir of <del> * any of the other 3 -- This might not sound reasonable, <del> * but consider things like mid-stream renegotiation of <del> * the ciphers. <del> * <del> * The four pipelines, using terminology of the client (server is just <del> * reversed): <del> * (1) Encrypted Output stream (Writing encrypted data to peer) <del> * (2) Encrypted Input stream (Reading encrypted data from peer) <del> * (3) Cleartext Output stream (Decrypted content from the peer) <del> * (4) Cleartext Input stream (Cleartext content to send to the peer) <del> * <del> * This function attempts to pull any available data out of the Cleartext <del> * input stream (4), and the Encrypted input stream (2). Then it pushes any <del> * data available from the cleartext output stream (3), and finally from the <del> * Encrypted output stream (1) <del> * <del> * It is called whenever we do something with OpenSSL -- post reciving <del> * content, trying to flush, trying to change ciphers, or shutting down the <del> * connection. <del> * <del> * Because it is also called everywhere, we also check if the connection has <del> * completed negotiation and emit 'secure' from here if it has. <del> */ <del>SecurePair.prototype._cycle = function() { <del> if (this._done) { <del> return; <del> } <del> <del> var self = this; <del> var rv; <del> var tmp; <del> var bytesRead; <del> var bytesWritten; <del> var chunkBytes; <del> var chunk = null; <del> var pool = null; <del> <del> // Pull in incoming encrypted data from the socket. <del> // This arrives via some code like this: <del> // <del> // socket.on('data', function (d) { <del> // pair.encrypted.write(d) <del> // }); <del> // <del> while (this._encInPending.length > 0) { <del> tmp = this._encInPending.shift(); <del> <del> try { <del> debug('writing from encIn'); <del> rv = this._ssl.encIn(tmp, 0, tmp.length); <del> } catch (e) { <del> return this._error(e); <del> } <del> <del> if (rv === 0) { <del> this._encInPending.unshift(tmp); <del> break; <del> } <del> <del> assert(rv === tmp.length); <del> } <del> <del> // Pull in any clear data coming from the application. <del> // This arrives via some code like this: <del> // <del> // pair.cleartext.write("hello world"); <del> // <del> while (this._clearInPending.length > 0) { <del> tmp = this._clearInPending.shift(); <del> try { <del> debug('writng from clearIn'); <del> rv = this._ssl.clearIn(tmp, 0, tmp.length); <del> } catch (e) { <del> return this._error(e); <del> } <del> <del> if (rv === 0) { <del> this._clearInPending.unshift(tmp); <del> break; <del> } <del> <del> assert(rv === tmp.length); <del> } <del> <del> function mover(reader, writer, checker) { <del> var bytesRead; <del> var pool; <del> var chunkBytes; <del> do { <del> bytesRead = 0; <del> chunkBytes = 0; <del> pool = new Buffer(4096); <del> pool.used = 0; <del> <del> do { <del> try { <del> chunkBytes = reader(pool, <del> pool.used + bytesRead, <del> pool.length - pool.used - bytesRead); <del> } catch (e) { <del> return self._error(e); <del> } <del> if (chunkBytes >= 0) { <del> bytesRead += chunkBytes; <del> } <del> } while ((chunkBytes > 0) && (pool.used + bytesRead < pool.length)); <del> <del> if (bytesRead > 0) { <del> chunk = pool.slice(0, bytesRead); <del> writer(chunk); <del> } <del> } while (checker(bytesRead)); <del> } <del> <del> // Move decryptoed, clear data out into the application. <del> // From the user's perspective this occurs as a 'data' event <del> // on the pair.cleartext. <del> mover( <del> function(pool, offset, length) { <del> debug('reading from clearOut'); <del> return self._ssl.clearOut(pool, offset, length); <del> }, <del> function(chunk) { <del> self.cleartext.emit('data', chunk); <del> }, <del> function(bytesRead) { <del> return bytesRead > 0 && self._cleartextWriteState === true; <del> }); <del> <del> // Move encrypted data to the stream. From the user's perspective this <del> // occurs as a 'data' event on the pair.encrypted. Usually the application <del> // will have some code which pipes the stream to a socket: <del> // <del> // pair.encrypted.on('data', function (d) { <del> // socket.write(d); <del> // }); <del> // <del> mover( <del> function(pool, offset, length) { <del> debug('reading from encOut'); <del> if (!self._ssl) return -1; <del> return self._ssl.encOut(pool, offset, length); <del> }, <del> function(chunk) { <del> self.encrypted.emit('data', chunk); <del> }, <del> function(bytesRead) { <del> if (!self._ssl) return false; <del> return bytesRead > 0 && self._encryptedWriteState === true; <del> }); <del> <del> <del> <del> if (this._ssl && !this._secureEstablished && this._ssl.isInitFinished()) { <del> this._secureEstablished = true; <del> debug('secure established'); <del> this.emit('secure'); <del> this._cycle(); <del> } <del>}; <del> <del> <del>SecurePair.prototype._destroy = function(err) { <del> if (!this._done) { <del> this._done = true; <del> this._ssl.close(); <del> this._ssl = null; <del> this.encrypted.emit('close'); <del> this.cleartext.emit('close'); <del> this.emit('end', err); <del> } <del>}; <del> <del> <del>SecurePair.prototype._error = function(err) { <del> if (this._isServer && <del> this._rejectUnauthorized && <del> /peer did not return a certificate/.test(err.message)) { <del> // Not really an error. <del> this._destroy(); <del> } else { <del> this.emit('error', err); <del> } <del>}; <del> <del> <del>SecurePair.prototype.getPeerCertificate = function(err) { <del> if (this._ssl) { <del> return this._ssl.getPeerCertificate(); <del> } else { <del> return null; <del> } <del>}; <del> <del> <del>SecurePair.prototype.getCipher = function(err) { <del> if (this._ssl) { <del> return this._ssl.getCurrentCipher(); <del> } else { <del> return null; <del> } <del>}; <ide><path>lib/tls.js <ide> var crypto = require('crypto'); <del>var securepair = require('securepair'); <add>var util = require('util'); <ide> var net = require('net'); <ide> var events = require('events'); <del>var inherits = require('util').inherits; <add>var stream = require('stream'); <ide> <ide> var assert = process.assert; <ide> <add>var debugLevel = parseInt(process.env.NODE_DEBUG, 16); <add>var debug; <add>if (debugLevel & 0x2) { <add> debug = function() { util.error.apply(this, arguments); }; <add>} else { <add> debug = function() { }; <add>} <add> <add> <add>/* Lazy Loaded crypto object */ <add>var SecureStream = null; <add> <add>/** <add> * Provides a pair of streams to do encrypted communication. <add> */ <add> <add>function SecurePair(credentials, isServer, requestCert, rejectUnauthorized) { <add> if (!(this instanceof SecurePair)) { <add> return new SecurePair(credentials, isServer, requestCert, rejectUnauthorized); <add> } <add> <add> var self = this; <add> <add> try { <add> SecureStream = process.binding('crypto').SecureStream; <add> } <add> catch (e) { <add> throw new Error('node.js not compiled with openssl crypto support.'); <add> } <add> <add> events.EventEmitter.call(this); <add> <add> this._secureEstablished = false; <add> this._isServer = isServer ? true : false; <add> this._encWriteState = true; <add> this._clearWriteState = true; <add> this._done = false; <add> <add> var crypto = require('crypto'); <add> <add> if (!credentials) { <add> this.credentials = crypto.createCredentials(); <add> } else { <add> this.credentials = credentials; <add> } <add> <add> if (!this._isServer) { <add> // For clients, we will always have either a given ca list or be using <add> // default one <add> requestCert = true; <add> } <add> <add> this._secureEstablished = false; <add> this._encInPending = []; <add> this._clearInPending = []; <add> <add> this._rejectUnauthorized = rejectUnauthorized ? true : false; <add> this._requestCert = requestCert ? true : false; <add> <add> this._ssl = new SecureStream(this.credentials.context, <add> this._isServer ? true : false, <add> this._requestCert, <add> this._rejectUnauthorized); <add> <add> <add> /* Acts as a r/w stream to the cleartext side of the stream. */ <add> this.cleartext = new stream.Stream(); <add> this.cleartext.readable = true; <add> this.cleartext.writable = true; <add> <add> /* Acts as a r/w stream to the encrypted side of the stream. */ <add> this.encrypted = new stream.Stream(); <add> this.encrypted.readable = true; <add> this.encrypted.writable = true; <add> <add> this.cleartext.write = function(data) { <add> if (typeof data == 'string') data = Buffer(data); <add> debug('clearIn data'); <add> self._clearInPending.push(data); <add> self._cycle(); <add> return self._cleartextWriteState; <add> }; <add> <add> this.cleartext.pause = function() { <add> debug('paused cleartext'); <add> self._cleartextWriteState = false; <add> }; <add> <add> this.cleartext.resume = function() { <add> debug('resumed cleartext'); <add> self._cleartextWriteState = true; <add> }; <add> <add> this.cleartext.end = function(err) { <add> debug('cleartext end'); <add> if (!self._done) { <add> self._ssl.shutdown(); <add> self._cycle(); <add> } <add> self._destroy(err); <add> }; <add> <add> this.encrypted.write = function(data) { <add> debug('encIn data'); <add> self._encInPending.push(data); <add> self._cycle(); <add> return self._encryptedWriteState; <add> }; <add> <add> this.encrypted.pause = function() { <add> if (typeof data == 'string') data = Buffer(data); <add> debug('pause encrypted'); <add> self._encryptedWriteState = false; <add> }; <add> <add> this.encrypted.resume = function() { <add> debug('resume encrypted'); <add> self._encryptedWriteState = true; <add> }; <add> <add> this.encrypted.end = function(err) { <add> debug('encrypted end'); <add> if (!self._done) { <add> self._ssl.shutdown(); <add> self._cycle(); <add> } <add> self._destroy(err); <add> }; <add> <add> this.cleartext.on('end', function(err) { <add> debug('clearIn end'); <add> if (!self._done) { <add> self._ssl.shutdown(); <add> self._cycle(); <add> } <add> self._destroy(err); <add> }); <add> <add> this.cleartext.on('close', function() { <add> debug('source close'); <add> self.emit('close'); <add> self._destroy(); <add> }); <add> <add> this.cleartext.on('drain', function() { <add> debug('source drain'); <add> self._cycle(); <add> self.encrypted.resume(); <add> }); <add> <add> this.encrypted.on('drain', function() { <add> debug('target drain'); <add> self._cycle(); <add> self.cleartext.resume(); <add> }); <add> <add> process.nextTick(function() { <add> self._ssl.start(); <add> self._cycle(); <add> }); <add>} <add> <add>util.inherits(SecurePair, events.EventEmitter); <add> <add> <add>exports.createSecurePair = function(credentials, <add> isServer, <add> requestCert, <add> rejectUnauthorized) { <add> var pair = new SecurePair(credentials, <add> isServer, <add> requestCert, <add> rejectUnauthorized); <add> return pair; <add>}; <add> <add> <add>/** <add> * Attempt to cycle OpenSSLs buffers in various directions. <add> * <add> * An SSL Connection can be viewed as four separate piplines, <add> * interacting with one has no connection to the behavoir of <add> * any of the other 3 -- This might not sound reasonable, <add> * but consider things like mid-stream renegotiation of <add> * the ciphers. <add> * <add> * The four pipelines, using terminology of the client (server is just <add> * reversed): <add> * (1) Encrypted Output stream (Writing encrypted data to peer) <add> * (2) Encrypted Input stream (Reading encrypted data from peer) <add> * (3) Cleartext Output stream (Decrypted content from the peer) <add> * (4) Cleartext Input stream (Cleartext content to send to the peer) <add> * <add> * This function attempts to pull any available data out of the Cleartext <add> * input stream (4), and the Encrypted input stream (2). Then it pushes any <add> * data available from the cleartext output stream (3), and finally from the <add> * Encrypted output stream (1) <add> * <add> * It is called whenever we do something with OpenSSL -- post reciving <add> * content, trying to flush, trying to change ciphers, or shutting down the <add> * connection. <add> * <add> * Because it is also called everywhere, we also check if the connection has <add> * completed negotiation and emit 'secure' from here if it has. <add> */ <add>SecurePair.prototype._cycle = function() { <add> if (this._done) { <add> return; <add> } <add> <add> var self = this; <add> var rv; <add> var tmp; <add> var bytesRead; <add> var bytesWritten; <add> var chunkBytes; <add> var chunk = null; <add> var pool = null; <add> <add> // Pull in incoming encrypted data from the socket. <add> // This arrives via some code like this: <add> // <add> // socket.on('data', function (d) { <add> // pair.encrypted.write(d) <add> // }); <add> // <add> while (this._encInPending.length > 0) { <add> tmp = this._encInPending.shift(); <add> <add> try { <add> debug('writing from encIn'); <add> rv = this._ssl.encIn(tmp, 0, tmp.length); <add> } catch (e) { <add> return this._error(e); <add> } <add> <add> if (rv === 0) { <add> this._encInPending.unshift(tmp); <add> break; <add> } <add> <add> assert(rv === tmp.length); <add> } <add> <add> // Pull in any clear data coming from the application. <add> // This arrives via some code like this: <add> // <add> // pair.cleartext.write("hello world"); <add> // <add> while (this._clearInPending.length > 0) { <add> tmp = this._clearInPending.shift(); <add> try { <add> debug('writng from clearIn'); <add> rv = this._ssl.clearIn(tmp, 0, tmp.length); <add> } catch (e) { <add> return this._error(e); <add> } <add> <add> if (rv === 0) { <add> this._clearInPending.unshift(tmp); <add> break; <add> } <add> <add> assert(rv === tmp.length); <add> } <add> <add> function mover(reader, writer, checker) { <add> var bytesRead; <add> var pool; <add> var chunkBytes; <add> do { <add> bytesRead = 0; <add> chunkBytes = 0; <add> pool = new Buffer(4096); <add> pool.used = 0; <add> <add> do { <add> try { <add> chunkBytes = reader(pool, <add> pool.used + bytesRead, <add> pool.length - pool.used - bytesRead); <add> } catch (e) { <add> return self._error(e); <add> } <add> if (chunkBytes >= 0) { <add> bytesRead += chunkBytes; <add> } <add> } while ((chunkBytes > 0) && (pool.used + bytesRead < pool.length)); <add> <add> if (bytesRead > 0) { <add> chunk = pool.slice(0, bytesRead); <add> writer(chunk); <add> } <add> } while (checker(bytesRead)); <add> } <add> <add> // Move decryptoed, clear data out into the application. <add> // From the user's perspective this occurs as a 'data' event <add> // on the pair.cleartext. <add> mover( <add> function(pool, offset, length) { <add> debug('reading from clearOut'); <add> return self._ssl.clearOut(pool, offset, length); <add> }, <add> function(chunk) { <add> self.cleartext.emit('data', chunk); <add> }, <add> function(bytesRead) { <add> return bytesRead > 0 && self._cleartextWriteState === true; <add> }); <add> <add> // Move encrypted data to the stream. From the user's perspective this <add> // occurs as a 'data' event on the pair.encrypted. Usually the application <add> // will have some code which pipes the stream to a socket: <add> // <add> // pair.encrypted.on('data', function (d) { <add> // socket.write(d); <add> // }); <add> // <add> mover( <add> function(pool, offset, length) { <add> debug('reading from encOut'); <add> if (!self._ssl) return -1; <add> return self._ssl.encOut(pool, offset, length); <add> }, <add> function(chunk) { <add> self.encrypted.emit('data', chunk); <add> }, <add> function(bytesRead) { <add> if (!self._ssl) return false; <add> return bytesRead > 0 && self._encryptedWriteState === true; <add> }); <add> <add> <add> <add> if (this._ssl && !this._secureEstablished && this._ssl.isInitFinished()) { <add> this._secureEstablished = true; <add> debug('secure established'); <add> this.emit('secure'); <add> this._cycle(); <add> } <add>}; <add> <add> <add>SecurePair.prototype._destroy = function(err) { <add> if (!this._done) { <add> this._done = true; <add> this._ssl.close(); <add> this._ssl = null; <add> this.encrypted.emit('close'); <add> this.cleartext.emit('close'); <add> this.emit('end', err); <add> } <add>}; <add> <add> <add>SecurePair.prototype._error = function(err) { <add> if (this._isServer && <add> this._rejectUnauthorized && <add> /peer did not return a certificate/.test(err.message)) { <add> // Not really an error. <add> this._destroy(); <add> } else { <add> this.emit('error', err); <add> } <add>}; <add> <add> <add>SecurePair.prototype.getPeerCertificate = function(err) { <add> if (this._ssl) { <add> return this._ssl.getPeerCertificate(); <add> } else { <add> return null; <add> } <add>}; <add> <add> <add>SecurePair.prototype.getCipher = function(err) { <add> if (this._ssl) { <add> return this._ssl.getCurrentCipher(); <add> } else { <add> return null; <add> } <add>}; <add> <ide> // TODO: support anonymous (nocert) and PSK <ide> // TODO: how to proxy maxConnections? <ide> <ide> function Server(/* [options], listener */) { <ide> { key: self.key, cert: self.cert, ca: self.ca }); <ide> creds.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); <ide> <del> var pair = securepair.createSecurePair(creds, <del> true, <del> self.requestCert, <del> self.rejectUnauthorized); <add> var pair = new SecurePair(creds, <add> true, <add> self.requestCert, <add> self.rejectUnauthorized); <ide> pair.encrypted.pipe(socket); <ide> socket.pipe(pair.encrypted); <ide> <ide> function Server(/* [options], listener */) { <ide> this.setOptions(options); <ide> } <ide> <del>inherits(Server, net.Server); <add>util.inherits(Server, net.Server); <ide> exports.Server = Server; <ide> exports.createServer = function(options, listener) { <ide> return new Server(options, listener); <ide><path>test/simple/test-securepair-client.js <ide> var net = require('net'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <ide> var crypto = require('crypto'); <add>var tls = require('tls'); <ide> var spawn = require('child_process').spawn; <ide> <ide> // FIXME: Avoid the common PORT as this test currently hits a C-level <ide> function startClient() { <ide> var sslcontext = crypto.createCredentials({key: key, cert: cert}); <ide> sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); <ide> <del> var pair = crypto.createPair(sslcontext, false); <add> var pair = tls.createSecurePair(sslcontext, false); <ide> <ide> assert.ok(pair.encrypted.writable); <ide> assert.ok(pair.cleartext.writable); <ide><path>test/simple/test-securepair-server.js <ide> var join = require('path').join; <ide> var net = require('net'); <ide> var fs = require('fs'); <ide> var crypto = require('crypto'); <add>var tls = require('tls'); <ide> var spawn = require('child_process').spawn; <ide> <ide> var connections = 0; <ide> var server = net.createServer(function(socket) { <ide> var sslcontext = crypto.createCredentials({key: key, cert: cert}); <ide> sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); <ide> <del> var pair = crypto.createPair(sslcontext, true); <add> var pair = tls.createSecurePair(sslcontext, true); <ide> <ide> assert.ok(pair.encrypted.writable); <ide> assert.ok(pair.cleartext.writable);
5
Javascript
Javascript
fix typo on example code
c6495531fbbcf9e8d0c287b717c0eb925691075b
<ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js <ide> var DRAWER_STATES = [ <ide> * drawerWidth={300} <ide> * drawerPosition={DrawerLayoutAndroid.positions.Left} <ide> * renderNavigationView={() => navigationView}> <del> * <Text style={{10, fontSize: 15, textAlign: 'right'}}>Hello</Text> <del> * <Text style={{10, fontSize: 15, textAlign: 'right'}}>World!</Text> <add> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> <add> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text> <ide> * </DrawerLayoutAndroid> <ide> * ); <ide> * },
1
Text
Text
use json to render code block
2590bad75fd6730da7a0800d376bc8ccc519f83d
<ide><path>docs/your-first-package.md <ide> its not there! To fix this open _package.json_ and find the property called <ide> delay a package's activation until it's needed. So add the `ascii-art:convert` <ide> to the activationEvents array: <ide> <del>```coffeescript <add>```json <ide> "activationEvents": ["ascii-art:convert"], <ide> ``` <ide>
1
Javascript
Javascript
deliver enoent on nexttick
40d5e9074a0001d53901df2a2e081c8821b3dc22
<ide><path>lib/child_process.js <ide> ChildProcess.prototype.spawn = function(options) { <ide> <ide> var err = this._handle.spawn(options); <ide> <del> if (err) { <add> if (!constants) <add> constants = process.binding('constants'); <add> <add> if (-err == constants.ENOENT) { <add> process.nextTick(function() { <add> self._handle.onexit(err); <add> }); <add> } else if (err) { <ide> // Close all opened fds on error <ide> stdio.forEach(function(stdio) { <ide> if (stdio.type === 'pipe') {
1
Text
Text
remove redundant name attribute
016819028131a40f15fa333c65b6177cfd561a03
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fad1cafcde010995e15306.md <ide> You should not give any of the `fieldset` elements a `name` attribute. <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fad6dfcc0d930a59becf12.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('body')?.fontSize, '16px') <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fad8e6148f310bba7890b1.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('h1, p')?.textAlign, 'cent <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fad99e09f9d30c1657e790.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('form')?.width, '60vw'); <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fadb18058e950c73925279.md <ide> assert.equal(fieldset?.paddingRight, '0px'); <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fadce90f85c50d0bb0dd4f.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('fieldset')?.borderBottom, <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fadd972e6ffe0d6858fa2d.md <ide> assert.equal(selFunc(['input, textarea, select', 'input, select, textarea', 'sel <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fadfa2b540b70dcfa8b771.md <ide> assert(document.querySelectorAll('fieldset:nth-child(2) input')?.[2]?.classList? <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fc219d333e37046f474a6e.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.inline')?.width, 'unset' <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fc22d1e64d1b04cdd4e602.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.inline')?.marginLeft, '0 <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fc236dc04532052926fdac.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.inline')?.verticalAlign, <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe1bc30415f042faea936.md <ide> assert.equal(selFunc(['input, textarea', 'textarea, input'].find(selFunc))?.bord <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe3936796ac04959285a9.md <ide> assert.equal(selFunc(['input, textarea', 'textarea, input'].find(selFunc))?.minH <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe4f4ec18cd04dc470c56.md <ide> assert.isEmpty(new __helpers.CSSHelp(document).getStyle('input, textarea')?.minH <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe69ee377c6055e192a46.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('input[type="submit"]')?.w <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe7d8aae62c05bcc9e7eb.md <ide> assert.isEmpty(new __helpers.CSSHelp(document).getStyle('input[type="submit"]')? <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe8a5ceb0e90618db06d9.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('input[type="submit"]')?.f <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe947a868ec068f7850f6.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('input[type="submit"]')?.b <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffe9cb47809106eda2f2c9.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('input[type="submit"]')?.m <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffec2825da1007509ddd06.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('input[type="file"]')?.pad <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffecefac971607ae73c60f.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('form')?.paddingBottom, '2 <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60ffefd6479a3d084fb77cbc.md <ide> assert.equal(new __helpers.CSSHelp(document).getStyle('a')?.color, 'rgb(223, 223 <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" class="inline" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" class="inline" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" class="inline" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/62b30924c5e4ef0daba23b5e.md <ide> assert(borderBottom === 'none' || borderBottom === 'medium none'); <ide> <fieldset> <ide> <label for="personal-account"><input id="personal-account" type="radio" name="account-type" /> Personal Account</label> <ide> <label for="business-account"><input id="business-account" type="radio" name="account-type" /> Business Account</label> <del> <label for="terms-and-conditions" name="terms-and-conditions"> <add> <label for="terms-and-conditions"> <ide> <input id="terms-and-conditions" type="checkbox" required name="terms-and-conditions" /> I accept the <a href="https://www.freecodecamp.org/news/terms-of-service/">terms and conditions</a> <ide> </label> <ide> </fieldset>
23
Ruby
Ruby
remove malware caveat
55084dd8abdd566817d24aaf16729a488a7f7a9e
<ide><path>Library/Homebrew/cask/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> #{web_page} <ide> EOS <ide> end <del> <del> caveat :malware do |radar_number| <del> <<~EOS <del> #{@cask} has been reported to bundle malware. Like with any app, use at your own risk. <del> <del> A report has been made to Apple about this app. Their certificate will hopefully be revoked. <del> See the public report at <del> #{Formatter.url("https://openradar.appspot.com/#{radar_number}")} <del> <del> If this report is accurate, please duplicate it at <del> #{Formatter.url("https://bugreport.apple.com/")} <del> If this report is a mistake, please let us know by opening an issue at <del> #{Formatter.url("https://github.com/Homebrew/homebrew-cask/issues/new")} <del> EOS <del> end <ide> end <ide> end <ide> end
1
Ruby
Ruby
build formula options better
42681b51f83193f0fb9c178c85e2d1b17926ebd2
<ide><path>Library/Homebrew/formula_installer.rb <ide> def effective_build_options_for(dependent, inherited_options = []) <ide> args = dependent.build.used_options <ide> args |= dependent == formula ? options : inherited_options <ide> args |= Tab.for_formula(dependent).used_options <add> args &= dependent.options <ide> BuildOptions.new(args, dependent.options) <ide> end <ide>
1
Ruby
Ruby
avoid skip in test, have a unified test for order
90c450f6cd792187eeb1e039e0ff3722beb8b5c1
<ide><path>activemodel/test/cases/serializers/json_serialization_test.rb <ide> def @contact.favorite_quote; "Constraints are liberating"; end <ide> end <ide> end <ide> <del> test "as_json should keep the MRI default order in the hash" do <del> skip "on JRuby as order is different" if defined? JRUBY_VERSION <add> test "as_json should keep the default order in the hash" do <ide> json = @contact.as_json <ide> <del> assert_equal %w(name age created_at awesome preferences), json.keys <del> end <del> <del> test "as_json should keep the JRuby default order in the hash" do <del> skip "on MRI as order is different" unless defined? JRUBY_VERSION <del> json = @contact.as_json <add> attributes_order = %w(name age created_at awesome preferences) <add> #Order on JRUBY is different <add> if defined? JRUBY_VERSION <add> attributes_order = %w(age name created_at awesome preferences) <add> end <ide> <del> assert_equal %w(age name created_at awesome preferences), json.keys <add> assert_equal attributes_order, json.keys <ide> end <ide> <del> <ide> test "from_json should work without a root (class attribute)" do <ide> json = @contact.to_json <ide> result = Contact.new.from_json(json)
1
Java
Java
reduce log level to debug when @tels isn't present
5710cf5ed29139e94853f3d14124eb100a924b82
<ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextManager.java <ide> /* <del> * Copyright 2002-2010 the original author or authors. <add> * Copyright 2002-2012 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> private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) { <ide> <ide> // Use defaults? <ide> if (declaringClass == null) { <del> if (logger.isInfoEnabled()) { <del> logger.info("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults."); <add> if (logger.isDebugEnabled()) { <add> logger.debug("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults."); <ide> } <ide> classesList.addAll(getDefaultTestExecutionListenerClasses()); <ide> defaultListeners = true;
1
Python
Python
add a flag to control the number of train examples
1c89b792ccdb53dd0cc2504f3bce502e5f0aa4e5
<ide><path>official/nlp/bert/input_pipeline.py <ide> def decode_record(record, name_to_features): <ide> return example <ide> <ide> <del>def single_file_dataset(input_file, name_to_features): <add>def single_file_dataset(input_file, name_to_features, num_samples=None): <ide> """Creates a single-file dataset to be passed for BERT custom training.""" <ide> # For training, we want a lot of parallel reading and shuffling. <ide> # For eval, we want no shuffling and parallel reading doesn't matter. <ide> d = tf.data.TFRecordDataset(input_file) <add> if num_samples: <add> d = d.take(num_samples) <ide> d = d.map( <ide> lambda record: decode_record(record, name_to_features), <ide> num_parallel_calls=tf.data.experimental.AUTOTUNE) <ide> def create_classifier_dataset(file_path, <ide> is_training=True, <ide> input_pipeline_context=None, <ide> label_type=tf.int64, <del> include_sample_weights=False): <add> include_sample_weights=False, <add> num_samples=None): <ide> """Creates input dataset from (tf)records files for train/eval.""" <ide> name_to_features = { <ide> 'input_ids': tf.io.FixedLenFeature([seq_length], tf.int64), <ide> def create_classifier_dataset(file_path, <ide> } <ide> if include_sample_weights: <ide> name_to_features['weight'] = tf.io.FixedLenFeature([], tf.float32) <del> dataset = single_file_dataset(file_path, name_to_features) <add> dataset = single_file_dataset(file_path, name_to_features, <add> num_samples=num_samples) <ide> <ide> # The dataset is always sharded by number of hosts. <ide> # num_input_pipelines is the number of hosts rather than number of cores. <ide><path>official/nlp/bert/run_classifier.py <ide> 'input_meta_data_path', None, <ide> 'Path to file that contains meta data about input ' <ide> 'to be used for training and evaluation.') <add>flags.DEFINE_integer('train_data_size', None, 'Number of training samples ' <add> 'to use. If None, uses the full train data. ' <add> '(default: None).') <ide> flags.DEFINE_string('predict_checkpoint_path', None, <ide> 'Path to the checkpoint for predictions.') <ide> flags.DEFINE_integer( <ide> def get_dataset_fn(input_file_pattern, <ide> global_batch_size, <ide> is_training, <ide> label_type=tf.int64, <del> include_sample_weights=False): <add> include_sample_weights=False, <add> num_samples=None): <ide> """Gets a closure to create a dataset.""" <ide> <ide> def _dataset_fn(ctx=None): <ide> def _dataset_fn(ctx=None): <ide> is_training=is_training, <ide> input_pipeline_context=ctx, <ide> label_type=label_type, <del> include_sample_weights=include_sample_weights) <add> include_sample_weights=include_sample_weights, <add> num_samples=num_samples) <ide> return dataset <ide> <ide> return _dataset_fn <ide> def run_bert(strategy, <ide> epochs = FLAGS.num_train_epochs * FLAGS.num_eval_per_epoch <ide> train_data_size = ( <ide> input_meta_data['train_data_size'] // FLAGS.num_eval_per_epoch) <add> if FLAGS.train_data_size: <add> train_data_size = min(train_data_size, FLAGS.train_data_size) <add> logging.info('Updated train_data_size: %s', train_data_size) <ide> steps_per_epoch = int(train_data_size / FLAGS.train_batch_size) <ide> warmup_steps = int(epochs * train_data_size * 0.1 / FLAGS.train_batch_size) <ide> eval_steps = int( <ide> def custom_main(custom_callbacks=None, custom_metrics=None): <ide> FLAGS.train_batch_size, <ide> is_training=True, <ide> label_type=label_type, <del> include_sample_weights=include_sample_weights) <add> include_sample_weights=include_sample_weights, <add> num_samples=FLAGS.train_data_size) <ide> run_bert( <ide> strategy, <ide> input_meta_data,
2
Ruby
Ruby
pass --trace and named args to rake
86bd9c9f39fbe4aa88791f3973d41b26ac37e036
<ide><path>Library/Homebrew/cmd/tests.rb <ide> def tests <ide> ENV["TESTOPTS"] = "-v" if ARGV.verbose? <ide> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" if ARGV.include? "--coverage" <ide> ENV["HOMEBREW_NO_COMPAT"] = "1" if ARGV.include? "--no-compat" <add> <ide> Homebrew.install_gem_setup_path! "bundler" <del> quiet_system("bundle", "check") || \ <del> system("bundle", "install", "--path", "vendor/bundle") <del> system "bundle", "exec", "rake", "test" <add> unless quiet_system("bundle", "check") <add> system "bundle", "install", "--path", "vendor/bundle" <add> end <add> <add> args = [] <add> args << "--trace" if ARGV.include? "--trace" <add> args += ARGV.named <add> system "bundle", "exec", "rake", "test", *args <add> <ide> Homebrew.failed = !$?.success? <add> <ide> if (fs_leak_log = HOMEBREW_LIBRARY/"Homebrew/test/fs_leak_log").file? <ide> fs_leak_log_content = fs_leak_log.read <ide> unless fs_leak_log_content.empty?
1
Python
Python
update affected tests
37ed7e59e4a549b8abc6d4e7f08838b597420c63
<ide><path>libcloud/test/common/test_aws.py <del>import mock <add>import sys <add>import unittest <ide> from datetime import datetime <ide> <del>from libcloud.common.aws import V4SignedAWSConnection <add>import mock <add> <add>from libcloud.common.aws import SignedAWSConnection <add>from libcloud.common.aws import AWSRequestSignerAlgorithmV4 <ide> from libcloud.test import LibcloudTestCase <ide> <ide> <ide> class EC2MockDriver(object): <ide> region_name = 'my_region' <ide> <ide> <del>class V4SignedAWSConnectionTest(LibcloudTestCase): <add>class AWSRequestSignerAlgorithmV4TestCase(LibcloudTestCase): <ide> <ide> def setUp(self): <del> V4SignedAWSConnection.service_name = 'my_service' <del> V4SignedAWSConnection.method = 'GET' <del> V4SignedAWSConnection.action = '/my_action/' <del> V4SignedAWSConnection.driver = EC2MockDriver() <add> SignedAWSConnection.driver = EC2MockDriver() <add> SignedAWSConnection.service_name = 'my_service' <add> SignedAWSConnection.version = '2013-10-15' <add> self.connection = SignedAWSConnection('my_key', 'my_secret') <add> <add> self.signer = AWSRequestSignerAlgorithmV4(access_key='my_key', <add> access_secret='my_secret', <add> version='2013-10-15', <add> connection=self.connection) <add> <add> SignedAWSConnection.action = '/my_action/' <add> SignedAWSConnection.driver = EC2MockDriver() <ide> <del> self.conn = V4SignedAWSConnection('my_key', 'my_secret') <ide> self.now = datetime(2015, 3, 4, hour=17, minute=34, second=52) <ide> <ide> def test_v4_signature(self): <del> sig = self.conn._get_authorization_v4_header({ <add> params = { <ide> 'Action': 'DescribeInstances', <ide> 'Version': '2013-10-15' <del> }, { <add> } <add> headers = { <ide> 'Host': 'ec2.eu-west-1.amazonaws.com', <ide> 'Accept-Encoding': 'gzip,deflate', <ide> 'X-AMZ-Date': '20150304T173452Z', <ide> 'User-Agent': 'libcloud/0.17.0 (Amazon EC2 (eu-central-1)) ' <del> }, self.now) <add> } <add> dt = self.now <add> sig = self.signer._get_authorization_v4_header(params=params, <add> headers=headers, <add> dt=dt, <add> method='GET', <add> path='/my_action/') <ide> self.assertEqual(sig, 'AWS4-HMAC-SHA256 ' <ide> 'Credential=my_key/20150304/my_region/my_service/aws4_request, ' <ide> 'SignedHeaders=accept-encoding;host;user-agent;x-amz-date, ' <ide> 'Signature=f9868f8414b3c3f856c7955019cc1691265541f5162b9b772d26044280d39bd3') <ide> <ide> def test_v4_signature_raises_error_if_request_method_not_GET(self): <del> V4SignedAWSConnection.method = 'POST' <del> <ide> with self.assertRaises(Exception): <del> self.conn._get_authorization_v4_header({}, {}, self.now) <add> self.signer._get_authorization_v4_header(params={}, headers={}, <add> dt=self.now, method='POST') <ide> <ide> def test_v4_signature_contains_user_id(self): <del> sig = self.conn._get_authorization_v4_header({}, {}, self.now) <add> sig = self.signer._get_authorization_v4_header(params={}, headers={}, <add> dt=self.now) <ide> self.assertIn('Credential=my_key/', sig) <ide> <ide> def test_v4_signature_contains_credential_scope(self): <del> with mock.patch('libcloud.common.aws.V4SignedAWSConnection._get_credential_scope') as mock_get_creds: <add> with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_credential_scope') as mock_get_creds: <ide> mock_get_creds.return_value = 'my_credential_scope' <del> sig = self.conn._get_authorization_v4_header({}, {}, self.now) <add> sig = self.signer._get_authorization_v4_header(params={}, headers={}, dt=self.now) <ide> <ide> self.assertIn('Credential=my_key/my_credential_scope, ', sig) <ide> <ide> def test_v4_signature_contains_signed_headers(self): <del> with mock.patch('libcloud.common.aws.V4SignedAWSConnection._get_signed_headers') as mock_get_headers: <add> with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_signed_headers') as mock_get_headers: <ide> mock_get_headers.return_value = 'my_signed_headers' <del> sig = self.conn._get_authorization_v4_header({}, {}, self.now) <add> sig = self.signer._get_authorization_v4_header({}, {}, self.now, <add> method='GET', <add> path='/') <ide> self.assertIn('SignedHeaders=my_signed_headers, ', sig) <ide> <ide> def test_v4_signature_contains_signature(self): <del> with mock.patch('libcloud.common.aws.V4SignedAWSConnection._get_signature') as mock_get_signature: <add> with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_signature') as mock_get_signature: <ide> mock_get_signature.return_value = 'my_signature' <del> sig = self.conn._get_authorization_v4_header({}, {}, self.now) <add> sig = self.signer._get_authorization_v4_header({}, {}, self.now) <ide> self.assertIn('Signature=my_signature', sig) <ide> <ide> def test_get_signature_(self): <ide> def _sign(key, msg, hex=False): <ide> else: <ide> return '%s|%s' % (key, msg) <ide> <del> with mock.patch('libcloud.common.aws.V4SignedAWSConnection._get_key_to_sign_with') as mock_get_key: <del> with mock.patch('libcloud.common.aws.V4SignedAWSConnection._get_string_to_sign') as mock_get_string: <add> with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_key_to_sign_with') as mock_get_key: <add> with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_string_to_sign') as mock_get_string: <ide> with mock.patch('libcloud.common.aws._sign', new=_sign): <ide> mock_get_key.return_value = 'my_signing_key' <ide> mock_get_string.return_value = 'my_string_to_sign' <del> sig = self.conn._get_signature({}, {}, self.now) <add> sig = self.signer._get_signature({}, {}, self.now, <add> method='GET', path='/') <ide> <ide> self.assertEqual(sig, 'H|my_signing_key|my_string_to_sign') <ide> <ide> def test_get_string_to_sign(self): <ide> with mock.patch('hashlib.sha256') as mock_sha256: <ide> mock_sha256.return_value.hexdigest.return_value = 'chksum_of_canonical_request' <del> to_sign = self.conn._get_string_to_sign({}, {}, self.now) <add> to_sign = self.signer._get_string_to_sign({}, {}, self.now, <add> method='GET', path='/') <ide> <ide> self.assertEqual(to_sign, <ide> 'AWS4-HMAC-SHA256\n' <ide> def _sign(key, msg, hex=False): <ide> return '%s|%s' % (key, msg) <ide> <ide> with mock.patch('libcloud.common.aws._sign', new=_sign): <del> key = self.conn._get_key_to_sign_with(self.now) <add> key = self.signer._get_key_to_sign_with(self.now) <ide> <ide> self.assertEqual(key, 'AWS4my_secret|20150304|my_region|my_service|aws4_request') <ide> <ide> def test_get_signed_headers_contains_all_headers_lowercased(self): <ide> headers = {'Content-Type': 'text/plain', 'Host': 'my_host', 'X-Special-Header': ''} <del> signed_headers = self.conn._get_signed_headers(headers) <add> signed_headers = self.signer._get_signed_headers(headers) <ide> <ide> self.assertIn('content-type', signed_headers) <ide> self.assertIn('host', signed_headers) <ide> self.assertIn('x-special-header', signed_headers) <ide> <ide> def test_get_signed_headers_concats_headers_sorted_lexically(self): <ide> headers = {'Host': 'my_host', 'X-Special-Header': '', '1St-Header': '2', 'Content-Type': 'text/plain'} <del> signed_headers = self.conn._get_signed_headers(headers) <add> signed_headers = self.signer._get_signed_headers(headers) <ide> <ide> self.assertEqual(signed_headers, '1st-header;content-type;host;x-special-header') <ide> <ide> def test_get_credential_scope(self): <del> scope = self.conn._get_credential_scope(self.now) <add> scope = self.signer._get_credential_scope(self.now) <ide> self.assertEqual(scope, '20150304/my_region/my_service/aws4_request') <ide> <ide> def test_get_canonical_headers_joins_all_headers(self): <ide> headers = { <ide> 'accept-encoding': 'gzip,deflate', <ide> 'host': 'my_host', <ide> } <del> self.assertEqual(self.conn._get_canonical_headers(headers), <add> self.assertEqual(self.signer._get_canonical_headers(headers), <ide> 'accept-encoding:gzip,deflate\n' <ide> 'host:my_host\n') <ide> <ide> def test_get_canonical_headers_sorts_headers_lexically(self): <ide> 'x-amz-date': '20150304T173452Z', <ide> 'user-agent': 'my-ua' <ide> } <del> self.assertEqual(self.conn._get_canonical_headers(headers), <add> self.assertEqual(self.signer._get_canonical_headers(headers), <ide> '1st-header:2\n' <ide> 'accept-encoding:gzip,deflate\n' <ide> 'host:my_host\n' <ide> def test_get_canonical_headers_lowercases_headers_names(self): <ide> 'Accept-Encoding': 'GZIP,DEFLATE', <ide> 'User-Agent': 'My-UA' <ide> } <del> self.assertEqual(self.conn._get_canonical_headers(headers), <add> self.assertEqual(self.signer._get_canonical_headers(headers), <ide> 'accept-encoding:GZIP,DEFLATE\n' <ide> 'user-agent:My-UA\n') <ide> <ide> def test_get_canonical_headers_trims_header_values(self): <ide> 'accept-encoding': ' gzip,deflate', <ide> 'user-agent': 'libcloud/0.17.0 ' <ide> } <del> self.assertEqual(self.conn._get_canonical_headers(headers), <add> self.assertEqual(self.signer._get_canonical_headers(headers), <ide> 'accept-encoding:gzip,deflate\n' <ide> 'user-agent:libcloud/0.17.0\n') <ide> <ide> def test_get_request_params_joins_params_sorted_lexically(self): <del> self.assertEqual(self.conn._get_request_params({ <add> self.assertEqual(self.signer._get_request_params({ <ide> 'Action': 'DescribeInstances', <ide> 'Filter.1.Name': 'state', <ide> 'Version': '2013-10-15' <ide> }), <ide> 'Action=DescribeInstances&Filter.1.Name=state&Version=2013-10-15') <ide> <ide> def test_get_request_params_allows_integers_as_value(self): <del> self.assertEqual(self.conn._get_request_params({'Action': 'DescribeInstances', 'Port': 22}), <add> self.assertEqual(self.signer._get_request_params({'Action': 'DescribeInstances', 'Port': 22}), <ide> 'Action=DescribeInstances&Port=22') <ide> <ide> def test_get_request_params_urlquotes_params_keys(self): <del> self.assertEqual(self.conn._get_request_params({'Action+Reaction': 'DescribeInstances'}), <add> self.assertEqual(self.signer._get_request_params({'Action+Reaction': 'DescribeInstances'}), <ide> 'Action%2BReaction=DescribeInstances') <ide> <ide> def test_get_request_params_urlquotes_params_values(self): <del> self.assertEqual(self.conn._get_request_params({ <add> self.assertEqual(self.signer._get_request_params({ <ide> 'Action': 'DescribeInstances&Addresses', <ide> 'Port-Range': '2000 3000' <ide> }), <ide> def test_get_request_params_urlquotes_params_values(self): <ide> def test_get_request_params_urlquotes_params_values_allows_safe_chars_in_value(self): <ide> # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html <ide> self.assertEqual('Action=a~b.c_d-e', <del> self.conn._get_request_params({'Action': 'a~b.c_d-e'})) <add> self.signer._get_request_params({'Action': 'a~b.c_d-e'})) <ide> <ide> def test_get_payload_hash_returns_digest_of_empty_string_for_GET_requests(self): <del> V4SignedAWSConnection.method = 'GET' <del> self.assertEqual(self.conn._get_payload_hash(), <add> SignedAWSConnection.method = 'GET' <add> self.assertEqual(self.signer._get_payload_hash(), <ide> 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') <ide> <ide> def test_get_canonical_request(self): <del> req = self.conn._get_canonical_request( <add> req = self.signer._get_canonical_request( <ide> {'Action': 'DescribeInstances', 'Version': '2013-10-15'}, <del> {'Accept-Encoding': 'gzip,deflate', 'User-Agent': 'My-UA'} <add> {'Accept-Encoding': 'gzip,deflate', 'User-Agent': 'My-UA'}, <add> method='GET', <add> path='/my_action/' <ide> ) <ide> self.assertEqual(req, 'GET\n' <ide> '/my_action/\n' <ide> def test_get_canonical_request(self): <ide> '\n' <ide> 'accept-encoding;user-agent\n' <ide> 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') <add> <add>if __name__ == '__main__': <add> sys.exit(unittest.main())
1
Javascript
Javascript
fix typo for messaging test in webview example
577fd0cbb930c055d27e24555160143c321ec6dc
<ide><path>Examples/UIExplorer/js/WebViewExample.js <ide> exports.examples = [ <ide> } <ide> }, <ide> { <del> title: 'Mesaging Test', <add> title: 'Messaging Test', <ide> render(): ReactElement<any> { return <MessagingTest />; } <ide> }, <ide> {
1
Go
Go
fix stdout premature eof
5572dbb7504c951f4ddd2710a4037844a95caa6a
<ide><path>daemon/attach.go <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status { <ide> var ( <ide> cStdin io.ReadCloser <ide> cStdout, cStderr io.Writer <del> cStdinCloser io.Closer <ide> ) <ide> <ide> if stdin { <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status { <ide> io.Copy(w, job.Stdin) <ide> }() <ide> cStdin = r <del> cStdinCloser = job.Stdin <ide> } <ide> if stdout { <ide> cStdout = job.Stdout <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status { <ide> cStderr = job.Stderr <ide> } <ide> <del> <-daemon.attach(&container.StreamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, cStdin, cStdinCloser, cStdout, cStderr) <add> <-daemon.attach(&container.StreamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, cStdin, cStdout, cStderr) <ide> // If we are in stdinonce mode, wait for the process to end <ide> // otherwise, simply return <ide> if container.Config.StdinOnce && !container.Config.Tty { <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status { <ide> return engine.StatusOK <ide> } <ide> <del>func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error { <add>func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error { <ide> var ( <ide> cStdout, cStderr io.ReadCloser <ide> nJobs int <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> go func() { <ide> log.Debugf("attach: stdin: begin") <ide> defer log.Debugf("attach: stdin: end") <del> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <ide> if stdinOnce && !tty { <ide> defer cStdin.Close() <ide> } else { <add> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <ide> defer func() { <ide> if cStdout != nil { <ide> cStdout.Close() <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> if stdinOnce && stdin != nil { <ide> defer stdin.Close() <ide> } <del> if stdinCloser != nil { <del> defer stdinCloser.Close() <del> } <ide> _, err := io.Copy(stdout, cStdout) <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> } else { <ide> // Point stdout of container to a no-op writer. <ide> go func() { <del> if stdinCloser != nil { <del> defer stdinCloser.Close() <del> } <ide> if cStdout, err := streamConfig.StdoutPipe(); err != nil { <ide> log.Errorf("attach: stdout pipe: %s", err) <ide> } else { <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> if stdinOnce && stdin != nil { <ide> defer stdin.Close() <ide> } <del> if stdinCloser != nil { <del> defer stdinCloser.Close() <del> } <ide> _, err := io.Copy(stderr, cStderr) <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> } else { <ide> // Point stderr at a no-op writer. <ide> go func() { <del> if stdinCloser != nil { <del> defer stdinCloser.Close() <del> } <del> <ide> if cStderr, err := streamConfig.StderrPipe(); err != nil { <ide> log.Errorf("attach: stdout pipe: %s", err) <ide> } else { <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> } <ide> }() <ide> <del> // FIXME: how to clean up the stdin goroutine without the unwanted side effect <del> // of closing the passed stdin? Add an intermediary io.Pipe? <ide> for i := 0; i < nJobs; i++ { <ide> log.Debugf("attach: waiting for job %d/%d", i+1, nJobs) <ide> if err := <-errors; err != nil { <ide><path>daemon/exec.go <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) engine.Status { <ide> var ( <ide> cStdin io.ReadCloser <ide> cStdout, cStderr io.Writer <del> cStdinCloser io.Closer <ide> execName = job.Args[0] <ide> ) <ide> <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) engine.Status { <ide> r, w := io.Pipe() <ide> go func() { <ide> defer w.Close() <add> defer log.Debugf("Closing buffered stdin pipe") <ide> io.Copy(w, job.Stdin) <ide> }() <ide> cStdin = r <del> cStdinCloser = job.Stdin <ide> } <ide> if execConfig.OpenStdout { <ide> cStdout = job.Stdout <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) engine.Status { <ide> execConfig.StreamConfig.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin <ide> } <ide> <del> attachErr := d.attach(&execConfig.StreamConfig, execConfig.OpenStdin, false, execConfig.ProcessConfig.Tty, cStdin, cStdinCloser, cStdout, cStderr) <add> attachErr := d.attach(&execConfig.StreamConfig, execConfig.OpenStdin, false, execConfig.ProcessConfig.Tty, cStdin, cStdout, cStderr) <ide> <ide> execErr := make(chan error) <ide> <ide><path>integration-cli/docker_cli_run_test.go <ide> import ( <ide> "bufio" <ide> "bytes" <ide> "fmt" <add> "io" <ide> "io/ioutil" <ide> "net" <ide> "os" <ide> func TestRunVolumesCleanPaths(t *testing.T) { <ide> <ide> logDone("run - volume paths are cleaned") <ide> } <add> <add>// Regression test for #3631 <add>func TestRunSlowStdoutConsumer(t *testing.T) { <add> defer deleteAllContainers() <add> <add> c := exec.Command("/bin/bash", "-c", dockerBinary+` run --rm -i busybox /bin/sh -c "dd if=/dev/zero of=/foo bs=1024 count=2000 &>/dev/null; catv /foo"`) <add> <add> stdout, err := c.StdoutPipe() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if err := c.Start(); err != nil { <add> t.Fatal(err) <add> } <add> n, err := consumeSlow(stdout, 10000, 5*time.Millisecond) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> expected := 2 * 1024 * 2000 <add> if n != expected { <add> t.Fatalf("Expected %d, got %d", expected, n) <add> } <add> <add> logDone("run - slow consumer") <add>} <add> <add>func consumeSlow(reader io.Reader, chunkSize int, interval time.Duration) (n int, err error) { <add> buffer := make([]byte, chunkSize) <add> for { <add> var readBytes int <add> readBytes, err = reader.Read(buffer) <add> n += readBytes <add> if err != nil { <add> if err == io.EOF { <add> err = nil <add> } <add> return <add> } <add> time.Sleep(interval) <add> } <add>}
3
Java
Java
remove junit dependency from headerresultmatchers
233b225b4fcb628e0a15c18f94941e2bdd5c6af2
<ide><path>spring-test/src/main/java/org/springframework/test/util/AssertionErrors.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.util.ObjectUtils; <ide> <ide> /** <del> * JUnit independent assertion class. <add> * Test assertions that are independent of any third-party assertion library. <ide> * <ide> * @author Lukas Krecan <ide> * @author Arjen Poutsma <add> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <ide> public abstract class AssertionErrors { <ide> <ide> /** <del> * Fails a test with the given message. <del> * @param message describes the reason for the failure <add> * Fail a test with the given message. <add> * @param message a message that describes the reason for the failure <ide> */ <ide> public static void fail(String message) { <ide> throw new AssertionError(message); <ide> } <ide> <ide> /** <del> * Fails a test with the given message passing along expected and actual <add> * Fail a test with the given message passing along expected and actual <ide> * values to be added to the message. <ide> * <p>For example given: <ide> * <pre class="code"> <ide> public static void fail(String message) { <ide> * <pre class="code"> <ide> * Response header [Accept] expected:&lt;application/json&gt; but was:&lt;text/plain&gt; <ide> * </pre> <del> * @param message describes the value that failed the match <del> * @param expected expected value <del> * @param actual actual value <add> * @param message a message describes the value that failed the match <add> * @param expected the expected value <add> * @param actual the actual value <ide> */ <ide> public static void fail(String message, @Nullable Object expected, @Nullable Object actual) { <ide> throw new AssertionError(message + " expected:<" + expected + "> but was:<" + actual + ">"); <ide> } <ide> <ide> /** <ide> * Assert the given condition is {@code true} and raise an <del> * {@link AssertionError} if it is not. <del> * @param message the message <add> * {@link AssertionError} otherwise. <add> * @param message a message that describes the reason for the failure <ide> * @param condition the condition to test for <ide> */ <ide> public static void assertTrue(String message, boolean condition) { <ide> public static void assertTrue(String message, boolean condition) { <ide> } <ide> <ide> /** <del> * Assert two objects are equal and raise an {@link AssertionError} if not. <add> * Assert that the given object is not {@code null} and raise an <add> * {@link AssertionError} otherwise. <add> * @param message a message that describes the reason for the failure <add> * @param object the object to check <add> * @since 5.1 <add> */ <add> public static void assertNotNull(String message, Object object) { <add> assertTrue(message, object != null); <add> } <add> <add> /** <add> * Assert two objects are equal and raise an {@link AssertionError} otherwise. <ide> * <p>For example: <ide> * <pre class="code"> <ide> * assertEquals("Response header [" + name + "]", expected, actual); <ide> * </pre> <del> * @param message describes the value being checked <add> * @param message a message that describes the reason for the failure <ide> * @param expected the expected value <ide> * @param actual the actual value <ide> */ <ide> public static void assertEquals(String message, @Nullable Object expected, @Null <ide> * <pre class="code"> <ide> * assertNotEquals("Response header [" + name + "]", expected, actual); <ide> * </pre> <del> * @param message describes the value being checked <add> * @param message a message that describes the reason for the failure <ide> * @param expected the expected value <ide> * @param actual the actual value <ide> */ <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.test.web.servlet.ResultMatcher; <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <del>import static org.junit.Assert.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertTrue; <ide> <ide> /**
2
Mixed
Python
update augmenter lookups and docs
a103ab5f1a038ccbd668e5e33d0bee2dabd75b4e
<ide><path>spacy/errors.py <ide> class Errors: <ide> E201 = ("Span index out of range.") <ide> <ide> # TODO: fix numbering after merging develop into master <add> E912 = ("No orth_variants lookups table for data augmentation available for " <add> "language '{lang}'. If orth_variants are available in " <add> "spacy-lookups-data, make sure the package is installed and the " <add> "table is loaded in the [initialize.lookups] block of your config. " <add> "Alternatively, you can provide your own Lookups object with a " <add> "table orth_variants as the argument 'lookuos' of the augmenter.") <ide> E913 = ("Corpus path can't be None. Maybe you forgot to define it in your " <ide> "config.cfg or override it on the CLI?") <ide> E914 = ("Executing {name} callback failed. Expected the function to " <ide><path>spacy/tests/training/test_training.py <ide> from spacy.training.augment import create_orth_variants_augmenter <ide> from spacy.lang.en import English <ide> from spacy.tokens import Doc, DocBin <add>from spacy.lookups import Lookups <ide> from spacy.util import get_words_and_spaces, minibatch <ide> from thinc.api import compounding <ide> import pytest <ide> def test_roundtrip_docs_to_docbin(doc): <ide> @pytest.mark.filterwarnings("ignore::UserWarning") <ide> def test_make_orth_variants(doc): <ide> nlp = English() <add> orth_variants = { <add> "single": [ <add> {"tags": ["NFP"], "variants": ["…", "..."]}, <add> {"tags": [":"], "variants": ["-", "—", "–", "--", "---", "——"]}, <add> ] <add> } <add> lookups = Lookups() <add> lookups.add_table("orth_variants", orth_variants) <add> augmenter = create_orth_variants_augmenter(level=0.2, lower=0.5, lookups=lookups) <ide> with make_tempdir() as tmpdir: <ide> output_file = tmpdir / "roundtrip.spacy" <ide> DocBin(docs=[doc]).to_disk(output_file) <ide> # due to randomness, test only that this runs with no errors for now <del> reader = Corpus( <del> output_file, augmenter=create_orth_variants_augmenter(level=0.2, lower=0.5) <del> ) <add> reader = Corpus(output_file, augmenter=augmenter) <ide> list(reader(nlp)) <ide> <ide> <ide><path>spacy/training/augment.py <del>from typing import Callable <add>from typing import Callable, Iterator, Dict, List, Tuple, Optional, TYPE_CHECKING <ide> import random <ide> import itertools <ide> import copy <ide> from functools import partial <del>from ..util import registry <del>from ..tokens import Doc <ide> <add>from ..util import registry, logger <add>from ..tokens import Doc <add>from .example import Example <add>from ..lookups import Lookups <add>from ..errors import Errors <ide> <del>@registry.augmenters("spacy.dont_augment.v1") <del>def create_null_augmenter(): <del> return dont_augment <add>if TYPE_CHECKING: <add> from ..language import Language # noqa: F401 <ide> <ide> <ide> @registry.augmenters("spacy.orth_variants.v1") <del>def create_orth_variants_augmenter(level: float, lower: float) -> Callable: <add>def create_orth_variants_augmenter( <add> level: float, lower: float, lookups: Optional[Lookups] = None, <add>) -> Callable[["Language", Example], Iterator[Example]]: <ide> """Create a data augmentation callback that uses orth-variant replacement. <ide> The callback can be added to a corpus or other data iterator during training. <ide> """ <del> return partial(orth_variants_augmenter, level=level, lower=lower) <add> return partial(orth_variants_augmenter, level=level, lower=lower, lookups=lookups) <ide> <ide> <del>def dont_augment(nlp, example): <add>def dont_augment(nlp: "Language", example: Example) -> Iterator[Example]: <ide> yield example <ide> <ide> <del>def orth_variants_augmenter(nlp, example, *, level: float = 0.0, lower: float = 0.0): <add>def orth_variants_augmenter( <add> nlp: "Language", <add> example: Example, <add> *, <add> level: float = 0.0, <add> lower: float = 0.0, <add> lookups: Optional[Lookups] = None, <add>) -> Iterator[Example]: <add> table_name = "orth_variants" <add> if lookups is not None: <add> orth_variants = lookups.get_table(table_name, {}) <add> logger.debug("Using data augmentation orth variants from provided lookups") <add> else: <add> orth_variants = nlp.vocab.lookups.get_table(table_name, {}) <add> logger.debug("Using data augmentation orth variants from default vocab lookups") <add> if not orth_variants: <add> raise ValueError(Errors.E912.format(lang=nlp.lang)) <ide> if random.random() >= level: <ide> yield example <ide> else: <ide> def orth_variants_augmenter(nlp, example, *, level: float = 0.0, lower: float = <ide> nlp, <ide> raw_text, <ide> orig_dict["token_annotation"], <add> orth_variants, <ide> lower=raw_text is not None and random.random() < lower, <ide> ) <ide> if variant_text: <ide> def orth_variants_augmenter(nlp, example, *, level: float = 0.0, lower: float = <ide> yield example.from_dict(doc, orig_dict) <ide> <ide> <del>def make_orth_variants(nlp, raw, token_dict, *, lower: bool = False): <add>def make_orth_variants( <add> nlp: "Language", <add> raw: str, <add> token_dict: Dict[str, List[str]], <add> orth_variants: Dict[str, list], <add> *, <add> lower: bool = False, <add>) -> Tuple[str, Dict[str, List[str]]]: <ide> orig_token_dict = copy.deepcopy(token_dict) <del> orth_variants = nlp.vocab.lookups.get_table("orth_variants", {}) <ide> ndsv = orth_variants.get("single", []) <ide> ndpv = orth_variants.get("paired", []) <ide> words = token_dict.get("words", []) <ide><path>website/docs/api/corpus.md <ide> new: 3 <ide> --- <ide> <ide> This class manages annotated corpora and can be used for training and <del>development datasets in the [DocBin](/api/docbin) (`.spacy`) format. To <add>development datasets in the [`DocBin`](/api/docbin) (`.spacy`) format. To <ide> customize the data loading during training, you can register your own <del>[data readers and batchers](/usage/training#custom-code-readers-batchers). <add>[data readers and batchers](/usage/training#custom-code-readers-batchers). Also <add>see the usage guide on [data utilities](/usage/training#data) for more details <add>and examples. <ide> <ide> ## Config and implementation {#config} <ide> <ide><path>website/docs/api/top-level.md <ide> menu: <ide> - ['Loggers', 'loggers'] <ide> - ['Readers', 'readers'] <ide> - ['Batchers', 'batchers'] <del> - ['Data & Alignment', 'gold'] <add> - ['Augmenters', 'augmenters'] <add> - ['Training & Alignment', 'gold'] <ide> - ['Utility Functions', 'util'] <ide> --- <ide> <ide> factories. <ide> | Registry name | Description | <ide> | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <ide> | `architectures` | Registry for functions that create [model architectures](/api/architectures). Can be used to register custom model architectures and reference them in the `config.cfg`. | <add>| `augmenters` | Registry for functions that create [data augmentation](#augmenters) callbacks for corpora and other training data iterators. | <ide> | `batchers` | Registry for training and evaluation [data batchers](#batchers). | <ide> | `callbacks` | Registry for custom callbacks to [modify the `nlp` object](/usage/training#custom-code-nlp-callbacks) before training. | <ide> | `displacy_colors` | Registry for custom color scheme for the [`displacy` NER visualizer](/usage/visualizers). Automatically reads from [entry points](/usage/saving-loading#entry-points). | <ide> sequences in the batch. <ide> | `discard_oversize` | Whether to discard sequences that are by themselves longer than the largest padded batch size. ~~bool~~ | <ide> | `get_length` | Optional function that receives a sequence item and returns its length. Defaults to the built-in `len()` if not set. ~~Optional[Callable[[Any], int]]~~ | <ide> <add>## Augmenters {#augmenters source="spacy/training/augment.py" new="3"} <add> <add><!-- TODO: intro, explain data augmentation concept --> <add> <add>### orth_variants {#orth_variants tag="registered function"} <add> <add>> #### Example config <add>> <add>> ```ini <add>> [corpora.train.augmenter] <add>> @augmenters = "spacy.orth_variants.v1" <add>> level = 0.0 <add>> lower = 0.0 <add>> lookups = null <add>> ``` <add> <add>Create a data augmentation callback that uses orth-variant replacement. The <add>callback can be added to a corpus or other data iterator during training. This <add>is especially useful for punctuation and case replacement, to help generalize <add>beyond corpora that don't have smart quotes, or only have smart quotes etc. <add> <add>| Name | Description | <add>| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | <add>| `level` | ~~float~~ | <add>| `lower` | ~~float~~ | <add>| `lookups` | Lookups table containing the orth variants to use. See [`orth_variants.json`](https://github.com/explosion/spacy-lookups-data/blob/master/spacy_lookups_data/data/en_orth_variants.json) for an example. If not set, tables from [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data) are used if available and added in the [`[initialize]`](/api/data-formats#config-initialize) block of the config. If no orth variants are found, spaCy will raise an error. Defaults to `None`. ~~Optional[Lookups]~~ | <add>| **RETURNS** | A function that takes the current `nlp` object and an [`Example`](/api/example) and yields augmented `Example` objects. ~~Callable[[Language, Example], Iterator[Example]]~~ | <add> <ide> ## Training data and alignment {#gold source="spacy/training"} <ide> <ide> ### training.offsets_to_biluo_tags {#offsets_to_biluo_tags tag="function"} <ide><path>website/docs/usage/training.md <ide> def MyModel(output_width: int) -> Model[List[Doc], List[Floats2d]]: <ide> <ide> ## Data utilities {#data} <ide> <del>spaCy includes various features and utilities to make it easy to train from your <del>own data. If you have training data in a standard format like `.conll` or <del>`.conllu`, the easiest way to convert it for use with spaCy is to run <del>[`spacy convert`](/api/cli#convert) and pass it a file and an output directory: <add>spaCy includes various features and utilities to make it easy to train models <add>using your own data, manage training and evaluation corpora, convert existing <add>annotations and configure data augmentation strategies for more robust models. <add> <add>### Converting existing corpora and annotations {#data-convert} <add> <add>If you have training data in a standard format like `.conll` or `.conllu`, the <add>easiest way to convert it for use with spaCy is to run <add>[`spacy convert`](/api/cli#convert) and pass it a file and an output directory. <add>By default, the command will pick the converter based on the file extension. <ide> <ide> ```cli <ide> $ python -m spacy convert ./train.gold.conll ./corpus <ide> ``` <ide> <add>> #### 💡 Tip: Converting from Prodigy <add>> <add>> If you're using the [Prodigy](https://prodi.gy) annotation tool to create <add>> training data, you can run the <add>> [`data-to-spacy` command](https://prodi.gy/docs/recipes#data-to-spacy) to <add>> merge and export multiple datasets for use with <add>> [`spacy train`](/api/cli#train). Different types of annotations on the same <add>> text will be combined, giving you one corpus to train multiple components. <add> <ide> <Infobox title="Tip: Manage multi-step workflows with projects" emoji="💡"> <ide> <ide> Training workflows often consist of multiple steps, from preprocessing the data <ide> data assets, track changes and share your end-to-end processes with your team. <ide> <ide> </Infobox> <ide> <add>The binary `.spacy` format is a serialized [`DocBin`](/api/docbin) containing <add>one or more [`Doc`](/api/doc) objects. It's is extremely **efficient in <add>storage**, especially when packing multiple documents together. You can also <add>create `Doc` objects manually, so you can write your own custom logic to convert <add>and store existing annotations for use in spaCy. <add> <add>```python <add>### Training data from Doc objects {highlight="6-9"} <add>import spacy <add>from spacy.tokens import Doc, DocBin <add> <add>nlp = spacy.blank("en") <add>docbin = DocBin(nlp.vocab) <add>words = ["Apple", "is", "looking", "at", "buying", "U.K.", "startup", "."] <add>spaces = [True, True, True, True, True, True, True, False] <add>ents = [("ORG", 0, 1), ("GPE", 5, 6)] <add>doc = Doc(nlp.vocab, words=words, spaces=spaces, ents=ents) <add>docbin.add(doc) <add>docbin.to_disk("./train.spacy") <add>``` <add> <ide> ### Working with corpora {#data-corpora} <ide> <ide> > #### Example
6
Text
Text
fix typo in docs
81756675c59751410ae89f88d113b77146c2fc26
<ide><path>research/deeplab/README.md <ide> work: <ide> } <ide> ``` <ide> <del> <ide> In the current implementation, we support adopting the following network <ide> backbones: <ide> <ide> 1. MobileNetv2 [8]: A fast network structure designed for mobile devices. **We <del>will provide MobileNetv2 support in the next update. Please stay tuned.** <add> will provide MobileNetv2 support in the next update. Please stay tuned.** <ide> <ide> 2. Xception [9, 10]: A powerful network structure intended for server-side <ide> deployment. <ide> Models: <ide> <ide> Misc: <ide> <del>* Please check <a href='g3doc/faq.md'>FAQ<a/a> if you have some questions before reporting the issues.<br> <add>* Please check <a href='g3doc/faq.md'>FAQ</a> if you have some questions before reporting the issues.<br> <ide> <ide> ## Getting Help <ide> <ide> To get help with issues you may encounter while using the DeepLab Tensorflow <del>implementation, create a new question on [StackOverflow](https://stackoverflow.com/) <del>with the tags "tensorflow" and "deeplab". <add>implementation, create a new question on <add>[StackOverflow](https://stackoverflow.com/) with the tags "tensorflow" and <add>"deeplab". <ide> <ide> Please report bugs (i.e., broken code, not usage questions) to the <ide> tensorflow/models GitHub [issue <ide><path>research/deeplab/g3doc/model_zoo.md <ide> is available, since we have already fine-tuned the batch normalization for you. <ide> In the latter case, one could directly evaluate the checkpoints on VOC 2012 test <ide> set or use this checkpoint for demo. <ide> <del>| Checkpoint name | Network | Pretrained | ASPP | Decoder | <del>: : backbone : dataset : : : <del>| ----------------------------- | :----------: | :--------: | :---: | :-----: | <del>| xception_coco_voc_trainaug | Xception_65 | MS-COCO | [6, | OS = 4 | <del>: : : <br> VOC : 12, : : <del>: : : 2012 : 18] : : <del>: : : train_aug : for : : <del>: : : set : OS=16 : : <del>: : : : <br> : : <del>: : : : [12, : : <del>: : : : 24, : : <del>: : : : 36] : : <del>: : : : for : : <del>: : : : OS=8 : : <del>| xception_coco_voc_trainval | Xception_65 | MS-COCO | [6, | OS = 4 | <del>: : : <br> VOC : 12, : : <del>: : : 2012 : 18] : : <del>: : : train_aug : for : : <del>: : : + trainval : OS=16 : : <del>: : : sets : <br> : : <del>: : : : [12, : : <del>: : : : 24, : : <del>: : : : 36] : : <del>: : : : for : : <del>: : : : OS=8 : : <add>Checkpoint name | Network backbone | Pretrained dataset | ASPP | Decoder <add>--------------------------- | :--------------: | :-----------------: | :---: | :-----: <add>xception_coco_voc_trainaug | Xception_65 | MS-COCO <br> VOC 2012 train_aug set| [6,12,18] for OS=16 <br> [12,24,36] for OS=8 | OS = 4 <add>xception_coco_voc_trainval | Xception_65 | MS-COCO <br> VOC 2012 train_aug + trainval sets | [6,12,18] for OS=16 <br> [12,24,36] for OS=8 | OS = 4 <ide> <ide> In the table, **OS** denotes output stride. <ide>
2
Javascript
Javascript
remove setupdevtools file
5dade01ca6389ea5745c696478943ece11be11dc
<ide><path>Libraries/Core/Devtools/setupDevtools.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>let register = function() { <del> // noop <del>}; <del> <del>if (__DEV__) { <del> const AppState = require('../../AppState/AppState'); <del> const reactDevTools = require('react-devtools-core'); <del> const getDevServer = require('./getDevServer'); <del> <del> // Don't steal the DevTools from currently active app. <del> // Note: if you add any AppState subscriptions to this file, <del> // you will also need to guard against `AppState.isAvailable`, <del> // or the code will throw for bundles that don't have it. <del> const isAppActive = () => AppState.currentState !== 'background'; <del> <del> // Get hostname from development server (packager) <del> const devServer = getDevServer(); <del> const host = devServer.bundleLoadedFromServer <del> ? devServer.url.replace(/https?:\/\//, '').split(':')[0] <del> : 'localhost'; <del> <del> reactDevTools.connectToDevTools({ <del> isAppActive, <del> host, <del> // Read the optional global variable for backward compatibility. <del> // It was added in https://github.com/facebook/react-native/commit/bf2b435322e89d0aeee8792b1c6e04656c2719a0. <del> port: window.__REACT_DEVTOOLS_PORT__, <del> resolveRNStyle: require('../../StyleSheet/flattenStyle'), <del> }); <del>} <del> <del>module.exports = { <del> register, <del>}; <ide><path>Libraries/Core/setUpDeveloperTools.js <ide> if (__DEV__) { <ide> // not when debugging in chrome <ide> // TODO(t12832058) This check is broken <ide> if (!window.document) { <del> require('./Devtools/setupDevtools'); <add> const AppState = require('../AppState/AppState'); <add> // $FlowFixMe Module is untyped <add> const reactDevTools = require('react-devtools-core'); <add> const getDevServer = require('./Devtools/getDevServer'); <add> <add> // Don't steal the DevTools from currently active app. <add> // Note: if you add any AppState subscriptions to this file, <add> // you will also need to guard against `AppState.isAvailable`, <add> // or the code will throw for bundles that don't have it. <add> const isAppActive = () => AppState.currentState !== 'background'; <add> <add> // Get hostname from development server (packager) <add> const devServer = getDevServer(); <add> const host = devServer.bundleLoadedFromServer <add> ? devServer.url.replace(/https?:\/\//, '').split(':')[0] <add> : 'localhost'; <add> <add> reactDevTools.connectToDevTools({ <add> isAppActive, <add> host, <add> // Read the optional global variable for backward compatibility. <add> // It was added in https://github.com/facebook/react-native/commit/bf2b435322e89d0aeee8792b1c6e04656c2719a0. <add> port: window.__REACT_DEVTOOLS_PORT__, <add> resolveRNStyle: require('../StyleSheet/flattenStyle'), <add> }); <ide> } <ide> <ide> // Set up inspector <ide><path>jest/setup.js <ide> global.cancelAnimationFrame = function(id) { <ide> clearTimeout(id); <ide> }; <ide> <del>jest.mock('../Libraries/Core/Devtools/setupDevtools'); <del> <ide> // there's a __mock__ for it. <ide> jest.setMock( <ide> '../Libraries/vendor/core/ErrorUtils',
3
Javascript
Javascript
fix reference error when tagging a release
55a115179e4717f10f25301a1b86fbc6cfd21de2
<ide><path>gulpfile.js <ide> gulp.task('bump', function(complete){ <ide> }); <ide> <ide> gulp.task('release', ['build'], function(){ <del> exec('git tag -a v' + newVersion); <add> exec('git tag -a v' + package.version); <ide> }); <ide> <ide> gulp.task('jshint', function(){
1
Ruby
Ruby
use admin group and not staff
98ec342ecc597d0bb2806fbd2a5fafb796caf8ed
<ide><path>install_homebrew.rb <ide> def macos_version <ide> abort "MacOS too old, see: https://gist.github.com/1144389" if macos_version < 10.5 <ide> abort "/usr/local/.git already exists!" unless Dir["/usr/local/.git/*"].empty? <ide> abort "Don't run this as root!" if Process.uid == 0 <del>abort <<-EOABORT unless `groups`.split.include? "staff" <del>This script requires the user #{ENV['USER']} to be in the staff group. If this <add>abort <<-EOABORT unless `groups`.split.include? "admin" <add>This script requires the user #{ENV['USER']} to be an Administrator. If this <ide> sucks for you then you can install Homebrew in your home directory or however <ide> you please; please refer to the website. If you still want to use this script <del>the following command should work: <del> <del> dscl /Local/Default -append /Groups/staff GroupMembership $USER <add>set your user to be an Administrator in System Preferences or `su'. <ide> EOABORT <ide> <ide> ohai "This script will install:" <ide> def macos_version <ide> puts *chmods <ide> end <ide> unless chgrps.empty? <del> ohai "The following directories will have their group set to #{Tty.underline 39}staff#{Tty.reset}:" <add> ohai "The following directories will have their group set to #{Tty.underline 39}admin#{Tty.reset}:" <ide> puts *chgrps <ide> end <ide> <ide> def macos_version <ide> <ide> if File.directory? "/usr/local" <ide> sudo "/bin/chmod", "g+rwx", *chmods unless chmods.empty? <del> # all admin users are in staff <del> sudo "/usr/bin/chgrp", "staff", *chgrps unless chgrps.empty? <add> sudo "/usr/bin/chgrp", "admin", *chgrps unless chgrps.empty? <ide> else <ide> sudo "/bin/mkdir /usr/local" <ide> sudo "/bin/chmod g+rwx /usr/local" <ide> # the group is set to wheel by default for some reason <del> sudo "/usr/bin/chgrp staff /usr/local" <add> sudo "/usr/bin/chgrp admin /usr/local" <ide> end <ide> <ide> Dir.chdir "/usr/local" do
1
PHP
PHP
update env var check
34ea1e41c5b684929034f2776326a62cb4b7dc28
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testEagerLoadOrderAndSubquery() <ide> public function testFormatResultsMemoryLeak() <ide> { <ide> $this->loadFixtures('Articles', 'Authors', 'Tags', 'ArticlesTags'); <del> $this->skipIf(env('CODECOVERAGE') === 1, 'Running coverage this causes this tests to fail sometimes.'); <add> $this->skipIf((bool)env('CODECOVERAGE'), 'Running coverage this causes this tests to fail sometimes.'); <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->belongsTo('Authors'); <ide> $table->belongsToMany('Tags'); <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testExtendWithPrefixElementBeforeExtend() <ide> */ <ide> public function testMemoryLeakInPaths() <ide> { <del> $this->skipIf(env('CODECOVERAGE') === 1, 'Running coverage this causes this tests to fail sometimes.'); <add> $this->skipIf((bool)env('CODECOVERAGE'), 'Running coverage this causes this tests to fail sometimes.'); <ide> $this->ThemeController->setPlugin(null); <ide> $this->ThemeController->setName('Posts'); <ide>
2
Ruby
Ruby
remove warning of shadowing outer local variable
86f287e6cfc4181447d936d0d1c0336d944e7327
<ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> def button_to(name = nil, options = nil, html_options = nil, &block) <ide> <ide> inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag) <ide> if params <del> params.each do |name, value| <del> inner_tags.safe_concat tag(:input, type: "hidden", name: name, value: value.to_param) <add> params.each do |param_name, value| <add> inner_tags.safe_concat tag(:input, type: "hidden", name: param_name, value: value.to_param) <ide> end <ide> end <ide> content_tag('form', content_tag('div', inner_tags), form_options)
1
Java
Java
add host property in httpserversupport
c6ed12297f284ef8b7385683fe40e1faf4d0ef95
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/HttpServer.java <ide> */ <ide> public interface HttpServer extends InitializingBean, Lifecycle { <ide> <add> void setHost(String host); <add> <ide> void setPort(int port); <ide> <ide> void setHandler(HttpHandler handler); <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/HttpServerSupport.java <ide> package org.springframework.http.server.reactive.boot; <ide> <ide> <add>import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.http.server.reactive.HttpHandler; <add>import org.springframework.util.SocketUtils; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class HttpServerSupport { <ide> <add> private String host = "0.0.0.0"; <add> <ide> private int port = -1; <ide> <ide> private HttpHandler httpHandler; <ide> <add> public void setHost(String host) { <add> this.host = host; <add> } <add> <add> public String getHost() { <add> return host; <add> } <ide> <ide> public void setPort(int port) { <ide> this.port = port; <ide> } <ide> <ide> public int getPort() { <add> if(this.port == -1) { <add> this.port = SocketUtils.findAvailableTcpPort(8080); <add> } <ide> return this.port; <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/JettyHttpServer.java <ide> import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.SocketUtils; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> public boolean isRunning() { <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <ide> <del> if (getPort() == -1) { <del> setPort(SocketUtils.findAvailableTcpPort(8080)); <del> } <del> <ide> this.jettyServer = new Server(); <ide> <ide> Assert.notNull(getHttpHandler()); <ide> public void afterPropertiesSet() throws Exception { <ide> contextHandler.addServlet(servletHolder, "/"); <ide> <ide> ServerConnector connector = new ServerConnector(this.jettyServer); <add> connector.setHost(getHost()); <ide> connector.setPort(getPort()); <ide> this.jettyServer.addConnector(connector); <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/ReactorHttpServer.java <ide> public void afterPropertiesSet() throws Exception { <ide> <ide> Assert.notNull(getHttpHandler()); <ide> this.reactorHandler = new ReactorHttpHandlerAdapter(getHttpHandler()); <del> <del> this.reactorServer = (getPort() != -1 ? reactor.io.netty.http.HttpServer.create(getPort()) : <del> reactor.io.netty.http.HttpServer.create()); <add> this.reactorServer = reactor.io.netty.http.HttpServer.create(getHost(), getPort()); <ide> } <ide> <ide> @Override <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/RxNettyHttpServer.java <ide> <ide> package org.springframework.http.server.reactive.boot; <ide> <add>import java.net.InetSocketAddress; <add> <ide> import io.netty.buffer.ByteBuf; <ide> <ide> import org.springframework.http.server.reactive.RxNettyHttpHandlerAdapter; <ide> public void afterPropertiesSet() throws Exception { <ide> Assert.notNull(getHttpHandler()); <ide> this.rxNettyHandler = new RxNettyHttpHandlerAdapter(getHttpHandler()); <ide> <del> this.rxNettyServer = (getPort() != -1 ? <del> io.reactivex.netty.protocol.http.server.HttpServer.newServer(getPort()) : <del> io.reactivex.netty.protocol.http.server.HttpServer.newServer()); <add> this.rxNettyServer = io.reactivex.netty.protocol.http.server.HttpServer <add> .newServer(new InetSocketAddress(getHost(), getPort())); <ide> } <ide> <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/TomcatHttpServer.java <ide> <ide> import org.apache.catalina.Context; <ide> import org.apache.catalina.LifecycleException; <add>import org.apache.catalina.core.StandardHost; <ide> import org.apache.catalina.startup.Tomcat; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide> public boolean isRunning() { <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <ide> <del> if (getPort() == -1) { <del> setPort(SocketUtils.findAvailableTcpPort(8080)); <del> } <del> <ide> this.tomcatServer = new Tomcat(); <add> this.tomcatServer.setHostname(getHost()); <ide> this.tomcatServer.setPort(getPort()); <ide> <ide> Assert.notNull(getHttpHandler()); <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/UndertowHttpServer.java <ide> public void afterPropertiesSet() throws Exception { <ide> Assert.notNull(getHttpHandler()); <ide> HttpHandler handler = <ide> new UndertowHttpHandlerAdapter(getHttpHandler(), dataBufferFactory); <del> int port = (getPort() != -1 ? getPort() : 8080); <del> this.server = Undertow.builder().addHttpListener(port, "localhost") <add> this.server = Undertow.builder().addHttpListener(getPort(), getHost()) <ide> .setHandler(handler).build(); <ide> } <ide>
7
Go
Go
fix typo in builder
979db00d9af4741572ece9c67061526d5d4a6616
<ide><path>builder.go <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e <ide> config = &Config{} <ide> <ide> break <del> case "mainainer": <add> case "maintainer": <ide> fmt.Fprintf(stdout, "MAINTAINER %s\n", arguments) <ide> maintainer = arguments <ide> break
1