content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Go
Go
implement untar via archive/tar
a4868e233c7ebce259fc02d3dbfb241c23471a4a
<ide><path>archive/archive.go <ide> import ( <ide> "os/exec" <ide> "path" <ide> "path/filepath" <add> "strings" <ide> "syscall" <ide> ) <ide> <ide> func TarFilter(path string, options *TarOptions) (io.Reader, error) { <ide> // The archive may be compressed with one of the following algorithms: <ide> // identity (uncompressed), gzip, bzip2, xz. <ide> // FIXME: specify behavior when target path exists vs. doesn't exist. <del>func Untar(archive io.Reader, path string, options *TarOptions) error { <add>func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> if archive == nil { <ide> return fmt.Errorf("Empty archive") <ide> } <ide> <del> buf := make([]byte, 10) <del> totalN := 0 <del> for totalN < 10 { <del> n, err := archive.Read(buf[totalN:]) <add> archive, err := DecompressStream(archive) <add> if err != nil { <add> return err <add> } <add> <add> tr := tar.NewReader(archive) <add> <add> var dirs []*tar.Header <add> <add> // Iterate through the files in the archive. <add> for { <add> hdr, err := tr.Next() <add> if err == io.EOF { <add> // end of tar archive <add> break <add> } <ide> if err != nil { <del> if err == io.EOF { <del> return fmt.Errorf("Tarball too short") <del> } <ide> return err <ide> } <del> totalN += n <del> utils.Debugf("[tar autodetect] n: %d", n) <del> } <ide> <del> compression := DetectCompression(buf) <add> if options != nil { <add> excludeFile := false <add> for _, exclude := range options.Excludes { <add> if strings.HasPrefix(hdr.Name, exclude) { <add> excludeFile = true <add> break <add> } <add> } <add> if excludeFile { <add> continue <add> } <add> } <ide> <del> utils.Debugf("Archive compression detected: %s", compression.Extension()) <del> args := []string{"--numeric-owner", "-f", "-", "-C", path, "-x" + compression.Flag()} <add> // Normalize name, for safety and for a simple is-root check <add> hdr.Name = filepath.Clean(hdr.Name) <ide> <del> if options != nil { <del> for _, exclude := range options.Excludes { <del> args = append(args, fmt.Sprintf("--exclude=%s", exclude)) <add> if !strings.HasSuffix(hdr.Name, "/") { <add> // Not the root directory, ensure that the parent directory exists <add> parent := filepath.Dir(hdr.Name) <add> parentPath := filepath.Join(dest, parent) <add> if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { <add> err = os.MkdirAll(parentPath, 600) <add> if err != nil { <add> return err <add> } <add> } <add> } <add> <add> path := filepath.Join(dest, hdr.Name) <add> <add> // If path exits we almost always just want to remove and replace it <add> // The only exception is when it is a directory *and* the file from <add> // the layer is also a directory. Then we want to merge them (i.e. <add> // just apply the metadata from the layer). <add> if fi, err := os.Lstat(path); err == nil { <add> if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { <add> if err := os.RemoveAll(path); err != nil { <add> return err <add> } <add> } <add> } <add> <add> if err := createTarFile(path, dest, hdr, tr); err != nil { <add> return err <add> } <add> <add> // Directory mtimes must be handled at the end to avoid further <add> // file creation in them to modify the directory mtime <add> if hdr.Typeflag == tar.TypeDir { <add> dirs = append(dirs, hdr) <ide> } <ide> } <ide> <del> cmd := exec.Command("tar", args...) <del> cmd.Stdin = io.MultiReader(bytes.NewReader(buf), archive) <del> // Hardcode locale environment for predictable outcome regardless of host configuration. <del> // (see https://github.com/dotcloud/docker/issues/355) <del> cmd.Env = []string{"LANG=en_US.utf-8", "LC_ALL=en_US.utf-8"} <del> output, err := cmd.CombinedOutput() <del> if err != nil { <del> return fmt.Errorf("%s: %s", err, output) <add> for _, hdr := range dirs { <add> path := filepath.Join(dest, hdr.Name) <add> ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} <add> if err := syscall.UtimesNano(path, ts); err != nil { <add> return err <add> } <ide> } <add> <ide> return nil <ide> } <ide>
1
Javascript
Javascript
fix typo in test/common/index.js
d0fa1e9b2d59d383723d195ede1647e0c6c93264
<ide><path>test/common/index.js <ide> let knownGlobals = [ <ide> <ide> // TODO(@jasnell): This check can be temporary. AbortController is <ide> // not currently supported in either Node.js 12 or 10, making it <del>// difficult to run tests comparitively on those versions. Once <add>// difficult to run tests comparatively on those versions. Once <ide> // all supported versions have AbortController as a global, this <ide> // check can be removed and AbortController can be added to the <ide> // knownGlobals list above.
1
Ruby
Ruby
add pip to blacklist
dfcff44e3e9129b7779e5baadc336a6d3156373f
<ide><path>Library/Homebrew/blacklist.rb <ide> def blacklisted? name <ide> <ide> easy_install mercurial <ide> EOS <del> when 'setuptools' then <<-EOS.undent <del> When working with a Homebrew-built Python, distribute is preferred over <del> setuptools, and can be used as the prerequisite for pip: <add> when 'pip' then <<-EOS.undent <add> Install pip with easy_install: <ide> <del> brew install distribute <add> easy_install pip <ide> EOS <ide> when 'npm' then <<-EOS.undent <ide> npm can be installed thusly by following the instructions at
1
Javascript
Javascript
make aftereach async
15b6f8bb7ff6e9f38e2089f363f4e37131af13f9
<ide><path>test/configCases/externals/global/index.js <del>afterEach(() => { <add>afterEach(done => { <ide> delete global.EXTERNAL_TEST_GLOBAL; <add> done(); <ide> }); <ide> <ide> it("should move externals in chunks into entry chunk", function() {
1
Ruby
Ruby
fix all rubocop violations
f7d0bd657f5003ceede4c7e6322cb0f013db06a8
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def initialize <ide> @binds = [] <ide> end <ide> <del> def << str <add> def <<(str) <ide> @parts << str <ide> self <ide> end <ide> <del> def add_bind obj <add> def add_bind(obj) <ide> @binds << obj <ide> @parts << Arel::Nodes::BindParam.new(1) <ide> self <ide><path>activesupport/lib/active_support/messages/metadata.rb <ide> # frozen_string_literal: true <add> <ide> require "time" <ide> <ide> module ActiveSupport <ide><path>tasks/release.rb <ide> def rc? <ide> versions = ENV["VERSIONS"] ? ENV["VERSIONS"].split(",") : [ version ] <ide> versions = versions.sort.map { |v| Announcement::Version.new(v) } <ide> <del> raise "Only valid for patch releases" if versions.any?(&:major_or_security?) <add> raise "Only valid for patch releases" if versions.any?(&:major_or_security?) <ide> <ide> if versions.any?(&:rc?) <ide> require "date"
3
Java
Java
fix failing tests
9a501fac46a9e4879ba8d72360ad1713169f2d8e
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java <ide> <ide> import static java.util.Arrays.asList; <ide> import static java.util.Collections.*; <add> <add>import com.fasterxml.jackson.databind.ObjectMapper; <ide> import org.junit.Test; <ide> <ide> import static org.springframework.core.ResolvableType.forClass; <ide> public void decodeEmptyBodyToMono() throws Exception { <ide> <ide> @Test <ide> public void invalidData() throws Exception { <del> Flux<DataBuffer> source = Flux.just(stringBuffer( "{\"property1\":\"foo\"")); <del> ResolvableType elementType = forClass(BeanWithNoDefaultConstructor.class); <del> Flux<Object> flux = new Jackson2JsonDecoder().decode(source, elementType, null, emptyMap()); <del> StepVerifier.create(flux).expectError(InternalCodecException.class); <add> Flux<DataBuffer> source = Flux.just(stringBuffer( "{\"foofoo\": \"foofoo\", \"barbar\": \"barbar\"}")); <add> ResolvableType elementType = forClass(Pojo.class); <add> Flux<Object> flux = new Jackson2JsonDecoder(new ObjectMapper()).decode(source, elementType, null, emptyMap()); <add> StepVerifier.create(flux).verifyErrorMatches(ex -> ex instanceof CodecException && !(ex instanceof InternalCodecException)); <ide> } <ide> <ide> @Test <ide> public void noDefaultConstructor() throws Exception { <ide> Flux<Object> flux = new Jackson2JsonDecoder().decode(source, elementType, null, emptyMap()); <ide> StepVerifier <ide> .create(flux) <del> .verifyErrorMatches(ex -> ex instanceof CodecException && !(ex instanceof InternalCodecException)); <add> .expectError(InternalCodecException.class); <ide> } <ide> <ide>
1
Javascript
Javascript
improve example for {{loc}}
3ef443b42171ddad81829032caa9bd733729f3ae
<ide><path>packages/ember-handlebars/lib/helpers/loc.js <ide> require('ember-handlebars/ext'); <ide> /** <ide> `loc` looks up the string in the localized strings hash. <ide> This is a convenient way to localize text. For example: <add> <add> ```javascript <add> App.ApplicationController = Ember.Controller.extend({ <add> welcomeMessage: '_Hello World' <add> }); <ide> <del> ```html <del> <script type="text/x-handlebars" data-template-name="home"> <del> {{loc welcome}} <del> </script> <add> Ember.STRINGS = { <add> '_Hello World': 'Bonjour le monde', <add> }; <ide> ``` <ide> <del> Take note that `welcome` is a string and not an object <del> reference. <add> ```handlebars <add> <span>{{loc welcomeMessage}}<span> <add> ``` <add> <add> ```html <add> <span>Bonjour le monde</span> <add> ``` <ide> <ide> @method loc <ide> @for Ember.Handlebars.helpers
1
Text
Text
get the length of an array - the count() function
1b4e3c01b76995b218d176533fbe56f3f7d18ae9
<ide><path>guide/english/php/arrays/index.md <ide> In PHP, there are two types of arrays: Indexed arrays and Associative arrays. Ea <ide> ### Indexed Array Example <ide> An indexed array is a list of ordered values. Each of these values in the array is assigned an index number. Indexes for arrays always start at `0` for the first value and then increase by one from there. <ide> <del>```PHP <add>```php <ide> <?php <ide> $shopping_list = array("eggs", "milk", "cheese"); <ide> ``` <ide> $shopping_list = array("eggs", "milk", "cheese"); <ide> ### Associative Array Example <ide> An associative array is a list of values that are accessed via a key instead of index numbers. The key can be any value but it must be unique to the array. <ide> <del>```PHP <add>```php <ide> <?php <ide> $student_scores = array("Joe" => 83, "Frank" => "93", "Benji" => "90"); <ide> ``` <ide> `$student_scores['Joe']` would return `83`, `$student_scores['Frank']` would return `93`, `$student_scores['Benji']` would return `90`. <ide> <ide> ### Multidimensional Array Example <ide> A multidimensional array is an array that contains other arrays. This lets you create complex data structures that can model a very complex group of data. <del>```PHP <add>```php <ide> <?php <ide> $students = <ide> array( <ide> Now you can get the first student's `first_name` with: <ide> ```PHP <ide> $students[0]['first_name'] <ide> ``` <add> <add>### Get The Length of an Array - The count() Function <add>The `"count()"` function is used to return the length (the number of elements) of an array: <add>```php <add><?php <add><?php <add>$cars = array("Volvo", "BMW", "Toyota"); <add>echo count($cars); <add>?> <add>``` <add> <ide> #### More Information: <del>* <a href="https://secure.php.net/manual/en/language.types.array.php" rel="nofollow">php.net arrays manual</a> <add>* <a href="https://secure.php.net/manual/en/language.types.array.php" rel="nofollow">php.net arrays manual</a> <ide>\ No newline at end of file
1
Javascript
Javascript
add pickingray method
bc27e18424abe3e5fe24a0d4701806b5cf4fc9a0
<ide><path>src/core/Projector.js <ide> THREE.Projector = function() { <ide> <ide> this.projectVector = function ( vector, camera ) { <ide> <del> _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse ); <add> _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse ); <ide> _projScreenMatrix.multiplyVector3( vector ); <ide> <ide> return vector; <ide> }; <ide> <del> this.unprojectVector = function ( vector, camera, ray ) { <del> var end, dir, t; <del> <del> //if ( camera instanceof THREE.OrthographicCamera ) { <del> <del> vector.z = -1.0; <del> end = new THREE.Vector3( vector.x, vector.y, 1.0); <del> <del> //} <add> this.unprojectVector = function ( vector, camera ) { <ide> <ide> _projScreenMatrix.multiply( camera.matrixWorld, THREE.Matrix4.makeInvert( camera.projectionMatrix ) ); <ide> _projScreenMatrix.multiplyVector3( vector ); <ide> <del> // if ( camera instanceof THREE.OrthographicCamera ) { <add> return vector; <add> }; <add> <add> this.pickingRay = function ( vector, camera ) { <add> var end, dir, ray, t; <ide> <del> _projScreenMatrix.multiplyVector3( end ); <add> vector.z = -1.0; <add> end = new THREE.Vector3( vector.x, vector.y, 1.0 ); <ide> <del> dir = new THREE.Vector3(); <del> dir.sub( end, vector ); <del> dir.normalize(); <del> <del> ray.origin = vector; <del> ray.direction = dir; <del> // } <add> this.unprojectVector( vector, camera ); <add> this.unprojectVector( end, camera ); <ide> <del> return vector; <add> dir = new THREE.Vector3(); <add> dir.sub( end, vector ); <add> dir.normalize(); <ide> <add> return new THREE.Ray( vector, dir ); <ide> }; <ide> <ide> this.projectObjects = function ( scene, camera, sort ) {
1
Mixed
Java
add ability to expose sync hooks from java to js
50d8d46733c24a4b432edc34af6e80d80f96ffc9
<ide><path>Libraries/Utilities/MessageQueue.js <ide> let SPY_MODE = false; <ide> let MethodTypes = keyMirror({ <ide> remote: null, <ide> remoteAsync: null, <add> syncHook: null, <ide> }); <ide> <ide> var guard = (fn) => { <ide> class MessageQueue { <ide> if (methodsConfig) { <ide> let methods = []; <ide> let asyncMethods = []; <add> let syncHooks = []; <ide> let methodNames = Object.keys(methodsConfig); <ide> for (var j = 0, ll = methodNames.length; j < ll; j++) { <ide> let methodName = methodNames[j]; <ide> let methodConfig = methodsConfig[methodName]; <ide> methods[methodConfig.methodID] = methodName; <ide> if (methodConfig.type === MethodTypes.remoteAsync) { <ide> asyncMethods.push(methodConfig.methodID); <add> } else if (methodConfig.type === MethodTypes.syncHook) { <add> syncHooks.push(methodConfig.methodID); <ide> } <ide> } <ide> if (methods.length) { <ide> module.push(methods); <del> if (asyncMethods.length) { <del> module.push(asyncMethods); <del> } <add> module.push(asyncMethods); <add> module.push(syncHooks); <ide> } <ide> } <ide> moduleArray[moduleConfig.moduleID] = module; <ide> class MessageQueue { <ide> return; <ide> } <ide> <del> let moduleName, constants, methods, asyncMethods; <add> let moduleName, constants, methods, asyncMethods, syncHooks; <ide> if (moduleHasConstants(config)) { <del> [moduleName, constants, methods, asyncMethods] = config; <add> [moduleName, constants, methods, asyncMethods, syncHooks] = config; <ide> } else { <del> [moduleName, methods, asyncMethods] = config; <add> [moduleName, methods, asyncMethods, syncHooks] = config; <ide> } <ide> <ide> let module = {}; <ide> methods && methods.forEach((methodName, methodID) => { <del> const methodType = <del> asyncMethods && arrayContains(asyncMethods, methodID) ? <del> MethodTypes.remoteAsync : MethodTypes.remote; <add> const isAsync = asyncMethods && arrayContains(asyncMethods, methodID); <add> const isSyncHook = syncHooks && arrayContains(syncHooks, methodID); <add> invariant(!isAsync || !isSyncHook, 'Cannot have a method that is both async and a sync hook'); <add> const methodType = isAsync ? MethodTypes.remoteAsync : <add> isSyncHook ? MethodTypes.syncHook : <add> MethodTypes.remote; <ide> module[methodName] = this._genMethod(moduleID, methodID, methodType); <ide> }); <ide> Object.assign(module, constants); <ide> class MessageQueue { <ide> }); <ide> }); <ide> }; <add> } else if (type === MethodTypes.syncHook) { <add> return function(...args) { <add> return global.nativeCallSyncHook(module, method, args); <add> } <ide> } else { <ide> fn = function(...args) { <ide> let lastArg = args.length > 0 ? args[args.length - 1] : null; <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java <ide> public abstract class BaseJavaModule implements NativeModule { <ide> // taken from Libraries/Utilities/MessageQueue.js <ide> static final public String METHOD_TYPE_REMOTE = "remote"; <ide> static final public String METHOD_TYPE_REMOTE_ASYNC = "remoteAsync"; <add> static final public String METHOD_TYPE_SYNC_HOOK = "syncHook"; <ide> <ide> private static abstract class ArgumentExtractor<T> { <ide> public int getJSArgumentsNeeded() { <ide> public String getSignature() { <ide> <ide> private String buildSignature(Class[] paramTypes) { <ide> StringBuilder builder = new StringBuilder(paramTypes.length); <add> builder.append("v."); <ide> for (int i = 0; i < paramTypes.length; i++) { <del> Class argumentClass = paramTypes[i]; <del> if (argumentClass == ExecutorToken.class) { <add> Class paramClass = paramTypes[i]; <add> if (paramClass == ExecutorToken.class) { <ide> if (!BaseJavaModule.this.supportsWebWorkers()) { <ide> throw new RuntimeException( <ide> "Module " + BaseJavaModule.this + " doesn't support web workers, but " + <ide> mMethod.getName() + <ide> " takes an ExecutorToken."); <ide> } <del> <del> builder.append('T'); <del> } else if (argumentClass == boolean.class) { <del> builder.append('z'); <del> } else if (argumentClass == Boolean.class) { <del> builder.append('Z'); <del> } else if (argumentClass == int.class) { <del> builder.append('i'); <del> } else if (argumentClass == Integer.class) { <del> builder.append('I'); <del> } else if (argumentClass == double.class) { <del> builder.append('d'); <del> } else if (argumentClass == Double.class) { <del> builder.append('D'); <del> } else if (argumentClass == float.class) { <del> builder.append('f'); <del> } else if (argumentClass == Float.class) { <del> builder.append('F'); <del> } else if (argumentClass == String.class) { <del> builder.append('S'); <del> } else if (argumentClass == Callback.class) { <del> builder.append('X'); <del> } else if (argumentClass == Promise.class) { <del> builder.append('P'); <add> } else if (paramClass == Promise.class) { <ide> Assertions.assertCondition( <ide> i == paramTypes.length - 1, "Promise must be used as last parameter only"); <ide> mType = METHOD_TYPE_REMOTE_ASYNC; <del> } else if (argumentClass == ReadableMap.class) { <del> builder.append('M'); <del> } else if (argumentClass == ReadableArray.class) { <del> builder.append('A'); <del> } else { <del> throw new RuntimeException( <del> "Got unknown argument class: " + argumentClass.getSimpleName()); <ide> } <add> builder.append(paramTypeToChar(paramClass)); <ide> } <ide> <ide> // Modules that support web workers are expected to take an ExecutorToken as the first <ide> // parameter to all their @ReactMethod-annotated methods. <ide> if (BaseJavaModule.this.supportsWebWorkers()) { <del> if (builder.charAt(0) != 'T') { <add> if (builder.charAt(2) != 'T') { <ide> throw new RuntimeException( <ide> "Module " + BaseJavaModule.this + " supports web workers, but " + mMethod.getName() + <ide> "does not take an ExecutorToken as its first parameter."); <ide> public String getType() { <ide> } <ide> } <ide> <del> @Override <del> public final Map<String, NativeMethod> getMethods() { <del> Map<String, NativeMethod> methods = new HashMap<String, NativeMethod>(); <add> public class SyncJavaHook implements SyncNativeHook { <add> <add> private Method mMethod; <add> private final String mSignature; <add> <add> public SyncJavaHook(Method method) { <add> mMethod = method; <add> mSignature = buildSignature(method); <add> } <add> <add> public Method getMethod() { <add> return mMethod; <add> } <add> <add> public String getSignature() { <add> return mSignature; <add> } <add> <add> private String buildSignature(Method method) { <add> Class[] paramTypes = method.getParameterTypes(); <add> StringBuilder builder = new StringBuilder(paramTypes.length + 2); <add> <add> builder.append(returnTypeToChar(method.getReturnType())); <add> builder.append('.'); <add> <add> for (int i = 0; i < paramTypes.length; i++) { <add> Class paramClass = paramTypes[i]; <add> if (paramClass == ExecutorToken.class) { <add> if (!BaseJavaModule.this.supportsWebWorkers()) { <add> throw new RuntimeException( <add> "Module " + BaseJavaModule.this + " doesn't support web workers, but " + <add> mMethod.getName() + <add> " takes an ExecutorToken."); <add> } <add> } else if (paramClass == Promise.class) { <add> Assertions.assertCondition( <add> i == paramTypes.length - 1, "Promise must be used as last parameter only"); <add> } <add> builder.append(paramTypeToChar(paramClass)); <add> } <add> <add> return builder.toString(); <add> } <add> } <add> <add> private final Map<String, NativeMethod> mMethods = new HashMap<>(); <add> private final Map<String, SyncNativeHook> mHooks = new HashMap<>(); <add> <add> public BaseJavaModule() { <ide> Method[] targetMethods = getClass().getDeclaredMethods(); <ide> for (int i = 0; i < targetMethods.length; i++) { <ide> Method targetMethod = targetMethods[i]; <ide> if (targetMethod.getAnnotation(ReactMethod.class) != null) { <ide> String methodName = targetMethod.getName(); <del> if (methods.containsKey(methodName)) { <add> if (mHooks.containsKey(methodName) || mMethods.containsKey(methodName)) { <ide> // We do not support method overloading since js sees a function as an object regardless <ide> // of number of params. <ide> throw new IllegalArgumentException( <del> "Java Module " + getName() + " method name already registered: " + methodName); <del> } <del> methods.put(methodName, new JavaMethod(targetMethod)); <add> "Java Module " + getName() + " sync method name already registered: " + methodName); <add> } <add> mMethods.put(methodName, new JavaMethod(targetMethod)); <add> } <add> if (targetMethod.getAnnotation(ReactSyncHook.class) != null) { <add> String methodName = targetMethod.getName(); <add> if (mHooks.containsKey(methodName) || mMethods.containsKey(methodName)) { <add> // We do not support method overloading since js sees a function as an object regardless <add> // of number of params. <add> throw new IllegalArgumentException( <add> "Java Module " + getName() + " sync method name already registered: " + methodName); <add> } <add> mHooks.put(methodName, new SyncJavaHook(targetMethod)); <ide> } <ide> } <del> return methods; <add> } <add> <add> @Override <add> public final Map<String, NativeMethod> getMethods() { <add> return mMethods; <ide> } <ide> <ide> /** <ide> public final Map<String, NativeMethod> getMethods() { <ide> return null; <ide> } <ide> <add> public final Map<String, SyncNativeHook> getSyncHooks() { <add> return mHooks; <add> } <add> <ide> @Override <ide> public final void writeConstantsField(JsonWriter writer, String fieldName) throws IOException { <ide> Map<String, Object> constants = getConstants(); <ide> public void onCatalystInstanceDestroy() { <ide> public boolean supportsWebWorkers() { <ide> return false; <ide> } <add> <add> private static char paramTypeToChar(Class paramClass) { <add> char tryCommon = commonTypeToChar(paramClass); <add> if (tryCommon != '\0') { <add> return tryCommon; <add> } <add> if (paramClass == ExecutorToken.class) { <add> return 'T'; <add> } else if (paramClass == Callback.class) { <add> return 'X'; <add> } else if (paramClass == Promise.class) { <add> return 'P'; <add> } else if (paramClass == ReadableMap.class) { <add> return 'M'; <add> } else if (paramClass == ReadableArray.class) { <add> return 'A'; <add> } else { <add> throw new RuntimeException( <add> "Got unknown param class: " + paramClass.getSimpleName()); <add> } <add> } <add> <add> private static char returnTypeToChar(Class returnClass) { <add> char tryCommon = commonTypeToChar(returnClass); <add> if (tryCommon != '\0') { <add> return tryCommon; <add> } <add> if (returnClass == void.class) { <add> return 'v'; <add> } else if (returnClass == WritableMap.class) { <add> return 'M'; <add> } else if (returnClass == WritableArray.class) { <add> return 'A'; <add> } else { <add> throw new RuntimeException( <add> "Got unknown return class: " + returnClass.getSimpleName()); <add> } <add> } <add> <add> private static char commonTypeToChar(Class typeClass) { <add> if (typeClass == boolean.class) { <add> return 'z'; <add> } else if (typeClass == Boolean.class) { <add> return 'Z'; <add> } else if (typeClass == int.class) { <add> return 'i'; <add> } else if (typeClass == Integer.class) { <add> return 'I'; <add> } else if (typeClass == double.class) { <add> return 'd'; <add> } else if (typeClass == Double.class) { <add> return 'D'; <add> } else if (typeClass == float.class) { <add> return 'f'; <add> } else if (typeClass == Float.class) { <add> return 'F'; <add> } else if (typeClass == String.class) { <add> return 'S'; <add> } else { <add> return '\0'; <add> } <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java <ide> interface NativeMethod { <ide> String getType(); <ide> } <ide> <add> /** <add> * A method that can be called from JS synchronously on the JS thread and return a result. <add> * @see ReactSyncHook <add> */ <add> interface SyncNativeHook { <add> } <add> <ide> /** <ide> * @return the name of this module. This will be the name used to {@code require()} this module <ide> * from javascript. <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactSyncHook.java <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <add>package com.facebook.react.bridge; <add> <add>import java.lang.annotation.Retention; <add> <add>import static java.lang.annotation.RetentionPolicy.RUNTIME; <add> <add>/** <add> * Annotation for a method in a {@link NativeModule} that can be called from JS synchronously **on <add> * the JS thread**, possibly returning a result. <add> * <add> * In order to support remote debugging, both the method args and return type must be serializable <add> * to JSON: this means that we only support the same args as {@link ReactMethod}, and the hook can <add> * only be void or return JSON values (e.g. bool, number, String, {@link WritableMap}, or <add> * {@link WritableArray}). <add> * <add> * In the vast majority of cases, you should use {@link ReactMethod} which allows your native module <add> * methods to be called asynchronously: calling methods synchronously can have strong performance <add> * penalties and introduce threading-related bugs to your native modules. <add> */ <add>@Retention(RUNTIME) <add>public @interface ReactSyncHook { <add>}
4
Python
Python
update weights url for inception_resnet_v2
0f1c8550576c0320632c5541caa42325833f1335
<ide><path>keras/applications/inception_resnet_v2.py <ide> from ..utils.data_utils import get_file <ide> from ..engine.topology import get_source_inputs <ide> from ..applications.imagenet_utils import _obtain_input_shape <add>from ..applications.imagenet_utils import decode_predictions <ide> from .. import backend as K <ide> <ide> <del>BASE_WEIGHT_URL = 'https://github.com/myutwo150/keras-inception-resnet-v2/releases/download/v0.1/' <add>BASE_WEIGHT_URL = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.7/' <ide> <ide> <ide> def preprocess_input(x):
1
Javascript
Javascript
fix prefetch url
540a86f007da211cd8aaea68ea50fd8739b3d3a4
<ide><path>lib/link.js <ide> export default class Link extends Component { <ide> }) <ide> } <ide> <add> prefetch () { <add> if (!this.props.prefetch) return <add> if (typeof window === 'undefined') return <add> <add> // Prefetch the JSON page if asked (only in the client) <add> const { pathname } = window.location <add> const href = resolve(pathname, this.props.href) <add> Router.prefetch(href) <add> } <add> <add> componentDidMount () { <add> this.prefetch() <add> } <add> <add> componentDidUpdate (prevProps) { <add> if (this.props.href !== prevProps.href) { <add> this.prefetch() <add> } <add> } <add> <ide> render () { <del> let { children, prefetch } = this.props <add> let { children } = this.props <ide> // Deprecated. Warning shown by propType check. If the childen provided is a string (<Link>example</Link>) we wrap it in an <a> tag <ide> if (typeof children === 'string') { <ide> children = <a>{children}</a> <ide> export default class Link extends Component { <ide> props.href = this.props.as || this.props.href <ide> } <ide> <del> // Prefetch the JSON page if asked (only in the client) <del> if (prefetch) { <del> if (typeof window !== 'undefined') { <del> const { pathname } = window.location <del> const href = resolve(pathname, props.href) <del> Router.prefetch(href) <del> } <del> } <del> <ide> return React.cloneElement(child, props) <ide> } <ide> } <ide><path>lib/prefetch.js <ide> export default class LinkPrefetch extends React.Component { <ide> wantLinkPrefetch() <ide> const props = { <ide> ...this.props, <del> prefetch: this.props.prefetch === false ? this.props.prefetch : true <add> prefetch: this.props.prefetch !== false <ide> } <ide> <ide> return (<Link {...props} />)
2
Text
Text
fix typescript casing
8df5fc5a8e292845f9044adc96f474d620fcc4d8
<ide><path>docs/api-reference/next/router.md <ide> function Page({ router }) { <ide> export default withRouter(Page) <ide> ``` <ide> <del>### Typescript <add>### TypeScript <ide> <ide> To use class components with `withRouter`, the component needs to accept a router prop: <ide>
1
Text
Text
fix typo in text
a90d3f18623cabc2d5a128d76fd73b28bb9d78da
<ide><path>examples/pytorch/translation/README.md <ide> and reply to the questions asked. Then <ide> accelerate test <ide> ``` <ide> <del>that will check everything is ready for training. Finally, you cna launch training with <add>that will check everything is ready for training. Finally, you can launch training with <ide> <ide> ```bash <ide> export TASK_NAME=mrpc
1
Ruby
Ruby
add docs about _scopes option on enum. [ci skip]
2ef9ecaf454f69db256da01001ad6cb0d5609072
<ide><path>activerecord/lib/active_record/enum.rb <ide> module ActiveRecord <ide> # Conversation.where(status: [:active, :archived]) <ide> # Conversation.where.not(status: :active) <ide> # <add> # Defining scopes can be disabled by setting +:_scopes+ to +false+. <add> # <add> # class Conversation < ActiveRecord::Base <add> # enum status: [ :active, :archived ], _scopes: false <add> # end <add> # <ide> # You can set the default value from the database declaration, like: <ide> # <ide> # create_table :conversations do |t|
1
Go
Go
add buffers to operations with tarballs
a377844998f6a866d59bf356790f76d0d25bf01f
<ide><path>archive/archive.go <ide> func (compression *Compression) Extension() string { <ide> return "" <ide> } <ide> <del>func addTarFile(path, name string, tw *tar.Writer) error { <add>func addTarFile(path, name string, tw *tar.Writer, twBuf *bufio.Writer) error { <ide> fi, err := os.Lstat(path) <ide> if err != nil { <ide> return err <ide> func addTarFile(path, name string, tw *tar.Writer) error { <ide> if err != nil { <ide> return err <ide> } <del> if _, err := io.Copy(tw, file); err != nil { <del> file.Close() <add> <add> twBuf.Reset(tw) <add> _, err = io.Copy(twBuf, file) <add> file.Close() <add> if err != nil { <ide> return err <ide> } <del> file.Close() <add> err = twBuf.Flush() <add> if err != nil { <add> return err <add> } <add> twBuf.Reset(nil) <ide> } <ide> <ide> return nil <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> options.Includes = []string{"."} <ide> } <ide> <add> twBuf := bufio.NewWriterSize(nil, twBufSize) <add> <ide> for _, include := range options.Includes { <ide> filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error { <ide> if err != nil { <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> } <ide> } <ide> <del> if err := addTarFile(filePath, relFilePath, tw); err != nil { <add> if err := addTarFile(filePath, relFilePath, tw, twBuf); err != nil { <ide> utils.Debugf("Can't add file %s to tar: %s\n", srcPath, err) <ide> } <ide> return nil <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> defer decompressedArchive.Close() <ide> <ide> tr := tar.NewReader(decompressedArchive) <add> trBuf := bufio.NewReaderSize(nil, trBufSize) <ide> <ide> var dirs []*tar.Header <ide> <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> } <ide> } <ide> } <del> if err := createTarFile(path, dest, hdr, tr, options == nil || !options.NoLchown); err != nil { <add> trBuf.Reset(tr) <add> if err := createTarFile(path, dest, hdr, trBuf, options == nil || !options.NoLchown); err != nil { <ide> return err <ide> } <ide> <ide><path>archive/changes.go <ide> package archive <ide> <ide> import ( <add> "bufio" <ide> "bytes" <ide> "fmt" <ide> "io" <ide> func ExportChanges(dir string, changes []Change) (Archive, error) { <ide> tw := tar.NewWriter(writer) <ide> <ide> go func() { <add> twBuf := bufio.NewWriterSize(nil, twBufSize) <ide> // In general we log errors here but ignore them because <ide> // during e.g. a diff operation the container can continue <ide> // mutating the filesystem and we can see transient errors <ide> func ExportChanges(dir string, changes []Change) (Archive, error) { <ide> } <ide> } else { <ide> path := filepath.Join(dir, change.Path) <del> if err := addTarFile(path, change.Path[1:], tw); err != nil { <add> if err := addTarFile(path, change.Path[1:], tw, twBuf); err != nil { <ide> utils.Debugf("Can't add file %s to tar: %s\n", path, err) <ide> } <ide> } <ide><path>archive/common.go <add>package archive <add> <add>const twBufSize = 32 * 1024 <add>const trBufSize = 32 * 1024 <ide><path>archive/diff.go <ide> package archive <ide> <ide> import ( <add> "bufio" <ide> "fmt" <ide> "io" <ide> "io/ioutil" <ide> func ApplyLayer(dest string, layer ArchiveReader) error { <ide> } <ide> <ide> tr := tar.NewReader(layer) <add> trBuf := bufio.NewReaderSize(nil, trBufSize) <ide> <ide> var dirs []*tar.Header <ide> <ide> func ApplyLayer(dest string, layer ArchiveReader) error { <ide> } <ide> } <ide> <del> srcData := io.Reader(tr) <add> trBuf.Reset(tr) <add> srcData := io.Reader(trBuf) <ide> srcHdr := hdr <ide> <ide> // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
4
Ruby
Ruby
extract native getter to attr_reader
6f47ea1a462886980eb7b34ea24e1d5e704897f6
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> class TableDefinition <ide> # An array of ColumnDefinition objects, representing the column changes <ide> # that have been defined. <ide> attr_accessor :indexes <del> attr_reader :name, :temporary, :options, :as, :foreign_keys <add> attr_reader :name, :temporary, :options, :as, :foreign_keys, :native <ide> <ide> def initialize(types, name, temporary, options, as = nil) <ide> @columns_hash = {} <ide> def create_column_definition(name, type) <ide> ColumnDefinition.new name, type <ide> end <ide> <del> def native <del> @native <del> end <del> <ide> def aliased_types(name, fallback) <ide> 'timestamp' == name ? :datetime : fallback <ide> end
1
Java
Java
use httpheaders.allow instead of string constant
a0ba8082179f7d80d9f284b4d69020358be9a6f3
<ide><path>spring-web/src/main/java/org/springframework/web/context/support/HttpRequestHandlerServlet.java <ide> import jakarta.servlet.http.HttpServletResponse; <ide> <ide> import org.springframework.context.i18n.LocaleContextHolder; <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <ide> protected void service(HttpServletRequest request, HttpServletResponse response) <ide> catch (HttpRequestMethodNotSupportedException ex) { <ide> String[] supportedMethods = ex.getSupportedMethods(); <ide> if (supportedMethods != null) { <del> response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); <add> response.setHeader(HttpHeaders.ALLOW, StringUtils.arrayToDelimitedString(supportedMethods, ", ")); <ide> } <ide> response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java <ide> import org.springframework.core.GenericTypeResolver; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <ide> import org.springframework.core.env.ConfigurableEnvironment; <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.lang.Nullable; <ide> protected void doOptions(HttpServletRequest request, HttpServletResponse respons <ide> <ide> if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) { <ide> processRequest(request, response); <del> if (response.containsHeader("Allow")) { <add> if (response.containsHeader(HttpHeaders.ALLOW)) { <ide> // Proper OPTIONS response coming from a handler - we're done. <ide> return; <ide> } <ide> protected void doOptions(HttpServletRequest request, HttpServletResponse respons <ide> super.doOptions(request, new HttpServletResponseWrapper(response) { <ide> @Override <ide> public void setHeader(String name, String value) { <del> if ("Allow".equals(name)) { <add> if (HttpHeaders.ALLOW.equals(name)) { <ide> value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name(); <ide> } <ide> super.setHeader(name, value); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/AbstractController.java <ide> import jakarta.servlet.http.HttpServletResponse; <ide> import jakarta.servlet.http.HttpSession; <ide> <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.web.servlet.ModelAndView; <ide> public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons <ide> throws Exception { <ide> <ide> if (HttpMethod.OPTIONS.matches(request.getMethod())) { <del> response.setHeader("Allow", getAllowHeader()); <add> response.setHeader(HttpHeaders.ALLOW, getAllowHeader()); <ide> return null; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> } <ide> <ide> if (HttpMethod.OPTIONS.matches(request.getMethod())) { <del> response.setHeader("Allow", getAllowHeader()); <add> response.setHeader(HttpHeaders.ALLOW, getAllowHeader()); <ide> return; <ide> } <ide>
4
Ruby
Ruby
fix unclosed tags [ci skip]
87d5415f0aa3e6f9f74f645a47370dd854375a1a
<ide><path>actionpack/lib/action_controller/renderer.rb <ide> def initialize(controller, env, defaults) <ide> # * <tt>:html</tt> - Renders the provided HTML safe string, otherwise <ide> # performs HTML escape on the string first. Sets the content type as <tt>text/html</tt>. <ide> # * <tt>:json</tt> - Renders the provided hash or object in JSON. You don't <del> # need to call <tt>.to_json<tt> on the object you want to render. <add> # need to call <tt>.to_json</tt> on the object you want to render. <ide> # * <tt>:body</tt> - Renders provided text and sets content type of <tt>text/plain</tt>. <ide> # <ide> # If no <tt>options</tt> hash is passed or if <tt>:update</tt> is specified, the default is <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb <ide> module AssetTagHelper <ide> # that path. <ide> # * <tt>:skip_pipeline</tt> - This option is used to bypass the asset pipeline <ide> # when it is set to true. <del> # * <tt>:nonce<tt> - When set to true, adds an automatic nonce value if <add> # * <tt>:nonce</tt> - When set to true, adds an automatic nonce value if <ide> # you have Content Security Policy enabled. <ide> # <ide> # ==== Examples
2
Go
Go
fix my own comments from
41e9e93e27ccd637d9490412622529bdc7d7b8ff
<ide><path>daemon/networkdriver/portmapper/mapper.go <ide> func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err er <ide> return nil, err <ide> } <ide> <del> m.userlandProxy = proxy <del> currentMappings[key] = m <del> <ide> cleanup := func() error { <ide> // need to undo the iptables rules before we return <del> forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) <ide> proxy.Stop() <ide> forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) <del> m.userlandProxy = nil <del> delete(currentMappings, key) <ide> if err := portallocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil { <ide> return err <ide> } <ide> func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err er <ide> if err := cleanup(); err != nil { <ide> return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) <ide> } <del> <del> if err == ErrPortMappingFailure { <del> return nil, portallocator.NewErrPortAlreadyAllocated(hostIP.String(), allocatedHostPort) <del> } <add> return nil, err <ide> } <del> <add> m.userlandProxy = proxy <add> currentMappings[key] = m <ide> return m.host, nil <ide> } <ide> <ide><path>daemon/networkdriver/portmapper/proxy.go <ide> package portmapper <ide> <ide> import ( <del> "errors" <ide> "flag" <add> "fmt" <add> "io/ioutil" <ide> "log" <ide> "net" <ide> "os" <ide> import ( <ide> "github.com/docker/docker/reexec" <ide> ) <ide> <del>var ErrPortMappingFailure = errors.New("Failure Mapping Port") <del> <ide> const userlandProxyCommandName = "docker-proxy" <ide> <ide> func init() { <ide> func execProxy() { <ide> p, err := proxy.NewProxy(host, container) <ide> if err != nil { <ide> os.Stdout.WriteString("1\n") <add> fmt.Fprint(os.Stderr, err) <ide> os.Exit(1) <ide> } <del> <del> os.Stdout.WriteString("0\n") <del> <ide> go handleStopSignals(p) <add> os.Stdout.WriteString("0\n") <ide> <ide> // Run will block until the proxy stops <ide> p.Run() <ide> func (p *proxyCommand) Start() error { <ide> if err != nil { <ide> return err <ide> } <add> defer stdout.Close() <add> stderr, err := p.cmd.StderrPipe() <add> if err != nil { <add> return err <add> } <add> defer stderr.Close() <ide> if err := p.cmd.Start(); err != nil { <ide> return err <ide> } <ide> <del> errchan := make(chan error) <del> after := time.After(1 * time.Second) <add> errchan := make(chan error, 1) <ide> go func() { <ide> buf := make([]byte, 2) <ide> stdout.Read(buf) <ide> <ide> if string(buf) != "0\n" { <del> errchan <- ErrPortMappingFailure <del> } else { <del> errchan <- nil <add> errStr, _ := ioutil.ReadAll(stderr) <add> errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr) <add> return <ide> } <add> errchan <- nil <ide> }() <ide> <del> var readErr error <del> <ide> select { <del> case readErr = <-errchan: <del> case <-after: <del> readErr = ErrPortMappingFailure <add> case err := <-errchan: <add> return err <add> case <-time.After(1 * time.Second): <add> return fmt.Errorf("Timed out proxy starting the userland proxy") <ide> } <del> <del> return readErr <ide> } <ide> <ide> func (p *proxyCommand) Stop() error { <ide> if p.cmd.Process != nil { <del> err := p.cmd.Process.Signal(os.Interrupt) <del> p.cmd.Wait() <del> return err <add> if err := p.cmd.Process.Signal(os.Interrupt); err != nil { <add> return err <add> } <add> return p.cmd.Wait() <ide> } <del> <ide> return nil <ide> } <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunPortInUse(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "-p", port+":80", "busybox", "true") <ide> out, _, err := runCommandWithOutput(cmd) <ide> if err == nil { <del> t.Fatalf("Host port %s already in use, has been allocated by docker: %q", port, out) <add> t.Fatalf("Binding on used port must fail") <add> } <add> if !strings.Contains(out, "address already in use") { <add> t.Fatalf("Out must be about \"address already in use\", got %s", out) <ide> } <ide> <ide> deleteAllContainers() <del> <del> logDone("run - port in use") <add> logDone("run - fail if port already in use") <ide> }
3
Ruby
Ruby
parse json early in github module
4d6df3e3bca5147f49deb530d930b2f40b032cd1
<ide><path>Library/Homebrew/cmd/search.rb <ide> require 'formula' <ide> require 'blacklist' <ide> require 'utils' <del>require 'utils/json' <ide> <ide> module Homebrew extend self <ide> <ide> def search_tap user, repo, rx <ide> return [] if (HOMEBREW_LIBRARY/"Taps/#{user.downcase}-#{repo.downcase}").directory? <ide> <ide> results = [] <del> GitHub.open "https://api.github.com/repos/#{user}/homebrew-#{repo}/git/trees/HEAD?recursive=1" do |f| <add> GitHub.open "https://api.github.com/repos/#{user}/homebrew-#{repo}/git/trees/HEAD?recursive=1" do |json| <ide> user = user.downcase if user == "Homebrew" # special handling for the Homebrew organization <del> Utils::JSON.load(f.read)["tree"].map{ |hash| hash['path'] }.compact.each do |file| <add> json["tree"].map{ |hash| hash['path'] }.compact.each do |file| <ide> name = File.basename(file, '.rb') <ide> if file =~ /\.rb$/ and name =~ rx <ide> results << "#{user}/#{repo}/#{name}" <ide> end <ide> end <ide> end <ide> results <del> rescue OpenURI::HTTPError, GitHub::Error, Utils::JSON::Error <del> opoo <<-EOS.undent <del> Failed to search tap: #{user}/#{repo}. Please run `brew update`. <del> EOS <add> rescue OpenURI::HTTPError, GitHub::Error <add> opoo "Failed to search tap: #{user}/#{repo}. Please run `brew update`" <ide> [] <ide> end <ide> <ide><path>Library/Homebrew/utils.rb <ide> def open url, headers={}, &block <ide> <ide> default_headers = {'User-Agent' => HOMEBREW_USER_AGENT} <ide> default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN <del> Kernel.open(url, default_headers.merge(headers), &block) <add> Kernel.open(url, default_headers.merge(headers)) do |f| <add> yield Utils::JSON.load(f.read) <add> end <ide> rescue OpenURI::HTTPError => e <ide> if e.io.meta['x-ratelimit-remaining'].to_i <= 0 <ide> raise <<-EOS.undent <ide> def open url, headers={}, &block <ide> end <ide> rescue SocketError, OpenSSL::SSL::SSLError => e <ide> raise Error, "Failed to connect to: #{url}\n#{e.message}" <add> rescue Utils::JSON::Error => e <add> raise Error, "Failed to parse JSON response\n#{e.message}" <ide> end <ide> <ide> def issues_matching(query) <ide> uri = ISSUES_URI + uri_escape(query) <del> open(uri) { |f| Utils::JSON.load(f.read)['issues'] } <add> open(uri) { |json| json["issues"] } <ide> end <ide> <ide> def uri_escape(query)
2
Ruby
Ruby
check version conflicts using linkage
ca6c75d229c73a2523e95aa3736a8031c2f8c158
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_install_sanity <ide> <ide> recursive_deps = formula.recursive_dependencies <ide> recursive_formulae = recursive_deps.map(&:to_formula) <del> recursive_runtime_formulae = <del> formula.runtime_formula_dependencies(undeclared: false) <ide> <ide> recursive_dependencies = [] <ide> recursive_formulae.each do |dep| <ide> def check_install_sanity <ide> EOS <ide> end <ide> <del> version_hash = {} <del> version_conflicts = Set.new <del> recursive_runtime_formulae.each do |f| <del> name = f.name <del> unversioned_name, = name.split("@") <del> next if unversioned_name == "python" <del> version_hash[unversioned_name] ||= Set.new <del> version_hash[unversioned_name] << name <del> next if version_hash[unversioned_name].length < 2 <del> version_conflicts += version_hash[unversioned_name] <del> end <del> unless version_conflicts.empty? <del> raise CannotInstallFormulaError, <<~EOS <del> #{formula.full_name} contains conflicting version recursive dependencies: <del> #{version_conflicts.to_a.join ", "} <del> View these with `brew deps --tree #{formula.full_name}`. <del> EOS <del> end <del> <ide> pinned_unsatisfied_deps = recursive_deps.select do |dep| <ide> dep.to_formula.pinned? && !dep.satisfied?(inherited_options_for(dep)) <ide> end <ide><path>Library/Homebrew/linkage_checker.rb <ide> def initialize(keg, formula = nil, cache_db:, rebuild_cache: false) <ide> @indirect_deps = [] <ide> @undeclared_deps = [] <ide> @unnecessary_deps = [] <add> @version_conflict_deps = [] <ide> <ide> check_dylibs(rebuild_cache: rebuild_cache) <ide> end <ide> def display_reverse_output <ide> def display_test_output(puts_output: true) <ide> display_items "Missing libraries", @broken_dylibs, puts_output: puts_output <ide> display_items "Broken dependencies", @broken_deps, puts_output: puts_output <add> display_items "Conflicting libraries", @version_conflict_deps, puts_output: puts_output <ide> puts "No broken library linkage" unless broken_library_linkage? <ide> end <ide> <ide> def broken_library_linkage? <del> !@broken_dylibs.empty? || !@broken_deps.empty? <add> !@broken_dylibs.empty? || <add> !@broken_deps.empty? || <add> !@version_conflict_deps.empty? <ide> end <ide> <ide> private <ide> def check_dylibs(rebuild_cache:) <ide> end <ide> <ide> if formula <del> @indirect_deps, @undeclared_deps, @unnecessary_deps = <del> check_undeclared_deps <add> @indirect_deps, @undeclared_deps, @unnecessary_deps, <add> @version_conflict_deps = check_formula_deps <ide> end <ide> <ide> return unless keg_files_dylibs_was_empty <ide> <ide> store&.update!(keg_files_dylibs: keg_files_dylibs) <ide> end <ide> <del> def check_undeclared_deps <add> def check_formula_deps <ide> filter_out = proc do |dep| <ide> next true if dep.build? <ide> next false unless dep.optional? || dep.recommended? <ide> def check_undeclared_deps <ide> unnecessary_deps = declared_deps_full_names.reject do |full_name| <ide> next true if Formula[full_name].bin.directory? <ide> name = full_name.split("/").last <del> @brewed_dylibs.keys.map { |x| x.split("/").last }.include?(name) <add> @brewed_dylibs.keys.map { |l| l.split("/").last }.include?(name) <ide> end <ide> <ide> missing_deps = @broken_deps.values.flatten.map { |d| dylib_to_dep(d) } <ide> unnecessary_deps -= missing_deps <ide> <del> [indirect_deps, undeclared_deps, unnecessary_deps] <add> version_hash = {} <add> version_conflict_deps = Set.new <add> @brewed_dylibs.keys.each do |l| <add> name = l.split("/").last <add> unversioned_name, = name.split("@") <add> version_hash[unversioned_name] ||= Set.new <add> version_hash[unversioned_name] << name <add> next if version_hash[unversioned_name].length < 2 <add> version_conflict_deps += version_hash[unversioned_name] <add> end <add> <add> [indirect_deps, undeclared_deps, <add> unnecessary_deps, version_conflict_deps.to_a] <ide> end <ide> <ide> def sort_by_formula_full_name!(arr)
2
PHP
PHP
fix expectedexceptionmessage to handle >=php7
0d7e70cd3566e11db0a5d80c0e9b9b0033b0a87b
<ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> public function testReadWithNonExistentFile() <ide> * Test reading an empty file. <ide> * <ide> * @expectedException \Cake\Core\Exception\Exception <del> * @expectedExceptionMessage Decoding JSON config file "empty.json" did not return an array <add> * @expectedExceptionMessage config file "empty.json" <ide> * @return void <ide> */ <ide> public function testReadEmptyFile()
1
Python
Python
change catacc to call sparsecatacc
a8385c3835a417dc85f8bc862ef87d9c35dc9017
<ide><path>keras/metrics/metrics.py <ide> def categorical_accuracy(y_true, y_pred): <ide> Returns: <ide> Categorical accuracy values. <ide> """ <del> return tf.cast( <del> tf.equal( <del> tf.math.argmax(y_true, axis=-1), tf.math.argmax(y_pred, axis=-1)), <del> backend.floatx()) <add> y_true = tf.math.argmax(y_true, axis=-1) <add> return sparse_categorical_accuracy(y_true, y_pred) <ide> <ide> <ide> @keras_export('keras.metrics.sparse_categorical_accuracy')
1
Text
Text
add documentation about variants
90a8ce645085e475f668643195652b7518a7b9cc
<ide><path>guides/CHANGELOG.md <add>* Added documentation about the `variants` option to `render` <add> <add> *Edward Rudd* <add> <add> <ide> ## Rails 6.0.0.beta3 (March 11, 2019) ## <ide> <ide> * No changes. <ide><path>guides/source/layouts_and_rendering.md <ide> Calls to the `render` method generally accept five options: <ide> * `:location` <ide> * `:status` <ide> * `:formats` <add>* `:variants` <ide> <ide> ##### The `:content_type` Option <ide> <ide> render formats: [:json, :xml] <ide> <ide> If a template with the specified format does not exist an `ActionView::MissingTemplate` error is raised. <ide> <add>##### The `:variants` Option <add> <add>This tells rails to look for template variations of the same format. <add>You can specify a list of variants by passing the `:variants` option with a symbol or an array. <add> <add>An example of use would be this. <add> <add>```ruby <add># called in HomeController#index <add>render variants: [:mobile, :desktop] <add>``` <add> <add>With this set of variants Rails will look for the following set of templates and use the first that exists. <add> <add>- `app/views/home/index.html+mobile.erb` <add>- `app/views/home/index.html+desktop.erb` <add>- `app/views/home/index.html.erb` <add> <add>If a template with the specified format does not exist an `ActionView::MissingTemplate` error is raised. <add> <add>Instead of setting the variant on the render call you may also set it on the request object in your controller action. <add> <add>```ruby <add>def index <add> request.variant = determine_variant <add>end <add> <add>private <add> <add>def determine_variant <add> variant = nil <add> # some code to determine the variant(s) to use <add> variant = :mobile if session[:use_mobile] <add> <add> variant <add>end <add>``` <add> <ide> #### Finding Layouts <ide> <ide> To find the current layout, Rails first looks for a file in `app/views/layouts` with the same base name as the controller. For example, rendering actions from the `PhotosController` class will use `app/views/layouts/photos.html.erb` (or `app/views/layouts/photos.builder`). If there is no such controller-specific layout, Rails will use `app/views/layouts/application.html.erb` or `app/views/layouts/application.builder`. If there is no `.erb` layout, Rails will use a `.builder` layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
2
Text
Text
update changelog for 2.7.0
8b2949cd06e5c30d9028f69b8eb19bf0818e5d52
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### 2.7.0-beta.3 (July 5, 2016) <add>### 2.7.0 (July 25, 2016) <ide> <add>- [#13764](https://github.com/emberjs/ember.js/pull/13764) [BUGFIX] Keep rest positional parameters when nesting contextual components if needed. <add>- [#13781](https://github.com/emberjs/ember.js/pull/13781) [BUGFIX] Fix NoneLocation#getURL <add>- [#13797](https://github.com/emberjs/ember.js/pull/13797) [BUGFIX] Ensure didInitAttrs deprecation is stripped in prod. <ide> - [#13768](https://github.com/emberjs/ember.js/pull/13768) [BUGFIX] Update route-recognizer to v0.2.0. This addresses a large number of per-existing bugs related to URL encoding. However, in doing so, it might inevitably break existing workarounds in this area. Please refer to the linked pull request for more details. <del> <del>### 2.7.0-beta.2 (June 27, 2016) <del> <ide> - [#13634](https://github.com/emberjs/ember.js/pull/13634) [BUGFIX] Fix issues with rerendering blockless and tagless components. <ide> - [#13605](https://github.com/emberjs/ember.js/pull/13605) [BUGFIX] Ensure `pauseTest` runs after other async helpers. <ide> - [#13655](https://github.com/emberjs/ember.js/pull/13655) [BUGFIX] Make debugging `this._super` much easier (remove manual `.call` / `.apply` optimizations). <ide> - [#13672](https://github.com/emberjs/ember.js/pull/13672) [BUGFIX] Fix issue with `this.render` and `this.disconnectOutlet` in routes. <ide> - [#13716](https://github.com/emberjs/ember.js/pull/13716) [BUGFIX] Ensure that `Ember.Test.waiters` allows access to configured test waiters. <ide> - [#13273](https://github.com/emberjs/ember.js/pull/13273) [BUGFIX] Fix a number of query param related issues reported. <del> <del>### 2.7.0-beta.1 (June 8, 2016) <del> <ide> - [#13424](https://github.com/emberjs/ember.js/pull/13424) [DEPRECATE] Deprecate Ember.Binding. See [the deprecation guide](http://emberjs.com/deprecations/v2.x/#toc_ember-binding) for more details. <ide> - [#13599](https://github.com/emberjs/ember.js/pull/13599) [FEATURE] Enable `ember-runtime-computed-uniq-by` feature. <ide>
1
Javascript
Javascript
fix typo in inlining example
9f2aaca65b72412dd12af49385602a7bfec62d51
<ide><path>src/auto/injector.js <ide> function annotate(fn) { <ide> * // ... <ide> * }; <ide> * tmpFn.$inject = ['$compile', '$rootScope']; <del> * injector.invoke(tempFn); <add> * injector.invoke(tmpFn); <ide> * <ide> * // To better support inline function the inline annotation is supported <ide> * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
1
Text
Text
fix some words, translate title
66860292676b2a674e263ce4c7acfb0cee90f25e
<ide><path>docs/docs/03-interactivity-and-dynamic-uis.ko-KR.md <ide> --- <del>id: interactivity-and-dynamic-uis <del>title: Interactivity and Dynamic UIs <add>id: interactivity-and-dynamic-uis-ko-KR <add>title: 상호 작용 및 동적 UI <ide> permalink: interactivity-and-dynamic-uis.ko-KR.html <ide> prev: jsx-gotchas.ko-KR.html <ide> next: multiple-components.ko-KR.html <ide> React를 폰이나 테블릿같은 터치 디바이스에서 사용하려 한다 <ide> **이벤트 딜리게이션:** React는 실제로는 노드자신에게 이벤트 핸들러를 붙이지 않습니다. React가 시작되면 React는 탑 레벨의 단일 이벤트 리스너로 모든 이벤트를 리스닝하기 시작합니다. 컴포넌트가 마운트되거나 언마운트 될 때, 이벤트 핸들러는 그냥 내부 매핑에서 넣거나 뺄 뿐입니다. 이벤트가 발생하면, React는 이 매핑을 사용해서 어떻게 디스패치할 지를 알게 됩니다. 매핑에 이벤트 핸들러가 남아있지 않으면, React의 이벤트 핸들러는 그냥 아무것도 하지 않습니다. 왜 이 방식이 빠른지 더 알고 싶으시면, [David Walsh의 멋진 블로그 글](http://davidwalsh.name/event-delegate)을 읽어 보세요. <ide> <ide> <del>## 컴포넌트는 그냥 상태 머신일 뿐 <add>## 컴포넌트는 그냥 state 머신일 뿐 <ide> <del>React는 UI를 간단한 상태머신이라 생각합니다. UI를 다양한 상태와 그 상태의 렌더링으로 생각함으로써 UI를 일관성 있게 관리하기 쉬워집니다. <add>React는 UI를 간단한 state 머신이라 생각합니다. UI를 다양한 state와 그 state의 렌더링으로 생각함으로써 UI를 일관성 있게 관리하기 쉬워집니다. <ide> <del>React에서는, 간단히 컴포넌트의 상태를 업데이트하고, 이 새로운 상태의 UI를 렌더링합니다. React는 DOM의 변경을 가장 효율적인 방법으로 관리해줍니다. <add>React에서는, 간단히 컴포넌트의 state를 업데이트하고, 이 새로운 state의 UI를 렌더링합니다. React는 DOM의 변경을 가장 효율적인 방법으로 관리해줍니다. <ide> <ide> <del>## 상태의 동작 원리 <add>## state의 동작 원리 <ide> <ide> React에게 데이터의 변경을 알리는 일반적인 방법은 `setState(data, callback)`을 호출하는 것입니다. 이 메서드는 `this.state`에 `data`를 머지하고 컴포넌트를 재 렌더링 합니다. 컴포넌트의 재 렌더링이 끝나면, 생략가능한 `callback`이 호출됩니다. 대부분의 경우 React가 UI를 최신상태로 유지해주기 때문에 `callback`을 사용할 필요가 없습니다. <ide> <ide> <del>## 어떤 컴포넌트가 상태를 가져야 할까요? <add>## 어떤 컴포넌트가 state를 가져야 할까요? <ide> <del>대부분의 컴포넌트는 `props`로부터 데이터를 받아 렌더할 뿐입니다만, 가끔 유저 인풋, 서버 리퀘스트, 시간의 경과에 반응해야 할 필요가 있습니다. 이럴 때 상태를 사용합니다. <add>대부분의 컴포넌트는 `props`로부터 데이터를 받아 렌더할 뿐입니다만, 가끔 유저 인풋, 서버 리퀘스트, 시간의 경과에 반응해야 할 필요가 있습니다. 이럴 때 state를 사용합니다. <ide> <del>**가능한 한 컴포넌트가 상태가 가지지 않도록(stateless) 하세요.** 이렇게 함으로써 가장 논리적인 장소로 상태를 격리하게 되고 쉽게 애플리케이션을 추론할 수 있도록 중복을 최소화할 수 있습니다. <add>**가능한 한 컴포넌트가 상태를 가지지 않도록(stateless) 하세요.** 이렇게 함으로써 가장 논리적인 장소로 state를 격리하게 되고 쉽게 애플리케이션을 추론할 수 있도록 중복을 최소화할 수 있습니다. <ide> <del>일반적인 패턴은 데이터만 렌더하는 여러 상태를 가지지 않은 컴포넌트를 만들고, 그 위에 상태기반 컴포넌트를 만들어 계층 안의 자식 컴포넌트에게 `props`를 통해 상태를 전달하는 것입니다. 상태를 가지지 않은 컴포넌트가 선언적인 방법으로 데이터를 렌더링 하는 동안, 상태기반 컴포넌트는 모든 상호작용 로직을 캡슐화합니다. <add>일반적인 패턴은 데이터만 렌더하는 여러 상태를 가지지 않은 컴포넌트를 만들고, 그 위에 상태기반(stateful) 컴포넌트를 만들어 계층 안의 자식 컴포넌트에게 `props`를 통해 state를 전달하는 것입니다. state를 가지지 않은 컴포넌트가 선언적인 방법으로 데이터를 렌더링 하는 동안, 상태기반 컴포넌트는 모든 상호작용 로직을 캡슐화합니다. <ide> <ide> <del>## 상태를 어떻게 *써야* 할까요? <add>## state를 어떻게 *써야* 할까요? <ide> <del>**상태는 컴포넌트의 이벤트 핸들러에 의해 UI 업데이트를 트리거할때 변경될 가능성이 있어, 그때 사용할 데이터를 가져야 합니다.** 실제 엡에서는 이 데이터는 매우 작고 JSON 직렬화 가능한 경향이 있습니다. 상태기반 컴포넌트를 만들때, 가능한 작게 상태를 서술하고 `this.state`에만 저장하도록 해보세요. 그냥 `render()` 안에서 이 상태를 기반으로 다른 모든 정보를 계산합니다. 이 방식으로 애플리케이션을 작성하고 생각하면 가장 최적의 애플리케이션으로 발전해가는 경향이 있다는 것을 발견하게 될것입니다. 장황하거나 계산된 값을 상태에 추가하는 것은 렌더가 그것을 계산하는 대신에 명시적으로 그것들을 싱크해야 하는 것을 의미하기 때문이죠. <add>**state는 컴포넌트의 이벤트 핸들러에 의해 UI 업데이트를 트리거할때 변경될 가능성이 있어, 그때 사용할 데이터를 가져야 합니다.** 실제 엡에서는 이 데이터는 매우 작고 JSON 직렬화 가능한 경향이 있습니다. 상태기반 컴포넌트를 만들때, 가능한 작게 state를 서술하고 `this.state`에만 저장하도록 해보세요. 그냥 `render()` 안에서 이 state를 기반으로 다른 모든 정보를 계산합니다. 이 방식으로 애플리케이션을 작성하고 생각하면 가장 최적의 애플리케이션으로 발전해가는 경향이 있다는 것을 발견하게 될것입니다. 장황하거나 계산된 값을 state에 추가하는 것은 렌더가 그것을 계산하는 대신에 명시적으로 그것들을 싱크해야 하는 것을 의미하기 때문이죠. <ide> <del>## 상태를 어떻게 *쓰지 말아야* 할까요? <add>## state를 어떻게 *쓰지 말아야* 할까요? <ide> <del>`this.state`는 UI의 상태를 표현할 최소한의 데이터만 가져야 합니다. 그래서 이런것을들 가지지 말아야 합니다. <add>`this.state`는 UI의 state를 표현할 최소한의 데이터만 가져야 합니다. 그래서 이런것을들 가지지 말아야 합니다. <ide> <del>* **계산된 데이터:** 상태에 따라 값을 미리 계산하는 것을 염려하지 마세요. 계산은 모두 `render()`에서 하는 것이 UI의 일관성을 유지하기 쉽습니다. 예를 들어, 상태에서 list items 배열을 가지고 있고 문자열으로 카운트를 렌더링 할 경우, 상태에 저장하기보다는 그냥 `render()` 메서드안에서 `this.state.listItems.length + ' list items'`를 렌더하세요. <del>* **React 컴포넌트:** 가지고 있는 props와 상태로 `render()`안에서 만드세요. <del>* **props에서 복사한 데이터:** 가능한한 원래의 소스로 props를 사용하도록 해보세요. props를 상태에 저장하는 단하나의 올바른 사용법은 이전 값을 알고 싶을 때입니다. props는 시간이 지나면 변경될 수도 있기 때문이죠. <add>* **계산된 데이터:** state에 따라 값을 미리 계산하는 것을 염려하지 마세요. 계산은 모두 `render()`에서 하는 것이 UI의 일관성을 유지하기 쉽습니다. 예를 들어, state에서 list items 배열을 가지고 있고 문자열으로 카운트를 렌더링 할 경우, state에 저장하기보다는 그냥 `render()` 메서드안에서 `this.state.listItems.length + ' list items'`를 렌더하세요. <add>* **React 컴포넌트:** 가지고 있는 props와 state로 `render()`안에서 만드세요. <add>* **props에서 복사한 데이터:** 가능한한 원래의 소스로 props를 사용하도록 해보세요. props를 state에 저장하는 단하나의 올바른 사용법은 이전 값을 알고 싶을 때입니다. props는 시간이 지나면 변경될 수도 있기 때문이죠.
1
PHP
PHP
make view with response status and headers
036a0bab0bd05cf2f8086363c35adc104a7cf631
<ide><path>laravel/response.php <ide> public static function make($content, $status = 200, $headers = array()) <ide> { <ide> return new static($content, $status, $headers); <ide> } <add> <add> /** <add> * Create a new response instance with status code. <add> * <add> * <code> <add> * // Create a response instance with a view <add> * return Response::view('home.no_such_page', 404); <add> * <add> * // Create a response instance with a view and data <add> * return Response::view('item.no_such_page', 404, array('message' => 'Nothing found'), array('header' => 'value')); <add> * </code> <add> * <add> * @param string $view <add> * @param int $status <add> * @param array $data <add> * @param array $headers <add> * @return Response <add> */ <add> public static function view_with_status($view, $status, $data = array(), $headers = array()) <add> { <add> return new static(View::make($view, $data), $status, $headers); <add> } <ide> <ide> /** <ide> * Create a new response instance containing a view.
1
Text
Text
correct import statement
8a10b50b6732176ac4335752045e3d7f4545443b
<ide><path>doc/api/esm.md <ide> To include an ES module into CommonJS, use [`import()`][]. <ide> <ide> ### <code>import</code> statements <ide> <del>An `import` statement can reference either ES module or CommonJS JavaScript. <del>Other file types such as JSON and Native modules are not supported. For those, <add>An `import` statement can reference an ES module, a CommonJS module, or JSON. <add>Other file types such as Native modules are not supported. For those, <ide> use [`module.createRequire()`][]. <ide> <ide> `import` statements are permitted only in ES modules. For similar functionality
1
Text
Text
improve spanish translation for ruby's guide
c7f8ff864616c5862debd4bacf7da211dca2e459
<ide><path>guide/spanish/ruby/ruby-arrays/index.md <ide> --- <ide> title: Ruby Arrays <del>localeTitle: Matrices de rubíes <add>localeTitle: Arrays de Ruby <ide> --- <del>## Matrices de rubíes <add>## Arrays de Ruby <ide> <del>Una matriz representa una lista de valores. Los valores individuales a menudo se llaman "elementos" de la matriz. Para hacer una matriz en Ruby, use corchetes y valores separados con comas: <add>Un array (arreglo) representa una lista de valores. Los valores individuales a menudo se llaman "elementos" del array. Para crear un array en Ruby, usa corchetes y valores separados por comas: <ide> <ide> ```ruby <ide> my_array = [1, 2, 3, 4, 5] <ide> ``` <ide> <del>El primer ejemplo es una matriz de números, pero una matriz Ruby puede contener valores de diferentes tipos, incluso otras matrices: <add>El primer ejemplo es un array de números, pero un array en Ruby puede contener valores de diferentes tipos, incluso otros arrays: <ide> <ide> ```ruby <ide> mixed_array = [5, "Hello World", true, [1,2,3]] <ide> ``` <ide> <del>Puede acceder a los elementos de una matriz con corchetes e índices numéricos. Observe que el primer elemento está en el índice 0, no 1: <add>Puedes acceder a los elementos de un array con corchetes e índices numéricos. Observa que el primer elemento está en el índice 0, no en el 1: <ide> <ide> ```ruby <ide> mixed_array[0] # 5 <del> mixed_array[1] # "Hello World" <del> mixed_array[2] # true <add>mixed_array[1] # "Hello World" <add>mixed_array[2] # true <ide> ``` <ide> <del>Puede verificar cuántos elementos tiene una matriz con el método de `length` : <add>Puedes verificar cuántos elementos tiene un array con el método `length`: <ide> <ide> ```ruby <del>mixed_array.length # 3 <del> [].length # 0 <add>mixed_array.length # 4 <add>[].length # 0 <ide> ``` <ide> <del>Puedes verificar el primer elemento de una matriz con el `first` método: <add>Puedes obtener el primer elemento de un array con el método `first`: <ide> <ide> ```ruby <ide> mixed_array.first # 5 <ide> ``` <ide> <del>Puedes verificar el último elemento de una matriz con el `last` método: <add>Puedes obtener el último elemento de un array con el método `last`: <ide> <ide> ```ruby <del>mixed_array.last # true <del>``` <del> <del>#### Ruby lambda <del> <del>Una lambda también se conoce comúnmente como una función anónima. Para crear un lambda en Ruby, puedes usar la siguiente sintaxis: <del> <del>```ruby <del>lambda = lambda {} <add>mixed_array.last # [1,2,3] <ide> ``` <ide> <ide> #### Más información: <ide> <del>[Ruby array documentación](https://ruby-doc.org/core-2.4.2/Array.html) <ide>\ No newline at end of file <add>[Documentación de Array de Ruby](https://ruby-doc.org/core-2.4.2/Array.html)
1
Ruby
Ruby
add ability to specify your own sanitizer
c7567c9a6dee1380432beaf88c1854a4ed6bb15b
<ide><path>activemodel/lib/active_model/mass_assignment_security.rb <ide> require 'active_support/core_ext/class/attribute.rb' <ide> require 'active_model/mass_assignment_security/permission_set' <add>require 'active_model/mass_assignment_security/sanitizer' <ide> <ide> module ActiveModel <ide> # = Active Model Mass-Assignment Security <ide> module MassAssignmentSecurity <ide> class_attribute :_accessible_attributes <ide> class_attribute :_protected_attributes <ide> class_attribute :_active_authorizer <add> class_attribute :mass_assignment_sanitizer <ide> end <ide> <ide> # Mass assignment security provides an interface for protecting attributes <ide> def attributes_protected_by_default <ide> <ide> def protected_attributes_configs <ide> self._protected_attributes ||= begin <del> default_black_list = BlackList.new(attributes_protected_by_default).tap do |w| <del> w.logger = self.logger if self.respond_to?(:logger) <del> end <add> default_black_list = BlackList.new(attributes_protected_by_default) <ide> Hash.new(default_black_list) <ide> end <ide> end <ide> <ide> def accessible_attributes_configs <ide> self._accessible_attributes ||= begin <del> default_white_list = WhiteList.new.tap { |w| w.logger = self.logger if self.respond_to?(:logger) } <add> default_white_list = WhiteList.new <ide> Hash.new(default_white_list) <ide> end <ide> end <ide> def accessible_attributes_configs <ide> protected <ide> <ide> def sanitize_for_mass_assignment(attributes, role = :default) <del> mass_assignment_authorizer(role).sanitize(attributes) <add> (mass_assignment_sanitizer || default_mass_assignment_sanitizer).sanitize(attributes, mass_assignment_authorizer(role)) <add> end <add> <add> def default_mass_assignment_sanitizer <add> DefaultSanitizer.new(self.respond_to?(:logger) && self.logger) <ide> end <ide> <ide> def mass_assignment_authorizer(role = :default) <ide><path>activemodel/lib/active_model/mass_assignment_security/permission_set.rb <ide> require 'set' <del>require 'active_model/mass_assignment_security/sanitizer' <ide> <ide> module ActiveModel <ide> module MassAssignmentSecurity <ide> class PermissionSet < Set <del> attr_accessor :logger <ide> <ide> def +(values) <ide> super(values.map(&:to_s)) <ide> def include?(key) <ide> super(remove_multiparameter_id(key)) <ide> end <ide> <add> def deny?(key) <add> raise NotImplementedError, "#deny?(key) suppose to be overwritten" <add> end <add> <ide> protected <ide> <ide> def remove_multiparameter_id(key) <ide> def remove_multiparameter_id(key) <ide> end <ide> <ide> class WhiteList < PermissionSet <del> include Sanitizer <ide> <ide> def deny?(key) <ide> !include?(key) <ide> end <ide> end <ide> <ide> class BlackList < PermissionSet <del> include Sanitizer <ide> <ide> def deny?(key) <ide> include?(key) <ide><path>activemodel/lib/active_model/mass_assignment_security/sanitizer.rb <ide> module ActiveModel <ide> module MassAssignmentSecurity <del> module Sanitizer <add> class Sanitizer <ide> # Returns all attributes not denied by the authorizer. <del> def sanitize(attributes) <del> sanitized_attributes = attributes.reject { |key, value| deny?(key) } <add> def sanitize(attributes, authorizer) <add> sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) } <ide> debug_protected_attribute_removal(attributes, sanitized_attributes) <ide> sanitized_attributes <ide> end <ide> def sanitize(attributes) <ide> <ide> def debug_protected_attribute_removal(attributes, sanitized_attributes) <ide> removed_keys = attributes.keys - sanitized_attributes.keys <del> warn!(removed_keys) if removed_keys.any? <add> process_removed_attributes(removed_keys) if removed_keys.any? <ide> end <add> <add> def process_removed_attributes(attrs) <add> raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten" <add> end <add> <add> end <add> class DefaultSanitizer < Sanitizer <ide> <del> def warn!(attrs) <add> attr_accessor :logger <add> <add> def initialize(logger = nil) <add> self.logger = logger <add> super() <add> end <add> <add> def process_removed_attributes(attrs) <ide> self.logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if self.logger <ide> end <ide> end <ide><path>activemodel/test/cases/mass_assignment_security/black_list_test.rb <ide> def setup <ide> assert_equal false, @black_list.deny?('first_name') <ide> end <ide> <del> test "sanitize attributes" do <del> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied', 'admin(1)' => 'denied' } <del> attributes = @black_list.sanitize(original_attributes) <del> <del> assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" <del> assert !attributes.key?('admin'), "Denied key should be rejected" <del> assert !attributes.key?('admin(1)'), "Multi-parameter key should be detected" <del> end <ide> <ide> end <ide><path>activemodel/test/cases/mass_assignment_security/sanitizer_test.rb <ide> <ide> class SanitizerTest < ActiveModel::TestCase <ide> <del> class SanitizingAuthorizer <del> include ActiveModel::MassAssignmentSecurity::Sanitizer <del> <del> attr_accessor :logger <ide> <add> class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet <ide> def deny?(key) <ide> key.in?(['admin']) <ide> end <del> <ide> end <ide> <ide> def setup <del> @sanitizer = SanitizingAuthorizer.new <add> @sanitizer = ActiveModel::MassAssignmentSecurity::DefaultSanitizer.new <add> @authorizer = Authorizer.new <ide> end <ide> <ide> test "sanitize attributes" do <ide> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } <del> attributes = @sanitizer.sanitize(original_attributes) <add> attributes = @sanitizer.sanitize(original_attributes, @authorizer) <ide> <ide> assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" <ide> assert !attributes.key?('admin'), "Denied key should be rejected" <ide> def setup <ide> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } <ide> log = StringIO.new <ide> @sanitizer.logger = Logger.new(log) <del> @sanitizer.sanitize(original_attributes) <add> @sanitizer.sanitize(original_attributes, @authorizer) <ide> assert_match(/admin/, log.string, "Should log removed attributes: #{log.string}") <ide> end <ide> <ide><path>activemodel/test/cases/mass_assignment_security/white_list_test.rb <ide> def setup <ide> assert_equal true, @white_list.deny?('admin') <ide> end <ide> <del> test "sanitize attributes" do <del> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied', 'admin(1)' => 'denied' } <del> attributes = @white_list.sanitize(original_attributes) <del> <del> assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" <del> assert !attributes.key?('admin'), "Denied key should be rejected" <del> assert !attributes.key?('admin(1)'), "Multi-parameter key should be detected" <del> end <del> <ide> end <ide><path>activemodel/test/cases/mass_assignment_security_test.rb <ide> require "cases/helper" <ide> require 'models/mass_assignment_specific' <ide> <add> <add>class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer <add> <add> def process_removed_attributes(attrs) <add> raise StandardError <add> end <add> <add>end <add> <ide> class MassAssignmentSecurityTest < ActiveModel::TestCase <ide> <ide> def test_attribute_protection <ide> def test_mass_assignment_multiparameter_protector <ide> assert_equal sanitized, { } <ide> end <ide> <add> def test_custom_sanitizer <add> user = User.new <add> User.mass_assignment_sanitizer = CustomSanitizer.new <add> assert_raise StandardError do <add> user.sanitize_for_mass_assignment("admin" => true) <add> end <add> ensure <add> User.mass_assignment_sanitizer = nil <add> <add> end <add> <ide> end
7
PHP
PHP
remove check for items in memcached cache driver
6c51536d7d8ae5ebf753738c8cc26d6397b8a743
<ide><path>system/cache/driver/memcached.php <ide> public function has($key) <ide> */ <ide> public function get($key) <ide> { <del> if (array_key_exists($key, $this->items)) <del> { <del> return $this->items[$key]; <del> } <del> <ide> $cache = \System\Memcached::instance()->get(\System\Config::get('cache.key').$key); <ide> <ide> if ($cache === false)
1
PHP
PHP
extract an if check into a method
3271f78e85a343bde67dae5a84c79739fbe8d4be
<ide><path>src/Illuminate/Encryption/Encrypter.php <ide> protected function getJsonPayload($payload) <ide> throw new DecryptException("Invalid data."); <ide> } <ide> <del> if ($payload['mac'] !== $this->hash($payload['iv'], $payload['value'])) <add> if ( ! $this->validMac($payload)) <ide> { <ide> throw new DecryptException("MAC is invalid."); <ide> } <ide> <ide> return $payload; <ide> } <ide> <add> /** <add> * Determine if the MAC for the given payload is valid. <add> * <add> * @param array $payload <add> * @return bool <add> */ <add> protected function validMac(array $payload) <add> { <add> return ($payload['mac'] == $this->hash($payload['iv'], $payload['value'])); <add> } <add> <ide> /** <ide> * Create a MAC for the given value. <ide> *
1
Text
Text
remove unnecessary intro in governance doc
38f0e382f7b431620323a3bb9cac052d3e7a539d
<ide><path>GOVERNANCE.md <ide> # Node.js Project Governance <ide> <del>The Node.js project is governed by its Collaborators, including a Technical <del>Steering Committee (TSC) which is responsible for high-level guidance of the <del>project. <del> <ide> <!-- TOC --> <ide> <ide> - [Collaborators](#collaborators)
1
Python
Python
add regression test for ticket #702
50a40534484d4797eab36e22561e0637f519d2bb
<ide><path>numpy/core/tests/test_regression.py <ide> def check_object_array_refcounting(self, level=rlevel): <ide> assert cnt(a) == cnt0_a + 5 + 2 <ide> assert cnt(b) == cnt0_b + 5 + 3 <ide> <add> def check_mem_custom_float_to_array(self, level=rlevel): <add> """Ticket 702""" <add> class MyFloat: <add> def __float__(self): <add> return 1 <add> <add> tmp = np.atleast_1d([MyFloat()]) <add> tmp2 = tmp.astype(float) <add> <ide> def check_object_array_refcount_self_assign(self, level=rlevel): <ide> """Ticket #711""" <ide> class VictimObject(object):
1
Text
Text
remove stray `
7788879c5a6fa69de935a1e045fe1ab657b9dc2e
<ide><path>import-into-idea.md <ide> _Within your locally cloned spring-framework working directory:_ <ide> <ide> ## Known issues <ide> <del>1. `spring-core` and ``spring-oxm` should be pre-compiled due to repackaged dependencies. <add>1. `spring-core` and `spring-oxm` should be pre-compiled due to repackaged dependencies. <ide> See `*RepackJar` tasks in the build and https://youtrack.jetbrains.com/issue/IDEA-160605). <ide> 2. `spring-aspects` does not compile due to references to aspect types unknown to <ide> IntelliJ IDEA. See http://youtrack.jetbrains.com/issue/IDEA-64446 for details. In the meantime, the
1
Python
Python
prepare 2.2.5 release
aa28910799bcd169d28ae1e5b50508c868df7380
<ide><path>keras/__init__.py <ide> from .models import Model <ide> from .models import Sequential <ide> <del>__version__ = '2.2.4' <add>__version__ = '2.2.5' <ide><path>keras/backend/tensorflow_backend.py <ide> _LOCAL_DEVICES = None <ide> <ide> <add>def _get_default_graph(): <add> try: <add> return tf.get_default_graph() <add> except AttributeError: <add> raise RuntimeError( <add> 'It looks like you are trying to use ' <add> 'a version of multi-backend Keras that ' <add> 'does not support TensorFlow 2.0. We recommend ' <add> 'using `tf.keras`, or alternatively, ' <add> 'downgrading to TensorFlow 1.14.') <add> <add> <ide> def get_uid(prefix=''): <ide> """Get the uid for the default graph. <ide> <ide> def get_uid(prefix=''): <ide> A unique identifier for the graph. <ide> """ <ide> global _GRAPH_UID_DICTS <del> graph = tf.get_default_graph() <add> graph = _get_default_graph() <ide> if graph not in _GRAPH_UID_DICTS: <ide> _GRAPH_UID_DICTS[graph] = defaultdict(int) <ide> _GRAPH_UID_DICTS[graph][prefix] += 1 <ide> def clear_session(): <ide> shape=(), <ide> name='keras_learning_phase') <ide> _GRAPH_LEARNING_PHASES = {} <del> _GRAPH_LEARNING_PHASES[tf.get_default_graph()] = phase <add> _GRAPH_LEARNING_PHASES[_get_default_graph()] = phase <ide> <ide> <ide> def manual_variable_initialization(value): <ide> def learning_phase(): <ide> # Returns <ide> Learning phase (scalar integer tensor or Python integer). <ide> """ <del> graph = tf.get_default_graph() <add> graph = _get_default_graph() <ide> if graph not in _GRAPH_LEARNING_PHASES: <ide> with tf.name_scope(''): <ide> phase = tf.placeholder_with_default( <ide> def set_learning_phase(value): <ide> if value not in {0, 1}: <ide> raise ValueError('Expected learning phase to be ' <ide> '0 or 1.') <del> _GRAPH_LEARNING_PHASES[tf.get_default_graph()] = value <add> _GRAPH_LEARNING_PHASES[_get_default_graph()] = value <ide> <ide> <ide> def get_session(): <ide> def _get_current_tf_device(): <ide> the device (`CPU` or `GPU`). If the scope is not explicitly set, it will <ide> return `None`. <ide> """ <del> g = tf.get_default_graph() <add> g = _get_default_graph() <ide> op = _TfDeviceCaptureOp() <ide> g._apply_device_functions(op) <ide> return op.device <ide><path>setup.py <ide> ''' <ide> <ide> setup(name='Keras', <del> version='2.2.4', <add> version='2.2.5', <ide> description='Deep Learning for humans', <ide> long_description=long_description, <ide> author='Francois Chollet', <ide> 'six>=1.9.0', <ide> 'pyyaml', <ide> 'h5py', <del> 'keras_applications>=1.0.6', <del> 'keras_preprocessing>=1.0.5'], <add> 'keras_applications>=1.0.8', <add> 'keras_preprocessing>=1.1.0'], <ide> extras_require={ <ide> 'visualize': ['pydot>=1.2.4'], <ide> 'tests': ['pytest', <ide><path>tests/docs/test_documentation.py <ide> def handle_class(name, member): <ide> <ide> <ide> def handle_function(name, member): <add> if name.startswith('_'): <add> return <ide> if is_accepted(name, member) or member_too_small(member): <ide> # We don't need to check this one. <ide> return <ide><path>tests/keras/engine/test_topology.py <ide> def test_recursion(): <ide> j_tf = tf.placeholder(dtype=K.floatx()) <ide> k_tf = tf.placeholder(dtype=K.floatx()) <ide> m_tf, n_tf = tf_model([j_tf, k_tf]) <del> assert m_tf.get_shape().as_list() == [None, 64] <del> assert n_tf.get_shape().as_list() == [None, 5] <ide> <ide> # test merge <ide> layers.concatenate([j_tf, k_tf], axis=1)
5
Ruby
Ruby
build fix, remove not null constraint
4c81c8ce533896be28bdc0b055ff30bb9dee1316
<ide><path>activerecord/test/cases/migration_test.rb <ide> def setup <ide> end <ide> Person.connection.remove_column("people", "first_name") rescue nil <ide> Person.connection.remove_column("people", "middle_name") rescue nil <del> Person.connection.add_column("people", "first_name", :string, null: false) <add> Person.connection.add_column("people", "first_name", :string) <ide> Person.reset_column_information <ide> end <ide>
1
Javascript
Javascript
avoid object iteration when creating dom factories
e5f9ae27058052e72d6fb6d89c6ca93075e4089a
<ide><path>src/isomorphic/classic/element/ReactDOMFactories.js <ide> <ide> var ReactElement = require('ReactElement'); <ide> <del>var mapObject = require('mapObject'); <del> <ide> /** <ide> * Create a factory that creates HTML tag elements. <ide> * <del> * @param {string} tag Tag name (e.g. `div`). <ide> * @private <ide> */ <del>function createDOMFactory(tag) { <del> if (__DEV__) { <del> var ReactElementValidator = require('ReactElementValidator'); <del> return ReactElementValidator.createFactory(tag); <del> } <del> return ReactElement.createFactory(tag); <add>var createDOMFactory = ReactElement.createFactory; <add>if (__DEV__) { <add> var ReactElementValidator = require('ReactElementValidator'); <add> createDOMFactory = ReactElementValidator.createFactory; <ide> } <ide> <ide> /** <ide> function createDOMFactory(tag) { <ide> * <ide> * @public <ide> */ <del>var ReactDOMFactories = mapObject({ <del> a: 'a', <del> abbr: 'abbr', <del> address: 'address', <del> area: 'area', <del> article: 'article', <del> aside: 'aside', <del> audio: 'audio', <del> b: 'b', <del> base: 'base', <del> bdi: 'bdi', <del> bdo: 'bdo', <del> big: 'big', <del> blockquote: 'blockquote', <del> body: 'body', <del> br: 'br', <del> button: 'button', <del> canvas: 'canvas', <del> caption: 'caption', <del> cite: 'cite', <del> code: 'code', <del> col: 'col', <del> colgroup: 'colgroup', <del> data: 'data', <del> datalist: 'datalist', <del> dd: 'dd', <del> del: 'del', <del> details: 'details', <del> dfn: 'dfn', <del> dialog: 'dialog', <del> div: 'div', <del> dl: 'dl', <del> dt: 'dt', <del> em: 'em', <del> embed: 'embed', <del> fieldset: 'fieldset', <del> figcaption: 'figcaption', <del> figure: 'figure', <del> footer: 'footer', <del> form: 'form', <del> h1: 'h1', <del> h2: 'h2', <del> h3: 'h3', <del> h4: 'h4', <del> h5: 'h5', <del> h6: 'h6', <del> head: 'head', <del> header: 'header', <del> hgroup: 'hgroup', <del> hr: 'hr', <del> html: 'html', <del> i: 'i', <del> iframe: 'iframe', <del> img: 'img', <del> input: 'input', <del> ins: 'ins', <del> kbd: 'kbd', <del> keygen: 'keygen', <del> label: 'label', <del> legend: 'legend', <del> li: 'li', <del> link: 'link', <del> main: 'main', <del> map: 'map', <del> mark: 'mark', <del> menu: 'menu', <del> menuitem: 'menuitem', <del> meta: 'meta', <del> meter: 'meter', <del> nav: 'nav', <del> noscript: 'noscript', <del> object: 'object', <del> ol: 'ol', <del> optgroup: 'optgroup', <del> option: 'option', <del> output: 'output', <del> p: 'p', <del> param: 'param', <del> picture: 'picture', <del> pre: 'pre', <del> progress: 'progress', <del> q: 'q', <del> rp: 'rp', <del> rt: 'rt', <del> ruby: 'ruby', <del> s: 's', <del> samp: 'samp', <del> script: 'script', <del> section: 'section', <del> select: 'select', <del> small: 'small', <del> source: 'source', <del> span: 'span', <del> strong: 'strong', <del> style: 'style', <del> sub: 'sub', <del> summary: 'summary', <del> sup: 'sup', <del> table: 'table', <del> tbody: 'tbody', <del> td: 'td', <del> textarea: 'textarea', <del> tfoot: 'tfoot', <del> th: 'th', <del> thead: 'thead', <del> time: 'time', <del> title: 'title', <del> tr: 'tr', <del> track: 'track', <del> u: 'u', <del> ul: 'ul', <del> 'var': 'var', <del> video: 'video', <del> wbr: 'wbr', <add>var ReactDOMFactories = { <add> a: createDOMFactory('a'), <add> abbr: createDOMFactory('abbr'), <add> address: createDOMFactory('address'), <add> area: createDOMFactory('area'), <add> article: createDOMFactory('article'), <add> aside: createDOMFactory('aside'), <add> audio: createDOMFactory('audio'), <add> b: createDOMFactory('b'), <add> base: createDOMFactory('base'), <add> bdi: createDOMFactory('bdi'), <add> bdo: createDOMFactory('bdo'), <add> big: createDOMFactory('big'), <add> blockquote: createDOMFactory('blockquote'), <add> body: createDOMFactory('body'), <add> br: createDOMFactory('br'), <add> button: createDOMFactory('button'), <add> canvas: createDOMFactory('canvas'), <add> caption: createDOMFactory('caption'), <add> cite: createDOMFactory('cite'), <add> code: createDOMFactory('code'), <add> col: createDOMFactory('col'), <add> colgroup: createDOMFactory('colgroup'), <add> data: createDOMFactory('data'), <add> datalist: createDOMFactory('datalist'), <add> dd: createDOMFactory('dd'), <add> del: createDOMFactory('del'), <add> details: createDOMFactory('details'), <add> dfn: createDOMFactory('dfn'), <add> dialog: createDOMFactory('dialog'), <add> div: createDOMFactory('div'), <add> dl: createDOMFactory('dl'), <add> dt: createDOMFactory('dt'), <add> em: createDOMFactory('em'), <add> embed: createDOMFactory('embed'), <add> fieldset: createDOMFactory('fieldset'), <add> figcaption: createDOMFactory('figcaption'), <add> figure: createDOMFactory('figure'), <add> footer: createDOMFactory('footer'), <add> form: createDOMFactory('form'), <add> h1: createDOMFactory('h1'), <add> h2: createDOMFactory('h2'), <add> h3: createDOMFactory('h3'), <add> h4: createDOMFactory('h4'), <add> h5: createDOMFactory('h5'), <add> h6: createDOMFactory('h6'), <add> head: createDOMFactory('head'), <add> header: createDOMFactory('header'), <add> hgroup: createDOMFactory('hgroup'), <add> hr: createDOMFactory('hr'), <add> html: createDOMFactory('html'), <add> i: createDOMFactory('i'), <add> iframe: createDOMFactory('iframe'), <add> img: createDOMFactory('img'), <add> input: createDOMFactory('input'), <add> ins: createDOMFactory('ins'), <add> kbd: createDOMFactory('kbd'), <add> keygen: createDOMFactory('keygen'), <add> label: createDOMFactory('label'), <add> legend: createDOMFactory('legend'), <add> li: createDOMFactory('li'), <add> link: createDOMFactory('link'), <add> main: createDOMFactory('main'), <add> map: createDOMFactory('map'), <add> mark: createDOMFactory('mark'), <add> menu: createDOMFactory('menu'), <add> menuitem: createDOMFactory('menuitem'), <add> meta: createDOMFactory('meta'), <add> meter: createDOMFactory('meter'), <add> nav: createDOMFactory('nav'), <add> noscript: createDOMFactory('noscript'), <add> object: createDOMFactory('object'), <add> ol: createDOMFactory('ol'), <add> optgroup: createDOMFactory('optgroup'), <add> option: createDOMFactory('option'), <add> output: createDOMFactory('output'), <add> p: createDOMFactory('p'), <add> param: createDOMFactory('param'), <add> picture: createDOMFactory('picture'), <add> pre: createDOMFactory('pre'), <add> progress: createDOMFactory('progress'), <add> q: createDOMFactory('q'), <add> rp: createDOMFactory('rp'), <add> rt: createDOMFactory('rt'), <add> ruby: createDOMFactory('ruby'), <add> s: createDOMFactory('s'), <add> samp: createDOMFactory('samp'), <add> script: createDOMFactory('script'), <add> section: createDOMFactory('section'), <add> select: createDOMFactory('select'), <add> small: createDOMFactory('small'), <add> source: createDOMFactory('source'), <add> span: createDOMFactory('span'), <add> strong: createDOMFactory('strong'), <add> style: createDOMFactory('style'), <add> sub: createDOMFactory('sub'), <add> summary: createDOMFactory('summary'), <add> sup: createDOMFactory('sup'), <add> table: createDOMFactory('table'), <add> tbody: createDOMFactory('tbody'), <add> td: createDOMFactory('td'), <add> textarea: createDOMFactory('textarea'), <add> tfoot: createDOMFactory('tfoot'), <add> th: createDOMFactory('th'), <add> thead: createDOMFactory('thead'), <add> time: createDOMFactory('time'), <add> title: createDOMFactory('title'), <add> tr: createDOMFactory('tr'), <add> track: createDOMFactory('track'), <add> u: createDOMFactory('u'), <add> ul: createDOMFactory('ul'), <add> 'var': createDOMFactory('var'), <add> video: createDOMFactory('video'), <add> wbr: createDOMFactory('wbr'), <ide> <ide> // SVG <del> circle: 'circle', <del> clipPath: 'clipPath', <del> defs: 'defs', <del> ellipse: 'ellipse', <del> g: 'g', <del> image: 'image', <del> line: 'line', <del> linearGradient: 'linearGradient', <del> mask: 'mask', <del> path: 'path', <del> pattern: 'pattern', <del> polygon: 'polygon', <del> polyline: 'polyline', <del> radialGradient: 'radialGradient', <del> rect: 'rect', <del> stop: 'stop', <del> svg: 'svg', <del> text: 'text', <del> tspan: 'tspan', <del> <del>}, createDOMFactory); <add> circle: createDOMFactory('circle'), <add> clipPath: createDOMFactory('clipPath'), <add> defs: createDOMFactory('defs'), <add> ellipse: createDOMFactory('ellipse'), <add> g: createDOMFactory('g'), <add> image: createDOMFactory('image'), <add> line: createDOMFactory('line'), <add> linearGradient: createDOMFactory('linearGradient'), <add> mask: createDOMFactory('mask'), <add> path: createDOMFactory('path'), <add> pattern: createDOMFactory('pattern'), <add> polygon: createDOMFactory('polygon'), <add> polyline: createDOMFactory('polyline'), <add> radialGradient: createDOMFactory('radialGradient'), <add> rect: createDOMFactory('rect'), <add> stop: createDOMFactory('stop'), <add> svg: createDOMFactory('svg'), <add> text: createDOMFactory('text'), <add> tspan: createDOMFactory('tspan'), <add>}; <ide> <ide> module.exports = ReactDOMFactories;
1
Javascript
Javascript
move props to virtualizedlistprops
03b4764836e80d305aad78d7c35809b87615685c
<ide><path>Libraries/Lists/VirtualizedList.js <ide> import type {ScrollResponderType} from '../Components/ScrollView/ScrollView'; <ide> import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; <ide> import type {LayoutEvent, ScrollEvent} from '../Types/CoreEventTypes'; <add> <add>import type {ViewToken} from './ViewabilityHelper'; <ide> import type { <del> ViewabilityConfig, <del> ViewabilityConfigCallbackPair, <del> ViewToken, <del>} from './ViewabilityHelper'; <add> Item, <add> Props, <add> RenderItemProps, <add> RenderItemType, <add> Separators, <add>} from './VirtualizedListProps'; <add>export type {RenderItemProps, RenderItemType, Separators}; <ide> <ide> import { <ide> type ChildListState, <ide> const invariant = require('invariant'); <ide> <ide> const ON_END_REACHED_EPSILON = 0.001; <ide> <del>type Item = any; <del> <del>export type Separators = { <del> highlight: () => void, <del> unhighlight: () => void, <del> updateProps: (select: 'leading' | 'trailing', newProps: Object) => void, <del> ... <del>}; <del> <del>export type RenderItemProps<ItemT> = { <del> item: ItemT, <del> index: number, <del> separators: Separators, <del> ... <del>}; <del> <del>export type RenderItemType<ItemT> = ( <del> info: RenderItemProps<ItemT>, <del>) => React.Node; <add>let _usedIndexForKey = false; <add>let _keylessItemComponentName: string = ''; <ide> <ide> type ViewabilityHelperCallbackTuple = { <ide> viewabilityHelper: ViewabilityHelper, <ide> type ViewabilityHelperCallbackTuple = { <ide> ... <ide> }; <ide> <del>type RequiredProps = {| <del> /** <del> * The default accessor functions assume this is an Array<{key: string} | {id: string}> but you can override <del> * getItem, getItemCount, and keyExtractor to handle any type of index-based data. <del> */ <del> data?: any, <del> /** <del> * A generic accessor for extracting an item from any sort of data blob. <del> */ <del> getItem: (data: any, index: number) => ?Item, <del> /** <del> * Determines how many items are in the data blob. <del> */ <del> getItemCount: (data: any) => number, <del>|}; <del>type OptionalProps = {| <del> renderItem?: ?RenderItemType<Item>, <del> /** <del> * `debug` will turn on extra logging and visual overlays to aid with debugging both usage and <del> * implementation, but with a significant perf hit. <del> */ <del> debug?: ?boolean, <del> /** <del> * DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully <del> * unmounts react instances that are outside of the render window. You should only need to disable <del> * this for debugging purposes. Defaults to false. <del> */ <del> disableVirtualization?: ?boolean, <del> /** <del> * A marker property for telling the list to re-render (since it implements `PureComponent`). If <del> * any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the <del> * `data` prop, stick it here and treat it immutably. <del> */ <del> extraData?: any, <del> // e.g. height, y <del> getItemLayout?: ( <del> data: any, <del> index: number, <del> ) => { <del> length: number, <del> offset: number, <del> index: number, <del> ... <del> }, <del> horizontal?: ?boolean, <del> /** <del> * How many items to render in the initial batch. This should be enough to fill the screen but not <del> * much more. Note these items will never be unmounted as part of the windowed rendering in order <del> * to improve perceived performance of scroll-to-top actions. <del> */ <del> initialNumToRender?: ?number, <del> /** <del> * Instead of starting at the top with the first item, start at `initialScrollIndex`. This <del> * disables the "scroll to top" optimization that keeps the first `initialNumToRender` items <del> * always rendered and immediately renders the items starting at this initial index. Requires <del> * `getItemLayout` to be implemented. <del> */ <del> initialScrollIndex?: ?number, <del> /** <del> * Reverses the direction of scroll. Uses scale transforms of -1. <del> */ <del> inverted?: ?boolean, <del> keyExtractor?: ?(item: Item, index: number) => string, <del> /** <del> * Each cell is rendered using this element. Can be a React Component Class, <del> * or a render function. Defaults to using View. <del> */ <del> CellRendererComponent?: ?React.ComponentType<any>, <del> /** <del> * Rendered in between each item, but not at the top or bottom. By default, `highlighted` and <del> * `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` <del> * which will update the `highlighted` prop, but you can also add custom props with <del> * `separators.updateProps`. <del> */ <del> ItemSeparatorComponent?: ?React.ComponentType<any>, <del> /** <del> * Takes an item from `data` and renders it into the list. Example usage: <del> * <del> * <FlatList <del> * ItemSeparatorComponent={Platform.OS !== 'android' && ({highlighted}) => ( <del> * <View style={[style.separator, highlighted && {marginLeft: 0}]} /> <del> * )} <del> * data={[{title: 'Title Text', key: 'item1'}]} <del> * ListItemComponent={({item, separators}) => ( <del> * <TouchableHighlight <del> * onPress={() => this._onPress(item)} <del> * onShowUnderlay={separators.highlight} <del> * onHideUnderlay={separators.unhighlight}> <del> * <View style={{backgroundColor: 'white'}}> <del> * <Text>{item.title}</Text> <del> * </View> <del> * </TouchableHighlight> <del> * )} <del> * /> <del> * <del> * Provides additional metadata like `index` if you need it, as well as a more generic <del> * `separators.updateProps` function which let's you set whatever props you want to change the <del> * rendering of either the leading separator or trailing separator in case the more common <del> * `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for <del> * your use-case. <del> */ <del> ListItemComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Rendered when the list is empty. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListEmptyComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Rendered at the bottom of all the items. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListFooterComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Styling for internal View for ListFooterComponent <del> */ <del> ListFooterComponentStyle?: ViewStyleProp, <del> /** <del> * Rendered at the top of all the items. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListHeaderComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Styling for internal View for ListHeaderComponent <del> */ <del> ListHeaderComponentStyle?: ViewStyleProp, <del> /** <del> * A unique identifier for this list. If there are multiple VirtualizedLists at the same level of <del> * nesting within another VirtualizedList, this key is necessary for virtualization to <del> * work properly. <del> */ <del> listKey?: string, <del> /** <del> * The maximum number of items to render in each incremental render batch. The more rendered at <del> * once, the better the fill rate, but responsiveness may suffer because rendering content may <del> * interfere with responding to button taps or other interactions. <del> */ <del> maxToRenderPerBatch?: ?number, <del> /** <del> * Called once when the scroll position gets within `onEndReachedThreshold` of the rendered <del> * content. <del> */ <del> onEndReached?: ?(info: {distanceFromEnd: number, ...}) => void, <del> /** <del> * How far from the end (in units of visible length of the list) the bottom edge of the <del> * list must be from the end of the content to trigger the `onEndReached` callback. <del> * Thus a value of 0.5 will trigger `onEndReached` when the end of the content is <del> * within half the visible length of the list. A value of 0 will not trigger until scrolling <del> * to the very end of the list. <del> */ <del> onEndReachedThreshold?: ?number, <del> /** <del> * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make <del> * sure to also set the `refreshing` prop correctly. <del> */ <del> onRefresh?: ?() => void, <del> /** <del> * Used to handle failures when scrolling to an index that has not been measured yet. Recommended <del> * action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and <del> * then try again after more items have been rendered. <del> */ <del> onScrollToIndexFailed?: ?(info: { <del> index: number, <del> highestMeasuredFrameIndex: number, <del> averageItemLength: number, <del> ... <del> }) => void, <del> /** <del> * Called when the viewability of rows changes, as defined by the <del> * `viewabilityConfig` prop. <del> */ <del> onViewableItemsChanged?: ?(info: { <del> viewableItems: Array<ViewToken>, <del> changed: Array<ViewToken>, <del> ... <del> }) => void, <del> persistentScrollbar?: ?boolean, <del> /** <del> * Set this when offset is needed for the loading indicator to show correctly. <del> */ <del> progressViewOffset?: number, <del> /** <del> * A custom refresh control element. When set, it overrides the default <del> * <RefreshControl> component built internally. The onRefresh and refreshing <del> * props are also ignored. Only works for vertical VirtualizedList. <del> */ <del> refreshControl?: ?React.Element<any>, <del> /** <del> * Set this true while waiting for new data from a refresh. <del> */ <del> refreshing?: ?boolean, <del> /** <del> * Note: may have bugs (missing content) in some circumstances - use at your own risk. <del> * <del> * This may improve scroll performance for large lists. <del> */ <del> removeClippedSubviews?: boolean, <del> /** <del> * Render a custom scroll component, e.g. with a differently styled `RefreshControl`. <del> */ <del> renderScrollComponent?: (props: Object) => React.Element<any>, <del> /** <del> * Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off <del> * screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`. <del> */ <del> updateCellsBatchingPeriod?: ?number, <del> /** <del> * See `ViewabilityHelper` for flow type and further documentation. <del> */ <del> viewabilityConfig?: ViewabilityConfig, <del> /** <del> * List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged <del> * will be called when its corresponding ViewabilityConfig's conditions are met. <del> */ <del> viewabilityConfigCallbackPairs?: Array<ViewabilityConfigCallbackPair>, <del> /** <del> * Determines the maximum number of items rendered outside of the visible area, in units of <del> * visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will <del> * render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing <del> * this number will reduce memory consumption and may improve performance, but will increase the <del> * chance that fast scrolling may reveal momentary blank areas of unrendered content. <del> */ <del> windowSize?: ?number, <del> /** <del> * The legacy implementation is no longer supported. <del> */ <del> legacyImplementation?: empty, <del>|}; <del> <del>export type Props = {| <del> ...React.ElementConfig<typeof ScrollView>, <del> ...RequiredProps, <del> ...OptionalProps, <del>|}; <del> <del>let _usedIndexForKey = false; <del>let _keylessItemComponentName: string = ''; <del> <ide> type State = { <ide> first: number, <ide> last: number, <ide><path>Libraries/Lists/VirtualizedListInjection.js <ide> <ide> import * as React from 'react'; <ide> import type VirtualizedList from './VirtualizedList'; <del>import type {Props as VirtualizedListProps} from './VirtualizedList'; <add>import type {Props as VirtualizedListProps} from './VirtualizedListProps'; <ide> import invariant from 'invariant'; <ide> <ide> export type ListImplementation = React.ComponentType<VirtualizedListProps> & <ide><path>Libraries/Lists/VirtualizedListProps.js <add>/** <add> * Copyright (c) Meta Platforms, Inc. and affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>import * as React from 'react'; <add>import type { <add> ViewabilityConfig, <add> ViewabilityConfigCallbackPair, <add> ViewToken, <add>} from './ViewabilityHelper'; <add> <add>import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; <add>import typeof ScrollView from '../Components/ScrollView/ScrollView'; <add> <add>export type Item = any; <add> <add>export type Separators = { <add> highlight: () => void, <add> unhighlight: () => void, <add> updateProps: (select: 'leading' | 'trailing', newProps: Object) => void, <add> ... <add>}; <add> <add>export type RenderItemProps<ItemT> = { <add> item: ItemT, <add> index: number, <add> separators: Separators, <add> ... <add>}; <add> <add>export type RenderItemType<ItemT> = ( <add> info: RenderItemProps<ItemT>, <add>) => React.Node; <add> <add>type RequiredProps = {| <add> /** <add> * The default accessor functions assume this is an Array<{key: string} | {id: string}> but you can override <add> * getItem, getItemCount, and keyExtractor to handle any type of index-based data. <add> */ <add> data?: any, <add> /** <add> * A generic accessor for extracting an item from any sort of data blob. <add> */ <add> getItem: (data: any, index: number) => ?Item, <add> /** <add> * Determines how many items are in the data blob. <add> */ <add> getItemCount: (data: any) => number, <add>|}; <add>type OptionalProps = {| <add> renderItem?: ?RenderItemType<Item>, <add> /** <add> * `debug` will turn on extra logging and visual overlays to aid with debugging both usage and <add> * implementation, but with a significant perf hit. <add> */ <add> debug?: ?boolean, <add> /** <add> * DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully <add> * unmounts react instances that are outside of the render window. You should only need to disable <add> * this for debugging purposes. Defaults to false. <add> */ <add> disableVirtualization?: ?boolean, <add> /** <add> * A marker property for telling the list to re-render (since it implements `PureComponent`). If <add> * any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the <add> * `data` prop, stick it here and treat it immutably. <add> */ <add> extraData?: any, <add> // e.g. height, y <add> getItemLayout?: ( <add> data: any, <add> index: number, <add> ) => { <add> length: number, <add> offset: number, <add> index: number, <add> ... <add> }, <add> horizontal?: ?boolean, <add> /** <add> * How many items to render in the initial batch. This should be enough to fill the screen but not <add> * much more. Note these items will never be unmounted as part of the windowed rendering in order <add> * to improve perceived performance of scroll-to-top actions. <add> */ <add> initialNumToRender?: ?number, <add> /** <add> * Instead of starting at the top with the first item, start at `initialScrollIndex`. This <add> * disables the "scroll to top" optimization that keeps the first `initialNumToRender` items <add> * always rendered and immediately renders the items starting at this initial index. Requires <add> * `getItemLayout` to be implemented. <add> */ <add> initialScrollIndex?: ?number, <add> /** <add> * Reverses the direction of scroll. Uses scale transforms of -1. <add> */ <add> inverted?: ?boolean, <add> keyExtractor?: ?(item: Item, index: number) => string, <add> /** <add> * Each cell is rendered using this element. Can be a React Component Class, <add> * or a render function. Defaults to using View. <add> */ <add> CellRendererComponent?: ?React.ComponentType<any>, <add> /** <add> * Rendered in between each item, but not at the top or bottom. By default, `highlighted` and <add> * `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` <add> * which will update the `highlighted` prop, but you can also add custom props with <add> * `separators.updateProps`. <add> */ <add> ItemSeparatorComponent?: ?React.ComponentType<any>, <add> /** <add> * Takes an item from `data` and renders it into the list. Example usage: <add> * <add> * <FlatList <add> * ItemSeparatorComponent={Platform.OS !== 'android' && ({highlighted}) => ( <add> * <View style={[style.separator, highlighted && {marginLeft: 0}]} /> <add> * )} <add> * data={[{title: 'Title Text', key: 'item1'}]} <add> * ListItemComponent={({item, separators}) => ( <add> * <TouchableHighlight <add> * onPress={() => this._onPress(item)} <add> * onShowUnderlay={separators.highlight} <add> * onHideUnderlay={separators.unhighlight}> <add> * <View style={{backgroundColor: 'white'}}> <add> * <Text>{item.title}</Text> <add> * </View> <add> * </TouchableHighlight> <add> * )} <add> * /> <add> * <add> * Provides additional metadata like `index` if you need it, as well as a more generic <add> * `separators.updateProps` function which let's you set whatever props you want to change the <add> * rendering of either the leading separator or trailing separator in case the more common <add> * `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for <add> * your use-case. <add> */ <add> ListItemComponent?: ?(React.ComponentType<any> | React.Element<any>), <add> /** <add> * Rendered when the list is empty. Can be a React Component Class, a render function, or <add> * a rendered element. <add> */ <add> ListEmptyComponent?: ?(React.ComponentType<any> | React.Element<any>), <add> /** <add> * Rendered at the bottom of all the items. Can be a React Component Class, a render function, or <add> * a rendered element. <add> */ <add> ListFooterComponent?: ?(React.ComponentType<any> | React.Element<any>), <add> /** <add> * Styling for internal View for ListFooterComponent <add> */ <add> ListFooterComponentStyle?: ViewStyleProp, <add> /** <add> * Rendered at the top of all the items. Can be a React Component Class, a render function, or <add> * a rendered element. <add> */ <add> ListHeaderComponent?: ?(React.ComponentType<any> | React.Element<any>), <add> /** <add> * Styling for internal View for ListHeaderComponent <add> */ <add> ListHeaderComponentStyle?: ViewStyleProp, <add> /** <add> * A unique identifier for this list. If there are multiple VirtualizedLists at the same level of <add> * nesting within another VirtualizedList, this key is necessary for virtualization to <add> * work properly. <add> */ <add> listKey?: string, <add> /** <add> * The maximum number of items to render in each incremental render batch. The more rendered at <add> * once, the better the fill rate, but responsiveness may suffer because rendering content may <add> * interfere with responding to button taps or other interactions. <add> */ <add> maxToRenderPerBatch?: ?number, <add> /** <add> * Called once when the scroll position gets within `onEndReachedThreshold` of the rendered <add> * content. <add> */ <add> onEndReached?: ?(info: {distanceFromEnd: number, ...}) => void, <add> /** <add> * How far from the end (in units of visible length of the list) the bottom edge of the <add> * list must be from the end of the content to trigger the `onEndReached` callback. <add> * Thus a value of 0.5 will trigger `onEndReached` when the end of the content is <add> * within half the visible length of the list. A value of 0 will not trigger until scrolling <add> * to the very end of the list. <add> */ <add> onEndReachedThreshold?: ?number, <add> /** <add> * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make <add> * sure to also set the `refreshing` prop correctly. <add> */ <add> onRefresh?: ?() => void, <add> /** <add> * Used to handle failures when scrolling to an index that has not been measured yet. Recommended <add> * action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and <add> * then try again after more items have been rendered. <add> */ <add> onScrollToIndexFailed?: ?(info: { <add> index: number, <add> highestMeasuredFrameIndex: number, <add> averageItemLength: number, <add> ... <add> }) => void, <add> /** <add> * Called when the viewability of rows changes, as defined by the <add> * `viewabilityConfig` prop. <add> */ <add> onViewableItemsChanged?: ?(info: { <add> viewableItems: Array<ViewToken>, <add> changed: Array<ViewToken>, <add> ... <add> }) => void, <add> persistentScrollbar?: ?boolean, <add> /** <add> * Set this when offset is needed for the loading indicator to show correctly. <add> */ <add> progressViewOffset?: number, <add> /** <add> * A custom refresh control element. When set, it overrides the default <add> * <RefreshControl> component built internally. The onRefresh and refreshing <add> * props are also ignored. Only works for vertical VirtualizedList. <add> */ <add> refreshControl?: ?React.Element<any>, <add> /** <add> * Set this true while waiting for new data from a refresh. <add> */ <add> refreshing?: ?boolean, <add> /** <add> * Note: may have bugs (missing content) in some circumstances - use at your own risk. <add> * <add> * This may improve scroll performance for large lists. <add> */ <add> removeClippedSubviews?: boolean, <add> /** <add> * Render a custom scroll component, e.g. with a differently styled `RefreshControl`. <add> */ <add> renderScrollComponent?: (props: Object) => React.Element<any>, <add> /** <add> * Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off <add> * screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`. <add> */ <add> updateCellsBatchingPeriod?: ?number, <add> /** <add> * See `ViewabilityHelper` for flow type and further documentation. <add> */ <add> viewabilityConfig?: ViewabilityConfig, <add> /** <add> * List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged <add> * will be called when its corresponding ViewabilityConfig's conditions are met. <add> */ <add> viewabilityConfigCallbackPairs?: Array<ViewabilityConfigCallbackPair>, <add> /** <add> * Determines the maximum number of items rendered outside of the visible area, in units of <add> * visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will <add> * render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing <add> * this number will reduce memory consumption and may improve performance, but will increase the <add> * chance that fast scrolling may reveal momentary blank areas of unrendered content. <add> */ <add> windowSize?: ?number, <add> /** <add> * The legacy implementation is no longer supported. <add> */ <add> legacyImplementation?: empty, <add>|}; <add> <add>export type Props = {| <add> ...React.ElementConfig<ScrollView>, <add> ...RequiredProps, <add> ...OptionalProps, <add>|}; <ide><path>Libraries/Lists/VirtualizedList_EXPERIMENTAL.js <ide> <ide> import type {ScrollResponderType} from '../Components/ScrollView/ScrollView'; <ide> import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; <del>import type {LayoutEvent, ScrollEvent} from '../Types/CoreEventTypes'; <ide> import type { <del> ViewabilityConfig, <del> ViewabilityConfigCallbackPair, <del> ViewToken, <del>} from './ViewabilityHelper'; <add> FocusEvent, <add> LayoutEvent, <add> ScrollEvent, <add>} from '../Types/CoreEventTypes'; <add> <add>import type {ViewToken} from './ViewabilityHelper'; <add>import type { <add> Item, <add> Props, <add> RenderItemProps, <add> RenderItemType, <add> Separators, <add>} from './VirtualizedListProps'; <add>export type {RenderItemProps, RenderItemType, Separators}; <ide> <ide> import { <ide> type ChildListState, <ide> import { <ide> } from './VirtualizeUtils'; <ide> import * as React from 'react'; <ide> <del>import type {FocusEvent} from '../Types/CoreEventTypes'; <del> <ide> import {CellRenderMask} from './CellRenderMask'; <ide> import clamp from '../Utilities/clamp'; <ide> <ide> const invariant = require('invariant'); <ide> <ide> const ON_END_REACHED_EPSILON = 0.001; <ide> <del>type Item = any; <del> <del>export type Separators = { <del> highlight: () => void, <del> unhighlight: () => void, <del> updateProps: (select: 'leading' | 'trailing', newProps: Object) => void, <del> ... <del>}; <del> <del>export type RenderItemProps<ItemT> = { <del> item: ItemT, <del> index: number, <del> separators: Separators, <del> ... <del>}; <del> <del>export type RenderItemType<ItemT> = ( <del> info: RenderItemProps<ItemT>, <del>) => React.Node; <add>let _usedIndexForKey = false; <add>let _keylessItemComponentName: string = ''; <ide> <ide> type ViewabilityHelperCallbackTuple = { <ide> viewabilityHelper: ViewabilityHelper, <ide> type ViewabilityHelperCallbackTuple = { <ide> ... <ide> }; <ide> <del>type RequiredProps = {| <del> /** <del> * The default accessor functions assume this is an Array<{key: string} | {id: string}> but you can override <del> * getItem, getItemCount, and keyExtractor to handle any type of index-based data. <del> */ <del> data?: any, <del> /** <del> * A generic accessor for extracting an item from any sort of data blob. <del> */ <del> getItem: (data: any, index: number) => ?Item, <del> /** <del> * Determines how many items are in the data blob. <del> */ <del> getItemCount: (data: any) => number, <del>|}; <del>type OptionalProps = {| <del> renderItem?: ?RenderItemType<Item>, <del> /** <del> * `debug` will turn on extra logging and visual overlays to aid with debugging both usage and <del> * implementation, but with a significant perf hit. <del> */ <del> debug?: ?boolean, <del> /** <del> * DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully <del> * unmounts react instances that are outside of the render window. You should only need to disable <del> * this for debugging purposes. Defaults to false. <del> */ <del> disableVirtualization?: ?boolean, <del> /** <del> * A marker property for telling the list to re-render (since it implements `PureComponent`). If <del> * any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the <del> * `data` prop, stick it here and treat it immutably. <del> */ <del> extraData?: any, <del> // e.g. height, y <del> getItemLayout?: ( <del> data: any, <del> index: number, <del> ) => { <del> length: number, <del> offset: number, <del> index: number, <del> ... <del> }, <del> horizontal?: ?boolean, <del> /** <del> * How many items to render in the initial batch. This should be enough to fill the screen but not <del> * much more. Note these items will never be unmounted as part of the windowed rendering in order <del> * to improve perceived performance of scroll-to-top actions. <del> */ <del> initialNumToRender?: ?number, <del> /** <del> * Instead of starting at the top with the first item, start at `initialScrollIndex`. This <del> * disables the "scroll to top" optimization that keeps the first `initialNumToRender` items <del> * always rendered and immediately renders the items starting at this initial index. Requires <del> * `getItemLayout` to be implemented. <del> */ <del> initialScrollIndex?: ?number, <del> /** <del> * Reverses the direction of scroll. Uses scale transforms of -1. <del> */ <del> inverted?: ?boolean, <del> keyExtractor?: ?(item: Item, index: number) => string, <del> /** <del> * Each cell is rendered using this element. Can be a React Component Class, <del> * or a render function. Defaults to using View. <del> */ <del> CellRendererComponent?: ?React.ComponentType<any>, <del> /** <del> * Rendered in between each item, but not at the top or bottom. By default, `highlighted` and <del> * `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` <del> * which will update the `highlighted` prop, but you can also add custom props with <del> * `separators.updateProps`. <del> */ <del> ItemSeparatorComponent?: ?React.ComponentType<any>, <del> /** <del> * Takes an item from `data` and renders it into the list. Example usage: <del> * <del> * <FlatList <del> * ItemSeparatorComponent={Platform.OS !== 'android' && ({highlighted}) => ( <del> * <View style={[style.separator, highlighted && {marginLeft: 0}]} /> <del> * )} <del> * data={[{title: 'Title Text', key: 'item1'}]} <del> * ListItemComponent={({item, separators}) => ( <del> * <TouchableHighlight <del> * onPress={() => this._onPress(item)} <del> * onShowUnderlay={separators.highlight} <del> * onHideUnderlay={separators.unhighlight}> <del> * <View style={{backgroundColor: 'white'}}> <del> * <Text>{item.title}</Text> <del> * </View> <del> * </TouchableHighlight> <del> * )} <del> * /> <del> * <del> * Provides additional metadata like `index` if you need it, as well as a more generic <del> * `separators.updateProps` function which let's you set whatever props you want to change the <del> * rendering of either the leading separator or trailing separator in case the more common <del> * `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for <del> * your use-case. <del> */ <del> ListItemComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Rendered when the list is empty. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListEmptyComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Rendered at the bottom of all the items. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListFooterComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Styling for internal View for ListFooterComponent <del> */ <del> ListFooterComponentStyle?: ViewStyleProp, <del> /** <del> * Rendered at the top of all the items. Can be a React Component Class, a render function, or <del> * a rendered element. <del> */ <del> ListHeaderComponent?: ?(React.ComponentType<any> | React.Element<any>), <del> /** <del> * Styling for internal View for ListHeaderComponent <del> */ <del> ListHeaderComponentStyle?: ViewStyleProp, <del> /** <del> * A unique identifier for this list. If there are multiple VirtualizedLists at the same level of <del> * nesting within another VirtualizedList, this key is necessary for virtualization to <del> * work properly. <del> */ <del> listKey?: string, <del> /** <del> * The maximum number of items to render in each incremental render batch. The more rendered at <del> * once, the better the fill rate, but responsiveness may suffer because rendering content may <del> * interfere with responding to button taps or other interactions. <del> */ <del> maxToRenderPerBatch?: ?number, <del> /** <del> * Called once when the scroll position gets within `onEndReachedThreshold` of the rendered <del> * content. <del> */ <del> onEndReached?: ?(info: {distanceFromEnd: number, ...}) => void, <del> /** <del> * How far from the end (in units of visible length of the list) the bottom edge of the <del> * list must be from the end of the content to trigger the `onEndReached` callback. <del> * Thus a value of 0.5 will trigger `onEndReached` when the end of the content is <del> * within half the visible length of the list. A value of 0 will not trigger until scrolling <del> * to the very end of the list. <del> */ <del> onEndReachedThreshold?: ?number, <del> /** <del> * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make <del> * sure to also set the `refreshing` prop correctly. <del> */ <del> onRefresh?: ?() => void, <del> /** <del> * Used to handle failures when scrolling to an index that has not been measured yet. Recommended <del> * action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and <del> * then try again after more items have been rendered. <del> */ <del> onScrollToIndexFailed?: ?(info: { <del> index: number, <del> highestMeasuredFrameIndex: number, <del> averageItemLength: number, <del> ... <del> }) => void, <del> /** <del> * Called when the viewability of rows changes, as defined by the <del> * `viewabilityConfig` prop. <del> */ <del> onViewableItemsChanged?: ?(info: { <del> viewableItems: Array<ViewToken>, <del> changed: Array<ViewToken>, <del> ... <del> }) => void, <del> persistentScrollbar?: ?boolean, <del> /** <del> * Set this when offset is needed for the loading indicator to show correctly. <del> */ <del> progressViewOffset?: number, <del> /** <del> * A custom refresh control element. When set, it overrides the default <del> * <RefreshControl> component built internally. The onRefresh and refreshing <del> * props are also ignored. Only works for vertical VirtualizedList. <del> */ <del> refreshControl?: ?React.Element<any>, <del> /** <del> * Set this true while waiting for new data from a refresh. <del> */ <del> refreshing?: ?boolean, <del> /** <del> * Note: may have bugs (missing content) in some circumstances - use at your own risk. <del> * <del> * This may improve scroll performance for large lists. <del> */ <del> removeClippedSubviews?: boolean, <del> /** <del> * Render a custom scroll component, e.g. with a differently styled `RefreshControl`. <del> */ <del> renderScrollComponent?: (props: Object) => React.Element<any>, <del> /** <del> * Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off <del> * screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`. <del> */ <del> updateCellsBatchingPeriod?: ?number, <del> /** <del> * See `ViewabilityHelper` for flow type and further documentation. <del> */ <del> viewabilityConfig?: ViewabilityConfig, <del> /** <del> * List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged <del> * will be called when its corresponding ViewabilityConfig's conditions are met. <del> */ <del> viewabilityConfigCallbackPairs?: Array<ViewabilityConfigCallbackPair>, <del> /** <del> * Determines the maximum number of items rendered outside of the visible area, in units of <del> * visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will <del> * render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing <del> * this number will reduce memory consumption and may improve performance, but will increase the <del> * chance that fast scrolling may reveal momentary blank areas of unrendered content. <del> */ <del> windowSize?: ?number, <del> /** <del> * The legacy implementation is no longer supported. <del> */ <del> legacyImplementation?: empty, <del>|}; <del> <del>export type Props = {| <del> ...React.ElementConfig<typeof ScrollView>, <del> ...RequiredProps, <del> ...OptionalProps, <del>|}; <del> <del>let _usedIndexForKey = false; <del>let _keylessItemComponentName: string = ''; <del> <ide> type State = { <ide> renderMask: CellRenderMask, <ide> cellsAroundViewport: {first: number, last: number},
4
Ruby
Ruby
use predicate method and eliminate local
9321873eef1c895b8d0fae23069dcfcf291f9a40
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> <ide> @time = Time.now - start_time <ide> <del> success = $?.success? <del> @status = success ? :passed : :failed <add> @status = $?.success? ? :passed : :failed <ide> puts_result <ide> <ide> if File.exist?(log) <ide> @output = File.read(log) <del> if has_output? and (not success or @puts_output_on_success) <add> if has_output? and (failed? or @puts_output_on_success) <ide> puts @output <ide> end <ide> FileUtils.rm(log) unless ARGV.include? "--keep-logs"
1
Python
Python
fix bidirectional regularization
b076e227da6beaf87d6c84eff1a92285e4662acf
<ide><path>keras/layers/wrappers.py <ide> def updates(self): <ide> return self.forward_layer.updates + self.backward_layer.updates <ide> return [] <ide> <add> def get_updates_for(self, inputs=None): <add> forward_updates = self.forward_layer.get_updates_for(inputs) <add> backward_updates = self.backward_layer.get_updates_for(inputs) <add> return (super(Wrapper, self).get_updates_for(inputs) + <add> forward_updates + backward_updates) <add> <ide> @property <ide> def losses(self): <ide> if hasattr(self.forward_layer, 'losses'): <ide> return self.forward_layer.losses + self.backward_layer.losses <ide> return [] <ide> <add> def get_losses_for(self, inputs=None): <add> forward_losses = self.forward_layer.get_losses_for(inputs) <add> backward_losses = self.backward_layer.get_losses_for(inputs) <add> return (super(Wrapper, self).get_losses_for(inputs) + <add> forward_losses + backward_losses) <add> <ide> @property <ide> def constraints(self): <ide> constraints = {} <ide><path>tests/keras/layers/wrappers_test.py <ide> def test_Bidirectional_trainable(): <ide> assert len(layer.trainable_weights) == 6 <ide> <ide> <add>@keras_test <add>def test_Bidirectional_updates(): <add> x = Input(shape=(3, 2)) <add> layer = wrappers.Bidirectional(layers.SimpleRNN(3)) <add> assert len(layer.updates) == 0 <add> assert len(layer.get_updates_for(None)) == 0 <add> assert len(layer.get_updates_for(x)) == 0 <add> layer.forward_layer.add_update(0, inputs=x) <add> layer.forward_layer.add_update(1, inputs=None) <add> layer.backward_layer.add_update(0, inputs=x) <add> layer.backward_layer.add_update(1, inputs=None) <add> assert len(layer.updates) == 4 <add> assert len(layer.get_updates_for(None)) == 2 <add> assert len(layer.get_updates_for(x)) == 2 <add> <add> <add>@keras_test <add>def test_Bidirectional_losses(): <add> x = Input(shape=(3, 2)) <add> layer = wrappers.Bidirectional( <add> layers.SimpleRNN(3, kernel_regularizer='l1', bias_regularizer='l1')) <add> _ = layer(x) <add> assert len(layer.losses) == 4 <add> assert len(layer.get_losses_for(None)) == 4 <add> assert len(layer.get_losses_for(x)) == 0 <add> layer.forward_layer.add_loss(0, inputs=x) <add> layer.forward_layer.add_loss(1, inputs=None) <add> layer.backward_layer.add_loss(0, inputs=x) <add> layer.backward_layer.add_loss(1, inputs=None) <add> assert len(layer.losses) == 8 <add> assert len(layer.get_losses_for(None)) == 6 <add> assert len(layer.get_losses_for(x)) == 2 <add> <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
2
Text
Text
fix typos in layer writing guide
fc470db7ab915d0e5f8be46c095937b297296fbb
<ide><path>docs/templates/layers/writing-your-own-keras-layers.md <ide> Here is the skeleton of a Keras layer. There are only three methods you need to <ide> ```python <ide> from keras import backend as K <ide> from keras.engine.topology import Layer <add>import numpy as np <ide> <ide> class MyLayer(Layer): <ide> def __init__(self, output_dim, **kwargs): <ide> class MyLayer(Layer): <ide> return K.dot(x, self.W) <ide> <ide> def get_output_shape_for(self, input_shape): <del> return (input_shape[0] + self.output_dim) <add> return (input_shape[0], self.output_dim) <ide> ``` <ide> <ide> The existing Keras layers provide ample examples of how to implement almost anything. Never hesitate to read the source code! <ide>\ No newline at end of file
1
Javascript
Javascript
remove android `settimeout` warning
480dabd66547a60522249eda203a3eb1934b02e5
<ide><path>Libraries/Core/Timers/JSTimers.js <ide> 'use strict'; <ide> <ide> const BatchedBridge = require('../../BatchedBridge/BatchedBridge'); <del>const Platform = require('../../Utilities/Platform'); <ide> const Systrace = require('../../Performance/Systrace'); <ide> <ide> const invariant = require('invariant'); <ide> export type JSTimerType = <ide> const FRAME_DURATION = 1000 / 60; <ide> const IDLE_CALLBACK_FRAME_DEADLINE = 1; <ide> <del>const MAX_TIMER_DURATION_MS = 60 * 1000; <del>const IS_ANDROID = Platform.OS === 'android'; <del>const ANDROID_LONG_TIMER_MESSAGE = <del> 'Setting a timer for a long period of time, i.e. multiple minutes, is a ' + <del> 'performance and correctness issue on Android as it keeps the timer ' + <del> 'module awake, and timers can only be called when the app is in the foreground. ' + <del> 'See https://github.com/facebook/react-native/issues/12981 for more info.'; <del> <ide> // Parallel arrays <ide> const callbacks: Array<?Function> = []; <ide> const types: Array<?JSTimerType> = []; <ide> const JSTimers = { <ide> * @param {number} duration Number of milliseconds. <ide> */ <ide> setTimeout: function(func: Function, duration: number, ...args: any): number { <del> if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) { <del> console.warn( <del> ANDROID_LONG_TIMER_MESSAGE + <del> '\n' + <del> '(Saw setTimeout with duration ' + <del> duration + <del> 'ms)', <del> ); <del> } <ide> const id = _allocateCallback( <ide> () => func.apply(undefined, args), <ide> 'setTimeout', <ide> const JSTimers = { <ide> duration: number, <ide> ...args: any <ide> ): number { <del> if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) { <del> console.warn( <del> ANDROID_LONG_TIMER_MESSAGE + <del> '\n' + <del> '(Saw setInterval with duration ' + <del> duration + <del> 'ms)', <del> ); <del> } <ide> const id = _allocateCallback( <ide> () => func.apply(undefined, args), <ide> 'setInterval',
1
PHP
PHP
apply fixes from styleci
feec50bc19f7861ac9792ccb04bdc9d4d7d46468
<ide><path>src/Illuminate/Cache/Repository.php <ide> use Illuminate\Contracts\Cache\Repository as CacheContract; <ide> <ide> /** <del> * @mixin \Illuminate\Contracts\Cache\Store <add> * @mixin \Illuminate\Contracts\Cache\Store <ide> */ <ide> class Repository implements CacheContract, ArrayAccess <ide> {
1
Ruby
Ruby
expand help and help-related tests
b53f0c5ada753d5ded6f6fbe4f920a4a43696394
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> def test_repository <ide> end <ide> <ide> def test_help <del> assert_match "Example usage:", <del> cmd("help") <add> assert_match "Example usage:\n", <add> cmd_fail # Generic help (empty argument list). <add> assert_match "Unknown command: command-that-does-not-exist", <add> cmd_fail("help", "command-that-does-not-exist") <add> assert_match(/^brew cat /, <add> cmd_fail("cat")) # Missing formula argument triggers help. <add> <add> assert_match "Example usage:\n", <add> cmd("help") # Generic help. <add> assert_match(/^brew cat /, <add> cmd("help", "cat")) # Internal command (documented, Ruby). <add> assert_match(/^brew update /, <add> cmd("help", "update")) # Internal command (documented, Shell). <add> assert_match "Example usage:\n", <add> cmd("help", "test-bot") # Internal command (undocumented). <ide> end <ide> <ide> def test_config
1
Javascript
Javascript
fix typo in comment (environement → environment)
0706162ba7dff8aeb4bf824473f423946c0168c9
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> return updateLane; <ide> } <ide> <del> // This update originated outside React. Ask the host environement for an <add> // This update originated outside React. Ask the host environment for an <ide> // appropriate priority, based on the type of event. <ide> // <ide> // The opaque type returned by the host config is internally a lane, so we can <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> return updateLane; <ide> } <ide> <del> // This update originated outside React. Ask the host environement for an <add> // This update originated outside React. Ask the host environment for an <ide> // appropriate priority, based on the type of event. <ide> // <ide> // The opaque type returned by the host config is internally a lane, so we can
2
Go
Go
use vt100 escape codes
f1dd299227b15696872822f40a4ab9f1a54098a7
<ide><path>commands.go <ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e <ide> } <ide> <ide> if resp.Header.Get("Content-Type") == "application/json" { <del> dec := json.NewDecoder(resp.Body) <del> jm := utils.JSONMessage{} <del> for { <del> if err := dec.Decode(&jm); err == io.EOF { <del> break <del> } else if err != nil { <del> return err <del> } <del> jm.Display(out) <del> } <del> if jm.Progress != "" { <del> fmt.Fprintf(out, "\n") <del> } <add> utils.DisplayJSONMessagesStream(resp.Body, out) <ide> } else { <ide> if _, err := io.Copy(out, resp.Body); err != nil { <ide> return err <ide><path>utils/utils.go <ide> func (jm *JSONMessage) Display(out io.Writer) (error) { <ide> if jm.Error != "" { <ide> return fmt.Errorf(jm.Error) <ide> } <add> fmt.Fprintf(out, "%c[2K", 27) <ide> if jm.Time != 0 { <ide> fmt.Fprintf(out, "[%s] ", time.Unix(jm.Time, 0)) <ide> } <ide> func (jm *JSONMessage) Display(out io.Writer) (error) { <ide> if jm.Progress != "" { <ide> fmt.Fprintf(out, "%s %s\r", jm.Status, jm.Progress) <ide> } else { <del> fmt.Fprintf(out, "%s\n", jm.Status) <add> fmt.Fprintf(out, "%s\r", jm.Status) <ide> } <add> if jm.ID == "" { <add> fmt.Fprintf(out, "\n") <add> } <add> return nil <add>} <add> <add>func DisplayJSONMessagesStream(in io.Reader, out io.Writer) error { <add> dec := json.NewDecoder(in) <add> jm := JSONMessage{} <add> ids := make(map[string]int) <add> diff := 0 <add> for { <add> if err := dec.Decode(&jm); err == io.EOF { <add> break <add> } else if err != nil { <add> return err <add> } <add> if jm.ID != "" { <add> line, ok := ids[jm.ID] <add> if !ok { <add> line = len(ids) <add> ids[jm.ID] = line <add> fmt.Fprintf(out, "\n") <add> diff = 0 <add> } else { <add> diff = len(ids) - line <add> } <add> fmt.Fprintf(out, "%c[%dA", 27, diff) <add> } <add> jm.Display(out) <add> if jm.ID != "" { <add> fmt.Fprintf(out, "%c[%dB", 27, diff) <add> } <add> } <add>// fmt.Fprintf(out, "\n") <ide> return nil <ide> } <ide>
2
Javascript
Javascript
fix error 500
21605a5f9fadcfbca28c0906127382c5ecf40b77
<ide><path>examples/with-deta-base/pages/api/todos/index.js <ide> const handler = async (req, res) => { <ide> let respBody = {} <ide> <ide> if (method === 'GET') { <del> const { value: items } = await base.fetch([]).next() <add> const { items } = await base.fetch([]) <ide> respBody = items <ide> res.statusCode = 200 <ide> } else if (method === 'POST') {
1
Ruby
Ruby
allow specifying committer for some `dev-cmd`s
59dae75709bb27c704ec7834779aa8c0f045d5b2
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_args <ide> switch "--only-json-tab", <ide> depends_on: "--json", <ide> description: "When passed with `--json`, the tab will be written to the JSON file but not the bottle." <add> flag "--committer=", <add> description: "Specify a committer name and email in `git`'s standard author format." <ide> flag "--root-url=", <ide> description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default." <ide> <ide> def merge(args:) <ide> path.atomic_write(formula_ast.process) <ide> <ide> unless args.no_commit? <del> Utils::Git.set_name_email! <add> Utils::Git.set_name_email!(committer: args.committer.blank?) <ide> Utils::Git.setup_gpg! <ide> <add> if (committer = args.committer) <add> committer = Utils.parse_author!(committer) <add> ENV["GIT_COMMITTER_NAME"] = committer[:name] <add> ENV["GIT_COMMITTER_EMAIL"] = committer[:email] <add> end <add> <ide> short_name = formula_name.split("/", -1).last <ide> pkg_version = bottle_hash["formula"]["pkg_version"] <ide> <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb <ide> def pr_pull_args <ide> switch "--warn-on-upload-failure", <ide> description: "Warn instead of raising an error if the bottle upload fails. "\ <ide> "Useful for repairing bottle uploads that previously failed." <add> flag "--committer=", <add> description: "Specify a committer name and email in `git`'s standard author format." <ide> flag "--message=", <ide> depends_on: "--autosquash", <ide> description: "Message to include when autosquashing revision bumps, deletions, and rebuilds." <ide> def pr_pull <ide> mirror_repo = args.bintray_mirror || "mirror" <ide> tap = Tap.fetch(args.tap || CoreTap.instance.name) <ide> <del> Utils::Git.set_name_email! <add> Utils::Git.set_name_email!(committer: args.committer.blank?) <ide> Utils::Git.setup_gpg! <ide> <add> if (committer = args.committer) <add> committer = Utils.parse_author!(committer) <add> ENV["GIT_COMMITTER_NAME"] = committer[:name] <add> ENV["GIT_COMMITTER_EMAIL"] = committer[:email] <add> end <add> <ide> args.named.uniq.each do |arg| <ide> arg = "#{tap.default_remote}/pull/#{arg}" if arg.to_i.positive? <ide> url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX <ide><path>Library/Homebrew/dev-cmd/pr-upload.rb <ide> def pr_upload_args <ide> switch "--warn-on-upload-failure", <ide> description: "Warn instead of raising an error if the bottle upload fails. "\ <ide> "Useful for repairing bottle uploads that previously failed." <add> flag "--committer=", <add> description: "Specify a committer name and email in `git`'s standard author format." <ide> flag "--archive-item=", <ide> description: "Upload to the specified Internet Archive item (default: `homebrew`)." <ide> flag "--bintray-org=", <ide> def pr_upload <ide> bottle_args << "--debug" if args.debug? <ide> bottle_args << "--keep-old" if args.keep_old? <ide> bottle_args << "--root-url=#{args.root_url}" if args.root_url <add> bottle_args << "--committer='#{args.committer}'" if args.committer <ide> bottle_args << "--no-commit" if args.no_commit? <ide> bottle_args += json_files <ide> <ide><path>Library/Homebrew/test/utils_spec.rb <ide> def esc(code) <ide> end <ide> end <ide> <add> specify "#parse_author!" do <add> parse_error_msg = /Unable to parse name and email/ <add> <add> expect(parse_author!("John Doe <john.doe@example.com>")) <add> .to eq({ name: "John Doe", email: "john.doe@example.com" }) <add> expect { parse_author!("") } <add> .to raise_error(parse_error_msg) <add> expect { parse_author!("John Doe") } <add> .to raise_error(parse_error_msg) <add> expect { parse_author!("<john.doe@example.com>") } <add> .to raise_error(parse_error_msg) <add> end <add> <ide> specify "#disk_usage_readable" do <ide> expect(disk_usage_readable(1)).to eq("1B") <ide> expect(disk_usage_readable(1000)).to eq("1000B") <ide><path>Library/Homebrew/utils.rb <ide> def paths <ide> end.uniq.compact <ide> end <ide> <add> def parse_author!(author) <add> /^(?<name>[^<]+?)[ \t]*<(?<email>[^>]+?)>$/ =~ author <add> raise "Unable to parse name and email." if name.blank? && email.blank? <add> <add> { name: name, email: email } <add> end <add> <ide> def disk_usage_readable(size_in_bytes) <ide> if size_in_bytes >= 1_073_741_824 <ide> size = size_in_bytes.to_f / 1_073_741_824
5
PHP
PHP
use tabs, always
6abdb1574dfc770d44083910c5f2d5147ad04595
<ide><path>app/Http/Filters/AuthFilter.php <ide> <ide> class AuthFilter { <ide> <del> /** <del> * The authenticator implementation. <del> * <del> * @var Authenticator <del> */ <del> protected $auth; <add> /** <add> * The authenticator implementation. <add> * <add> * @var Authenticator <add> */ <add> protected $auth; <ide> <del> /** <del> * The response factory implementation. <del> * <del> * @var ResponseFactory <del> */ <del> protected $response; <add> /** <add> * The response factory implementation. <add> * <add> * @var ResponseFactory <add> */ <add> protected $response; <ide> <del> /** <del> * Create a new filter instance. <del> * <del> * @param Authenticator $auth <del> * @param ResponseFactory $response <del> * @return void <del> */ <del> public function __construct(Authenticator $auth, <del> ResponseFactory $response) <del> { <del> $this->auth = $auth; <del> $this->response = $response; <del> } <add> /** <add> * Create a new filter instance. <add> * <add> * @param Authenticator $auth <add> * @param ResponseFactory $response <add> * @return void <add> */ <add> public function __construct(Authenticator $auth, <add> ResponseFactory $response) <add> { <add> $this->auth = $auth; <add> $this->response = $response; <add> } <ide> <del> /** <del> * Run the request filter. <del> * <del> * @param \Illuminate\Routing\Route $route <del> * @param \Illuminate\Http\Request $request <del> * @return mixed <del> */ <del> public function filter(Route $route, Request $request) <del> { <del> if ($this->auth->guest()) <del> { <del> if ($request->ajax()) <del> { <del> return $this->response->make('Unauthorized', 401); <del> } <del> else <del> { <del> return $this->response->redirectGuest('auth/login'); <del> } <del> } <del> } <add> /** <add> * Run the request filter. <add> * <add> * @param \Illuminate\Routing\Route $route <add> * @param \Illuminate\Http\Request $request <add> * @return mixed <add> */ <add> public function filter(Route $route, Request $request) <add> { <add> if ($this->auth->guest()) <add> { <add> if ($request->ajax()) <add> { <add> return $this->response->make('Unauthorized', 401); <add> } <add> else <add> { <add> return $this->response->redirectGuest('auth/login'); <add> } <add> } <add> } <ide> <ide> } <ide><path>app/Http/Filters/GuestFilter.php <ide> class GuestFilter { <ide> */ <ide> protected $auth; <ide> <del> /** <del> * The response factory implementation. <del> * <del> * @var ResponseFactory <del> */ <del> protected $response; <add> /** <add> * The response factory implementation. <add> * <add> * @var ResponseFactory <add> */ <add> protected $response; <ide> <ide> /** <ide> * Create a new filter instance. <ide> class GuestFilter { <ide> * @return void <ide> */ <ide> public function __construct(Authenticator $auth, <del> ResponseFacotry $response) <add> ResponseFacotry $response) <ide> { <ide> $this->auth = $auth; <ide> $this->response = $response; <ide><path>app/Http/Filters/MaintenanceFilter.php <ide> class MaintenanceFilter { <ide> */ <ide> protected $app; <ide> <del> /** <del> * The response factory implementation. <del> * <del> * @var ResponseFactory <del> */ <del> protected $response; <add> /** <add> * The response factory implementation. <add> * <add> * @var ResponseFactory <add> */ <add> protected $response; <ide> <ide> /** <ide> * Create a new filter instance.
3
Python
Python
make a nested if flat
0d64b4a704eed2fb483de66a7e7271ac83144530
<ide><path>djangorestframework/serializer.py <ide> def serialize_model(self, instance): <ide> # serialize each required field <ide> for fname in fields: <ide> try: <del> if hasattr(self, smart_str(fname)): <add> if inspect.ismethod(getattr(self, fname, None)) and \ <add> len(inspect.getargspec(getattr(self, fname))[0]) == 2: <ide> # check first for a method 'fname' on self first <del> meth = getattr(self, fname) <del> if inspect.ismethod(meth) and len(inspect.getargspec(meth)[0]) == 2: <del> obj = meth(instance) <add> obj = meth(instance) <ide> elif hasattr(instance, '__contains__') and fname in instance: <ide> # check for a key 'fname' on the instance <ide> obj = instance[fname]
1
Javascript
Javascript
add tests, better tostring
56e44601d285483ffe3c6efa3b80743900d84856
<ide><path>lib/internal/event_target.js <ide> class EventTarget { <ide> <ide> return `${name} ${inspect({}, opts)}`; <ide> } <add> get [Symbol.toStringTag]() { return 'EventTarget'; } <ide> } <ide> <ide> Object.defineProperties(EventTarget.prototype, { <ide><path>test/parallel/test-eventtarget.js <ide> ok(EventTarget); <ide> eventTarget.removeEventListener('foo', ev1); <ide> eventTarget.dispatchEvent(new Event('foo')); <ide> } <del> <add>{ <add> // event subclassing <add> const SubEvent = class extends Event {}; <add> const ev = new SubEvent('foo'); <add> const eventTarget = new EventTarget(); <add> const fn = common.mustCall((event) => strictEqual(event, ev)); <add> eventTarget.addEventListener('foo', fn, { once: true }); <add> eventTarget.dispatchEvent(ev); <add>} <ide> { <ide> const eventTarget = new NodeEventTarget(); <ide> strictEqual(eventTarget.listenerCount('foo'), 0); <ide> ok(EventTarget); <ide> target.removeEventListener('foo', a, { capture: false }); <ide> target.dispatchEvent(new Event('foo')); <ide> } <add> <add>{ <add> const target = new EventTarget(); <add> strictEqual(target.toString(), '[object EventTarget]'); <add> const event = new Event(); <add> strictEqual(event.toString(), '[object Event]'); <add>}
2
Text
Text
add a bundlefile example in the documentation
e68a4b18e9808c8fcd56c8f779e7bf97e07ddfe6
<ide><path>experimental/docker-stacks-and-bundles.md <ide> A service has the following fields: <ide> </dd> <ide> </dl> <ide> <add>The following is an example of bundlefile with two services: <add> <add>```json <add>{ <add> "Version": "0.1", <add> "Services": { <add> "redis": { <add> "Image": "redis@sha256:4b24131101fa0117bcaa18ac37055fffd9176aa1a240392bb8ea85e0be50f2ce", <add> "Networks": ["default"] <add> }, <add> "web": { <add> "Image": "dockercloud/hello-world@sha256:fe79a2cfbd17eefc344fb8419420808df95a1e22d93b7f621a7399fd1e9dca1d", <add> "Networks": ["default"], <add> "User": "web" <add> } <add> } <add>} <add>```
1
Go
Go
normalize comment formatting
d29f420424db6ffe1bd16f6155d01d88caed85fd
<ide><path>libcontainerd/local/local_windows.go <ide> func (c *client) Version(ctx context.Context) (containerd.Version, error) { <ide> // Isolation=Process example: <ide> // <ide> // { <del>// "SystemType": "Container", <del>// "Name": "5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776", <del>// "Owner": "docker", <del>// "VolumePath": "\\\\\\\\?\\\\Volume{66d1ef4c-7a00-11e6-8948-00155ddbef9d}", <del>// "IgnoreFlushesDuringBoot": true, <del>// "LayerFolderPath": "C:\\\\control\\\\windowsfilter\\\\5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776", <del>// "Layers": [{ <del>// "ID": "18955d65-d45a-557b-bf1c-49d6dfefc526", <del>// "Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c" <del>// }], <del>// "HostName": "5e0055c814a6", <del>// "MappedDirectories": [], <del>// "HvPartition": false, <del>// "EndpointList": ["eef2649d-bb17-4d53-9937-295a8efe6f2c"], <del>//} <add>// "SystemType": "Container", <add>// "Name": "5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776", <add>// "Owner": "docker", <add>// "VolumePath": "\\\\\\\\?\\\\Volume{66d1ef4c-7a00-11e6-8948-00155ddbef9d}", <add>// "IgnoreFlushesDuringBoot": true, <add>// "LayerFolderPath": "C:\\\\control\\\\windowsfilter\\\\5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776", <add>// "Layers": [{ <add>// "ID": "18955d65-d45a-557b-bf1c-49d6dfefc526", <add>// "Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c" <add>// }], <add>// "HostName": "5e0055c814a6", <add>// "MappedDirectories": [], <add>// "HvPartition": false, <add>// "EndpointList": ["eef2649d-bb17-4d53-9937-295a8efe6f2c"], <add>// } <ide> // <ide> // Isolation=Hyper-V example: <ide> // <del>//{ <del>// "SystemType": "Container", <del>// "Name": "475c2c58933b72687a88a441e7e0ca4bd72d76413c5f9d5031fee83b98f6045d", <del>// "Owner": "docker", <del>// "IgnoreFlushesDuringBoot": true, <del>// "Layers": [{ <del>// "ID": "18955d65-d45a-557b-bf1c-49d6dfefc526", <del>// "Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c" <del>// }], <del>// "HostName": "475c2c58933b", <del>// "MappedDirectories": [], <del>// "HvPartition": true, <del>// "EndpointList": ["e1bb1e61-d56f-405e-b75d-fd520cefa0cb"], <del>// "DNSSearchList": "a.com,b.com,c.com", <del>// "HvRuntime": { <del>// "ImagePath": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c\\\\UtilityVM" <del>// }, <del>//} <add>// { <add>// "SystemType": "Container", <add>// "Name": "475c2c58933b72687a88a441e7e0ca4bd72d76413c5f9d5031fee83b98f6045d", <add>// "Owner": "docker", <add>// "IgnoreFlushesDuringBoot": true, <add>// "Layers": [{ <add>// "ID": "18955d65-d45a-557b-bf1c-49d6dfefc526", <add>// "Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c" <add>// }], <add>// "HostName": "475c2c58933b", <add>// "MappedDirectories": [], <add>// "HvPartition": true, <add>// "EndpointList": ["e1bb1e61-d56f-405e-b75d-fd520cefa0cb"], <add>// "DNSSearchList": "a.com,b.com,c.com", <add>// "HvRuntime": { <add>// "ImagePath": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c\\\\UtilityVM" <add>// }, <add>// } <ide> func (c *client) Create(_ context.Context, id string, spec *specs.Spec, runtimeOptions interface{}, opts ...containerd.NewContainerOpts) error { <ide> if ctr := c.getContainer(id); ctr != nil { <ide> return errors.WithStack(errdefs.Conflict(errors.New("id already in use"))) <ide><path>libcontainerd/queue/queue_test.go <ide> func TestSerialization(t *testing.T) { <ide> ) <ide> <ide> q.Append("aaa", func() { <del> //simulate a long time task <add> // simulate a long time task <ide> time.Sleep(10 * time.Millisecond) <ide> assert.Equal(t, serialization, 1) <ide> serialization = 2
2
Go
Go
return weird behaviour of returning json errors
ec51ba01dbbeadb06cc7f3c14e94f8a2ee938a34
<ide><path>api/server/server.go <ide> func (s *Server) postImagesPush(eng *engine.Engine, version version.Version, w h <ide> useJSON := version.GreaterThan("1.0") <ide> name := vars["name"] <ide> <add> output := utils.NewWriteFlusher(w) <ide> imagePushConfig := &graph.ImagePushConfig{ <ide> MetaHeaders: metaHeaders, <ide> AuthConfig: authConfig, <ide> Tag: r.Form.Get("tag"), <del> OutStream: utils.NewWriteFlusher(w), <add> OutStream: output, <ide> Json: useJSON, <ide> } <ide> if useJSON { <ide> w.Header().Set("Content-Type", "application/json") <ide> } <ide> <ide> if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil { <add> if !output.Flushed() { <add> return err <add> } <ide> sf := streamformatter.NewStreamFormatter(useJSON) <del> return fmt.Errorf(string(sf.FormatError(err))) <add> output.Write(sf.FormatError(err)) <ide> } <ide> return nil <ide>
1
Mixed
Ruby
improve documentation of `load_async`
718059ed9d4198591391818348c8fda68154c7fb
<ide><path>activerecord/lib/active_record/relation.rb <ide> def delete_by(*args) <ide> # Schedule the query to be performed from a background thread pool. <ide> # <ide> # Post.where(published: true).load_async # => #<ActiveRecord::Relation> <add> # <add> # When the +Relation+ is iterated, if the background query wasn't executed yet, <add> # it will be performed by the foreground thread. <add> # <add> # Note that {config.active_record.async_query_executor}[https://guides.rubyonrails.org/configuring.html#config-active-record-async-query-executor] must be configured <add> # for queries to actually be executed concurrently. Otherwise it defaults to <add> # executing them in the foreground. <add> # <add> # +load_async+ will also fallback to executing in the foreground in the test environment when transactional <add> # fixtures are enabled. <add> # <add> # If the query was actually executed in the background, the Active Record logs will show <add> # it by prefixing the log line with <tt>ASYNC</tt>: <add> # <add> # ASYNC Post Load (0.0ms) (db time 2ms) SELECT "posts".* FROM "posts" LIMIT 100 <ide> def load_async <ide> return load if !connection.async_enabled? <ide> <ide><path>guides/source/configuring.md <ide> regular expressions. <ide> <ide> Specifies if source locations of methods that call database queries should be logged below relevant queries. By default, the flag is `true` in development and `false` in all other environments. <ide> <add>#### `config.active_record.async_query_executor` <add> <add>Specifies how asynchronous queries are pooled. <add> <add>It defaults to `nil`, which means `load_async` is disabled and instead directly executes queries in the foreground. <add>For queries to actually be performed asynchronously, it must be set to either `:global_thread_pool` or `:multi_thread_pool`. <add> <add>`:global_thread_pool` will use a single pool for all databases the application connects to. This is the preferred configuration <add>for applications with only a single database, or applications which only ever query one database shard at a time. <add> <add>`:multi_thread_pool` will use one pool per database, and each pool size can be configured individually in `database.yml` through the <add>`max_threads` and `min_thread` properties. This can be useful to applications regularly querying multiple databases at a time, and that need to more precisely define the max concurrency. <add> <add>#### `config.active_record.global_executor_concurrency` <add> <add>Used in conjunction with `config.active_record.async_query_executor = :global_thread_pool`, defines how many asynchronous <add>queries can be executed concurrently. <add> <add>Defaults to `4`. <add> <add>This number must be considered in accordance with the database pool size configured in `database.yml`. The connection pool <add>should be large enough to accommodate both the foreground threads (.e.g web server or job worker threads) and background threads. <add> <ide> #### `ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans` <ide> <ide> Controls whether the Active Record MySQL adapter will consider all `tinyint(1)` columns as booleans. Defaults to `true`.
2
Text
Text
fix typo in collaborator_guide.md
59f71ea4ddf081b55f50334158c25ea19808b3d6
<ide><path>COLLABORATOR_GUIDE.md <ide> LTS working group and the Release team. <ide> | `lib/domains` | @nodejs/domains | <ide> | `lib/fs`, `src/{fs,file}` | @nodejs/fs | <ide> | `lib/{_}http{*}` | @nodejs/http | <del>| `lib/inspector.js`, `src/inspector_*` | @nodejs/V8-inspector | <add>| `lib/inspector.js`, `src/inspector_*` | @nodejs/v8-inspector | <ide> | `lib/internal/bootstrap/*` | @nodejs/process | <ide> | `lib/internal/url`, `src/node_url` | @nodejs/url | <ide> | `lib/net` | @bnoordhuis, @indutny, @nodejs/streams |
1
PHP
PHP
replace more mocks with concrete classes
ec64c1be8824b385a3dba594027a8537979f7f59
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> class ErrorHandlerTest extends TestCase <ide> protected $_restoreError = false; <ide> <ide> /** <del> * @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject <add> * @var \Cake\Log\Engine\ArrayLog <ide> */ <del> protected $_logger; <add> protected $logger; <ide> <ide> /** <ide> * error level property <del> * <ide> */ <ide> private static $errorLevel; <ide> <ide> public function setUp(): void <ide> Router::setRequest($request); <ide> Configure::write('debug', true); <ide> <del> $this->_logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); <del> <ide> Log::reset(); <del> Log::setConfig('error_test', [ <del> 'engine' => $this->_logger, <del> ]); <add> Log::setConfig('error_test', ['className' => 'Array']); <add> $this->logger = Log::engine('error_test'); <ide> } <ide> <ide> /** <ide> public function testHandleErrorDebugOff() <ide> $errorHandler->register(); <ide> $this->_restoreError = true; <ide> <del> $this->_logger->expects($this->once()) <del> ->method('log') <del> ->with( <del> $this->matchesRegularExpression('(notice|debug)'), <del> 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n" <del> ); <del> <ide> $out = $out + 1; <add> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString( <add> 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 4) . ']' . "\n\n", <add> $messages[0] <add> ); <ide> } <ide> <ide> /** <ide> public function testHandleErrorLoggingTrace() <ide> $errorHandler->register(); <ide> $this->_restoreError = true; <ide> <del> $this->_logger->expects($this->once()) <del> ->method('log') <del> ->with( <del> $this->matchesRegularExpression('(notice|debug)'), <del> $this->logicalAnd( <del> $this->stringContains('Notice (8): Undefined variable: out in '), <del> $this->stringContains('Trace:'), <del> $this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()'), <del> $this->stringContains('Request URL:'), <del> $this->stringContains('Referer URL:') <del> ) <del> ); <del> <ide> $out = $out + 1; <add> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString( <add> 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 4) . ']', <add> $messages[0] <add> ); <add> $this->assertStringContainsString('Trace:', $messages[0]); <add> $this->assertStringContainsString(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()', $messages[0]); <add> $this->assertStringContainsString('Request URL:', $messages[0]); <add> $this->assertStringContainsString('Referer URL:', $messages[0]); <ide> } <ide> <ide> /** <ide> public function testHandleExceptionLog() <ide> ]); <ide> <ide> $error = new NotFoundException('Kaboom!'); <del> <del> $this->_logger->expects($this->at(0)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'), <del> $this->stringContains(str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php')) <del> )); <del> <del> $this->_logger->expects($this->at(1)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'), <del> $this->logicalNot($this->stringContains(str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'))) <del> )); <del> <ide> $errorHandler->handleException($error); <ide> $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.'); <ide> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[0]); <add> $this->assertStringContainsString( <add> str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'), <add> $messages[0] <add> ); <add> <ide> $errorHandler = new TestErrorHandler([ <ide> 'log' => true, <ide> 'trace' => false, <ide> ]); <ide> $errorHandler->handleException($error); <add> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[1]); <add> $this->assertStringNotContainsString( <add> str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'), <add> $messages[1] <add> ); <ide> } <ide> <ide> /** <ide> public function testHandleExceptionLogAttributes() <ide> ]); <ide> <ide> $error = new MissingControllerException(['class' => 'Derp']); <del> <del> $this->_logger->expects($this->at(0)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains( <del> '[Cake\Http\Exception\MissingControllerException] ' . <del> 'Controller class Derp could not be found.' <del> ), <del> $this->stringContains('Exception Attributes:'), <del> $this->stringContains('Request URL:'), <del> $this->stringContains('Referer URL:') <del> )); <del> <del> $this->_logger->expects($this->at(1)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains( <del> '[Cake\Http\Exception\MissingControllerException] ' . <del> 'Controller class Derp could not be found.' <del> ), <del> $this->logicalNot($this->stringContains('Exception Attributes:')) <del> )); <ide> $errorHandler->handleException($error); <ide> <ide> Configure::write('debug', false); <ide> $errorHandler->handleException($error); <add> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString( <add> '[Cake\Http\Exception\MissingControllerException] Controller class Derp could not be found.', <add> $messages[0] <add> ); <add> $this->assertStringContainsString('Exception Attributes:', $messages[0]); <add> $this->assertStringContainsString('Request URL:', $messages[0]); <add> $this->assertStringContainsString('Referer URL:', $messages[0]); <add> <add> $this->assertStringContainsString( <add> '[Cake\Http\Exception\MissingControllerException] Controller class Derp could not be found.', <add> $messages[1] <add> ); <add> $this->assertStringNotContainsString('Exception Attributes:', $messages[1]); <ide> } <ide> <ide> /** <ide> public function testHandleExceptionLogPrevious() <ide> <ide> $previous = new RecordNotFoundException('Previous logged'); <ide> $error = new NotFoundException('Kaboom!', null, $previous); <del> <del> $this->_logger->expects($this->at(0)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains('[Cake\Http\Exception\NotFoundException] Kaboom!'), <del> $this->stringContains('Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged'), <del> $this->stringContains(str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php')) <del> )); <del> <ide> $errorHandler->handleException($error); <add> <add> $messages = $this->logger->read(); <add> $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[0]); <add> $this->assertStringContainsString( <add> 'Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged', <add> $messages[0] <add> ); <add> $this->assertStringContainsString( <add> str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'), <add> $messages[0] <add> ); <ide> } <ide> <ide> /** <ide> public function testHandleExceptionLogSkipping() <ide> { <ide> $notFound = new NotFoundException('Kaboom!'); <ide> $forbidden = new ForbiddenException('Fooled you!'); <del> <del> $this->_logger->expects($this->once()) <del> ->method('log') <del> ->with( <del> 'error', <del> $this->stringContains('[Cake\Http\Exception\ForbiddenException] Fooled you!') <del> ); <del> <ide> $errorHandler = new TestErrorHandler([ <ide> 'log' => true, <ide> 'skipLog' => ['Cake\Http\Exception\NotFoundException'], <ide> public function testHandleExceptionLogSkipping() <ide> <ide> $errorHandler->handleException($forbidden); <ide> $this->assertStringContainsString('Fooled you!', (string)$errorHandler->response->getBody(), 'message missing.'); <add> <add> $messages = $this->logger->read(); <add> $this->assertCount(1, $messages); <add> $this->assertStringContainsString( <add> '[Cake\Http\Exception\ForbiddenException] Fooled you!', <add> $messages[0] <add> ); <ide> } <ide> <ide> /** <ide> public function testHandleFatalErrorPage() <ide> */ <ide> public function testHandleFatalErrorLog() <ide> { <del> $this->_logger->expects($this->at(0)) <del> ->method('log') <del> ->with('error', $this->logicalAnd( <del> $this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)), <del> $this->stringContains('Fatal Error (1)'), <del> $this->stringContains('Something wrong') <del> )); <del> $this->_logger->expects($this->at(1)) <del> ->method('log') <del> ->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong')); <del> <ide> $errorHandler = new TestErrorHandler(['log' => true]); <ide> $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__); <add> <add> $messages = $this->logger->read(); <add> $this->assertCount(2, $messages); <add> $this->assertStringContainsString(__FILE__ . ', line ' . (__LINE__ - 4), $messages[0]); <add> $this->assertStringContainsString('Fatal Error (1)', $messages[0]); <add> $this->assertStringContainsString('Something wrong', $messages[0]); <add> $this->assertStringContainsString('[Cake\Error\FatalErrorException] Something wrong', $messages[1]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View; <ide> <add>use Cake\Event\EventManager; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> public function testBuildComplete() <ide> { <ide> $request = new ServerRequest(); <ide> $response = new Response(); <del> $events = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <add> $events = new EventManager(); <ide> <ide> $builder = new ViewBuilder(); <ide> $builder->setName('Articles')
2
Ruby
Ruby
add create_association! for belongs_to
52c47556b7cf55549f97f3cfd5f69b2563198eac
<ide><path>activerecord/lib/active_record/associations.rb <ide> def collection_accessor_methods(reflection, writer = true) <ide> <ide> def association_constructor_methods(reflection) <ide> constructors = { <del> "build_#{reflection.name}" => "build", <del> "create_#{reflection.name}" => "create" <add> "build_#{reflection.name}" => "build", <add> "create_#{reflection.name}" => "create", <add> "create_#{reflection.name}!" => "create!" <ide> } <del> constructors["create_#{reflection.name}!"] = "create!" if reflection.macro == :has_one <ide> <ide> constructors.each do |name, proxy_name| <ide> redefine_method(name) do |*params| <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb <ide> def create(attributes = {}) <ide> replace(@reflection.create_association(attributes)) <ide> end <ide> <add> def create!(attributes = {}) <add> build(attributes).tap { |record| record.save! } <add> end <add> <ide> def build(attributes = {}) <ide> replace(@reflection.build_association(attributes)) <ide> end <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> def test_building_the_belonging_object_with_primary_key <ide> assert_equal apple.name, client.firm_name <ide> end <ide> <add> def test_create! <add> client = Client.create!(:name => "Jimmy") <add> account = client.create_account!(:credit_limit => 10) <add> assert_equal account, client.account <add> assert account.persisted? <add> client.save <add> client.reload <add> assert_equal account, client.account <add> end <add> <add> def test_failing_create! <add> client = Client.create!(:name => "Jimmy") <add> assert_raise(ActiveRecord::RecordInvalid) { client.create_account! } <add> assert_not_nil client.account <add> assert client.account.new_record? <add> end <add> <ide> def test_natural_assignment_to_nil <ide> client = Client.find(3) <ide> client.firm = nil <ide><path>activerecord/test/models/company.rb <ide> class Client < Company <ide> belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name <ide> belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true <ide> has_many :accounts, :through => :firm <add> belongs_to :account <ide> <ide> # Record destruction so we can test whether firm.clients.clear has <ide> # is calling client.destroy, deleting from the database, or setting <ide><path>activerecord/test/schema/schema.rb <ide> def create_table(*args, &block) <ide> t.string :name <ide> t.integer :client_of <ide> t.integer :rating, :default => 1 <add> t.integer :account_id <ide> end <ide> <ide> add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index"
5
Ruby
Ruby
remove remaining http_only? calls
e1824c5991f0e694cf041c3aacd43a53ce97b0dd
<ide><path>railties/lib/rails/application.rb <ide> def default_middleware_stack <ide> <ide> middleware.use ::Rack::Lock unless config.allow_concurrency <ide> middleware.use ::Rack::Runtime <del> middleware.use ::Rack::MethodOverride unless config.middleware.http_only? <add> middleware.use ::Rack::MethodOverride <ide> middleware.use ::ActionDispatch::RequestId <ide> middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods <ide> middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path) <ide> def default_middleware_stack <ide> end <ide> <ide> middleware.use ::ActionDispatch::Callbacks <del> middleware.use ::ActionDispatch::Cookies unless config.middleware.http_only? <add> middleware.use ::ActionDispatch::Cookies <ide> <del> if !config.middleware.http_only? && config.session_store <add> if config.session_store <ide> if config.force_ssl && !config.session_options.key?(:secure) <ide> config.session_options[:secure] = true <ide> end <ide> def default_middleware_stack <ide> middleware.use ::Rack::ConditionalGet <ide> middleware.use ::Rack::ETag, "no-cache" <ide> <del> if !config.middleware.http_only? && config.action_dispatch.best_standards_support <add> if config.action_dispatch.best_standards_support <ide> middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support <ide> end <ide> end <ide><path>railties/lib/rails/configuration.rb <ide> module Configuration <ide> # <ide> # config.middleware.delete ActionDispatch::BestStandardsSupport <ide> # <del> # In addition to these methods to handle the stack, if your application is <del> # going to be used as an API endpoint only, the middleware stack can be <del> # configured like this: <del> # <del> # config.middleware.http_only! <del> # <del> # By doing this, Rails will create a smaller middleware stack, by not adding <del> # some middlewares that are usually useful for browser access only, such as <del> # Cookies, Session and Flash, BestStandardsSupport, and MethodOverride. You <del> # can always add any of them later manually if you want. <ide> class MiddlewareStackProxy <ide> def initialize <ide> @operations = []
2
Python
Python
add short names of months to tokenizer_exceptions
e8f40ceed8d259df3102dc68bbb13cdb34d704f1
<ide><path>spacy/lang/da/tokenizer_exceptions.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ...symbols import ORTH, LEMMA <add>from ...symbols import ORTH, LEMMA, NORM <ide> <ide> <ide> _exc = {} <ide> <add>for exc_data in [ <add> {ORTH: "Kbh.", LEMMA: "København", NORM: "København"}, <add> <add> {ORTH: "Jan.", LEMMA: "januar", NORM: "januar"}, <add> {ORTH: "Feb.", LEMMA: "februar", NORM: "februar"}, <add> {ORTH: "Mar.", LEMMA: "marts", NORM: "marts"}, <add> {ORTH: "Apr.", LEMMA: "april", NORM: "april"}, <add> {ORTH: "Maj.", LEMMA: "maj", NORM: "maj"}, <add> {ORTH: "Jun.", LEMMA: "juni", NORM: "juni"}, <add> {ORTH: "Jul.", LEMMA: "juli", NORM: "juli"}, <add> {ORTH: "Aug.", LEMMA: "august", NORM: "august"}, <add> {ORTH: "Sep.", LEMMA: "september", NORM: "september"}, <add> {ORTH: "Okt.", LEMMA: "oktober", NORM: "oktober"}, <add> {ORTH: "Nov.", LEMMA: "november", NORM: "november"}, <add> {ORTH: "Dec.", LEMMA: "december", NORM: "december"}]: <add> _exc[exc_data[ORTH]] = [dict(exc_data)] <ide> <ide> for orth in [ <ide> "A/S", "beg.", "bl.a.", "ca.", "d.s.s.", "dvs.", "f.eks.", "fr.", "hhv.",
1
Go
Go
return error for utils.matches in archive
8891e912b44c4ff597f7a45658c4d3030d730c98
<ide><path>archive/archive.go <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> skip, err := utils.Matches(relFilePath, options.Excludes) <ide> if err != nil { <ide> utils.Debugf("Error matching %s\n", relFilePath, err) <del> return nil <add> return err <ide> } <add> <ide> if skip { <ide> if f.IsDir() { <ide> return filepath.SkipDir
1
Python
Python
fix deprecation warnings in relations_nested tests
14482a966168a98d43099d00c163d1c8c3b6471b
<ide><path>rest_framework/tests/relations_nested.py <ide> class Meta: <ide> <ide> def test_one_to_one_retrieve(self): <ide> queryset = OneToOneTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <ide> {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <ide> def test_one_to_one_create(self): <ide> # Ensure (target 4, target_source 4, source 4) are added, and <ide> # everything else is as expected. <ide> queryset = OneToOneTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <ide> {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <ide> def test_one_to_one_update(self): <ide> # Ensure (target 3, target_source 3, source 3) are updated, <ide> # and everything else is as expected. <ide> queryset = OneToOneTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <ide> {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <ide> class Meta: <ide> <ide> def test_one_to_one_retrieve(self): <ide> queryset = OneToOneSource.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <ide> {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <ide> def test_one_to_one_create(self): <ide> # Ensure (target 4, target_source 4, source 4) are added, and <ide> # everything else is as expected. <ide> queryset = OneToOneSource.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <ide> {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <ide> def test_one_to_one_update(self): <ide> # Ensure (target 3, target_source 3, source 3) are updated, <ide> # and everything else is as expected. <ide> queryset = OneToOneSource.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <ide> {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <ide> class Meta: <ide> <ide> def test_one_to_many_retrieve(self): <ide> queryset = OneToManyTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <ide> {'id': 2, 'name': 'source-2'}, <ide> def test_one_to_many_create(self): <ide> # Ensure source 4 is added, and everything else is as <ide> # expected. <ide> queryset = OneToManyTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <ide> {'id': 2, 'name': 'source-2'}, <ide> def test_one_to_many_update(self): <ide> # Ensure (target 1, source 1) are updated, <ide> # and everything else is as expected. <ide> queryset = OneToManyTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, <ide> {'id': 2, 'name': 'source-2'}, <ide> def test_one_to_many_delete(self): <ide> # Ensure source 2 is deleted, and everything else is as <ide> # expected. <ide> queryset = OneToManyTarget.objects.all() <del> serializer = self.Serializer(queryset) <add> serializer = self.Serializer(queryset, many=True) <ide> expected = [ <ide> {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <ide> {'id': 3, 'name': 'source-3'}]}
1
Javascript
Javascript
fix warning message
c0f74e2614841a75d03a795dd72dd9fadeb9d393
<ide><path>packages/ember-routing/lib/system/route.js <ide> function parentTemplate(route, isRecursive) { <ide> <ide> if (!parent) { return; } <ide> <del> Ember.warn(fmt("The immediate parent route ('%@') did not render into the main outlet and the default 'into' option ('%@') may not be expected", get(parent, 'routeName'), get(route, 'routeName')), !isRecursive); <add> Ember.warn(fmt("The immediate parent route ('%@') did not render into the main outlet and the default 'into' option ('%@') may not be expected", [get(parent, 'routeName'), get(route, 'routeName')]), !isRecursive); <ide> <ide> if (template = parent.lastRenderedTemplate) { <ide> return template;
1
Go
Go
move change to the archive package
01990b65a3cf3da5e04aa6612a17ead2a6cac2c9
<ide><path>utils.go <ide> import ( <ide> "syscall" <ide> ) <ide> <del> <ide> type Change struct { <ide> archive.Change <ide> } <ide> <del> <ide> // Compare two Config struct. Do not compare the "Image" nor "Hostname" fields <ide> // If OpenStdin is set, then it differs <ide> func CompareConfig(a, b *Config) bool {
1
Ruby
Ruby
add min node
5daafa8e959acc64fc19e9522470282ac0f25f33
<ide><path>lib/arel/attributes/attribute.rb <ide> def maximum <ide> Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id') <ide> end <ide> <add> def minimum <add> Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id') <add> end <add> <ide> def average <ide> Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id') <ide> end <ide><path>lib/arel/nodes.rb <ide> require 'arel/nodes/offset' <ide> require 'arel/nodes/sum' <ide> require 'arel/nodes/max' <add>require 'arel/nodes/min' <ide> require 'arel/nodes/avg' <ide> require 'arel/nodes/having' <ide> require 'arel/nodes/sql_literal' <ide><path>lib/arel/nodes/min.rb <add>module Arel <add> module Nodes <add> class Min < Arel::Nodes::Function <add> end <add> end <add>end <ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_Max o <ide> visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}" <ide> end <ide> <add> def visit_Arel_Nodes_Min o <add> "MIN(#{o.expressions.map { |x| <add> visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}" <add> end <add> <ide> def visit_Arel_Nodes_Avg o <ide> "AVG(#{o.expressions.map { |x| <ide> visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}" <ide><path>spec/arel/attributes/attribute_spec.rb <ide> module Attributes <ide> end <ide> end <ide> <add> describe '#minimum' do <add> it 'should create a Min node' do <add> relation = Table.new(:users) <add> relation[:id].minimum.should be_kind_of Nodes::Min <add> end <add> end <add> <ide> describe '#sum' do <ide> it 'should create a SUM node' do <ide> relation = Table.new(:users)
5
PHP
PHP
add clarification to comment
abaee25b562a580460a38c43b7a35fe23fd16116
<ide><path>app/Exceptions/Handler.php <ide> class Handler extends ExceptionHandler { <ide> /** <ide> * Report or log an exception. <ide> * <add> * This is a great location to send exceptions to Sentry, Bugsnag, etc. <add> * <ide> * @param \Exception $e <ide> * @return void <ide> */
1
Javascript
Javascript
fix example rendering
5d7ae49a64600d1e107dbbbac37b4ca901cd7ef9
<ide><path>packages/ember-testing/lib/helpers/current_route_name.js <ide> import { get } from 'ember-metal'; <ide> /** <ide> Returns the currently active route name. <add> <ide> Example: <add> <ide> ```javascript <ide> function validateRouteName() { <ide> equal(currentRouteName(), 'some.path', "correct route was transitioned into."); <ide> } <ide> visit('/some/path').then(validateRouteName) <ide> ``` <add> <ide> @method currentRouteName <ide> @return {Object} The name of the currently active route. <ide> @since 1.5.0
1
Javascript
Javascript
reset progress reporter outside of hooks
1991da2c51ff615b60d9f0e6fa9621ace0c2f67f
<ide><path>lib/ProgressPlugin.js <ide> class ProgressPlugin { <ide> handler(percentage, "sealing", title); <ide> }, <ide> done() { <add> progressReporters.set(compiler, undefined); <ide> handler(percentage, "sealing", title); <ide> }, <ide> result() { <ide> class ProgressPlugin { <ide> handler(progress, category, name); <ide> }, <ide> done() { <add> progressReporters.set(compiler, undefined); <ide> handler(progress, category, name); <ide> }, <ide> result() {
1
Text
Text
fix text to follow portuguese language syntax
b6d13ddf39c97fe8a77ee676e4de017b381a0a96
<ide><path>curriculum/challenges/portuguese/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.portuguese.md <ide> localeTitle: Alinhar elementos usando a propriedade justify-content <ide> --- <ide> <ide> ## Description <del><section id="description"> Às vezes, os itens flexíveis dentro de um contêiner flexível não preenchem todo o espaço no contêiner. É comum querer dizer ao CSS como alinhar e espaçar os itens flexíveis de uma determinada maneira. Felizmente, a propriedade <code>justify-content</code> possui várias opções para fazer isso. Mas primeiro, há alguma terminologia importante para entender antes de rever essas opções. <a href="https://www.w3.org/TR/css-flexbox-1/images/flex-direction-terms.svg" target="_blank">Aqui está uma imagem útil mostrando uma linha para ilustrar os conceitos abaixo.</a> Lembre-se de que definir um contêiner flexível como uma linha coloca os itens flexíveis lado a lado da esquerda para a direita. Um conjunto de contêiner flexível como uma coluna coloca os itens flexíveis em uma pilha vertical de cima para baixo. Para cada um, a direção em que os itens flexíveis são organizados é chamada de <strong>eixo principal</strong> . Por uma linha, esta é uma linha horizontal que corta cada item. E para uma coluna, o eixo principal é uma linha vertical através dos itens. Existem várias opções de como espaçar os itens flexíveis ao longo da linha que é o eixo principal. Um dos mais usados ​​é o <code>justify-content: center;</code> , que alinha todos os itens flexíveis ao centro dentro do contêiner flexível. Outras opções incluem: <ul><li> <code>flex-start</code> : alinha os itens ao início do contêiner flexível. Para uma linha, isso empurra os itens para a esquerda do contêiner. Para uma coluna, isso empurra os itens para o topo do contêiner. </li><li> <code>flex-end</code> : alinha os itens ao final do contêiner flexível. Para uma linha, isso empurra os itens para a direita do contêiner. Para uma coluna, isso empurra os itens para o fundo do contêiner. </li><li> <code>space-between</code> : alinha itens ao centro do eixo principal, com espaço extra colocado entre os itens. O primeiro e o último item são empurrados para a borda do contêiner flexível. Por exemplo, em uma linha, o primeiro item está contra o lado esquerdo do contêiner, o último item está contra o lado direito do contêiner e, em seguida, os outros itens entre eles são espaçados uniformemente. </li><li> <code>space-around</code> : semelhante ao <code>space-between</code> mas o primeiro e último itens não estão bloqueados para as bordas do contêiner, o espaço é distribuído em torno de todos os itens </li></ul></section> <add><section id="description"> Às vezes, os itens flexíveis dentro de um contêiner flexível não preenchem todo o espaço no contêiner. É comum querer dizer ao CSS como alinhar e espaçar os itens flexíveis de uma determinada maneira. Felizmente, a propriedade <code>justify-content</code> possui várias opções para fazer isso. Mas primeiro, há alguma terminologia importante para entender antes de rever essas opções. <add><a href="https://www.w3.org/TR/css-flexbox-1/images/flex-direction-terms.svg" target="_blank">Aqui está uma imagem útil mostrando uma linha para ilustrar os conceitos abaixo.</a> <add>Lembre-se de que definir um contêiner flexível como uma linha coloca os itens flexíveis lado a lado da esquerda para a direita. Um contêiner flexível definido como uma coluna coloca os itens flexíveis em uma pilha vertical de cima para baixo. Para cada um, a direção em que os itens flexíveis são organizados é chamada de <strong>eixo principal</strong> . Para uma linha, esta é uma linha horizontal que corta cada item. E para uma coluna, o eixo principal é uma linha vertical que passa através dos itens. <add>Existem várias opções de como espaçar os itens flexíveis ao longo da linha que é o eixo principal. Um dos mais usados é a <code>justify-content: center;</code> , que alinha todos os itens flexíveis ao centro dentro do contêiner flexível. Outras opções incluem: <ul><li> <code>flex-start</code> : alinha os itens ao início do contêiner flexível. Para uma linha, isso empurra os itens para a esquerda do contêiner. Para uma coluna, isso empurra os itens para o topo do contêiner. </li><li> <code>flex-end</code> : alinha os itens ao final do contêiner flexível. Para uma linha, isso empurra os itens para a direita do contêiner. Para uma coluna, isso empurra os itens para o fundo do contêiner. </li><li> <code>space-between</code> : alinha itens ao centro do eixo principal, com espaço extra colocado entre os itens. O primeiro e o último item são empurrados para a borda do contêiner flexível. Por exemplo, em uma linha, o primeiro item está contra o lado esquerdo do contêiner, o último item está contra o lado direito do contêiner e, em seguida, os outros itens entre eles são espaçados uniformemente. </li><li> <code>space-around</code> : semelhante ao <code>space-between</code> mas o primeiro e último itens não estão encostados às bordas do contêiner, o espaço é distribuído em torno de todos os itens </li></ul></section> <ide> <ide> ## Instructions <del><section id="instructions"> Um exemplo ajuda a mostrar essa propriedade em ação. Adicione a propriedade CSS <code>justify-content</code> ao elemento <code>#box-container</code> e atribua a ela um valor de center. <strong>Bônus</strong> <br> Tente as outras opções para a propriedade <code>justify-content</code> no editor de código para ver suas diferenças. Mas note que um valor de centro é o único que passará este desafio. </section> <add><section id="instructions"> Um exemplo ajuda a mostrar essa propriedade em ação. Adicione a propriedade CSS <code>justify-content</code> ao elemento <code>#box-container</code> e atribua a ela um valor de *center*. <strong>Bônus</strong> <br> Experimente as outras opções na propriedade <code>justify-content</code> no editor de código para ver suas diferenças. Mas note que um valor de *center* é o único que passará este desafio. </section> <ide> <ide> ## Tests <ide> <section id='tests'>
1
Python
Python
fix e741 flake8 warning (x14)
b0f7db73cd2fd10142668d43fd30906a438f05f3
<ide><path>examples/contrib/run_swag.py <ide> def __str__(self): <ide> return self.__repr__() <ide> <ide> def __repr__(self): <del> l = [ <add> attributes = [ <ide> "swag_id: {}".format(self.swag_id), <ide> "context_sentence: {}".format(self.context_sentence), <ide> "start_ending: {}".format(self.start_ending), <ide> def __repr__(self): <ide> ] <ide> <ide> if self.label is not None: <del> l.append("label: {}".format(self.label)) <add> attributes.append("label: {}".format(self.label)) <ide> <del> return ", ".join(l) <add> return ", ".join(attributes) <ide> <ide> <ide> class InputFeatures(object): <ide><path>templates/adding_a_new_model/modeling_xxx.py <ide> def load_tf_weights_in_xxx(model, config, tf_checkpoint_path): <ide> pointer = model <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+_\d+", m_name): <del> l = re.split(r"_(\d+)", m_name) <add> scope_names = re.split(r"_(\d+)", m_name) <ide> else: <del> l = [m_name] <del> if l[0] == "kernel" or l[0] == "gamma": <add> scope_names = [m_name] <add> if scope_names[0] == "kernel" or scope_names[0] == "gamma": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "output_bias" or l[0] == "beta": <add> elif scope_names[0] == "output_bias" or scope_names[0] == "beta": <ide> pointer = getattr(pointer, "bias") <del> elif l[0] == "output_weights": <add> elif scope_names[0] == "output_weights": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "squad": <add> elif scope_names[0] == "squad": <ide> pointer = getattr(pointer, "classifier") <ide> else: <ide> try: <del> pointer = getattr(pointer, l[0]) <add> pointer = getattr(pointer, scope_names[0]) <ide> except AttributeError: <ide> logger.info("Skipping {}".format("/".join(name))) <ide> continue <del> if len(l) >= 2: <del> num = int(l[1]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <ide> if m_name[-11:] == "_embeddings": <ide> pointer = getattr(pointer, "weight") <ide><path>transformers/modeling_albert.py <ide> def load_tf_weights_in_albert(model, config, tf_checkpoint_path): <ide> pointer = model <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+_\d+", m_name): <del> l = re.split(r"_(\d+)", m_name) <add> scope_names = re.split(r"_(\d+)", m_name) <ide> else: <del> l = [m_name] <add> scope_names = [m_name] <ide> <del> if l[0] == "kernel" or l[0] == "gamma": <add> if scope_names[0] == "kernel" or scope_names[0] == "gamma": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "output_bias" or l[0] == "beta": <add> elif scope_names[0] == "output_bias" or scope_names[0] == "beta": <ide> pointer = getattr(pointer, "bias") <del> elif l[0] == "output_weights": <add> elif scope_names[0] == "output_weights": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "squad": <add> elif scope_names[0] == "squad": <ide> pointer = getattr(pointer, "classifier") <ide> else: <ide> try: <del> pointer = getattr(pointer, l[0]) <add> pointer = getattr(pointer, scope_names[0]) <ide> except AttributeError: <ide> logger.info("Skipping {}".format("/".join(name))) <ide> continue <del> if len(l) >= 2: <del> num = int(l[1]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <ide> <ide> if m_name[-11:] == "_embeddings": <ide><path>transformers/modeling_bert.py <ide> def load_tf_weights_in_bert(model, config, tf_checkpoint_path): <ide> pointer = model <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+_\d+", m_name): <del> l = re.split(r"_(\d+)", m_name) <add> scope_names = re.split(r"_(\d+)", m_name) <ide> else: <del> l = [m_name] <del> if l[0] == "kernel" or l[0] == "gamma": <add> scope_names = [m_name] <add> if scope_names[0] == "kernel" or scope_names[0] == "gamma": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "output_bias" or l[0] == "beta": <add> elif scope_names[0] == "output_bias" or scope_names[0] == "beta": <ide> pointer = getattr(pointer, "bias") <del> elif l[0] == "output_weights": <add> elif scope_names[0] == "output_weights": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "squad": <add> elif scope_names[0] == "squad": <ide> pointer = getattr(pointer, "classifier") <ide> else: <ide> try: <del> pointer = getattr(pointer, l[0]) <add> pointer = getattr(pointer, scope_names[0]) <ide> except AttributeError: <ide> logger.info("Skipping {}".format("/".join(name))) <ide> continue <del> if len(l) >= 2: <del> num = int(l[1]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <ide> if m_name[-11:] == "_embeddings": <ide> pointer = getattr(pointer, "weight") <ide><path>transformers/modeling_gpt2.py <ide> def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path): <ide> pointer = model <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+\d+", m_name): <del> l = re.split(r"(\d+)", m_name) <add> scope_names = re.split(r"(\d+)", m_name) <ide> else: <del> l = [m_name] <del> if l[0] == "w" or l[0] == "g": <add> scope_names = [m_name] <add> if scope_names[0] == "w" or scope_names[0] == "g": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "b": <add> elif scope_names[0] == "b": <ide> pointer = getattr(pointer, "bias") <del> elif l[0] == "wpe" or l[0] == "wte": <del> pointer = getattr(pointer, l[0]) <add> elif scope_names[0] == "wpe" or scope_names[0] == "wte": <add> pointer = getattr(pointer, scope_names[0]) <ide> pointer = getattr(pointer, "weight") <ide> else: <del> pointer = getattr(pointer, l[0]) <del> if len(l) >= 2: <del> num = int(l[1]) <add> pointer = getattr(pointer, scope_names[0]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <ide> try: <ide> assert pointer.shape == array.shape <ide><path>transformers/modeling_openai.py <ide> def load_tf_weights_in_openai_gpt(model, config, openai_checkpoint_folder_path): <ide> pointer = model <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+\d+", m_name): <del> l = re.split(r"(\d+)", m_name) <add> scope_names = re.split(r"(\d+)", m_name) <ide> else: <del> l = [m_name] <del> if l[0] == "g": <add> scope_names = [m_name] <add> if scope_names[0] == "g": <ide> pointer = getattr(pointer, "weight") <del> elif l[0] == "b": <add> elif scope_names[0] == "b": <ide> pointer = getattr(pointer, "bias") <del> elif l[0] == "w": <add> elif scope_names[0] == "w": <ide> pointer = getattr(pointer, "weight") <ide> else: <del> pointer = getattr(pointer, l[0]) <del> if len(l) >= 2: <del> num = int(l[1]) <add> pointer = getattr(pointer, scope_names[0]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <ide> try: <ide> assert pointer.shape == array.shape <ide><path>transformers/modeling_t5.py <ide> def load_tf_weights_in_t5(model, config, tf_checkpoint_path): <ide> array = tf_weights[txt_name] <ide> for m_name in name: <ide> if re.fullmatch(r"[A-Za-z]+_\d+", m_name): <del> l = re.split(r"_(\d+)", m_name) <add> scope_names = re.split(r"_(\d+)", m_name) <ide> else: <del> l = [m_name] <del> if l[0] in ["kernel", "scale", "embedding"]: <add> scope_names = [m_name] <add> if scope_names[0] in ["kernel", "scale", "embedding"]: <ide> pointer = getattr(pointer, "weight") <del> # elif l[0] == 'scale': <add> # elif scope_names[0] == 'scale': <ide> # pointer = getattr(pointer, 'weight') <del> # elif l[0] == 'output_bias' or l[0] == 'beta': <add> # elif scope_names[0] == 'output_bias' or scope_names[0] == 'beta': <ide> # pointer = getattr(pointer, 'bias') <del> # elif l[0] == 'squad': <add> # elif scope_names[0] == 'squad': <ide> # pointer = getattr(pointer, 'classifier') <ide> else: <ide> try: <del> pointer = getattr(pointer, l[0]) <add> pointer = getattr(pointer, scope_names[0]) <ide> except AttributeError: <ide> logger.info("Skipping {}".format("/".join(name))) <ide> continue <del> if len(l) >= 2: <del> num = int(l[1]) <add> if len(scope_names) >= 2: <add> num = int(scope_names[1]) <ide> pointer = pointer[num] <del> if l[0] not in ["kernel", "scale", "embedding"]: <add> if scope_names[0] not in ["kernel", "scale", "embedding"]: <ide> pointer = getattr(pointer, "weight") <del> if l[0] != "embedding": <add> if scope_names[0] != "embedding": <ide> logger.info("Transposing numpy weight of shape {} for {}".format(array.shape, name)) <ide> array = np.transpose(array) <ide> try: <ide><path>transformers/tokenization_t5.py <ide> def _tokenize(self, text, return_unicode=True, sample=False): <ide> def _convert_token_to_id(self, token): <ide> """ Converts a token (str/unicode) in an id using the vocab. """ <ide> if token.startswith("<extra_id_"): <del> l = re.match(r"<extra_id_(\d+)>", token) <del> num = int(l.group(1)) <add> match = re.match(r"<extra_id_(\d+)>", token) <add> num = int(match.group(1)) <ide> return self.vocab_size - num - 1 <ide> return self.sp_model.piece_to_id(token) <ide>
8
Python
Python
handle app factory with arguments in flask_app
7106fb63578deef49741096d3d5aa04db89e15ae
<ide><path>flask/cli.py <ide> :license: BSD, see LICENSE for more details. <ide> """ <ide> <add>import ast <add>import inspect <ide> import os <add>import re <ide> import sys <ide> import traceback <ide> from functools import update_wrapper <ide> def find_best_app(script_info, module): <ide> ' one.'.format(module=module.__name__) <ide> ) <ide> <del> # Search for app factory callables. <add> # Search for app factory functions. <ide> for attr_name in ('create_app', 'make_app'): <ide> app_factory = getattr(module, attr_name, None) <ide> <del> if callable(app_factory): <add> if inspect.isfunction(app_factory): <ide> try: <ide> app = call_factory(app_factory, script_info) <ide> if isinstance(app, Flask): <ide> return app <ide> except TypeError: <ide> raise NoAppException( <del> 'Auto-detected "{callable}()" in module "{module}", but ' <add> 'Auto-detected "{function}()" in module "{module}", but ' <ide> 'could not call it without specifying arguments.'.format( <del> callable=attr_name, module=module.__name__ <add> function=attr_name, module=module.__name__ <ide> ) <ide> ) <ide> <ide> def locate_app(script_info, app_id): <ide> if app_obj is None: <ide> app = find_best_app(script_info, mod) <ide> else: <del> app = getattr(mod, app_obj, None) <add> function_regex = r'^([\w_][\w_\d]*)\((.*)\)$' <add> match = re.match(function_regex, app_obj) <add> try: <add> if match: <add> function_name = match.group(1) <add> arguments = match.group(2) <add> if arguments: <add> arguments = ast.literal_eval( <add> "({arguments}, )".format(arguments=arguments)) <add> else: <add> arguments = () <add> app_factory = getattr(mod, function_name, None) <add> app_factory_arg_names = getargspec(app_factory).args <add> if 'script_info' in app_factory_arg_names: <add> app = app_factory(*arguments, script_info=script_info) <add> elif arguments: <add> app = app_factory(*arguments) <add> elif not arguments and len(app_factory_arg_names) == 1: <add> app = app_factory(script_info) <add> else: <add> app = app_factory() <add> else: <add> attr = getattr(mod, app_obj, None) <add> if inspect.isfunction(attr): <add> app = call_factory(attr, script_info) <add> else: <add> app = attr <add> except TypeError as e: <add> new_error = NoAppException( <add> '{e}\nThe app factory "{factory}" in module "{module}" could' <add> ' not be called with the specified arguments (and a' <add> ' script_info argument automatically added if applicable).' <add> ' Did you make sure to use the right number of arguments as' <add> ' well as not using keyword arguments or' <add> ' non-literals?'.format(e=e, factory=app_obj, module=module)) <add> reraise(NoAppException, new_error, sys.exc_info()[2]) <ide> if app is None: <del> raise RuntimeError('Failed to find application in module "%s"' <del> % module) <add> raise RuntimeError('Failed to find application in module ' <add> '"{name}"'.format(name=module)) <ide> <ide> return app <ide> <ide><path>tests/test_apps/cliapp/factory.py <add>from __future__ import absolute_import, print_function <add> <add>from flask import Flask <add> <add> <add>def create_app(): <add> return Flask('create_app') <add> <add> <add>def create_app2(foo, bar): <add> return Flask("_".join(['create_app2', foo, bar])) <add> <add> <add>def create_app3(foo, bar, script_info): <add> return Flask("_".join(['create_app3', foo, bar])) <ide><path>tests/test_cli.py <ide> def test_locate_app(test_apps): <ide> script_info = ScriptInfo() <ide> assert locate_app(script_info, "cliapp.app").name == "testapp" <ide> assert locate_app(script_info, "cliapp.app:testapp").name == "testapp" <add> assert locate_app(script_info, "cliapp.factory").name == "create_app" <add> assert locate_app( <add> script_info, "cliapp.factory").name == "create_app" <add> assert locate_app( <add> script_info, "cliapp.factory:create_app").name == "create_app" <add> assert locate_app( <add> script_info, "cliapp.factory:create_app()").name == "create_app" <add> assert locate_app( <add> script_info, "cliapp.factory:create_app2('foo', 'bar')" <add> ).name == "create_app2_foo_bar" <add> assert locate_app( <add> script_info, "cliapp.factory:create_app3('baz', 'qux')" <add> ).name == "create_app3_baz_qux" <ide> assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1" <del> pytest.raises(NoAppException, locate_app, <del> script_info, "notanpp.py") <del> pytest.raises(NoAppException, locate_app, <del> script_info, "cliapp/app") <del> pytest.raises(RuntimeError, locate_app, <del> script_info, "cliapp.app:notanapp") <del> pytest.raises(NoAppException, locate_app, <del> script_info, "cliapp.importerrorapp") <add> pytest.raises( <add> NoAppException, locate_app, script_info, "notanpp.py") <add> pytest.raises( <add> NoAppException, locate_app, script_info, "cliapp/app") <add> pytest.raises( <add> RuntimeError, locate_app, script_info, "cliapp.app:notanapp") <add> pytest.raises( <add> NoAppException, locate_app, <add> script_info, "cliapp.factory:create_app2('foo')") <add> pytest.raises( <add> NoAppException, locate_app, script_info, "cliapp.importerrorapp") <ide> <ide> <ide> def test_find_default_import_path(test_apps, monkeypatch, tmpdir):
3
PHP
PHP
update input parsing to work with patch & delete
2b35abe7534594e597c45bd1d60a37675c432d6e
<ide><path>lib/Cake/Network/Request.php <ide> class Request implements \ArrayAccess { <ide> <ide> /** <ide> * Array of POST data. Will contain form data as well as uploaded files. <del> * Inputs prefixed with 'data' will have the data prefix removed. If there is <del> * overlap between an input prefixed with data and one without, the 'data' prefixed <del> * value will take precedence. <add> * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded <add> * data. <ide> * <ide> * @var array <ide> */ <ide> class Request implements \ArrayAccess { <ide> /** <ide> * Wrapper method to create a new request from PHP superglobals. <ide> * <add> * Uses the $_GET, $_POST, $_FILES, $_COOKIE and php://input data to construct <add> * the request. <add> * <ide> * @return Cake\Network\Request <ide> */ <ide> public static function createFromGlobals() { <ide> public static function createFromGlobals() { <ide> * - `url` The url without the base path for the request. <ide> * - `base` The base url for the request. <ide> * - `webroot` The webroot directory for the request. <add> * - `input` The data that would come from php://input this is useful for simulating <add> * requests with put, patch or delete data. <ide> * <ide> * @param string|array $config An array of request data to create a request with. <ide> */ <ide> public function __construct($config = array()) { <ide> 'url' => '', <ide> 'base' => '', <ide> 'webroot' => '', <add> 'input' => null, <ide> ); <ide> $this->_setConfig($config); <ide> } <ide> protected function _setConfig($config) { <ide> $this->here = $this->base . '/' . $this->url; <ide> $this->webroot = $config['webroot']; <ide> <add> if (isset($config['input'])) { <add> $this->_input = $config['input']; <add> } <ide> $config['post'] = $this->_processPost($config['post']); <ide> $this->data = $this->_processFiles($config['post'], $config['files']); <ide> $this->query = $this->_processGet($config['query']); <ide> protected function _setConfig($config) { <ide> * @return array <ide> */ <ide> protected function _processPost($data) { <del> if ($this->is('put')) { <del> $data = $this->_readInput(); <del> if (env('CONTENT_TYPE') === 'application/x-www-form-urlencoded') { <del> parse_str($data, $data); <del> } <add> if ( <add> in_array(env('REQUEST_METHOD'), array('PUT', 'DELETE', 'PATCH')) && <add> env('CONTENT_TYPE') === 'application/x-www-form-urlencoded' <add> ) { <add> $data = $this->input(); <add> parse_str($data, $data); <ide> } <ide> if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) { <ide> $data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE'); <ide><path>lib/Cake/Test/TestCase/Network/RequestTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Xml; <ide> <del>class TestRequest extends Request { <del> <del> public function reConstruct($url = 'some/path', $parseEnvironment = true) { <del> $this->_base(); <del> if (empty($url)) { <del> $url = $this->_url(); <del> } <del> if ($url[0] == '/') { <del> $url = substr($url, 1); <del> } <del> $this->url = $url; <del> <del> if ($parseEnvironment) { <del> $this->_processPost(); <del> $this->_processGet(); <del> $this->_processFiles(); <del> } <del> $this->here = $this->base . '/' . $this->url; <del> } <del> <del>} <del> <ide> class RequestTest extends TestCase { <ide> <ide> /** <ide> public function testPutParsing() { <ide> $_SERVER['REQUEST_METHOD'] = 'PUT'; <ide> $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; <ide> <del> $data = array('data' => array( <add> $data = array( <ide> 'Article' => array('title') <add> ); <add> $request = new Request(array( <add> 'input' => 'Article[]=title' <ide> )); <del> <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('data[Article][]=title')); <del> $request->reConstruct(); <del> $this->assertEquals($data['data'], $request->data); <add> $this->assertEquals($data, $request->data); <ide> <ide> $data = array('one' => 1, 'two' => 'three'); <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('one=1&two=three')); <del> $request->reConstruct(); <add> $request = new Request(array( <add> 'input' => 'one=1&two=three' <add> )); <ide> $this->assertEquals($data, $request->data); <ide> <del> $data = array( <del> 'data' => array( <del> 'Article' => array('title' => 'Testing'), <del> ), <del> 'action' => 'update' <del> ); <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('data[Article][title]=Testing&action=update')); <del> $request->reConstruct(); <add> $_SERVER['REQUEST_METHOD'] = 'DELETE'; <add> $request = new Request(array( <add> 'input' => 'Article[title]=Testing&action=update' <add> )); <ide> $expected = array( <ide> 'Article' => array('title' => 'Testing'), <ide> 'action' => 'update' <ide> ); <ide> $this->assertEquals($expected, $request->data); <ide> <del> $_SERVER['REQUEST_METHOD'] = 'DELETE'; <del> $data = array('data' => array( <add> $_SERVER['REQUEST_METHOD'] = 'PATCH'; <add> $data = array( <ide> 'Article' => array('title'), <ide> 'Tag' => array('Tag' => array(1, 2)) <del> )); <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('data[Article][]=title&Tag[Tag][]=1&Tag[Tag][]=2')); <del> $request->reConstruct(); <del> $this->assertEquals($data['data'], $request->data); <del> <del> $data = array('data' => array( <del> 'Article' => array('title' => 'some title'), <del> 'Tag' => array('Tag' => array(1, 2)) <del> )); <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('data[Article][title]=some%20title&Tag[Tag][]=1&Tag[Tag][]=2')); <del> $request->reConstruct(); <del> $this->assertEquals($data['data'], $request->data); <del> <del> $data = array( <del> 'a' => array(1, 2), <del> 'b' => array(1, 2) <ide> ); <del> $request = $this->getMock(__NAMESPACE__ . '\TestRequest', array('_readInput')); <del> $request->expects($this->at(0))->method('_readInput') <del> ->will($this->returnValue('a[]=1&a[]=2&b[]=1&b[]=2')); <del> $request->reConstruct(); <add> $request = new Request(array( <add> 'input' => 'Article[]=title&Tag[Tag][]=1&Tag[Tag][]=2' <add> )); <ide> $this->assertEquals($data, $request->data); <ide> } <ide>
2
Ruby
Ruby
add use_sprockets flag
954d73df5312f4829c96a76f1929e45597e85680
<ide><path>railties/lib/rails/application/configuration.rb <ide> class Configuration < ::Rails::Engine::Configuration <ide> :filter_parameters, :helpers_paths, :logger, <ide> :preload_frameworks, :reload_plugins, <ide> :secret_token, :serve_static_assets, :session_options, <del> :time_zone, :whiny_nils, <del> :compile_assets <add> :time_zone, :whiny_nils <ide> <ide> attr_writer :log_level <ide> <ide> def initialize(*) <ide> @log_level = nil <ide> @middleware = app_middleware <ide> @generators = app_generators <del> @compile_assets = [] <ide> end <ide> <ide> def compiled_asset_path <ide><path>railties/lib/rails/engine.rb <ide> def env_config <ide> <ide> def routes <ide> @routes ||= ActionDispatch::Routing::RouteSet.new <del> @routes.add_route(assets, {}, {}, {}, nil, false) <add> @routes.add_route(assets, {}, {}, {}, nil, false) if config.use_sprockets <ide> @routes.append(&Proc.new) if block_given? <ide> @routes <ide> end <ide> def assets <ide> end <ide> <ide> def build_asset_environment <add> return nil if !use_sprockets <add> <ide> require 'sprockets' <ide> <ide> env = Sprockets::Environment.new(root.to_s) <ide><path>railties/lib/rails/engine/configuration.rb <ide> class Engine <ide> class Configuration < ::Rails::Railtie::Configuration <ide> attr_reader :root <ide> attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths <del> attr_accessor :plugins, :asset_path <add> attr_accessor :plugins, :asset_path, :use_sprockets, :compile_assets <ide> <ide> def initialize(root=nil) <ide> super() <ide> @root = root <ide> @generators = app_generators.dup <add> <add> @use_sprockets = false <add> @compile_assets = [] <ide> end <ide> <ide> # Returns the middleware stack for the engine.
3
Ruby
Ruby
remove backports for ruby 1.8.6
ec1727a1bed5c431941972aeae064b6345e51321
<ide><path>Library/Homebrew/extend/enumerable.rb <del>module Enumerable <del> def group_by <del> inject({}) do |h, e| <del> h.fetch(yield(e)) { |k| h[k] = [] } << e; h <del> end <del> end unless method_defined?(:group_by) <del>end <ide><path>Library/Homebrew/extend/string.rb <ide> def undent <ide> # EOS <ide> alias_method :undent_________________________________________________________72, :undent <ide> <del> def start_with?(*prefixes) <del> prefixes.any? do |prefix| <del> if prefix.respond_to?(:to_str) <del> prefix = prefix.to_str <del> self[0, prefix.length] == prefix <del> end <del> end <del> end unless method_defined?(:start_with?) <del> <del> def end_with?(*suffixes) <del> suffixes.any? do |suffix| <del> if suffix.respond_to?(:to_str) <del> suffix = suffix.to_str <del> self[-suffix.length, suffix.length] == suffix <del> end <del> end <del> end unless method_defined?(:end_with?) <del> <del> # 1.8.7 or later; used in bottle code <del> def rpartition(separator) <del> if ind = rindex(separator) <del> [slice(0, ind), separator, slice(ind+1, -1) || ''] <del> else <del> ['', '', dup] <del> end <del> end unless method_defined?(:rpartition) <del> <ide> # String.chomp, but if result is empty: returns nil instead. <ide> # Allows `chuzzle || foo` short-circuits. <ide> def chuzzle <ide><path>Library/Homebrew/extend/symbol.rb <del>class Symbol <del> def to_proc <del> proc { |*args| args.shift.send(self, *args) } <del> end unless method_defined?(:to_proc) <del>end <ide><path>Library/Homebrew/global.rb <ide> require 'extend/pathname' <ide> require 'extend/ARGV' <ide> require 'extend/string' <del>require 'extend/symbol' <del>require 'extend/enumerable' <ide> require 'os' <ide> require 'utils' <ide> require 'exceptions'
4
Javascript
Javascript
simplify jquery.parsexml method
5a0867d1e94794fbfc3be1f18f4c0a168dc18d95
<ide><path>src/ajax/parseXML.js <ide> define([ <ide> <ide> // Cross-browser xml parsing <ide> jQuery.parseXML = function( data ) { <del> var xml, tmp; <add> var xml; <ide> if ( !data || typeof data !== "string" ) { <ide> return null; <ide> } <ide> <ide> // Support: IE9 <ide> try { <del> tmp = new DOMParser(); <del> xml = tmp.parseFromString( data, "text/xml" ); <add> xml = ( new DOMParser() ).parseFromString( data, "text/xml" ); <ide> } catch ( e ) { <ide> xml = undefined; <ide> }
1
Text
Text
clarify+make the reducer description more concise
a14b3fc2273607a8f06aa43da666f70a7e0d2dd5
<ide><path>guide/english/redux/redux-reducers/index.md <ide> title: Redux Reducers <ide> --- <ide> ## Redux Reducers <ide> <del>Redux reducers allow you to make changes to your state in your application. Actions in redux only tell the application what basically happened. Whether it was a click event that took place or some mouse scroll it will just tell that this thing happened. Now how do you go about changing the state of your application which lives inside the store well you do that by using a reducer. <add>Redux reducers allow you to make changes to your state in your application. While Redux actions inform the application about events that happened (eg click/scroll events), Redux reducers allow you to change the state of the application. <ide> <ide> Now a reducer in redux needs to be a pure function. A pure function is a type of function that does not have additional side-effects. You pass it some arguments and it returns the expected result. For example: <ide>
1
Text
Text
fix entrytypes type and missing link
049a8d7c1d9c69602b39bcd149ee1c093d72b970
<ide><path>doc/api/perf_hooks.md <ide> const obs = new PerformanceObserver((list) => { <ide> obs.disconnect(); <ide> performance.clearFunctions(); <ide> }); <del>obs.observe({ entryTypes: 'function' }); <add>obs.observe({ entryTypes: ['function'] }); <ide> <ide> // A performance timeline entry will be created <ide> wrapped(); <ide> require('some-module'); <ide> ``` <ide> <ide> [`timeOrigin`]: https://w3c.github.io/hr-time/#dom-performance-timeorigin <add>[Async Hooks]: async_hooks.html <ide> [W3C Performance Timeline]: https://w3c.github.io/performance-timeline/
1
Text
Text
fix typo in api documents
2f0d4946823019d2b41a0aac7eaa6b84f8e96e49
<ide><path>docs/api/v1.22.md <ide> Update resource configs of one or more containers. <ide> "Memory": 314572800, <ide> "MemorySwap": 514288000, <ide> "MemoryReservation": 209715200, <del> "KernelMemory": 52428800, <add> "KernelMemory": 52428800 <ide> } <ide> <ide> **Example response**: <ide><path>docs/api/v1.23.md <ide> Update configuration of one or more containers. <ide> "RestartPolicy": { <ide> "MaximumRetryCount": 4, <ide> "Name": "on-failure" <del> }, <add> } <ide> } <ide> <ide> **Example response**: <ide><path>docs/api/v1.24.md <ide> Update configuration of one or more containers. <ide> "RestartPolicy": { <ide> "MaximumRetryCount": 4, <ide> "Name": "on-failure" <del> }, <add> } <ide> } <ide> <ide> **Example response**:
3
Ruby
Ruby
align all the assigments
028faabc5fbfaa27c17484a0c992ebd8338566e1
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def config <ide> end <ide> <ide> def config_when_updating <del> cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb") <del> action_cable_config_exist = File.exist?("config/cable.yml") <del> active_storage_config_exist = File.exist?("config/storage.yml") <del> rack_cors_config_exist = File.exist?("config/initializers/cors.rb") <del> assets_config_exist = File.exist?("config/initializers/assets.rb") <del> asset_manifest_exist = File.exist?("app/assets/config/manifest.js") <del> asset_app_stylesheet_exist = File.exist?("app/assets/stylesheets/application.css") <del> csp_config_exist = File.exist?("config/initializers/content_security_policy.rb") <add> cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb") <add> action_cable_config_exist = File.exist?("config/cable.yml") <add> active_storage_config_exist = File.exist?("config/storage.yml") <add> rack_cors_config_exist = File.exist?("config/initializers/cors.rb") <add> assets_config_exist = File.exist?("config/initializers/assets.rb") <add> asset_manifest_exist = File.exist?("app/assets/config/manifest.js") <add> asset_app_stylesheet_exist = File.exist?("app/assets/stylesheets/application.css") <add> csp_config_exist = File.exist?("config/initializers/content_security_policy.rb") <ide> permissions_policy_config_exist = File.exist?("config/initializers/permissions_policy.rb") <ide> <ide> @config_target_version = Rails.application.config.loaded_config_version || "5.0"
1
Javascript
Javascript
remove donate settings page
c40680b81e6c62332392ec6c66ccc5a2b17ebf2e
<ide><path>client/src/client-only-routes/ShowSettings.js <ide> import Portfolio from '../components/settings/Portfolio'; <ide> import Honesty from '../components/settings/Honesty'; <ide> import Certification from '../components/settings/Certification'; <ide> import DangerZone from '../components/settings/DangerZone'; <del>import SectionHeader from '../components/settings/SectionHeader.js'; <ide> <ide> const propTypes = { <ide> createFlashMessage: PropTypes.func.isRequired, <ide> const propTypes = { <ide> isApisMicroservicesCert: PropTypes.bool, <ide> isBackEndCert: PropTypes.bool, <ide> isDataVisCert: PropTypes.bool, <del> isDonating: PropTypes.bool, <ide> isEmailVerified: PropTypes.bool, <ide> isFrontEndCert: PropTypes.bool, <ide> isFrontEndLibsCert: PropTypes.bool, <ide> export function ShowSettings(props) { <ide> user: { <ide> completedChallenges, <ide> email, <del> isDonating, <ide> is2018DataVisCert, <ide> isApisMicroservicesCert, <ide> isJsAlgoDataStructCert, <ide> export function ShowSettings(props) { <ide> updateQuincyEmail={updateQuincyEmail} <ide> /> <ide> <Spacer /> <del> {isDonating ? ( <del> <div> <del> <SectionHeader>Donation Settings</SectionHeader> <del> <FullWidthRow className='button-group'> <del> <Link <del> className='btn-invert btn btn-lg btn-primary btn-block' <del> to={`/donation/settings`} <del> > <del> Manage your existing donations <del> </Link> <del> </FullWidthRow> <del> <Spacer /> <del> </div> <del> ) : null} <ide> <Internet <ide> githubProfile={githubProfile} <ide> linkedin={linkedin} <ide><path>client/src/components/Donation/components/DonateForm.js <ide> const numToCommas = num => <ide> num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); <ide> <ide> const propTypes = { <del> enableDonationSettingsPage: PropTypes.func.isRequired, <ide> isDonating: PropTypes.bool, <ide> isSignedIn: PropTypes.bool, <ide> navigate: PropTypes.func.isRequired, <ide> class DonateForm extends Component { <ide> } <ide> <ide> renderDonationOptions() { <del> const { stripe, enableDonationSettingsPage } = this.props; <add> const { stripe } = this.props; <ide> const { donationAmount, donationDuration, paymentType } = this.state; <ide> return ( <ide> <div> <ide> class DonateForm extends Component { <ide> <DonateFormChildViewForHOC <ide> donationAmount={donationAmount} <ide> donationDuration={donationDuration} <del> enableDonationSettingsPage={enableDonationSettingsPage} <ide> getDonationButtonLabel={this.getDonationButtonLabel} <ide> hideAmountOptionsCB={this.hideAmountOptionsCB} <ide> /> <ide><path>client/src/components/Donation/components/DonateFormChildViewForHOC.js <ide> const propTypes = { <ide> donationAmount: PropTypes.number.isRequired, <ide> donationDuration: PropTypes.string.isRequired, <ide> email: PropTypes.string, <del> enableDonationSettingsPage: PropTypes.func.isRequired, <ide> getDonationButtonLabel: PropTypes.func.isRequired, <ide> hideAmountOptionsCB: PropTypes.func.isRequired, <ide> isSignedIn: PropTypes.bool, <ide> class DonateFormChildViewForHOC extends Component { <ide> } <ide> <ide> postDonation(token) { <del> const { enableDonationSettingsPage } = this.props; <ide> const { donationAmount: amount, donationDuration: duration } = this.state; <ide> this.setState(state => ({ <ide> ...state, <ide> class DonateFormChildViewForHOC extends Component { <ide> error: data.error ? data.error : null <ide> } <ide> })); <del> enableDonationSettingsPage(); <ide> }) <ide> .catch(error => { <ide> const data = <ide><path>client/src/components/Donation/components/DonateServicebotEmbed.js <del>import React, { Component } from 'react'; <del>import PropTypes from 'prop-types'; <del> <del>import { servicebotId } from '../../../../config/env.json'; <del>import { servicebotScriptLoader } from '../../../utils/scriptLoaders'; <del> <del>import '../Donation.css'; <del> <del>const propTypes = { <del> email: PropTypes.string.isRequired, <del> hash: PropTypes.string.isRequired <del>}; <del> <del>export class DonationServicebotEmbed extends Component { <del> constructor(...props) { <del> super(...props); <del> <del> this.state = { <del> email: this.props.email, <del> hash: this.props.hash <del> }; <del> <del> this.setServiceBotConfig = this.setServiceBotConfig.bind(this); <del> } <del> <del> setServiceBotConfig() { <del> const { email, hash } = this.state; <del> /* eslint-disable camelcase */ <del> window.servicebotSettings = { <del> type: 'portal', <del> servicebot_id: servicebotId, <del> service: 'freeCodeCamp.org', <del> email, <del> hash, <del> options: { <del> cancel_now: true, <del> disableCoupon: true, <del> forceCard: true, <del> hideTiers: [ <del> 'Monthly $3 Donation - Unavailable', <del> 'Monthly $10 Donation - Unavailable' <del> ], <del> card: { <del> hideName: true, <del> hideAddress: true, <del> hideCountryPostal: true <del> }, <del> messageOnCancel: `Thanks again for supporting our tiny nonprofit. We are helping millions of people around the world learn to code for free. Please confirm: are you certain you want to stop your donation?` <del> } <del> }; <del> /* eslint-enable camelcase */ <del> } <del> <del> componentDidMount() { <del> servicebotScriptLoader(); <del> } <del> <del> render() { <del> this.setServiceBotConfig(); <del> return ( <del> <div className='fcc-servicebot-embed-portal'> <del> <div id='servicebot-subscription-portal'></div> <del> </div> <del> ); <del> } <del>} <del> <del>DonationServicebotEmbed.displayName = 'DonationServicebotEmbed'; <del>DonationServicebotEmbed.propTypes = propTypes; <del> <del>export default DonationServicebotEmbed; <ide><path>client/src/pages/donate.js <ide> import { createSelector } from 'reselect'; <ide> import { Grid, Row, Col } from '@freecodecamp/react-bootstrap'; <ide> <ide> import { stripePublicKey } from '../../config/env.json'; <del>import { Spacer, Loader, FullWidthRow, Link } from '../components/helpers'; <add>import { Spacer, Loader, FullWidthRow } from '../components/helpers'; <ide> import DonateForm from '../components/Donation/components/DonateForm'; <ide> import DonateText from '../components/Donation/components/DonateText'; <ide> import { signInLoadingSelector, userSelector } from '../redux'; <ide> export class DonatePage extends Component { <ide> constructor(...props) { <ide> super(...props); <ide> this.state = { <del> stripe: null, <del> enableSettings: false <add> stripe: null <ide> }; <ide> <del> this.enableDonationSettingsPage = this.enableDonationSettingsPage.bind( <del> this <del> ); <ide> this.handleStripeLoad = this.handleStripeLoad.bind(this); <ide> } <ide> <ide> export class DonatePage extends Component { <ide> } <ide> } <ide> <del> enableDonationSettingsPage(enableSettings = true) { <del> this.setState({ enableSettings }); <del> } <del> <ide> render() { <ide> const { stripe } = this.state; <del> const { showLoading, isDonating } = this.props; <del> const { enableSettings } = this.state; <add> const { showLoading } = this.props; <ide> <ide> if (showLoading) { <ide> return <Loader fullScreen={true} />; <ide> export class DonatePage extends Component { <ide> <Spacer /> <ide> <Row> <ide> <Col md={6}> <del> <DonateForm <del> enableDonationSettingsPage={this.enableDonationSettingsPage} <del> stripe={stripe} <del> /> <del> <Row> <del> <Col sm={10} smOffset={1} xs={12}> <del> <Spacer size={2} /> <del> <h3 className='text-center'> <del> Manage your existing donation <del> </h3> <del> <div className='button-group'> <del> {[ <del> `Update your existing donation`, <del> `Download donation receipts` <del> ].map(donationSettingOps => ( <del> <Link <del> className='btn btn-block' <del> disabled={!isDonating && !enableSettings} <del> key={donationSettingOps} <del> to='/donation/settings' <del> > <del> {donationSettingOps} <del> </Link> <del> ))} <del> </div> <del> </Col> <del> </Row> <add> <DonateForm stripe={stripe} /> <ide> </Col> <ide> <Col md={6}> <ide> <DonateText /> <ide><path>client/src/pages/donation/settings.js <del>import React, { Component, Fragment } from 'react'; <del>import Helmet from 'react-helmet'; <del>import PropTypes from 'prop-types'; <del>import { connect } from 'react-redux'; <del>import { createSelector } from 'reselect'; <del>import { Grid, Button, Panel } from '@freecodecamp/react-bootstrap'; <del>import { uniq } from 'lodash'; <del> <del>import { apiLocation } from '../../../config/env.json'; <del>import { postCreateHmacHash } from '../../utils/ajax'; <del>import { <del> signInLoadingSelector, <del> userSelector, <del> hardGoTo as navigate, <del> isSignedInSelector <del>} from '../../redux'; <del>// eslint-disable-next-line max-len <del>import DonateServicebotEmbed from '../../components/Donation/components/DonateServicebotEmbed'; <del>import { Loader, Spacer, Link, FullWidthRow } from '../../components/helpers'; <del>import SectionHeader from '../../components/settings/SectionHeader.js'; <del> <del>const propTypes = { <del> donationEmails: PropTypes.array, <del> email: PropTypes.string, <del> isDonating: PropTypes.bool, <del> isSignedIn: PropTypes.bool, <del> navigate: PropTypes.func.isRequired, <del> showLoading: PropTypes.bool.isRequired <del>}; <del> <del>const mapStateToProps = createSelector( <del> isSignedInSelector, <del> userSelector, <del> signInLoadingSelector, <del> (isSignedIn, { email, isDonating, donationEmails }, showLoading) => ({ <del> isSignedIn, <del> email, <del> isDonating, <del> donationEmails, <del> showLoading <del> }) <del>); <del> <del>const mapDispatchToProps = { <del> navigate <del>}; <del> <del>export class DonationSettingsPage extends Component { <del> constructor(...props) { <del> super(...props); <del> <del> this.state = { <del> hash: null, <del> currentSettingsEmail: null <del> }; <del> <del> this.getEmailHmacHash = this.getEmailHmacHash.bind(this); <del> this.handleSelectDonationEmail = this.handleSelectDonationEmail.bind(this); <del> } <del> <del> getEmailHmacHash(currentSettingsEmail) { <del> return postCreateHmacHash({ <del> email: currentSettingsEmail <del> }) <del> .then(response => { <del> const data = response && response.data; <del> this.setState({ hash: '' + data.hash, currentSettingsEmail }); <del> }) <del> .catch(error => { <del> const data = <del> error.response && error.response.data <del> ? error.response.data <del> : { <del> error: <del> 'Something is not right. Please contact team@freecodecamp.org' <del> }; <del> console.error(data.error); <del> }); <del> } <del> <del> handleSelectDonationEmail(e) { <del> e.preventDefault(); <del> this.setState({ hash: null, currentSettingsEmail: null }); <del> this.getEmailHmacHash(e.currentTarget.value); <del> } <del> <del> renderServicebotEmbed() { <del> const { donationEmails } = this.props; <del> if (!donationEmails || donationEmails.length === 0) { <del> return null; <del> } <del> const { currentSettingsEmail, hash } = this.state; <del> return ( <del> <div className='servicebot-embed-panel'> <del> {!hash || !currentSettingsEmail ? ( <del> <Panel> <del> <Spacer /> <del> <p className='text-center'> <del> Select the email associated with your donations above. <del> </p> <del> </Panel> <del> ) : ( <del> <Panel> <del> <Spacer /> <del> <DonateServicebotEmbed email={currentSettingsEmail} hash={hash} /> <del> <Spacer /> <del> </Panel> <del> )} <del> </div> <del> ); <del> } <del> <del> renderDonationEmailsList() { <del> const { donationEmails } = this.props; <del> if (!donationEmails || donationEmails.length === 0) { <del> return ( <del> <p> <del> Some of the data associated with your donation is unavailable. Please <del> contact team@freeCodeCamp.org to get your donation updated manually. <del> </p> <del> ); <del> } <del> return uniq(donationEmails).map(email => ( <del> <Button <del> bsStyle='primary' <del> className='btn btn-block' <del> key={email} <del> onClick={this.handleSelectDonationEmail} <del> value={email} <del> > <del> {`Show donations for your ${email} email address`} <del> </Button> <del> )); <del> } <del> <del> render() { <del> const { showLoading, isSignedIn, isDonating, navigate } = this.props; <del> <del> if (showLoading) { <del> return <Loader fullScreen={true} />; <del> } <del> <del> if (!isSignedIn) { <del> navigate(`${apiLocation}/signin?returnTo=donation/settings`); <del> return <Loader fullScreen={true} />; <del> } <del> <del> if (!isDonating) { <del> navigate(`/donate`); <del> return <Loader fullScreen={true} />; <del> } <del> <del> return ( <del> <Fragment> <del> <Helmet title='Manage your donation | freeCodeCamp.org' /> <del> <Grid> <del> <main> <del> <Spacer size={2} /> <del> <del> <FullWidthRow className='button-group'> <del> <Link <del> className='btn-invert btn btn-lg btn-primary btn-block' <del> to={`/donate`} <del> > <del> Go to donate page <del> </Link> <del> <Link <del> className='btn-invert btn btn-lg btn-primary btn-block' <del> to={`/settings`} <del> > <del> Update my account settings <del> </Link> <del> </FullWidthRow> <del> <del> <FullWidthRow> <del> <Spacer /> <del> <h1 className='text-center'>Manage your donations</h1> <del> </FullWidthRow> <del> <del> <Spacer /> <del> <SectionHeader> <del> Donations made using a credit or debit card <del> </SectionHeader> <del> <FullWidthRow className='button-group'> <del> {this.renderDonationEmailsList()} <del> </FullWidthRow> <del> <Spacer /> <del> <FullWidthRow>{this.renderServicebotEmbed()}</FullWidthRow> <del> <del> <Spacer /> <del> <SectionHeader>Donations made using PayPal</SectionHeader> <del> <FullWidthRow> <del> <p className='text-center'> <del> You can update your PayPal donation{' '} <del> <Link <del> external={true} <del> to='https://www.paypal.com/cgi-bin/webscr?cmd=_manage-paylist' <del> > <del> directly on PayPal <del> </Link> <del> . <del> </p> <del> </FullWidthRow> <del> <del> <Spacer /> <del> <SectionHeader>Still need help?</SectionHeader> <del> <FullWidthRow> <del> <p> <del> If you can't see your donation here, forward a donation receipt <del> you have recieved in your email to team@freeCodeCamp.org and <del> tell us how we can help you with it. <del> </p> <del> </FullWidthRow> <del> <del> <Spacer /> <del> </main> <del> </Grid> <del> </Fragment> <del> ); <del> } <del>} <del> <del>DonationSettingsPage.displayName = 'DonationSettingsPage'; <del>DonationSettingsPage.propTypes = propTypes; <del> <del>export default connect( <del> mapStateToProps, <del> mapDispatchToProps <del>)(DonationSettingsPage);
6
Go
Go
set utilizecache to false on cache miss
1e746a8a2b2f8a88903feca430f254605dcc6cc8
<ide><path>builder/internals.go <ide> func (b *Builder) probeCache() (bool, error) { <ide> return true, nil <ide> } else { <ide> log.Debugf("[BUILDER] Cache miss") <add> // after a miss we no longer need to probe <add> b.UtilizeCache = false <ide> } <ide> } <ide> return false, nil
1
Java
Java
fix textinput padding on nodes
3061606fe65062b93704155eb7c7e15c70280d16
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTTextInput.java <ide> import android.view.ViewGroup; <ide> import android.widget.EditText; <ide> <del>import com.facebook.csslayout.CSSDirection; <ide> import com.facebook.csslayout.CSSMeasureMode; <ide> import com.facebook.csslayout.CSSNodeAPI; <ide> import com.facebook.csslayout.MeasureOutput; <ide> public void setText(@Nullable String text) { <ide> <ide> @Override <ide> public void setPadding(int spacingType, float padding) { <del> if (getPadding().set(spacingType, padding)) { <del> mPaddingChanged = true; <del> dirty(); <del> } <add> super.setPadding(spacingType, padding); <add> mPaddingChanged = true; <add> dirty(); <ide> } <ide> <ide> @Override
1
Ruby
Ruby
pull nil checks up
8d572ad1baa9171253957f174bf88283f84018e8
<ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb <ide> def polymorphic_url(record_or_hash_or_array, options = {}) <ide> record_list = extract_record_list(record_or_hash_or_array) <ide> end <ide> <add> if record_list.empty? || record_list.any?(&:nil?) <add> raise ArgumentError, "Nil location provided. Can't build URI." <add> end <add> <ide> record = convert_to_model(record_list.pop) <ide> <ide> inflection = if options[:action] && options[:action].to_s == "new" <ide> def routing_type(options) <ide> def build_route_part(record, inflection) <ide> if record.is_a?(Symbol) || record.is_a?(String) <ide> record.to_s <del> elsif record <add> else <ide> if inflection == :singular <ide> model_name_from_record_or_class(record).singular_route_key <ide> else <ide> model_name_from_record_or_class(record).route_key <ide> end <del> else <del> raise ArgumentError, "Nil location provided. Can't build URI." <ide> end <ide> end <ide>
1
Ruby
Ruby
fix rubocop violations
c0af72bf86701e03ac97a50754beddf2b5d7943f
<ide><path>actionview/test/lib/test_component.rb <ide> def self.compile <ide> end <ide> <ide> private <del> <ide> attr_reader :content, :title, :view_context <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb <ide> def test_schema_dumper_for_uuid_primary_key_default <ide> end <ide> end <ide> <del> uses_transaction \ <ide> def test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration <ide> @verbose_was = ActiveRecord::Migration.verbose <ide> ActiveRecord::Migration.verbose = false <ide> def migrate(x) <ide> ActiveRecord::Migration.verbose = @verbose_was <ide> ActiveRecord::SchemaMigration.delete_all <ide> end <add> uses_transaction :test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration <ide> end <ide> <ide> class PostgresqlUUIDTestNilDefault < ActiveRecord::PostgreSQLTestCase <ide> def test_schema_dumper_for_uuid_primary_key_with_default_override_via_nil <ide> assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: nil/, schema) <ide> end <ide> <del> uses_transaction \ <ide> def test_schema_dumper_for_uuid_primary_key_with_default_nil_in_legacy_migration <ide> @verbose_was = ActiveRecord::Migration.verbose <ide> ActiveRecord::Migration.verbose = false <ide> def migrate(x) <ide> ActiveRecord::Migration.verbose = @verbose_was <ide> ActiveRecord::SchemaMigration.delete_all <ide> end <add> uses_transaction :test_schema_dumper_for_uuid_primary_key_with_default_nil_in_legacy_migration <ide> end <ide> <ide> class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase
2
Ruby
Ruby
remove stray undent
db361e29b8d4909757e624fafdfb6186d0fe112a
<ide><path>Library/Homebrew/extend/os/linux/diagnostic.rb <ide> def check_tmpdir_executable <ide> f.close <ide> return if system f.path <ide> <del> <<~EOS.undent <add> <<~EOS <ide> The directory #{HOMEBREW_TEMP} does not permit executing <ide> programs. It is likely mounted as "noexec". Please set HOMEBREW_TEMP <ide> in your #{shell_profile} to a different directory, for example:
1
Go
Go
ignore dir sizes in treesize func
a4f14528c25c4a092c30334d05008fe44275a79e
<ide><path>aufs/aufs_test.go <ide> func TestChanges(t *testing.T) { <ide> } <ide> } <ide> <del>/* FIXME: How to properly test this? <ide> func TestDiffSize(t *testing.T) { <ide> d := newDriver(t) <ide> defer os.RemoveAll(tmp) <ide> func TestDiffSize(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> diffSize, err := d.DiffSize("1") <add> diffSize, err := d.Size("1") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> if diffSize != size { <ide> t.Fatalf("Expected size to be %d got %d", size, diffSize) <ide> } <ide> } <del>*/ <ide><path>utils/fs.go <ide> import ( <ide> // TreeSize walks a directory tree and returns its total size in bytes. <ide> func TreeSize(dir string) (size int64, err error) { <ide> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { <add> // Ignore directory sizes <add> if fileInfo.IsDir() { <add> return nil <add> } <ide> size += fileInfo.Size() <ide> return nil <ide> })
2
Text
Text
add marked source in tutorial doc
25ef456b132e389210c289222604bf43d0b3bbcd
<ide><path>docs/docs/tutorial.md <ide> For sake of simplicity, the server we will run uses a `JSON` file as a database. <ide> <ide> ### Getting started <ide> <del>For this tutorial, we're going to make it as easy as possible. Included in the server package discussed above is an HTML file which we'll work in. Open up `public/index.html` in your favorite editor. It should look something like this (with perhaps some minor differences, we'll add an additional `<script>` tag later): <add>For this tutorial, we're going to make it as easy as possible. Included in the server package discussed above is an HTML file which we'll work in. Open up `public/index.html` in your favorite editor. It should look something like this: <ide> <ide> ```html <ide> <!-- index.html --> <ide> For this tutorial, we're going to make it as easy as possible. Included in the s <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react-dom.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script> <ide> </head> <ide> <body> <ide> <div id="content"></div> <ide> Note that we have passed some data from the parent `CommentList` component to th <ide> <ide> Markdown is a simple way to format your text inline. For example, surrounding text with asterisks will make it emphasized. <ide> <del>First, add the third-party library **marked** to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground): <del> <del>```html{9} <del><!-- index.html --> <del><head> <del> <meta charset="utf-8" /> <del> <title>React Tutorial</title> <del> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <del> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react-dom.js"></script> <del> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <del> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <del> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script> <del></head> <del>``` <del> <del>Next, let's convert the comment text to Markdown and output it: <add>In this tutorial we use a third-party library **marked** which takes Markdown text and converts it to raw HTML. We already included this library with the original markup for the page, so we can just start using it. Let's convert the comment text to Markdown and output it: <ide> <ide> ```javascript{9} <ide> // tutorial6.js
1
PHP
PHP
fix failing tests from upstream 3.0
7cf205556c9b745d3c04b0307f5c5d3131bc8440
<ide><path>Cake/Test/TestCase/ORM/TableTest.php <ide> public function testReciprocalHasManyLoading() { <ide> * @return void <ide> */ <ide> public function testReciprocalBelongsToMany() { <del> $table = new \TestApp\Model\Repository\ArticleTable; <add> $table = new \TestApp\Model\Repository\ArticleTable([ <add> 'connection' => $this->connection, <add> ]); <ide> $result = $table->find('all')->contain(['tag'])->first(); <ide> $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]); <ide> $this->assertInstanceOf('TestApp\Model\Entity\ArticlesTag', $result->tags[0]->extraInfo); <ide> public function testSaveNewEntity() { <ide> 'created' => new \DateTime('2013-10-10 00:00'), <ide> 'updated' => new \DateTime('2013-10-10 00:00') <ide> ]); <del> $table = Table::build('user'); <add> $table = TableRegistry::get('user'); <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertEquals($entity->id, 5); <ide>
1
PHP
PHP
remove extra alias
9aea079a6c6ed15dd5f764d05dd75c7325fdd50f
<ide><path>src/Illuminate/Mail/TransportManager.php <ide> use Illuminate\Mail\Transport\LogTransport; <ide> use Illuminate\Mail\Transport\SesTransport; <ide> use Illuminate\Mail\Transport\ArrayTransport; <del>use Swift_SendmailTransport as MailTransport; <ide> use Illuminate\Mail\Transport\MailgunTransport; <ide> use Illuminate\Mail\Transport\MandrillTransport; <ide> use Illuminate\Mail\Transport\SparkPostTransport; <ide> protected function addSesCredentials(array $config) <ide> */ <ide> protected function createMailDriver() <ide> { <del> return new MailTransport; <add> return new SendmailTransport; <ide> } <ide> <ide> /**
1
Python
Python
fix indentation -.-
857454ffa0c7d66a788d15e1f6feb1ba6ba1ba59
<ide><path>spacy/de/__init__.py <ide> class German(Language): <ide> lang = 'de' <ide> <del> @classmethod <add> @classmethod <ide> def default_vocab(cls, package, get_lex_attr=None, vectors_package=None): <ide> vocab = super(German,cls).default_vocab(package,get_lex_attr,vectors_package) <del> # for now until the morphology is done for German <add> # set a dummy lemmatizer for now that simply returns the same string <add> # until the morphology is done for German <ide> vocab.morphology.lemmatizer = lambda string,pos: set([string]) <ide> return vocab
1
Text
Text
fix a broken link
a03d5bc2887b0dfd537262e57baa73864b707aa3
<ide><path>docs/creating-a-theme.md <ide> a few things before starting: <ide> is used to help distribute your theme to Atom users. <ide> * Your theme's _package.json_ must contain a `"theme"` key with a value <ide> of `"ui"` or `"syntax"` for Atom to recognize and load it as a theme. <del>* You can find existing themes to install or fork on [atom.io](atomio). <add>* You can find existing themes to install or fork on <add> [atom.io](https://atom.io/themes). <ide> <ide> ## Creating a Syntax Theme <ide>
1
Javascript
Javascript
remind user that hot updates stopped
216b435c25e29178973290e3a0f7356b725d1d6b
<ide><path>hot/only-dev-server.js <ide> if(module.hot) { <ide> var hotEmitter = require("./emitter"); <ide> hotEmitter.on("webpackHotUpdate", function(currentHash) { <ide> lastHash = currentHash; <del> if(!upToDate() && module.hot.status() === "idle") { <del> console.log("[HMR] Checking for updates on the server..."); <del> check(); <add> if(!upToDate()) { <add> var status = module.hot.status(); <add> if(status === "idle") { <add> console.log("[HMR] Checking for updates on the server..."); <add> check(); <add> } else if(["abort", "fail"].indexOf(status) >= 0) { <add> console.warn("[HMR] Cannot apply update as a previous update " + status + "ed. Need to do a full reload!"); <add> } <ide> } <ide> }); <ide> console.log("[HMR] Waiting for update signal from WDS...");
1
Python
Python
attach volume upon machine creation
0b8b51b66067b7c7d3f873102feadd133691d4bf
<ide><path>libcloud/compute/drivers/digitalocean.py <ide> def list_volumes(self): <ide> return list(map(self._to_volume, data)) <ide> <ide> def create_node(self, name, size, image, location, ex_create_attr=None, <del> ex_ssh_key_ids=None, ex_user_data=None): <add> ex_ssh_key_ids=None, ex_user_data=None, volumes=[]): <ide> """ <ide> Create a node. <ide> <ide> def create_node(self, name, size, image, location, ex_create_attr=None, <ide> " favor of the ex_create_attr parameter.") <ide> attr['ssh_keys'] = ex_ssh_key_ids <ide> <add> ex_volumes = [] <add> if volumes and volumes[0].get('volume_id'): <add> ex_volumes.append(volumes[0].get('volume_id')) <add> attr['volumes'] = ex_volumes <add> <ide> ex_create_attr = ex_create_attr or {} <ide> for key in ex_create_attr.keys(): <ide> if key in self.EX_CREATE_ATTRIBUTES: <ide> def create_node(self, name, size, image, location, ex_create_attr=None, <ide> data = res.object['droplet'] <ide> # TODO: Handle this in the response class <ide> status = res.object.get('status', 'OK') <add> node = self._to_node(data=data) <ide> if status == 'ERROR': <ide> message = res.object.get('message', None) <ide> error_message = res.object.get('error_message', message) <ide> raise ValueError('Failed to create node: %s' % (error_message)) <ide> <del> return self._to_node(data=data) <add> else: <add> if volumes and volumes[0].get('size'): <add> volume = self.create_volume(size=volumes[0].get('size'), <add> name=name+'-disk', <add> location=location.id) <add> from time import sleep <add> i = 0 <add> # try for 30 secs, as in the beginning get the error <add> # that Droplet already has a pending event <add> while (i < 30): <add> try: <add> self.attach_volume(node, volume) <add> break <add> except Exception: <add> sleep(3) <add> i+=1 <add> <add> return node <ide> <ide> def ex_start_node(self, node): <ide> params = {"type": "power_on"}
1
Python
Python
restore description for provider packages.
983e5a62df6d74cd35fbb1fc7f830e32000c299c
<ide><path>backport_packages/setup_backport_packages.py <ide> def get_long_description(provider_package_id: str) -> str: <ide> :return: content of the description (README file) <ide> """ <ide> package_folder = get_target_providers_package_folder(provider_package_id) <del> with open(os.path.join(package_folder, "README.md"), encoding='utf-8', mode="w+") as file: <add> readme_file = os.path.join(package_folder, "README.md") <add> if not(os.path.exists(readme_file)): <add> return "" <add> with open(os.path.join(package_folder, "README.md"), encoding='utf-8', mode="r") as file: <ide> readme_contents = file.read() <ide> copying = True <ide> long_description = ""
1
Go
Go
fix registry pushing/tagging
5aa304f9696d8fcc2e39628ce68a39bfc932adb4
<ide><path>server.go <ide> func (srv *Server) ImagePull(localName string, tag string, out io.Writer, sf *ut <ide> } <ide> <ide> // Retrieve the all the images to be uploaded in the correct order <del>// Note: we can't use a map as it is not ordered <del>func (srv *Server) getImageList(localRepo map[string]string) ([][]*registry.ImgData, error) { <del> imgList := map[string]*registry.ImgData{} <del> depGraph := utils.NewDependencyGraph() <add>func (srv *Server) getImageList(localRepo map[string]string) ([]string, map[string][]string, error) { <add> var ( <add> imageList []string <add> imagesSeen map[string]bool = make(map[string]bool) <add> tagsByImage map[string][]string = make(map[string][]string) <add> ) <ide> <ide> for tag, id := range localRepo { <del> img, err := srv.runtime.graph.Get(id) <add> var imageListForThisTag []string <add> <add> tagsByImage[id] = append(tagsByImage[id], tag) <add> <add> for img, err := srv.runtime.graph.Get(id); img != nil; img, err = img.GetParent() { <ide> if err != nil { <del> return nil, err <add> return nil, nil, err <ide> } <del> depGraph.NewNode(img.ID) <del> img.WalkHistory(func(current *Image) error { <del> imgList[current.ID] = &registry.ImgData{ <del> ID: current.ID, <del> Tag: tag, <del> } <del> parent, err := current.GetParent() <del> if err != nil { <del> return err <del> } <del> if parent == nil { <del> return nil <add> <add> if imagesSeen[img.ID] { <add> // This image is already on the list, we can ignore it and all its parents <add> break <ide> } <del> depGraph.NewNode(parent.ID) <del> depGraph.AddDependency(current.ID, parent.ID) <del> return nil <del> }) <del> } <ide> <del> traversalMap, err := depGraph.GenerateTraversalMap() <del> if err != nil { <del> return nil, err <add> imagesSeen[img.ID] = true <add> imageListForThisTag = append(imageListForThisTag, img.ID) <ide> } <ide> <del> utils.Debugf("Traversal map: %v", traversalMap) <del> result := [][]*registry.ImgData{} <del> for _, round := range traversalMap { <del> dataRound := []*registry.ImgData{} <del> for _, imgID := range round { <del> dataRound = append(dataRound, imgList[imgID]) <del> } <del> result = append(result, dataRound) <add> // reverse the image list for this tag (so the "most"-parent image is first) <add> for i, j := 0, len(imageListForThisTag) - 1; i < j; i, j = i + 1, j - 1 { <add> imageListForThisTag[i], imageListForThisTag[j] = imageListForThisTag[j], imageListForThisTag[i] <ide> } <del> return result, nil <add> <add> // append to main image list <add> imageList = append(imageList, imageListForThisTag...) <ide> } <ide> <del>func flatten(slc [][]*registry.ImgData) []*registry.ImgData { <del> result := []*registry.ImgData{} <del> for _, x := range slc { <del> result = append(result, x...) <del> } <del> return result <add> utils.Debugf("Image list: %v", imageList) <add> utils.Debugf("Tags by image: %v", tagsByImage) <add> <add> return imageList, tagsByImage, nil <ide> } <ide> <ide> func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName, remoteName string, localRepo map[string]string, sf *utils.StreamFormatter) error { <ide> out = utils.NewWriteFlusher(out) <del> imgList, err := srv.getImageList(localRepo) <add> utils.Debugf("Local repo: %s", localRepo) <add> imgList, tagsByImage, err := srv.getImageList(localRepo) <ide> if err != nil { <ide> return err <ide> } <del> flattenedImgList := flatten(imgList) <add> <ide> out.Write(sf.FormatStatus("", "Sending image list")) <ide> <ide> var repoData *registry.RepositoryData <del> repoData, err = r.PushImageJSONIndex(remoteName, flattenedImgList, false, nil) <add> var imageIndex []*registry.ImgData <add> <add> for imgId, tags := range tagsByImage { <add> for _, tag := range tags { <add> imageIndex = append(imageIndex, &registry.ImgData{ <add> ID: imgId, <add> Tag: tag, <add> }) <add> } <add> } <add> <add> repoData, err = r.PushImageJSONIndex(remoteName, imageIndex, false, nil) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> for _, ep := range repoData.Endpoints { <ide> out.Write(sf.FormatStatus("", "Pushing repository %s (%d tags)", localName, len(localRepo))) <del> // This section can not be parallelized (each round depends on the previous one) <del> for i, round := range imgList { <del> // FIXME: This section can be parallelized <del> for _, elem := range round { <add> <add> for _, imgId := range imgList { <ide> var pushTags func() error <ide> pushTags = func() error { <del> if i < (len(imgList) - 1) { <del> // Only tag the top layer in the repository <del> return nil <del> } <add> for _, tag := range tagsByImage[imgId] { <add> out.Write(sf.FormatStatus("", "Pushing tag for rev [%s] on {%s}", utils.TruncateID(imgId), ep+"repositories/"+remoteName+"/tags/"+tag)) <ide> <del> out.Write(sf.FormatStatus("", "Pushing tags for rev [%s] on {%s}", utils.TruncateID(elem.ID), ep+"repositories/"+remoteName+"/tags/"+elem.Tag)) <del> if err := r.PushRegistryTag(remoteName, elem.ID, elem.Tag, ep, repoData.Tokens); err != nil { <add> if err := r.PushRegistryTag(remoteName, imgId, tag, ep, repoData.Tokens); err != nil { <ide> return err <ide> } <add> } <add> <ide> return nil <ide> } <del> if _, exists := repoData.ImgList[elem.ID]; exists { <add> <add> if r.LookupRemoteImage(imgId, ep, repoData.Tokens) { <ide> if err := pushTags(); err != nil { <ide> return err <ide> } <del> out.Write(sf.FormatProgress(utils.TruncateID(elem.ID), "Image already pushed, skipping", nil)) <add> out.Write(sf.FormatStatus("", "Image %s already pushed, skipping", utils.TruncateID(imgId))) <ide> continue <del> } else if r.LookupRemoteImage(elem.ID, ep, repoData.Tokens) { <del> if err := pushTags(); err != nil { <del> return err <ide> } <del> out.Write(sf.FormatProgress(utils.TruncateID(elem.ID), "Image already pushed, skipping", nil)) <del> continue <del> } <del> checksum, err := srv.pushImage(r, out, remoteName, elem.ID, ep, repoData.Tokens, sf) <add> <add> _, err := srv.pushImage(r, out, remoteName, imgId, ep, repoData.Tokens, sf) <ide> if err != nil { <ide> // FIXME: Continue on error? <ide> return err <ide> } <del> elem.Checksum = checksum <ide> <ide> if err := pushTags(); err != nil { <ide> return err <ide> } <ide> } <ide> } <del> } <ide> <del> if _, err := r.PushImageJSONIndex(remoteName, flattenedImgList, true, repoData.Endpoints); err != nil { <add> if _, err := r.PushImageJSONIndex(remoteName, imageIndex, true, repoData.Endpoints); err != nil { <ide> return err <ide> } <ide> <ide> func (srv *Server) ImageDelete(name string, autoPrune bool) ([]APIRmi, error) { <ide> } <ide> } <ide> return srv.deleteImage(img, repository, tag) <del>} <add> } <ide> <ide> func (srv *Server) canDeleteImage(imgID string) error { <del> for _, container := range srv.runtime.List() { <del> parent, err := srv.runtime.repositories.LookupImage(container.Image) <del> if err != nil { <add> for _, container := range srv.runtime.List() { <add> parent, err := srv.runtime.repositories.LookupImage(container.Image) <add> if err != nil { <ide> return err <del> } <add> } <ide> <del> if err := parent.WalkHistory(func(p *Image) error { <add> if err := parent.WalkHistory(func(p *Image) error { <ide> if imgID == p.ID { <ide> return fmt.Errorf("Conflict, cannot delete %s because the container %s is using it", utils.TruncateID(imgID), utils.TruncateID(container.ID)) <del> } <del> return nil <del> }); err != nil { <add> } <add> return nil <add> }); err != nil { <ide> return err <add> } <ide> } <del> } <ide> return nil <ide> } <ide> <ide> func (srv *Server) ImageGetCached(imgID string, config *Config) (*Image, error) <ide> imageMap := make(map[string][]string) <ide> for _, img := range images { <ide> imageMap[img.Parent] = append(imageMap[img.Parent], img.ID) <del> } <add> } <ide> sort.Strings(imageMap[imgID]) <ide> // Loop on the children of the given image and check the config <ide> for _, elem := range imageMap[imgID] {
1
Javascript
Javascript
add tests for ignoring null nodes
c22d45027ce5971420f871f725addde39bd341f7
<ide><path>test/core/selection-append-test.js <ide> suite.addBatch({ <ide> assert.isTrue(svg[0][1].parentNode === div[0][1]); <ide> assert.isTrue(div[0][0].lastChild === svg[0][0]); <ide> assert.isTrue(div[0][1].lastChild === svg[0][1]); <add> }, <add> "ignores null nodes": function(div) { <add> div.html(""); <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> var span = some.append("span"); <add> assert.equal(span[0].length, 2); <add> assert.equal(span[0][0].tagName, "SPAN"); <add> assert.isNull(span[0][1]); <add> assert.isTrue(span[0][0].parentNode === div[0][0]); <add> assert.isTrue(div[0][0].lastChild === span[0][0]); <add> assert.isNull(div[0][1].lastChild); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-attr-test.js <ide> suite.addBatch({ <ide> div.attr("xlink:foo", "bar").attr("xlink:foo", function() { return null; }); <ide> assert.equal(div[0][0].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), ""); <ide> assert.equal(div[0][1].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), ""); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> some.attr("href", null).attr("href", "url"); <add> assert.equal(div[0][0].getAttribute("href"), "url"); <add> assert.equal(div[0][1].getAttribute("href"), ""); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-classed-test.js <ide> suite.addBatch({ <ide> assert.isFalse(div.classed("foob")); <ide> assert.isFalse(div.classed("bare")); <ide> assert.isFalse(div.classed("rbaz")); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> some.attr("class", null).classed("foo", true); <add> assert.equal(div[0][0].className, "foo"); <add> assert.equal(div[0][1].className, ""); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-filter-test.js <ide> suite.addBatch({ <ide> var indexes = []; <ide> span.filter(function(d, i) { return d & 1; }).each(function(d, i) { indexes.push(i); }); <ide> assert.deepEqual(indexes, [0, 0]); <add> }, <add> "ignores null nodes": function() { <add> var span = d3.selectAll("span"); <add> span[0][1] = null; <add> var some = span.filter(function(d, i) { return d & 1; }); <add> assert.isTrue(some[0][0] === span[0][3]); <add> assert.equal(some.length, 1); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-property-test.js <ide> suite.addBatch({ <ide> div.property("bgcolor", "yellow").property("bgcolor", function() { return null }); <ide> assert.isFalse("bgcolor" in div[0][0]); <ide> assert.isFalse("bgcolor" in div[0][1]); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> some.property("bgcolor", null).property("bgcolor", "red"); <add> assert.equal(div[0][0].bgcolor, "red"); <add> assert.isFalse("bgcolor" in div[0][1]); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-select-test.js <ide> suite.addBatch({ <ide> assert.equal(div[0][1], null); <ide> assert.equal(div.length, 1); <ide> assert.equal(div[0].length, 2); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> var span = some.select("span"); <add> assert.equal(span.length, 1); <add> assert.equal(span[0].length, 2); <add> assert.isTrue(span[0][0].parentNode === div[0][0]); <add> assert.isNull(span[0][1]); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-selectAll-test.js <ide> suite.addBatch({ <ide> assert.equal(div.length, 2); <ide> assert.equal(div[0].length, 0); <ide> assert.equal(div[1].length, 0); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> var span = some.selectAll("span"); <add> assert.equal(span.length, 1); <add> assert.equal(span[0].length, 2); <add> assert.isTrue(span[0][0].parentNode === div[0][0]); <add> assert.isTrue(span[0][1].parentNode === div[0][0]); <ide> } <ide> } <ide> }); <ide><path>test/core/selection-style-test.js <ide> suite.addBatch({ <ide> div.style("background-color", "red").style("background-color", function() { return null; }); <ide> assert.equal(div[0][0].style["background-color"], ""); <ide> assert.equal(div[0][1].style["background-color"], ""); <add> }, <add> "ignores null nodes": function(div) { <add> var some = d3.selectAll("div"); <add> some[0][1] = null; <add> some.style("background-color", null).style("background-color", "red"); <add> assert.equal(div[0][0].style["background-color"], "red"); <add> assert.equal(div[0][1].style["background-color"], ""); <ide> } <ide> } <ide> });
8
PHP
PHP
use collection@lists in builder@lists
ef734e77237fff4c1202e0056da499ecec724b85
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function orWhereNotNull($column) <ide> { <ide> return $this->whereNotNull($column, 'or'); <ide> } <del> <add> <ide> /** <ide> * Add a "where date" statement to the query. <ide> * <ide> public function whereDate($column, $operator, $value, $boolean = 'and') <ide> { <ide> return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean); <ide> } <del> <add> <ide> /** <ide> * Add a "where day" statement to the query. <ide> * <ide> public function lists($column, $key = null) <ide> { <ide> $columns = $this->getListSelect($column, $key); <ide> <del> // First we will just get all of the column values for the record result set <del> // then we can associate those values with the column if it was specified <del> // otherwise we can just give these values back without a specific key. <ide> $results = new Collection($this->get($columns)); <ide> <del> $values = $results->fetch($columns[0])->all(); <del> <del> // If a key was specified and we have results, we will go ahead and combine <del> // the values with the keys of all of the records so that the values can <del> // be accessed by the key of the rows instead of simply being numeric. <del> if ( ! is_null($key) && count($results) > 0) <del> { <del> $keys = $results->fetch($key)->all(); <del> <del> return array_combine($keys, $values); <del> } <del> <del> return $values; <add> return $results->lists($columns[0], array_get($columns, 1)); <ide> } <ide> <ide> /** <ide> protected function getListSelect($column, $key) <ide> // If the selected column contains a "dot", we will remove it so that the list <ide> // operation can run normally. Specifying the table is not needed, since we <ide> // really want the names of the columns as it is in this resulting array. <del> if (($dot = strpos($select[0], '.')) !== false) <add> return array_map(function($column) <ide> { <del> $select[0] = substr($select[0], $dot + 1); <del> } <add> $dot = strpos($column, '.'); <ide> <del> return $select; <add> return $dot === false ? $column : substr($column, $dot + 1); <add> }, $select); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentIntegrationTest.php <ide> public function testBasicModelCollectionRetrieval() <ide> } <ide> <ide> <add> public function testListsRetrieval() <add> { <add> EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); <add> EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']); <add> <add> $simple = EloquentTestUser::oldest('id')->lists('users.email'); <add> $keyed = EloquentTestUser::oldest('id')->lists('users.email', 'users.id'); <add> <add> $this->assertEquals(['taylorotwell@gmail.com', 'abigailotwell@gmail.com'], $simple); <add> $this->assertEquals([1 => 'taylorotwell@gmail.com', 2 => 'abigailotwell@gmail.com'], $keyed); <add> } <add> <add> <ide> public function testFindOrFail() <ide> { <ide> EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
2